diff --git a/cmd/os/windows/kstat/kstat.c b/cmd/os/windows/kstat/kstat.c index 72326301e5b..112150b729b 100644 --- a/cmd/os/windows/kstat/kstat.c +++ b/cmd/os/windows/kstat/kstat.c @@ -45,8 +45,6 @@ #include #include #include -//#include - //#include #include #include #include @@ -118,7 +116,7 @@ main(int argc, char **argv) #if !defined(TEXT_DOMAIN) /* Should be defined by cc -D */ #define TEXT_DOMAIN "SYS_TEST" /* Use this only if it wasn't */ #endif - //(void) textdomain(TEXT_DOMAIN); + // (void) textdomain(TEXT_DOMAIN); /* * Create the selector list and a dummy default selector to match @@ -222,7 +220,8 @@ main(int argc, char **argv) argv += optind; if (g_wflg) { - /* kstat_write mode: consume commandline arguments: + /* + * kstat_write mode: consume commandline arguments: * kstat -w module:instance:name:statistic_name=value */ n = write_mode(argc, argv); @@ -383,15 +382,15 @@ main(int argc, char **argv) static void usage(void) { - (void)fprintf(stderr, gettext( - "Usage:\n" - "kstat [ -Cjlpq ] [ -T d|u ] [ -c class ]\n" - " [ -m module ] [ -i instance ] [ -n name ] [ -s statistic ]\n" - " [ interval [ count ] ]\n" - "kstat [ -Cjlpq ] [ -T d|u ] [ -c class ]\n" - " [ module[:instance[:name[:statistic]]] ... ]\n" - " [ interval [ count ] ]\n" - "kstat -w module:instance:name:statistic=value [ ... ] \n")); + (void) fprintf(stderr, gettext( + "Usage:\n" + "kstat [ -Cjlpq ] [ -T d|u ] [ -c class ]\n" + " [ -m module ] [ -i instance ] [ -n name ] [ -s statistic ]\n" + " [ interval [ count ] ]\n" + "kstat [ -Cjlpq ] [ -T d|u ] [ -c class ]\n" + " [ module[:instance[:name[:statistic]]] ... ]\n" + " [ interval [ count ] ]\n" + "kstat -w module:instance:name:statistic=value [ ... ] \n")); } /* @@ -427,7 +426,7 @@ ks_safe_strdup(char *str) while ((ret = _strdup(str)) == NULL) { if (errno == EAGAIN) { - (void)usleep(200); + (void) usleep(200); } else { perror("strdup"); exit(3); @@ -1045,7 +1044,8 @@ ks_instances_print(void) * e.g. "kstat -w zfs:0:tunable:zfs_arc_mac=1234567890 * */ -int write_mode(int argc, char **argv) +int +write_mode(int argc, char **argv) { char *arg; int instance, rc = 0; @@ -1055,14 +1055,15 @@ int write_mode(int argc, char **argv) if (argc == 0) { usage(); - (void)fprintf(stderr, "-w takes at least one argument\n"); - (void)fprintf(stderr, "\te.g. kstat -w zfs:0:tunable:zfs_arc_max=1200000\n"); - return -1; + (void) fprintf(stderr, "-w takes at least one argument\n"); + (void) fprintf(stderr, + "\te.g. kstat -w zfs:0:tunable:zfs_arc_max=1200000\n"); + return (-1); } while ((kc = kstat_open()) == NULL) { if (errno == EAGAIN) { - (void)usleep(200); + (void) usleep(200); } else { perror("kstat_open"); exit(3); @@ -1070,37 +1071,48 @@ int write_mode(int argc, char **argv) } while (argc--) { - char mod[KSTAT_STRLEN + 1], name[KSTAT_STRLEN + 1], stat[KSTAT_STRLEN + 1]; + char mod[KSTAT_STRLEN + 1], name[KSTAT_STRLEN + 1], + stat[KSTAT_STRLEN + 1]; arg = *argv; - // TODO: make this more flexible. Spaces, and other types than uint64. + // TODO: make this more flexible. Spaces, and other types than + // uint64. // Call C11 sscanf_s which takes string-width following ptr. - if ((rc = sscanf_s(arg, "%[^:]:%d:%[^:]:%[^=]=%llu", - mod, KSTAT_STRLEN, - &instance, - name, KSTAT_STRLEN, - stat, KSTAT_STRLEN, - &value)) != 5) { - (void)fprintf(stderr, "Unable to parse '%s'\n input not in 'module:instance:name:statisticname=value' format. %d\n", arg, rc); + if ((rc = sscanf_s(arg, + "%[^:]:%d:%[^:]:%[^=]=%llu", + mod, KSTAT_STRLEN, + &instance, + name, KSTAT_STRLEN, + stat, KSTAT_STRLEN, + &value)) != 5) { + (void) fprintf(stderr, "Unable to parse '%s'\n input " + "not in 'module:instance:name:statisticname=value' " + "format. %d\n", arg, rc); failure++; } else { kstat_t *ks; ks = kstat_lookup(kc, mod, instance, name); if (ks == NULL) { - (void)fprintf(stderr, "Unable to lookup '%s:%d:%s': %d\n", - mod, instance, name, errno); + (void) fprintf(stderr, + "Unable to lookup '%s:%d:%s': %d\n", + mod, instance, name, errno); failure++; } else { if (kstat_read(kc, ks, NULL) == -1) { - (void)fprintf(stderr, "Unable to read '%s:%d:%s': %d\n", - mod, instance, name, errno); + (void) fprintf(stderr, + "Unable to read '%s:%d:%s': %d\n", + mod, instance, name, errno); failure++; } else { - kstat_named_t *kn = kstat_data_lookup(ks, stat); + kstat_named_t *kn = + kstat_data_lookup(ks, stat); if (kn == NULL) { - (void)fprintf(stderr, "Unable to find '%s' in '%s:%d:%s': %d\n", - stat, mod, instance, name, errno); + (void) fprintf(stderr, + "Unable to find '%s' in " + "'%s:%d:%s': %d\n", + stat, mod, instance, + name, errno); failure++; } else { before_value = kn->value.ui64; @@ -1110,12 +1122,22 @@ int write_mode(int argc, char **argv) rc = kstat_write(kc, ks, NULL); if (rc == -1) { - (void)fprintf(stderr, "Unable to write '%s:%d:%s:%s': %d\n", - mod, instance, name, stat, errno); + (void) fprintf(stderr, + "Unable to write " + "'%s:%d:%s:%s': " + "%d\n", + mod, instance, + name, + stat, errno); failure++; } else { - (void)fprintf(stderr, "%s:%d:%s:%s: %llu -> %llu\n", - mod, instance, name, stat, before_value, value); + (void) fprintf(stderr, + "%s:%d:%s:%s: %llu " + "-> %llu\n", + mod, instance, + name, stat, + before_value, + value); } // rc } // kstat_data_lookup } // kstat_read @@ -1125,11 +1147,10 @@ int write_mode(int argc, char **argv) } kstat_close(kc); - return failure; + return (failure); } - #ifndef WIN32 static void save_cpu_stat(kstat_t *kp, ks_instance_t *ksi) @@ -1607,7 +1628,7 @@ save_fault_list(kstat_t *kp, ks_instance_t *ksi) } } #endif -#endif +#endif static void save_named(kstat_t *kp, ks_instance_t *ksi) diff --git a/cmd/os/windows/kstat/kstat.h b/cmd/os/windows/kstat/kstat.h index af72060ad85..90e1d72fb81 100644 --- a/cmd/os/windows/kstat/kstat.h +++ b/cmd/os/windows/kstat/kstat.h @@ -30,14 +30,8 @@ /* * Structures needed by the kstat reader functions. */ -//#include #include -//#include -//#include -//#include #include -//#include -//#include #ifdef __sparc #include @@ -107,7 +101,7 @@ typedef union ks_value { { \ ks_value_t v; \ v.str.addr.ptr = _strdup(S->N); \ - v.str.len = (uint32_t) strlen(S->N); \ + v.str.len = (uint32_t)strlen(S->N); \ nvpair_insert(I, #N, &v, KSTAT_DATA_STRING); \ } @@ -143,7 +137,7 @@ typedef union ks_value { { \ ks_value_t v; \ v.str.addr.ptr = _strdup(V); \ - v.str.len = (uint32_t)( (V) ? strlen(V) : 0 ); \ + v.str.len = (uint32_t)((V) ? strlen(V) : 0); \ nvpair_insert(I, N, &v, KSTAT_DATA_STRING); \ } diff --git a/cmd/os/windows/zfsinstaller/zfsinstaller.h b/cmd/os/windows/zfsinstaller/zfsinstaller.h index 295dd4dcd21..a7ed59791d8 100644 --- a/cmd/os/windows/zfsinstaller/zfsinstaller.h +++ b/cmd/os/windows/zfsinstaller/zfsinstaller.h @@ -18,13 +18,12 @@ * * CDDL HEADER END */ - /* - * Copyright (c) 2018 Julian Heuking - */ +/* + * Copyright (c) 2018 Julian Heuking + */ #pragma once - #include #include #include @@ -33,7 +32,7 @@ DWORD zfs_install(char *); DWORD zfs_uninstall(char *); DWORD executeInfSection(const char *, char *); -DWORD startService(char*); +DWORD startService(char *); void printUsage(); DWORD send_zfs_ioc_unregister_fs(); DWORD installRootDevice(char *inf_path); diff --git a/cmd/zpool/zpool_vdev.c b/cmd/zpool/zpool_vdev.c index 909cf7288b4..1be292d8867 100644 --- a/cmd/zpool/zpool_vdev.c +++ b/cmd/zpool/zpool_vdev.c @@ -981,8 +981,9 @@ make_disks(zpool_handle_t *zhp, nvlist_t *nv) */ if (is_mpath_whole_disk(path)) { update_vdev_config_dev_strs(nv); - /* update might change path, so fetch it again */ - verify(!nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path)); + /* update might change path, so fetch again */ + verify(!nvlist_lookup_string(nv, + ZPOOL_CONFIG_PATH, &path)); } if (!is_spare(NULL, path)) (void) zero_label(path); @@ -1033,7 +1034,7 @@ make_disks(zpool_handle_t *zhp, nvlist_t *nv) #ifdef _WIN32 char *backslash = strrchr(devpath, '\\'); if (devnode == NULL || backslash > devnode) - devnode = backslash; + devnode = backslash; #endif devnode = &devnode[1]; @@ -1068,8 +1069,11 @@ make_disks(zpool_handle_t *zhp, nvlist_t *nv) if (ret) return (ret); #ifdef _WIN32 - // Append_partition will only work once label_disk has been called - // (To find offset+length). Call it again to get correct path. + /* + * Append_partition will only work once label_disk has + * been called (To find offset+length). + * Call it again to get correct path. + */ (void) zfs_append_partition(udevpath, MAXPATHLEN); #endif } diff --git a/include/os/windows/Trace.h b/include/os/windows/Trace.h index dbc1d532400..de056ab7be5 100644 --- a/include/os/windows/Trace.h +++ b/include/os/windows/Trace.h @@ -1,8 +1,12 @@ #pragma once -#if !defined WPPFILE || !defined RUN_WPP // To enable Wpp; Select Yes under Run Wpp Tracing in Project properties -#undef WPPFILE // And define both RUN_WPP and WPPFILE="%(FileName).tmh" in C/C++ preprocessor -#undef RUN_WPP // To disable Wpp; Select No under Run Wpp Tracing; undef RUN_WPP/WPPFILE in C/C++ preprocessor +#if !defined WPPFILE || !defined RUN_WPP +// To enable Wpp; Select Yes under Run Wpp Tracing in Project properties +#undef WPPFILE +// And define both RUN_WPP and WPPFILE="%(FileName).tmh" in C/C++ preprocessor +#undef RUN_WPP +// To disable Wpp; Select No under Run Wpp Tracing; +// undef RUN_WPP/WPPFILE in C/C++ preprocessor #endif static const int TRACE_FATAL = 1; @@ -13,31 +17,32 @@ static const int TRACE_VERBOSE = 5; static const int TRACE_NOISY = 8; #if defined RUN_WPP && defined WPPFILE -#define WPPNAME ZFSinTraceGuid -#define WPPGUID c20c603c,afd4,467d,bf76,c0a4c10553df +#define WPPNAME ZFSinTraceGuid +#define WPPGUID c20c603c, afd4, 467d, bf76, c0a4c10553df -#define WPP_DEFINE_DEFAULT_BITS \ - WPP_DEFINE_BIT(MYDRIVER_ALL_INFO) \ - WPP_DEFINE_BIT(TRACE_KDPRINT) \ - WPP_DEFINE_BIT(DEFAULT_TRACE_LEVEL) +#define WPP_DEFINE_DEFAULT_BITS \ + WPP_DEFINE_BIT(MYDRIVER_ALL_INFO) \ + WPP_DEFINE_BIT(TRACE_KDPRINT) \ + WPP_DEFINE_BIT(DEFAULT_TRACE_LEVEL) -#undef WPP_DEFINE_CONTROL_GUID -#define WPP_CONTROL_GUIDS \ - WPP_DEFINE_CONTROL_GUID(WPPNAME,(WPPGUID), \ - WPP_DEFINE_DEFAULT_BITS ) +#undef WPP_DEFINE_CONTROL_GUID +#define WPP_CONTROL_GUIDS \ + WPP_DEFINE_CONTROL_GUID(WPPNAME, (WPPGUID), \ + WPP_DEFINE_DEFAULT_BITS) -#define WPP_FLAGS_LEVEL_LOGGER(Flags, level) \ +#define WPP_FLAGS_LEVEL_LOGGER(Flags, level) \ WPP_LEVEL_LOGGER(Flags) -#define WPP_FLAGS_LEVEL_ENABLED(Flags, level) \ - (WPP_LEVEL_ENABLED(Flags) && \ +#define WPP_FLAGS_LEVEL_ENABLED(Flags, level) \ + (WPP_LEVEL_ENABLED(Flags) && \ WPP_CONTROL(WPP_BIT_ ## Flags).Level >= level) -#define WPP_LEVEL_FLAGS_LOGGER(lvl,flags) \ - WPP_LEVEL_LOGGER(flags) +#define WPP_LEVEL_FLAGS_LOGGER(lvl, flags) \ + WPP_LEVEL_LOGGER(flags) -#define WPP_LEVEL_FLAGS_ENABLED(lvl, flags) \ - (WPP_LEVEL_ENABLED(flags) && WPP_CONTROL(WPP_BIT_ ## flags).Level >= lvl) +#define WPP_LEVEL_FLAGS_ENABLED(lvl, flags) \ + (WPP_LEVEL_ENABLED(flags) && \ + WPP_CONTROL(WPP_BIT_ ## flags).Level >= lvl) // begin_wpp config @@ -50,17 +55,17 @@ static const int TRACE_NOISY = 8; #else #undef WPP_INIT_TRACING -#define WPP_INIT_TRACING(...) ((void)(0, __VA_ARGS__)) +#define WPP_INIT_TRACING(...) ((void)(0, __VA_ARGS__)) #undef WPP_CLEANUP -#define WPP_CLEANUP(...) ((void)(0, __VA_ARGS__)) +#define WPP_CLEANUP(...) ((void)(0, __VA_ARGS__)) #endif #ifndef WPP_CHECK_INIT -#define WPP_CHECK_INIT +#define WPP_CHECK_INIT #endif void ZFSWppInit(PDRIVER_OBJECT pDriverObject, PUNICODE_STRING pRegistryPath); -void ZFSWppCleanup(PDRIVER_OBJECT pDriverObject); \ No newline at end of file +void ZFSWppCleanup(PDRIVER_OBJECT pDriverObject); diff --git a/include/os/windows/spl/rpc/types.h b/include/os/windows/spl/rpc/types.h index 4602ededc06..50b0459b81f 100644 --- a/include/os/windows/spl/rpc/types.h +++ b/include/os/windows/spl/rpc/types.h @@ -1,6 +1,28 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + * + * Copyright (c) 1989, 2011, Oracle and/or its affiliates. All rights reserved. + */ #ifndef _SPL_RPC_TYPES_H -#define _SPL_RPC_TYPES_H +#define _SPL_RPC_TYPES_H typedef int bool_t; diff --git a/include/os/windows/spl/rpc/xdr.h b/include/os/windows/spl/rpc/xdr.h index e00968188a5..64da4b8d2ab 100644 --- a/include/os/windows/spl/rpc/xdr.h +++ b/include/os/windows/spl/rpc/xdr.h @@ -34,7 +34,7 @@ */ #ifndef _SPL_RPC_XDR_H -#define _SPL_RPC_XDR_H +#define _SPL_RPC_XDR_H #include @@ -51,11 +51,10 @@ enum xdr_op { struct xdr_ops; typedef struct { - struct xdr_ops *x_ops; /* Also used to let caller know if - xdrmem_create() succeeds (sigh..) */ - caddr_t x_addr; /* Current buffer addr */ - caddr_t x_addr_end; /* End of the buffer */ - enum xdr_op x_op; /* Stream direction */ + struct xdr_ops *x_ops; + caddr_t x_addr; + caddr_t x_addr_end; + enum xdr_op x_op; } XDR; typedef bool_t (*xdrproc_t)(XDR *xdrs, void *ptr); @@ -71,13 +70,13 @@ struct xdr_ops { bool_t (*xdr_opaque)(XDR *, caddr_t, const uint_t); bool_t (*xdr_string)(XDR *, char **, const uint_t); bool_t (*xdr_array)(XDR *, caddr_t *, uint_t *, const uint_t, - const uint_t, const xdrproc_t); + const uint_t, const xdrproc_t); }; /* * XDR control operator. */ -#define XDR_GET_BYTES_AVAIL 1 +#define XDR_GET_BYTES_AVAIL 1 struct xdr_bytesrec { bool_t xc_is_last_record; @@ -91,11 +90,11 @@ typedef struct xdr_bytesrec xdr_bytesrec; */ void xdrmem_create(XDR *xdrs, const caddr_t addr, const uint_t size, const enum xdr_op op); -#define xdr_destroy(xdrs) ((void) 0) /* Currently not needed. If needed later, - we'll add it to struct xdr_ops */ -#define xdr_control(xdrs, req, info) (xdrs)->x_ops->xdr_control((xdrs), \ - (req), (info)) +#define xdr_destroy(xdrs) ((void) 0) + +#define xdr_control(xdrs, req, info) (xdrs)->x_ops->xdr_control((xdrs),\ + (req), (info)) /* * For precaution, the following are defined as static inlines instead of macros @@ -106,40 +105,40 @@ void xdrmem_create(XDR *xdrs, const caddr_t addr, const uint_t size, */ static inline bool_t xdr_char(XDR *xdrs, char *cp) { - return xdrs->x_ops->xdr_char(xdrs, cp); + return (xdrs->x_ops->xdr_char(xdrs, cp)); } static inline bool_t xdr_u_short(XDR *xdrs, unsigned short *usp) { - return xdrs->x_ops->xdr_u_short(xdrs, usp); + return (xdrs->x_ops->xdr_u_short(xdrs, usp)); } static inline bool_t xdr_short(XDR *xdrs, short *sp) { - //BUILD_BUG_ON(sizeof(short) != 2); - return xdrs->x_ops->xdr_u_short(xdrs, (unsigned short *) sp); + // BUILD_BUG_ON(sizeof(short) != 2); + return (xdrs->x_ops->xdr_u_short(xdrs, (unsigned short *) sp)); } static inline bool_t xdr_u_int(XDR *xdrs, unsigned *up) { - return xdrs->x_ops->xdr_u_int(xdrs, up); + return (xdrs->x_ops->xdr_u_int(xdrs, up)); } static inline bool_t xdr_int(XDR *xdrs, int *ip) { - //BUILD_BUG_ON(sizeof(int) != 4); - return xdrs->x_ops->xdr_u_int(xdrs, (unsigned *) ip); + // BUILD_BUG_ON(sizeof(int) != 4); + return (xdrs->x_ops->xdr_u_int(xdrs, (unsigned *)ip)); } static inline bool_t xdr_u_longlong_t(XDR *xdrs, u_longlong_t *ullp) { - return xdrs->x_ops->xdr_u_longlong_t(xdrs, ullp); + return (xdrs->x_ops->xdr_u_longlong_t(xdrs, ullp)); } static inline bool_t xdr_longlong_t(XDR *xdrs, longlong_t *llp) { - //BUILD_BUG_ON(sizeof(longlong_t) != 8); - return xdrs->x_ops->xdr_u_longlong_t(xdrs, (u_longlong_t *) llp); + // BUILD_BUG_ON(sizeof(longlong_t) != 8); + return (xdrs->x_ops->xdr_u_longlong_t(xdrs, (u_longlong_t *)llp)); } /* @@ -147,7 +146,7 @@ static inline bool_t xdr_longlong_t(XDR *xdrs, longlong_t *llp) */ static inline bool_t xdr_opaque(XDR *xdrs, caddr_t cp, const uint_t cnt) { - return xdrs->x_ops->xdr_opaque(xdrs, cp, cnt); + return (xdrs->x_ops->xdr_opaque(xdrs, cp, cnt)); } /* @@ -156,7 +155,7 @@ static inline bool_t xdr_opaque(XDR *xdrs, caddr_t cp, const uint_t cnt) */ static inline bool_t xdr_string(XDR *xdrs, char **sp, const uint_t maxsize) { - return xdrs->x_ops->xdr_string(xdrs, sp, maxsize); + return (xdrs->x_ops->xdr_string(xdrs, sp, maxsize)); } /* @@ -165,8 +164,8 @@ static inline bool_t xdr_string(XDR *xdrs, char **sp, const uint_t maxsize) static inline bool_t xdr_array(XDR *xdrs, caddr_t *arrp, uint_t *sizep, const uint_t maxsize, const uint_t elsize, const xdrproc_t elproc) { - return xdrs->x_ops->xdr_array(xdrs, arrp, sizep, maxsize, elsize, - elproc); + return (xdrs->x_ops->xdr_array(xdrs, arrp, sizep, maxsize, elsize, + elproc)); } #endif /* SPL_RPC_XDR_H */ diff --git a/include/os/windows/spl/spl-bmalloc.h b/include/os/windows/spl/spl-bmalloc.h deleted file mode 100644 index 7fd9f4b8f76..00000000000 --- a/include/os/windows/spl/spl-bmalloc.h +++ /dev/null @@ -1,218 +0,0 @@ - -/* - * CDDL HEADER START - * - * The contents of this file are subject to the terms of the - * Common Development and Distribution License (the "License"). - * You may not use this file except in compliance with the License. - * - * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE - * or http://www.opensolaris.org/os/licensing. - * See the License for the specific language governing permissions - * and limitations under the License. - * - * When distributing Covered Code, include this CDDL HEADER in each - * file and include the License file at usr/src/OPENSOLARIS.LICENSE. - * If applicable, add the following below this CDDL HEADER, with the - * fields enclosed by brackets "[]" replaced with your own identifying - * information: Portions Copyright [yyyy] [name of copyright owner] - * - * Copyright 2014 Brendon Humphrey (brendon.humphrey@mac.com) - * - * CDDL HEADER END - */ - -#ifndef BMALLOC_H -#define BMALLOC_H - -#include - -/* - * Knobs and controls - */ - -/* - * Place the allocator in thread-safe mode. If you have an application where the - * allocator does not have to be thread safe, then removing the mutexes will - * improve the allocator performance by about 30%. - */ -#define THREAD_SAFE 1 - -/* - * Provide extra locking around the slice lists, as under some conditions, - * memory handling errors in the application can interfere with the locking - * strategy used. - */ -// #define SLICE_SPINLOCK 1 - -/* - * Turn on counting of the number of allocations made to each allocator. Major - * performance killer. Keep turned off. - */ -// #define COUNT_ALLOCATIONS 1 - -/* - * Borrow an idea from the Linux kernel SLUB allocator - namely, have the Slice - * Allocator simply forget about full slices. They are "found" again when a free - * occurs from the full slice, and added to the partial list again. This saves a - * small amount of list processing overhead and storage space. (The performance - * difference is probably purely academic.) - * - * You will want to enable this if hunting memory leaks. - */ -// #define SLICE_ALLOCATOR_TRACK_FULL_SLABS 1 - -// #define DEBUG 1 - -#ifdef DEBUG - -/* Select a logging mechanism. */ -// #define REPORT_PANIC 1 -#define REPORT_LOG 1 - -/* - * Check whether an application is writing beyond the number of bytes allocated - * in a call to bmalloc(). Implemented using buffer poisoning. - */ -#define SLICE_CHECK_BOUNDS_WRITE 1 - -/* - * Check for writes to memory after free. Works in part by poisoning the user - * memory on free. The idea is that if a buffer is not fully poisoned on - * allocate, there is evidence of use after free. This may have the side effect - * of causing other failures - if an application relies on valid data in the - * memory after free, bad things can happen. - */ -#define SLICE_CHECK_WRITE_AFTER_FREE 1 - -/* Check integrity of slice row headers. */ -#define SLICE_CHECK_ROW_HEADERS 1 - -/* - * Check that the number of bytes passed to bmalloc to release matches the - * number of bytes allocated. - */ -#define SLICE_CHECK_FREE_SIZE 1 - -/* - * Instrument the Slice object to detect concurrent threads accessing the data - * structures - indicative of a serious programming error. - */ -#define SLICE_CHECK_THREADS 1 - -/* - * Have the SA check that any operations performed on a slice are performed on a - * slice that the the SA actually owns. - */ -#define SA_CHECK_SLICE_SIZE 1 - -/* Select correct dependencies based on debug flags. */ - -#ifdef SLICE_CHECK_WRITE_AFTER_FREE -/* Poison user allocatable portions of slice rows on free. */ -#define SLICE_POISON_USER_SPACE 1 -#endif /* SLICE_CHECK_WRITE_AFTER_FREE */ - -#endif /* DEBUG */ - -/* - * Data Types - */ -typedef uint64_t sa_size_t; -typedef uint8_t sa_byte_t; -typedef uint8_t sa_bool_t; -typedef uint64_t sa_hrtime_t; -typedef uint32_t large_offset_t; - -typedef struct slice_allocator { - - /* - * Statistics - */ - uint64_t slices_created; /* slices added to sa */ - uint64_t slices_destroyed; /* empty slices freed */ - uint64_t slice_alloc; /* allocation count */ - uint64_t slice_free; /* free count */ - uint64_t slice_alloc_fail; /* num failed allocs */ - uint64_t free_slices; /* number of empty slices cached */ - - /* - * State - */ - - uint64_t flags; - sa_size_t slice_size; - list_t free; - list_t partial; -#ifdef SLICE_ALLOCATOR_TRACK_FULL_SLABS - list_t full; -#endif /* SLICE_ALLOCATOR_TRACK_FULL_SLABS */ - /* Max alloc size for slice */ - sa_size_t max_alloc_size; - /* Number of rows to be allocated in the Slices */ - sa_size_t num_allocs_per_slice; - lck_spin_t *spinlock; -} slice_allocator_t; - -// Convenient way to access kernel_memory_allocate and kmem_free -void * osif_malloc(sa_size_t size); -void osif_free(void* buf, sa_size_t size); - -// -// Initialises the allocator, must be called before any other function. -// -void bmalloc_init(); - -// -// Allocate bytes of memory for the application -// -void* bmalloc(uint64_t size, int flags); -void* bzmalloc(uint64_t size, int flags); - -// -// Release memory from the application -// -void bfree(void* buf, uint64_t size); - -// -// Attempt to release pages of -// memory from the free memory block collection. -// Returns number of pages released. -uint64_t bmalloc_release_pages(uint64_t num_pages); - -// -// Manages from free memory within the allocator. -// Should be called periodically (say at least -// every 10 seconds). -// Returns the number of pages released as a result -uint64_t bmalloc_garbage_collect(); - -// -// Release all remaining memory and allocator resources -// -void bmalloc_fini(); - -/* - * Slice allocator interfaces for kmem to use as "slabs" for its caches - */ - -void -slice_allocator_init(slice_allocator_t *sa, sa_size_t max_alloc_size); - -void * -slice_allocator_alloc(slice_allocator_t *sa, sa_size_t size); - -void -slice_allocator_free(slice_allocator_t *sa, void *buf, sa_size_t size); - -void -slice_allocator_garbage_collect(slice_allocator_t *sa); - -uint64_t -slice_allocator_release_pages(slice_allocator_t *sa, uint64_t num_pages); - -void -slice_allocator_fini(slice_allocator_t *sa); - - -#endif diff --git a/include/os/windows/spl/spl-ctl.h b/include/os/windows/spl/spl-ctl.h deleted file mode 100644 index 9db13907348..00000000000 --- a/include/os/windows/spl/spl-ctl.h +++ /dev/null @@ -1,45 +0,0 @@ -/*****************************************************************************\ - * Copyright (C) 2007-2010 Lawrence Livermore National Security, LLC. - * Copyright (C) 2007 The Regents of the University of California. - * Produced at Lawrence Livermore National Laboratory (cf, DISCLAIMER). - * Written by Brian Behlendorf . - * UCRL-CODE-235197 - * - * This file is part of the SPL, Solaris Porting Layer. - * For details, see . - * - * The SPL is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by the - * Free Software Foundation; either version 2 of the License, or (at your - * option) any later version. - * - * The SPL is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with the SPL. If not, see . -\*****************************************************************************/ - -#ifndef _DEBUG_CTL_H -#define _DEBUG_CTL_H - -/* - * Contains shared definitions which both the user space - * and kernel space portions of splat must agree on. - */ -typedef struct spl_debug_header { - int ph_len; - int ph_flags; - int ph_subsys; - int ph_mask; - int ph_cpu_id; - int ph_sec; - long ph_usec; - int ph_stack; - int ph_pid; - int ph_line_num; -} spl_debug_header_t; - -#endif /* _DEBUG_CTL_H */ diff --git a/include/os/windows/spl/spl-debug.h b/include/os/windows/spl/spl-debug.h index c6557775d2f..9dac67b30b3 100644 --- a/include/os/windows/spl/spl-debug.h +++ b/include/os/windows/spl/spl-debug.h @@ -1,4 +1,4 @@ -/*****************************************************************************\ +/* * Copyright (C) 2007-2010 Lawrence Livermore National Security, LLC. * Copyright (C) 2007 The Regents of the University of California. * Produced at Lawrence Livermore National Laboratory (cf, DISCLAIMER). @@ -20,7 +20,7 @@ * * You should have received a copy of the GNU General Public License along * with the SPL. If not, see . -\*****************************************************************************/ + */ /* * Available debug functions. These function should be used by any @@ -40,11 +40,8 @@ */ #ifndef _SPL_DEBUG_INTERNAL_H -#define _SPL_DEBUG_INTERNAL_H +#define _SPL_DEBUG_INTERNAL_H -//#include -//#include -//#include #include #ifdef __cplusplus // To make C++ happier about strnlen in kcdata.h diff --git a/include/os/windows/spl/spl-device.h b/include/os/windows/spl/spl-device.h deleted file mode 100644 index 51e8b3e0481..00000000000 --- a/include/os/windows/spl/spl-device.h +++ /dev/null @@ -1,29 +0,0 @@ -/*****************************************************************************\ - * Copyright (C) 2007-2010 Lawrence Livermore National Security, LLC. - * Copyright (C) 2007 The Regents of the University of California. - * Produced at Lawrence Livermore National Laboratory (cf, DISCLAIMER). - * Written by Brian Behlendorf . - * UCRL-CODE-235197 - * - * This file is part of the SPL, Solaris Porting Layer. - * For details, see . - * - * The SPL is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by the - * Free Software Foundation; either version 2 of the License, or (at your - * option) any later version. - * - * The SPL is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with the SPL. If not, see . -\*****************************************************************************/ - -#ifndef _SPL_DEVICE_H -#define _SPL_DEVICE_H - - -#endif /* _SPL_DEVICE_H */ diff --git a/include/os/windows/spl/spl-trace.h b/include/os/windows/spl/spl-trace.h deleted file mode 100644 index e89bbe08c7b..00000000000 --- a/include/os/windows/spl/spl-trace.h +++ /dev/null @@ -1,29 +0,0 @@ -/*****************************************************************************\ - * Copyright (C) 2007-2010 Lawrence Livermore National Security, LLC. - * Copyright (C) 2007 The Regents of the University of California. - * Produced at Lawrence Livermore National Laboratory (cf, DISCLAIMER). - * Written by Brian Behlendorf . - * UCRL-CODE-235197 - * - * This file is part of the SPL, Solaris Porting Layer. - * For details, see . - * - * The SPL is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by the - * Free Software Foundation; either version 2 of the License, or (at your - * option) any later version. - * - * The SPL is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License along - * with the SPL. If not, see . -\*****************************************************************************/ - -#ifndef _SPL_TRACE_H -#define _SPL_TRACE_H - - -#endif /* SPL_TRACE_H */ diff --git a/include/os/windows/spl/strings.h b/include/os/windows/spl/strings.h index 697ac4db61c..0048ab771da 100644 --- a/include/os/windows/spl/strings.h +++ b/include/os/windows/spl/strings.h @@ -1,4 +1,4 @@ #ifndef _SPL_STRINGS_H -#define _SPL_STRINGS_H +#define _SPL_STRINGS_H #endif /* SPL_STRINGS_H */ diff --git a/include/os/windows/spl/sys/acl.h b/include/os/windows/spl/sys/acl.h index 8c9ed04e229..e7dcdfe697f 100644 --- a/include/os/windows/spl/sys/acl.h +++ b/include/os/windows/spl/sys/acl.h @@ -1,127 +1,128 @@ /* -* CDDL HEADER START -* -* The contents of this file are subject to the terms of the -* Common Development and Distribution License (the "License"). -* You may not use this file except in compliance with the License. -* -* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE -* or http://www.opensolaris.org/os/licensing. -* See the License for the specific language governing permissions -* and limitations under the License. -* -* When distributing Covered Code, include this CDDL HEADER in each -* file and include the License file at usr/src/OPENSOLARIS.LICENSE. -* If applicable, add the following below this CDDL HEADER, with the -* fields enclosed by brackets "[]" replaced with your own identifying -* information: Portions Copyright [yyyy] [name of copyright owner] -* -* CDDL HEADER END -*/ + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ /* -* Copyright 2009 Sun Microsystems, Inc. All rights reserved. -* Use is subject to license terms. -*/ + * Copyright 2009 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ #ifndef _SPL_ACL_H -#define _SPL_ACL_H +#define _SPL_ACL_H #include typedef struct ace { - uid_t a_who; - uint32_t a_access_mask; - uint16_t a_flags; - uint16_t a_type; + uid_t a_who; + uint32_t a_access_mask; + uint16_t a_flags; + uint16_t a_type; } ace_t; typedef struct ace_object { - uid_t a_who; /* uid or gid */ - uint32_t a_access_mask; /* read,write,... */ - uint16_t a_flags; /* see below */ - uint16_t a_type; /* allow or deny */ - uint8_t a_obj_type[16]; /* obj type */ - uint8_t a_inherit_obj_type[16]; /* inherit obj */ + uid_t a_who; /* uid or gid */ + uint32_t a_access_mask; /* read,write,... */ + uint16_t a_flags; /* see below */ + uint16_t a_type; /* allow or deny */ + uint8_t a_obj_type[16]; /* obj type */ + uint8_t a_inherit_obj_type[16]; /* inherit obj */ } ace_object_t; -#define MAX_ACL_ENTRIES 1024 - -#define ACE_READ_DATA 0x00000001 -#define ACE_LIST_DIRECTORY 0x00000001 -#define ACE_WRITE_DATA 0x00000002 -#define ACE_ADD_FILE 0x00000002 -#define ACE_APPEND_DATA 0x00000004 -#define ACE_ADD_SUBDIRECTORY 0x00000004 -#define ACE_READ_NAMED_ATTRS 0x00000008 -#define ACE_WRITE_NAMED_ATTRS 0x00000010 -#define ACE_EXECUTE 0x00000020 -#define ACE_DELETE_CHILD 0x00000040 -#define ACE_READ_ATTRIBUTES 0x00000080 -#define ACE_WRITE_ATTRIBUTES 0x00000100 -#define ACE_DELETE 0x00010000 -#define ACE_READ_ACL 0x00020000 -#define ACE_WRITE_ACL 0x00040000 -#define ACE_WRITE_OWNER 0x00080000 -#define ACE_SYNCHRONIZE 0x00100000 - -#define ACE_FILE_INHERIT_ACE 0x0001 -#define ACE_DIRECTORY_INHERIT_ACE 0x0002 -#define ACE_NO_PROPAGATE_INHERIT_ACE 0x0004 -#define ACE_INHERIT_ONLY_ACE 0x0008 -#define ACE_SUCCESSFUL_ACCESS_ACE_FLAG 0x0010 -#define ACE_FAILED_ACCESS_ACE_FLAG 0x0020 -#define ACE_IDENTIFIER_GROUP 0x0040 -#define ACE_INHERITED_ACE 0x0080 -#define ACE_OWNER 0x1000 -#define ACE_GROUP 0x2000 -#define ACE_EVERYONE 0x4000 - -#define ACE_ACCESS_ALLOWED_ACE_TYPE 0x0000 -#define ACE_ACCESS_DENIED_ACE_TYPE 0x0001 -#define ACE_SYSTEM_AUDIT_ACE_TYPE 0x0002 -#define ACE_SYSTEM_ALARM_ACE_TYPE 0x0003 - -#define ACL_AUTO_INHERIT 0x0001 -#define ACL_PROTECTED 0x0002 -#define ACL_DEFAULTED 0x0004 -#define ACL_FLAGS_ALL (ACL_AUTO_INHERIT|ACL_PROTECTED|ACL_DEFAULTED) - -#define ACE_ACCESS_ALLOWED_COMPOUND_ACE_TYPE 0x04 -#define ACE_ACCESS_ALLOWED_OBJECT_ACE_TYPE 0x05 -#define ACE_ACCESS_DENIED_OBJECT_ACE_TYPE 0x06 -#define ACE_SYSTEM_AUDIT_OBJECT_ACE_TYPE 0x07 -#define ACE_SYSTEM_ALARM_OBJECT_ACE_TYPE 0x08 -#define ACE_ACCESS_ALLOWED_CALLBACK_ACE_TYPE 0x09 -#define ACE_ACCESS_DENIED_CALLBACK_ACE_TYPE 0x0A -#define ACE_ACCESS_ALLOWED_CALLBACK_OBJECT_ACE_TYPE 0x0B -#define ACE_ACCESS_DENIED_CALLBACK_OBJECT_ACE_TYPE 0x0C -#define ACE_SYSTEM_AUDIT_CALLBACK_ACE_TYPE 0x0D -#define ACE_SYSTEM_ALARM_CALLBACK_ACE_TYPE 0x0E -#define ACE_SYSTEM_AUDIT_CALLBACK_OBJECT_ACE_TYPE 0x0F -#define ACE_SYSTEM_ALARM_CALLBACK_OBJECT_ACE_TYPE 0x10 - -#define ACE_ALL_TYPES 0x001F - -#define ACE_TYPE_FLAGS (ACE_OWNER|ACE_GROUP|ACE_EVERYONE|ACE_IDENTIFIER_GROUP) - -#define ACE_ALL_PERMS (ACE_READ_DATA|ACE_LIST_DIRECTORY|ACE_WRITE_DATA| \ - ACE_ADD_FILE|ACE_APPEND_DATA|ACE_ADD_SUBDIRECTORY|ACE_READ_NAMED_ATTRS| \ - ACE_WRITE_NAMED_ATTRS|ACE_EXECUTE|ACE_DELETE_CHILD|ACE_READ_ATTRIBUTES| \ - ACE_WRITE_ATTRIBUTES|ACE_DELETE|ACE_READ_ACL|ACE_WRITE_ACL| \ - ACE_WRITE_OWNER|ACE_SYNCHRONIZE) - -#define VSA_ACE 0x0010 -#define VSA_ACECNT 0x0020 -#define VSA_ACE_ALLTYPES 0x0040 -#define VSA_ACE_ACLFLAGS 0x0080 +#define MAX_ACL_ENTRIES 1024 + +#define ACE_READ_DATA 0x00000001 +#define ACE_LIST_DIRECTORY 0x00000001 +#define ACE_WRITE_DATA 0x00000002 +#define ACE_ADD_FILE 0x00000002 +#define ACE_APPEND_DATA 0x00000004 +#define ACE_ADD_SUBDIRECTORY 0x00000004 +#define ACE_READ_NAMED_ATTRS 0x00000008 +#define ACE_WRITE_NAMED_ATTRS 0x00000010 +#define ACE_EXECUTE 0x00000020 +#define ACE_DELETE_CHILD 0x00000040 +#define ACE_READ_ATTRIBUTES 0x00000080 +#define ACE_WRITE_ATTRIBUTES 0x00000100 +#define ACE_DELETE 0x00010000 +#define ACE_READ_ACL 0x00020000 +#define ACE_WRITE_ACL 0x00040000 +#define ACE_WRITE_OWNER 0x00080000 +#define ACE_SYNCHRONIZE 0x00100000 + +#define ACE_FILE_INHERIT_ACE 0x0001 +#define ACE_DIRECTORY_INHERIT_ACE 0x0002 +#define ACE_NO_PROPAGATE_INHERIT_ACE 0x0004 +#define ACE_INHERIT_ONLY_ACE 0x0008 +#define ACE_SUCCESSFUL_ACCESS_ACE_FLAG 0x0010 +#define ACE_FAILED_ACCESS_ACE_FLAG 0x0020 +#define ACE_IDENTIFIER_GROUP 0x0040 +#define ACE_INHERITED_ACE 0x0080 +#define ACE_OWNER 0x1000 +#define ACE_GROUP 0x2000 +#define ACE_EVERYONE 0x4000 + +#define ACE_ACCESS_ALLOWED_ACE_TYPE 0x0000 +#define ACE_ACCESS_DENIED_ACE_TYPE 0x0001 +#define ACE_SYSTEM_AUDIT_ACE_TYPE 0x0002 +#define ACE_SYSTEM_ALARM_ACE_TYPE 0x0003 + +#define ACL_AUTO_INHERIT 0x0001 +#define ACL_PROTECTED 0x0002 +#define ACL_DEFAULTED 0x0004 +#define ACL_FLAGS_ALL (ACL_AUTO_INHERIT|ACL_PROTECTED|ACL_DEFAULTED) + +#define ACE_ACCESS_ALLOWED_COMPOUND_ACE_TYPE 0x04 +#define ACE_ACCESS_ALLOWED_OBJECT_ACE_TYPE 0x05 +#define ACE_ACCESS_DENIED_OBJECT_ACE_TYPE 0x06 +#define ACE_SYSTEM_AUDIT_OBJECT_ACE_TYPE 0x07 +#define ACE_SYSTEM_ALARM_OBJECT_ACE_TYPE 0x08 +#define ACE_ACCESS_ALLOWED_CALLBACK_ACE_TYPE 0x09 +#define ACE_ACCESS_DENIED_CALLBACK_ACE_TYPE 0x0A +#define ACE_ACCESS_ALLOWED_CALLBACK_OBJECT_ACE_TYPE 0x0B +#define ACE_ACCESS_DENIED_CALLBACK_OBJECT_ACE_TYPE 0x0C +#define ACE_SYSTEM_AUDIT_CALLBACK_ACE_TYPE 0x0D +#define ACE_SYSTEM_ALARM_CALLBACK_ACE_TYPE 0x0E +#define ACE_SYSTEM_AUDIT_CALLBACK_OBJECT_ACE_TYPE 0x0F +#define ACE_SYSTEM_ALARM_CALLBACK_OBJECT_ACE_TYPE 0x10 + +#define ACE_ALL_TYPES 0x001F + +#define ACE_TYPE_FLAGS (ACE_OWNER|ACE_GROUP|ACE_EVERYONE|ACE_IDENTIFIER_GROUP) + +#define ACE_ALL_PERMS (ACE_READ_DATA|ACE_LIST_DIRECTORY|ACE_WRITE_DATA| \ + ACE_ADD_FILE|ACE_APPEND_DATA|ACE_ADD_SUBDIRECTORY| \ + ACE_READ_NAMED_ATTRS|ACE_WRITE_NAMED_ATTRS|ACE_EXECUTE| \ + ACE_DELETE_CHILD|ACE_READ_ATTRIBUTES|ACE_WRITE_ATTRIBUTES| \ + ACE_DELETE|ACE_READ_ACL|ACE_WRITE_ACL|ACE_WRITE_OWNER| \ + ACE_SYNCHRONIZE) + +#define VSA_ACE 0x0010 +#define VSA_ACECNT 0x0020 +#define VSA_ACE_ALLTYPES 0x0040 +#define VSA_ACE_ACLFLAGS 0x0080 typedef struct trivial_acl { - uint32_t allow0; /* allow mask for bits only in owner */ - uint32_t deny1; /* deny mask for bits not in owner */ - uint32_t deny2; /* deny mask for bits not in group */ - uint32_t owner; /* allow mask matching mode */ - uint32_t group; /* allow mask matching mode */ - uint32_t everyone; /* allow mask matching mode */ + uint32_t allow0; /* allow mask for bits only in owner */ + uint32_t deny1; /* deny mask for bits not in owner */ + uint32_t deny2; /* deny mask for bits not in group */ + uint32_t owner; /* allow mask matching mode */ + uint32_t group; /* allow mask matching mode */ + uint32_t everyone; /* allow mask matching mode */ } trivial_acl_t; #endif /* _SPL_ACL_H */ diff --git a/include/os/windows/spl/sys/acl_impl.h b/include/os/windows/spl/sys/acl_impl.h index 663e78cc0f6..96a4949c3e9 100644 --- a/include/os/windows/spl/sys/acl_impl.h +++ b/include/os/windows/spl/sys/acl_impl.h @@ -1,5 +1,5 @@ #ifndef _SPL_ACL_IMPL_H -#define _SPL_ACL_IMPL_H +#define _SPL_ACL_IMPL_H #endif /* _SPL_ACL_IMPL_H */ diff --git a/include/os/windows/spl/sys/atomic.h b/include/os/windows/spl/sys/atomic.h index 2f1b0108720..91218132ea6 100644 --- a/include/os/windows/spl/sys/atomic.h +++ b/include/os/windows/spl/sys/atomic.h @@ -28,7 +28,7 @@ */ #ifndef _SPL_ATOMIC_H -#define _SPL_ATOMIC_H +#define _SPL_ATOMIC_H #include @@ -58,15 +58,13 @@ static inline void atomic_inc_64(volatile uint64_t *target) } static inline int32_t atomic_inc_32_nv(volatile uint32_t *target) { - return InterlockedIncrement((volatile LONG *)target); + return (InterlockedIncrement((volatile LONG *)target)); } static inline int64_t atomic_inc_64_nv(volatile uint64_t *target) { - return InterlockedIncrement64((volatile LONG64 *)target); + return (InterlockedIncrement64((volatile LONG64 *)target)); } - - /* * Decrement target */ @@ -80,11 +78,11 @@ static inline void atomic_dec_64(volatile uint64_t *target) } static inline int32_t atomic_dec_32_nv(volatile uint32_t *target) { - return InterlockedDecrement((volatile LONG *)target); + return (InterlockedDecrement((volatile LONG *)target)); } static inline int64_t atomic_dec_64_nv(volatile uint64_t *target) { - return InterlockedDecrement64((volatile LONG64 *)target); + return (InterlockedDecrement64((volatile LONG64 *)target)); } @@ -98,23 +96,26 @@ atomic_add_32(volatile uint32_t *target, int32_t delta) { InterlockedExchangeAdd((volatile LONG *)target, delta); } + static inline uint32_t atomic_add_32_nv(volatile uint32_t *target, int32_t delta) { - return InterlockedExchangeAdd((volatile LONG *)target, delta) + delta; + return (InterlockedExchangeAdd((volatile LONG *)target, delta) + delta); } + static inline void atomic_add_64(volatile uint64_t *target, int64_t delta) { InterlockedExchangeAdd64((volatile LONG64 *)target, delta); } + static inline uint64_t atomic_add_64_nv(volatile uint64_t *target, int64_t delta) { - return InterlockedExchangeAdd64((volatile LONG64 *)target, delta) + delta; + return (InterlockedExchangeAdd64((volatile LONG64 *)target, + delta) + delta); } - /* * Subtract delta to target */ @@ -123,18 +124,20 @@ atomic_sub_32(volatile uint32_t *target, int32_t delta) { InterlockedExchangeAdd((volatile LONG *)target, -delta); } + static inline void atomic_sub_64(volatile uint64_t *target, int64_t delta) { InterlockedExchangeAdd64((volatile LONG64 *)target, -delta); } + static inline uint64_t atomic_sub_64_nv(volatile uint64_t *target, int64_t delta) { - return InterlockedExchangeAdd64((volatile LONG64 *)target, -delta) - delta; + return (InterlockedExchangeAdd64((volatile LONG64 *)target, + -delta) - delta); } - /* * logical OR bits with target */ @@ -143,7 +146,6 @@ atomic_sub_64_nv(volatile uint64_t *target, int64_t delta) * logical AND bits with target */ - /* * Compare And Set * if *arg1 == arg2, then set *arg1 = arg3; return old value. @@ -152,29 +154,36 @@ atomic_sub_64_nv(volatile uint64_t *target, int64_t delta) static inline uint32_t atomic_cas_32(volatile uint32_t *_target, uint32_t _cmp, uint32_t _new) { - return InterlockedCompareExchange((volatile LONG *)_target, _new, _cmp); + return (InterlockedCompareExchange((volatile LONG *)_target, _new, + _cmp)); } + static inline uint64_t atomic_cas_64(volatile uint64_t *_target, uint64_t _cmp, uint64_t _new) { - return InterlockedCompareExchange64((volatile LONG64 *)_target, _new, _cmp); + return (InterlockedCompareExchange64((volatile LONG64 *)_target, + _new, _cmp)); } static inline uint32_t atomic_swap_32(volatile uint32_t *_target, uint32_t _new) { - return InterlockedExchange((volatile LONG *)_target, _new); + return (InterlockedExchange((volatile LONG *)_target, _new)); } static inline uint64_t atomic_swap_64(volatile uint64_t *_target, uint64_t _new) { - return InterlockedExchange64((volatile LONG64 *)_target, _new); + return (InterlockedExchange64((volatile LONG64 *)_target, _new)); } extern void *atomic_cas_ptr(volatile void *_target, void *_cmp, void *_new); -static inline void membar_producer(void) { _mm_mfence(); } +static inline void +membar_producer(void) +{ + _mm_mfence(); +} #ifdef __cplusplus } diff --git a/include/os/windows/spl/sys/attr.h b/include/os/windows/spl/sys/attr.h index 93995b44944..ec9486197e3 100644 --- a/include/os/windows/spl/sys/attr.h +++ b/include/os/windows/spl/sys/attr.h @@ -1,7 +1,25 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ #ifndef _SPL_ATTR_H -#define _SPL_ATTR_H - -//#include_next +#define _SPL_ATTR_H #endif /* SPL_ATTR_H */ diff --git a/include/os/windows/spl/sys/bitmap.h b/include/os/windows/spl/sys/bitmap.h index f04d679e86a..3f029e08a39 100644 --- a/include/os/windows/spl/sys/bitmap.h +++ b/include/os/windows/spl/sys/bitmap.h @@ -1,5 +1,25 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ #ifndef _SPL_BITMAP_H -#define _SPL_BITMAP_H +#define _SPL_BITMAP_H #endif /* SPL_BITMAP_H */ diff --git a/include/os/windows/spl/sys/bootconf.h b/include/os/windows/spl/sys/bootconf.h index 853b9804db0..81619bed776 100644 --- a/include/os/windows/spl/sys/bootconf.h +++ b/include/os/windows/spl/sys/bootconf.h @@ -1,5 +1,25 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ #ifndef _SPL_BOOTCONF_H -#define _SPL_BOOTCONF_H +#define _SPL_BOOTCONF_H #endif /* SPL_BOOTCONF_H */ diff --git a/include/os/windows/spl/sys/bootprops.h b/include/os/windows/spl/sys/bootprops.h index 2ea8b06670e..940d0d5fdc9 100644 --- a/include/os/windows/spl/sys/bootprops.h +++ b/include/os/windows/spl/sys/bootprops.h @@ -1,5 +1,25 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ #ifndef _SPL_BOOTPROPS_H -#define _SPL_BOOTPROPS_H +#define _SPL_BOOTPROPS_H #endif /* SPL_BOOTPROPS_H */ diff --git a/include/os/windows/spl/sys/buf.h b/include/os/windows/spl/sys/buf.h index 755cee52d74..e66e088efa1 100644 --- a/include/os/windows/spl/sys/buf.h +++ b/include/os/windows/spl/sys/buf.h @@ -1,5 +1,25 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ #ifndef _SPL_BUF_H -#define _SPL_BUF_H +#define _SPL_BUF_H #endif /* SPL_BUF_H */ diff --git a/include/os/windows/spl/sys/byteorder.h b/include/os/windows/spl/sys/byteorder.h index 6e078446f07..638d0c1cad4 100644 --- a/include/os/windows/spl/sys/byteorder.h +++ b/include/os/windows/spl/sys/byteorder.h @@ -26,49 +26,46 @@ */ #ifndef _SPL_BYTEORDER_H -#define _SPL_BYTEORDER_H +#define _SPL_BYTEORDER_H -//#include -//#include #include -#define LE_16(x) (x) -#define LE_32(x) (x) -#define LE_64(x) (x) +#define LE_16(x) (x) +#define LE_32(x) (x) +#define LE_64(x) (x) #if defined(_MSC_VER) && !defined(__clang__) #include -#define BE_16(x) _byteswap_ushort(x) -#define BE_32(x) _byteswap_ulong(x) fff= -#define BE_64(x) _byteswap_uint64(x) +#define BE_16(x) _byteswap_ushort(x) +#define BE_32(x) _byteswap_ulong(x) fff= +#define BE_64(x) _byteswap_uint64(x) #else -#define BE_16(x) __builtin_bswap16(x) -#define BE_32(x) __builtin_bswap32(x) -#define BE_64(x) __builtin_bswap64(x) +#define BE_16(x) __builtin_bswap16(x) +#define BE_32(x) __builtin_bswap32(x) +#define BE_64(x) __builtin_bswap64(x) #endif -#define BE_IN8(xa) \ - *((uint8_t *)(xa)) +#define BE_IN8(xa) \ + *((uint8_t *)(xa)) -#define BE_IN16(xa) \ - (((uint16_t)BE_IN8(xa) << 8) | BE_IN8((uint8_t *)(xa)+1)) - -#define BE_IN32(xa) \ - (((uint32_t)BE_IN16(xa) << 16) | BE_IN16((uint8_t *)(xa)+2)) +#define BE_IN16(xa) \ + (((uint16_t)BE_IN8(xa) << 8) | BE_IN8((uint8_t *)(xa)+1)) +#define BE_IN32(xa) \ + (((uint32_t)BE_IN16(xa) << 16) | BE_IN16((uint8_t *)(xa)+2)) #if !defined(htonll) -#define htonll(x) BE_64(x) +#define htonll(x) BE_64(x) #endif #if !defined(ntohll) -#define ntohll(x) BE_64(x) +#define ntohll(x) BE_64(x) #endif #if !defined(htonl) -#define htonl(x) BE_32(x) +#define htonl(x) BE_32(x) #endif // I'm going to assume windows in LE for now -#define _ZFS_LITTLE_ENDIAN +#define _ZFS_LITTLE_ENDIAN #endif /* SPL_BYTEORDER_H */ diff --git a/include/os/windows/spl/sys/callb.h b/include/os/windows/spl/sys/callb.h index f94c56834ac..5b1074dd67b 100644 --- a/include/os/windows/spl/sys/callb.h +++ b/include/os/windows/spl/sys/callb.h @@ -24,44 +24,44 @@ */ #ifndef _SPL_CALLB_H -#define _SPL_CALLB_H +#define _SPL_CALLB_H #include -#define CALLB_CPR_ASSERT(cp) ASSERT(MUTEX_HELD((cp)->cc_lockp)); +#define CALLB_CPR_ASSERT(cp) ASSERT(MUTEX_HELD((cp)->cc_lockp)); typedef struct callb_cpr { - kmutex_t *cc_lockp; + kmutex_t *cc_lockp; } callb_cpr_t; -#define CALLB_CPR_INIT(cp, lockp, func, name) { \ - (cp)->cc_lockp = lockp; \ +#define CALLB_CPR_INIT(cp, lockp, func, name) { \ + (cp)->cc_lockp = lockp; \ } -#define CALLB_CPR_SAFE_BEGIN(cp) { \ - CALLB_CPR_ASSERT(cp); \ +#define CALLB_CPR_SAFE_BEGIN(cp) { \ + CALLB_CPR_ASSERT(cp); \ } -#define CALLB_CPR_SAFE_END(cp, lockp) { \ - CALLB_CPR_ASSERT(cp); \ +#define CALLB_CPR_SAFE_END(cp, lockp) { \ + CALLB_CPR_ASSERT(cp); \ } -#define CALLB_CPR_EXIT(cp) { \ - ASSERT(MUTEX_HELD((cp)->cc_lockp)); \ - mutex_exit((cp)->cc_lockp); \ +#define CALLB_CPR_EXIT(cp) { \ + ASSERT(MUTEX_HELD((cp)->cc_lockp)); \ + mutex_exit((cp)->cc_lockp); \ } -#define CALLOUT_FLAG_ROUNDUP 0x1 -#define CALLOUT_FLAG_ABSOLUTE 0x2 -#define CALLOUT_FLAG_HRESTIME 0x4 -#define CALLOUT_FLAG_32BIT 0x8 +#define CALLOUT_FLAG_ROUNDUP 0x1 +#define CALLOUT_FLAG_ABSOLUTE 0x2 +#define CALLOUT_FLAG_HRESTIME 0x4 +#define CALLOUT_FLAG_32BIT 0x8 /* Move me to more correct "sys/callo.h" file when convenient. */ -#define CALLOUT_NORMAL 1 +#define CALLOUT_NORMAL 1 typedef uint64_t callout_id_t; callout_id_t timeout_generic(int, void (*)(void *), void *, hrtime_t, hrtime_t, - int); + int); #endif /* _SPL_CALLB_H */ diff --git a/include/os/windows/spl/sys/cmn_err.h b/include/os/windows/spl/sys/cmn_err.h index 921d7381f43..bb3cd29c19f 100644 --- a/include/os/windows/spl/sys/cmn_err.h +++ b/include/os/windows/spl/sys/cmn_err.h @@ -31,16 +31,16 @@ */ #ifndef _SPL_CMN_ERR_H -#define _SPL_CMN_ERR_H +#define _SPL_CMN_ERR_H #include #include -#define CE_CONT 0 /* continuation */ -#define CE_NOTE 1 /* notice */ -#define CE_WARN 2 /* warning */ -#define CE_PANIC 3 /* panic */ -#define CE_IGNORE 4 /* print nothing */ +#define CE_CONT 0 /* continuation */ +#define CE_NOTE 1 /* notice */ +#define CE_WARN 2 /* warning */ +#define CE_PANIC 3 /* panic */ +#define CE_IGNORE 4 /* print nothing */ #ifdef _KERNEL @@ -49,6 +49,6 @@ extern void cmn_err(int, const char *, ...); #endif /* _KERNEL */ -#define fm_panic panic +#define fm_panic panic #endif /* SPL_CMN_ERR_H */ diff --git a/include/os/windows/spl/sys/compress.h b/include/os/windows/spl/sys/compress.h index 13967e5e5f8..9811518b928 100644 --- a/include/os/windows/spl/sys/compress.h +++ b/include/os/windows/spl/sys/compress.h @@ -1,5 +1,25 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ #ifndef _SPL_COMPRESS_H -#define _SPL_COMPRESS_H +#define _SPL_COMPRESS_H #endif /* SPL_COMPRESS_H */ diff --git a/include/os/windows/spl/sys/condvar.h b/include/os/windows/spl/sys/condvar.h index aeaeeea2ece..7ba86cfc882 100644 --- a/include/os/windows/spl/sys/condvar.h +++ b/include/os/windows/spl/sys/condvar.h @@ -24,17 +24,17 @@ */ #ifndef SPL_CONDVAR_H -#define SPL_CONDVAR_H +#define SPL_CONDVAR_H #include struct kmutex; -#define hz 119 /* frequency when using gethrtime() >> 23 for lbolt */ +#define hz 119 /* frequency when using gethrtime() >> 23 for lbolt */ typedef enum { - CV_DEFAULT, - CV_DRIVER + CV_DEFAULT, + CV_DRIVER } kcv_type_t; enum { @@ -44,83 +44,82 @@ enum { }; struct cv { - KEVENT kevent[CV_MAX_EVENTS]; // signal event, broadcast event - KSPIN_LOCK waiters_count_lock; - uint32_t waiters_count; - uint32_t initialised; // Just used as sanity + KEVENT cv_kevent[CV_MAX_EVENTS]; // signal event, broadcast event + KSPIN_LOCK cv_waiters_count_lock; + uint32_t cv_waiters_count; + uint32_t cv_initialised; // Just used as sanity }; typedef struct cv kcondvar_t; -#define PRIBIO 1 -#define PCATCH 2 - +#define PRIBIO 1 +#define PCATCH 2 void spl_cv_init(kcondvar_t *cvp, char *name, kcv_type_t type, void *arg); void spl_cv_destroy(kcondvar_t *cvp); void spl_cv_signal(kcondvar_t *cvp); void spl_cv_broadcast(kcondvar_t *cvp); int spl_cv_wait(kcondvar_t *cvp, struct kmutex *mp, int flags, const char *msg); -int spl_cv_timedwait(kcondvar_t *cvp, struct kmutex *mp, clock_t tim, int flags, - const char *msg); +int spl_cv_timedwait(kcondvar_t *cvp, struct kmutex *mp, clock_t tim, int flags, + const char *msg); int cv_timedwait_hires(kcondvar_t *cvp, struct kmutex *mp, - hrtime_t tim, hrtime_t res, int flag); - + hrtime_t tim, hrtime_t res, int flag); /* * Use these wrapper macros to obtain the CV variable * name to make ZFS more gdb debugging friendly! * This name shows up as a thread's wait_event string. */ -#define cv_wait(cvp, mp) \ +#define cv_wait(cvp, mp) \ (void) spl_cv_wait((cvp), (mp), PRIBIO, #cvp) -/* Linux provides a cv_wait_io so the schedular will know why we block. +/* + * Linux provides a cv_wait_io so the schedular will know why we block. * find OSX equivalent? */ -#define cv_wait_io(cvp, mp) \ - (void) spl_cv_wait((cvp), (mp), PRIBIO, #cvp) +#define cv_wait_io(cvp, mp) \ + (void) spl_cv_wait((cvp), (mp), PRIBIO, #cvp) -#define cv_wait_idle(cvp, mp) \ - (void) spl_cv_wait((cvp), (mp), PRIBIO, #cvp) +#define cv_wait_idle(cvp, mp) \ + (void) spl_cv_wait((cvp), (mp), PRIBIO, #cvp) -#define cv_timedwait(cvp, mp, tim) \ +#define cv_timedwait(cvp, mp, tim) \ spl_cv_timedwait((cvp), (mp), (tim), PRIBIO, #cvp) -#define cv_timedwait_io(cvp, mp, tim) \ - spl_cv_timedwait((cvp), (mp), (tim), PRIBIO, #cvp) +#define cv_timedwait_io(cvp, mp, tim) \ + spl_cv_timedwait((cvp), (mp), (tim), PRIBIO, #cvp) -#define cv_timedwait_idle(cvp, mp, tim) \ - spl_cv_timedwait((cvp), (mp), (tim), PRIBIO, #cvp) +#define cv_timedwait_idle(cvp, mp, tim) \ + spl_cv_timedwait((cvp), (mp), (tim), PRIBIO, #cvp) -#define cv_wait_interruptible(cvp, mp) \ +#define cv_wait_interruptible(cvp, mp) \ (void) spl_cv_wait((cvp), (mp), PRIBIO|PCATCH, #cvp) -#define cv_timedwait_interruptible(cvp, mp, tim) \ +#define cv_timedwait_interruptible(cvp, mp, tim) \ spl_cv_timedwait((cvp), (mp), (tim), PRIBIO|PCATCH, #cvp) /* cv_wait_sig is the correct name for cv_wait_interruptible */ -#define cv_wait_sig(cvp, mp) \ +#define cv_wait_sig(cvp, mp) \ spl_cv_wait((cvp), (mp), PRIBIO|PCATCH, #cvp) #define cv_wait_io_sig(cvp, mp) \ spl_cv_wait((cvp), (mp), PRIBIO|PCATCH, #cvp) -#define cv_timedwait_sig(cvp, mp, tim) \ +#define cv_timedwait_sig(cvp, mp, tim) \ spl_cv_timedwait((cvp), (mp), (tim), PRIBIO|PCATCH, #cvp) -#define TICK_TO_NSEC(tick) ((hrtime_t)(tick) * 1000000000 / hz) -#define cv_reltimedwait(cvp, mp, tim, type) \ +#define TICK_TO_NSEC(tick) ((hrtime_t)(tick) * 1000000000 / hz) +#define cv_reltimedwait(cvp, mp, tim, type) \ cv_timedwait_hires((cvp), (mp), TICK_TO_NSEC((tim)), 0, 0) -#define cv_timedwait_idle_hires(cvp, mp, tim, res, flag) \ - cv_timedwait_hires(cvp, mp, tim, res, (flag)|PCATCH) +#define cv_timedwait_idle_hires(cvp, mp, tim, res, flag) \ + cv_timedwait_hires(cvp, mp, tim, res, (flag)|PCATCH) -#define cv_init spl_cv_init -#define cv_destroy spl_cv_destroy -#define cv_broadcast spl_cv_broadcast -#define cv_signal spl_cv_signal +#define cv_init spl_cv_init +#define cv_destroy spl_cv_destroy +#define cv_broadcast spl_cv_broadcast +#define cv_signal spl_cv_signal #endif diff --git a/include/os/windows/spl/sys/conf.h b/include/os/windows/spl/sys/conf.h index c9bdd0cf20c..6b928f14b68 100644 --- a/include/os/windows/spl/sys/conf.h +++ b/include/os/windows/spl/sys/conf.h @@ -1,7 +1,25 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ #ifndef _SPL_CONF_H -#define _SPL_CONF_H - -//#include_next +#define _SPL_CONF_H #endif /* SPL_CONF_H */ diff --git a/include/os/windows/spl/sys/console.h b/include/os/windows/spl/sys/console.h index c6ce229f174..968b2a8d665 100644 --- a/include/os/windows/spl/sys/console.h +++ b/include/os/windows/spl/sys/console.h @@ -24,7 +24,7 @@ #ifndef _SPL_CONSOLE_H #define _SPL_CONSOLE_H -#define console_vprintf(...) +#define console_vprintf(...) #define console_printf(...) #endif /* _SPL_CONSOLE_H */ diff --git a/include/os/windows/spl/sys/cpupart.h b/include/os/windows/spl/sys/cpupart.h index 8c7b303f8aa..201b6e106a1 100644 --- a/include/os/windows/spl/sys/cpupart.h +++ b/include/os/windows/spl/sys/cpupart.h @@ -1,5 +1,25 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ #ifndef _SPL_CPUPART_H -#define _SPL_CPUPART_H +#define _SPL_CPUPART_H #endif /* SPL_CPUPART_H */ diff --git a/include/os/windows/spl/sys/cpuvar.h b/include/os/windows/spl/sys/cpuvar.h index aeae4644b8d..4f6d25073c5 100644 --- a/include/os/windows/spl/sys/cpuvar.h +++ b/include/os/windows/spl/sys/cpuvar.h @@ -1,5 +1,25 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ #ifndef _SPL_CPUVAR_H -#define _SPL_CPUVAR_H +#define _SPL_CPUVAR_H #endif /* SPL_CPUVAR_H */ diff --git a/include/os/windows/spl/sys/crc32.h b/include/os/windows/spl/sys/crc32.h index 2eee7303bfc..32169ed9e33 100644 --- a/include/os/windows/spl/sys/crc32.h +++ b/include/os/windows/spl/sys/crc32.h @@ -1,5 +1,25 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ #ifndef _SPL_CRC32_H -#define _SPL_CRC32_H +#define _SPL_CRC32_H #endif /* SPL_CRC32_H */ diff --git a/include/os/windows/spl/sys/cred.h b/include/os/windows/spl/sys/cred.h index f6a69d85aec..0dc0302c498 100644 --- a/include/os/windows/spl/sys/cred.h +++ b/include/os/windows/spl/sys/cred.h @@ -26,31 +26,27 @@ */ #ifndef _SPL_CRED_H -#define _SPL_CRED_H +#define _SPL_CRED_H #include #include -//#include struct ucred; // fixme typedef struct ucred cred_t; -#define kcred (cred_t *)NULL -#define CRED() (cred_t *)NULL -#define KUID_TO_SUID(x) (x) -#define KGID_TO_SGID(x) (x) - -//#include +#define kcred (cred_t *)NULL +#define CRED() (cred_t *)NULL +#define KUID_TO_SUID(x) (x) +#define KGID_TO_SGID(x) (x) // Older OSX API #if !(MAC_OS_X_VERSION_MIN_REQUIRED >= 1070) -#define kauth_cred_getruid(x) (x)->cr_ruid -#define kauth_cred_getrgid(x) (x)->cr_rgid -#define kauth_cred_getsvuid(x) (x)->cr_svuid -#define kauth_cred_getsvgid(x) (x)->cr_svgid +#define kauth_cred_getruid(x) (x)->cr_ruid +#define kauth_cred_getrgid(x) (x)->cr_rgid +#define kauth_cred_getsvuid(x) (x)->cr_svuid +#define kauth_cred_getsvgid(x) (x)->cr_svgid #endif - extern void crhold(cred_t *cr); extern void crfree(cred_t *cr); extern uid_t crgetuid(const cred_t *cr); @@ -62,10 +58,10 @@ extern gid_t crgetrgid(const cred_t *cr); extern gid_t crgetsgid(const cred_t *cr); extern gid_t crgetfsgid(const cred_t *cr); extern int crgetngroups(const cred_t *cr); -extern gid_t * crgetgroups(const cred_t *cr); +extern gid_t *crgetgroups(const cred_t *cr); extern void crgetgroupsfree(gid_t *gids); extern int spl_cred_ismember_gid(cred_t *cr, gid_t gid); -#define crgetsid(cred, i) (NULL) +#define crgetsid(cred, i) (NULL) #endif /* _SPL_CRED_H */ diff --git a/include/os/windows/spl/sys/ctype.h b/include/os/windows/spl/sys/ctype.h index 0ae5b945fb5..d71cddea228 100644 --- a/include/os/windows/spl/sys/ctype.h +++ b/include/os/windows/spl/sys/ctype.h @@ -20,9 +20,8 @@ * CDDL HEADER END */ #ifndef _SPL_CTYPE_H -#define _SPL_CTYPE_H +#define _SPL_CTYPE_H -//#include_next -#define iscntrl(C) (uchar(C) <= 0x1f || uchar(C) == 0x7f) +#define iscntrl(C) (uchar(C) <= 0x1f || uchar(C) == 0x7f) #endif /* SPL_CTYPE_H */ diff --git a/include/os/windows/spl/sys/ddi.h b/include/os/windows/spl/sys/ddi.h index 1c5827e6775..0ecb2e63aa2 100644 --- a/include/os/windows/spl/sys/ddi.h +++ b/include/os/windows/spl/sys/ddi.h @@ -1,5 +1,25 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ #ifndef _SPL_DDI_H -#define _SPL_DDI_H +#define _SPL_DDI_H #endif /* SPL_DDI_H */ diff --git a/include/os/windows/spl/sys/debug.h b/include/os/windows/spl/sys/debug.h index e9749bb7107..0a9498a873b 100644 --- a/include/os/windows/spl/sys/debug.h +++ b/include/os/windows/spl/sys/debug.h @@ -53,21 +53,21 @@ */ #ifndef _SPL_DEBUG_H -#define _SPL_DEBUG_H +#define _SPL_DEBUG_H #include #include #ifdef _MSC_VER -#define unlikely -#define likely -#define __attribute__(X) -#define __maybe_unused -#define __printflike(X,Y) -#define __unused -#define always_inline __forceinline -#define __NORETURN +#define unlikely +#define likely +#define __attribute__(X) +#define __maybe_unused +#define __printflike(X, Y) +#define __unused +#define always_inline __forceinline +#define __NORETURN #else @@ -75,17 +75,17 @@ #define except __except #ifndef expect -#define expect(expr, value) (__builtin_expect((expr), (value))) +#define expect(expr, value) (__builtin_expect((expr), (value))) #endif -#define likely(x) __builtin_expect(!!(x), 1) -#define unlikely(x) __builtin_expect(!!(x), 0) +#define likely(x) __builtin_expect(!!(x), 1) +#define unlikely(x) __builtin_expect(!!(x), 0) #ifndef __maybe_unused -#define __maybe_unused __attribute__((unused)) +#define __maybe_unused __attribute__((unused)) #endif -#define __printflike(a, b) __attribute__((__format__ (__printf__, a, b))) +#define __printflike(a, b) __attribute__((__format__(__printf__, a, b))) -#define __unused __attribute__((unused)) +#define __unused __attribute__((unused)) #define __NORETURN __attribute__((__noreturn__)) #endif @@ -96,116 +96,125 @@ extern void panic(const char *fmt, ...) __attribute__((__noreturn__)); extern void printBuffer(const char *fmt, ...); -#define LUDICROUS_SPEED // use circular buffer +#define LUDICROUS_SPEED // use circular buffer // xprintf is always printed // dprintf is printed in DEBUG builds // IOLog is printed in DEBUG builds (legacy from osx) // #ifdef DBG /* Debugging Disabled */ - #ifdef LUDICROUS_SPEED - #define dprintf(...) printBuffer(__VA_ARGS__) - #define IOLog(...) printBuffer(__VA_ARGS__) - #define xprintf(...) KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, __VA_ARGS__)) - #define TraceEvent(x, ...) printBuffer(__VA_ARGS__) - #else - #undef KdPrintEx - #define KdPrintEx(_x_) DbgPrintEx _x_ - #define dprintf(...) KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, __VA_ARGS__)) - #define IOLog(...) KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, __VA_ARGS__)) - #define xprintf(...) KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, __VA_ARGS__)) - #define TraceEvent(level, ...) KdPrintEx((DPFLTR_IHVDRIVER_ID, level, __VA_ARGS__)) - //#define dprintf(...) - //#define IOLog(...) - #endif - #define PANIC(fmt, ...) \ - do { \ - xprintf(fmt, __VA_ARGS__); \ - DbgBreakPoint(); \ - } while (0) -#else - //#undef KdPrintEx - //#define KdPrintEx(_x_) DbgPrintEx _x_ - //#define dprintf(...) KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, __VA_ARGS__)) - //#define IOLog(...) KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, __VA_ARGS__)) - #define TraceEvent(x, ...) - #define xprintf(...) DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, __VA_ARGS__) - #define dprintf(...) - #define IOLog(...) - #define PANIC(fmt, ...) \ - do { \ - xprintf(fmt, __VA_ARGS__); \ +#ifdef LUDICROUS_SPEED +#define dprintf(...) printBuffer(__VA_ARGS__) +#define IOLog(...) printBuffer(__VA_ARGS__) +#define xprintf(...) KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, \ + __VA_ARGS__)) +#define TraceEvent(x, ...) printBuffer(__VA_ARGS__) + +#else // LUDICROUS_SPEED + +#undef KdPrintEx +#define KdPrintEx(_x_) DbgPrintEx _x_ +#define dprintf(...) KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, \ + __VA_ARGS__)) +#define IOLog(...) KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, \ + __VA_ARGS__)) +#define xprintf(...) KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, \ + __VA_ARGS__)) +#define TraceEvent(level, ...) KdPrintEx((DPFLTR_IHVDRIVER_ID, level, \ + __VA_ARGS__)) + +#endif // LUDICROUS_SPEED + +#define PANIC(fmt, ...) \ + do { \ + xprintf(fmt, __VA_ARGS__); \ + DbgBreakPoint(); \ + } while (0) + +#else // DBG + +#define TraceEvent(x, ...) +#define xprintf(...) DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, \ + __VA_ARGS__) +#define dprintf(...) +#define IOLog(...) +#define PANIC(fmt, ...) \ + do { \ + xprintf(fmt, __VA_ARGS__); \ } while (0) #endif #ifdef DBG /* Debugging Disabled */ - /* Define SPL_DEBUG_STR to make clear which ASSERT definitions are used */ -#define SPL_DEBUG_STR " (DEBUG mode)" +#define SPL_DEBUG_STR " (DEBUG mode)" /* ASSERTION that is safe to use within the debug system */ -#define __ASSERT(cond) \ -do { \ - if (unlikely(!(cond))) { \ - printk(KERN_EMERG "ASSERTION(" #cond ") failed\n"); \ - BUG(); \ - } \ -} while (0) - -#define ASSERTF(cond, fmt, ...) \ -do { \ - if (unlikely(!(cond))) \ - PANIC("ASSERTION(" #cond ") failed: " fmt, __VA_ARGS__); \ -} while (0) - -#define ASSERT3B(x,y,z) VERIFY3B(x, y, z) -#define ASSERT3S(x,y,z) VERIFY3S(x, y, z) -#define ASSERT3U(x,y,z) VERIFY3U(x, y, z) -#define ASSERT3P(x,y,z) VERIFY3P(x, y, z) -#define ASSERT0(x) VERIFY0(x) - -#define ASSERTV(x) x +#define __ASSERT(cond) \ + do { \ + if (unlikely(!(cond))) { \ + printk(KERN_EMERG "ASSERTION(" #cond ") failed\n"); \ + BUG(); \ + } \ + } while (0) + +#define ASSERTF(cond, fmt, ...) \ + do { \ + if (unlikely(!(cond))) \ + PANIC("ASSERTION(" #cond ") failed: " fmt, \ + __VA_ARGS__); \ + } while (0) + +#define ASSERT3B(x, y, z) VERIFY3B(x, y, z) +#define ASSERT3S(x, y, z) VERIFY3S(x, y, z) +#define ASSERT3U(x, y, z) VERIFY3U(x, y, z) +#define ASSERT3P(x, y, z) VERIFY3P(x, y, z) +#define ASSERT0(x) VERIFY0(x) + +#define ASSERTV(x) x #ifndef ZFS_DEBUG -#define ZFS_DEBUG 1 +#define ZFS_DEBUG 1 #endif #else /* Debugging Enabled */ /* Define SPL_DEBUG_STR to make clear which ASSERT definitions are used */ -#define SPL_DEBUG_STR "" +#define SPL_DEBUG_STR "" -#define __ASSERT(x) ((void)0) -#define ASSERTF(x, y, z, ...) ((void)0) -#define ASSERTV(x) +#define __ASSERT(x) ((void)0) +#define ASSERTF(x, y, z, ...) ((void)0) +#define ASSERTV(x) -#define ASSERT3B(x,y,z) ((void)0) -#define ASSERT3S(x,y,z) ((void)0) -#define ASSERT3U(x,y,z) ((void)0) -#define ASSERT3P(x,y,z) ((void)0) -#define ASSERT0(x) ((void)0) +#define ASSERT3B(x, y, z) ((void)0) +#define ASSERT3S(x, y, z) ((void)0) +#define ASSERT3U(x, y, z) ((void)0) +#define ASSERT3P(x, y, z) ((void)0) +#define ASSERT0(x) ((void)0) #endif /* DBG */ -#define VERIFY3_IMPL(LEFT, OP, RIGHT, TYPE, FMT, CAST) \ - do { \ - TYPE _verify3_left = (TYPE)(LEFT); \ - TYPE _verify3_right = (TYPE)(RIGHT); \ - if (!(_verify3_left OP _verify3_right)) \ - PANIC("VERIFY3( %s " #OP " %s ) " \ - "failed (" FMT " " #OP " " FMT ")\n", \ - #LEFT, #RIGHT, \ - CAST (_verify3_left), CAST (_verify3_right)); \ +#define VERIFY3_IMPL(LEFT, OP, RIGHT, TYPE, FMT, CAST) \ + do { \ + TYPE _verify3_left = (TYPE)(LEFT); \ + TYPE _verify3_right = (TYPE)(RIGHT); \ + if (!(_verify3_left OP _verify3_right)) \ + PANIC("VERIFY3( %s " #OP " %s ) " \ + "failed (" FMT " " #OP " " FMT \ + ")\n", #LEFT, #RIGHT, \ + CAST(_verify3_left), CAST(_verify3_right)); \ } while (0) -#define VERIFY3B(x,y,z) VERIFY3_IMPL(x, y, z, int64_t, "%lld", (boolean_t)) -#define VERIFY3S(x,y,z) VERIFY3_IMPL(x, y, z, int64_t, "%lld", (long long)) -#define VERIFY3U(x,y,z) VERIFY3_IMPL(x, y, z, uint64_t, "%llu", \ - (unsigned long long)) -#define VERIFY3P(x,y,z) VERIFY3_IMPL(x, y, z, uintptr_t, "%p", (void *)) -#define VERIFY0(x) VERIFY3_IMPL(0, ==, x, int64_t, "%lld", (long long)) +#define VERIFY3B(x, y, z) VERIFY3_IMPL(x, y, z, int64_t, "%lld", (boolean_t)) +#define VERIFY3S(x, y, z) VERIFY3_IMPL(x, y, z, int64_t, "%lld", (long long)) +#define VERIFY3U(x, y, z) VERIFY3_IMPL(x, y, z, uint64_t, "%llu", \ + (unsigned long long)) +#define VERIFY3P(x, y, z) VERIFY3_IMPL(x, y, z, uintptr_t, "%p", (void *)) +#define VERIFY0(x) VERIFY3_IMPL(0, ==, x, int64_t, "%lld", (long long)) -#define VERIFY(EX) do { if (!(EX)) panic("PANIC: %s %s:%d\n", #EX, __FILE__, __LINE__); } while(0) +#define VERIFY(EX) do { \ + if (!(EX)) panic("PANIC: %s %s:%d\n", #EX, __FILE__, \ + __LINE__); \ + } while (0) /* * IMPLY and EQUIV are assertions of the form: @@ -215,15 +224,16 @@ do { \ * if (a) then (b) *AND* if (b) then (a) */ #if DEBAG -#define IMPLY(A, B) \ - ((void)(((!(A)) || (B)) || \ - panic("(" #A ") implies (" #B ")", __FILE__, __LINE__))) -#define EQUIV(A, B) \ - ((void)((!!(A) == !!(B)) || \ - panic("(" #A ") is equivalent to (" #B ")", __FILE__, __LINE__))) +#define IMPLY(A, B) \ + ((void)(((!(A)) || (B)) || \ + panic("(" #A ") implies (" #B ")", __FILE__, __LINE__))) +#define EQUIV(A, B) \ + ((void)((!!(A) == !!(B)) || \ + panic("(" #A ") is equivalent to (" #B ")", __FILE__, \ + __LINE__))) #else -#define IMPLY(A, B) ((void)0) -#define EQUIV(A, B) ((void)0) +#define IMPLY(A, B) ((void)0) +#define EQUIV(A, B) ((void)0) #endif @@ -234,7 +244,7 @@ do { \ #define CTASSERT(x) { _CTASSERT(x, __LINE__); } #define _CTASSERT(x, y) __CTASSERT(x, y) #define __CTASSERT(x, y) \ - typedef char __attribute__ ((unused)) \ + typedef char __attribute__((unused)) \ __compile_time_assertion__ ## y[(x) ? 1 : -1] #endif /* SPL_DEBUG_H */ diff --git a/include/os/windows/spl/sys/dirent.h b/include/os/windows/spl/sys/dirent.h index fe964fc9894..4a8a0839244 100644 --- a/include/os/windows/spl/sys/dirent.h +++ b/include/os/windows/spl/sys/dirent.h @@ -1,37 +1,57 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ #ifndef _SPL_DIRENT_H -#define _SPL_DIRENT_H +#define _SPL_DIRENT_H #include -#define MAXNAMLEN 255 +#define MAXNAMLEN 255 /* * File types */ -#define DT_UNKNOWN 0 -#define DT_FIFO 1 -#define DT_CHR 2 -#define DT_DIR 4 -#define DT_BLK 6 -#define DT_REG 8 -#define DT_LNK 10 -#define DT_SOCK 12 -#define DT_WHT 14 - -struct dirent { - uint64_t d_ino; /* file number of entry */ - uint64_t d_seekoff; /* seek offset (optional, used by servers) */ - uint16_t d_reclen; /* length of this record */ - uint16_t d_namlen; /* length of string in d_name */ - uint8_t d_type; /* file type, see below */ - char d_name[MAXPATHLEN]; /* entry name (up to MAXPATHLEN bytes) */ +#define DT_UNKNOWN 0 +#define DT_FIFO 1 +#define DT_CHR 2 +#define DT_DIR 4 +#define DT_BLK 6 +#define DT_REG 8 +#define DT_LNK 10 +#define DT_SOCK 12 +#define DT_WHT 14 + +struct dirent { + uint64_t d_ino; /* file number of entry */ + uint64_t d_seekoff; /* seek offset (optional, used by servers) */ + uint16_t d_reclen; /* length of this record */ + uint16_t d_namlen; /* length of string in d_name */ + uint8_t d_type; /* file type, see below */ + char d_name[MAXPATHLEN]; /* entry name (up to MAXPATHLEN bytes) */ }; #ifndef IFTODT -#define IFTODT(mode) (((mode) & 0170000) >> 12) +#define IFTODT(mode) (((mode) & 0170000) >> 12) #endif -#define DTTOIF(dirtype) ((dirtype) << 12) +#define DTTOIF(dirtype) ((dirtype) << 12) #endif /* SPL_DIRENT_H */ diff --git a/include/os/windows/spl/sys/disp.h b/include/os/windows/spl/sys/disp.h index e8606ede4a4..4011902d2df 100644 --- a/include/os/windows/spl/sys/disp.h +++ b/include/os/windows/spl/sys/disp.h @@ -1,5 +1,25 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ #ifndef _SPL_DISP_H -#define _SPL_DISP_H +#define _SPL_DISP_H #endif /* SPL_DISP_H */ diff --git a/include/os/windows/spl/sys/dnlc.h b/include/os/windows/spl/sys/dnlc.h index 6f378a61f16..8c542d6bc7e 100644 --- a/include/os/windows/spl/sys/dnlc.h +++ b/include/os/windows/spl/sys/dnlc.h @@ -1,6 +1,26 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ #ifndef _SPL_DNLC_H -#define _SPL_DNLC_H +#define _SPL_DNLC_H /* * Reduce the dcache and icache then reap the free'd slabs. Note the @@ -13,12 +33,6 @@ static inline void dnlc_reduce_cache(void *reduce_percent) { -#if 0 - int nr = (uintptr_t)reduce_percent * 10000; - shrink_dcache_memory(nr, GFP_KERNEL); - shrink_icache_memory(nr, GFP_KERNEL); - kmem_reap(); -#endif } #endif /* SPL_DNLC_H */ diff --git a/include/os/windows/spl/sys/dumphdr.h b/include/os/windows/spl/sys/dumphdr.h index fe40873174a..76cb792f9db 100644 --- a/include/os/windows/spl/sys/dumphdr.h +++ b/include/os/windows/spl/sys/dumphdr.h @@ -1,4 +1,25 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ + #ifndef _SPL_DUMPHDR_H -#define _SPL_DUMPHDR_H +#define _SPL_DUMPHDR_H #endif /* SPL_DUMPHDR_H */ diff --git a/include/os/windows/spl/sys/efi_partition.h b/include/os/windows/spl/sys/efi_partition.h index bbbaef1e614..5c5e35de394 100644 --- a/include/os/windows/spl/sys/efi_partition.h +++ b/include/os/windows/spl/sys/efi_partition.h @@ -1,5 +1,25 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ #ifndef _SPL_EFI_PARTITION_H -#define _SPL_EFI_PARTITION_H +#define _SPL_EFI_PARTITION_H #endif /* SPL_EFI_PARTITION_H */ diff --git a/include/os/windows/spl/sys/errno.h b/include/os/windows/spl/sys/errno.h index b8fdeeb7098..a28a19ff716 100644 --- a/include/os/windows/spl/sys/errno.h +++ b/include/os/windows/spl/sys/errno.h @@ -46,8 +46,8 @@ extern "C" { #endif #ifdef _KERNEL -#define ERESTART (-1) /* restart syscall */ -#define EJUSTRETURN (-2) /* don't modify regs, just return */ +#define ERESTART (-1) /* restart syscall */ +#define EJUSTRETURN (-2) /* don't modify regs, just return */ #endif @@ -89,69 +89,69 @@ extern "C" { #define EDOM 33 /* Math arg out of domain of func */ #define ERANGE 34 /* Math result not representable */ -#define EDEADLK 36 -#define ENAMETOOLONG 38 -#define ENOLCK 39 -#define ENOSYS 40 -#define ENOTEMPTY 41 -#define EILSEQ 42 /* Illegal byte sequence */ +#define EDEADLK 36 +#define ENAMETOOLONG 38 +#define ENOLCK 39 +#define ENOSYS 40 +#define ENOTEMPTY 41 +#define EILSEQ 42 /* Illegal byte sequence */ -#define EDQUOT 49 /* Disc quota exceeded */ -#define EBADE 50 /* invalid exchange */ +#define EDQUOT 49 /* Disc quota exceeded */ +#define EBADE 50 /* invalid exchange */ #define ECKSUM EBADE -#define ESHUTDOWN 58 /* Can't send after socket shutdown */ -#define ESTALE 70 /* Stale NFS file handle */ +#define ESHUTDOWN 58 /* Can't send after socket shutdown */ +#define ESTALE 70 /* Stale NFS file handle */ #ifndef _KERNEL -#define ERESTART 85 /* Interrupted system call should be restarted */ +#define ERESTART 85 /* Interrupted system call should be restarted */ #endif -#define EADDRINUSE 100 -#define EADDRNOTAVAIL 101 -#define EAFNOSUPPORT 102 -#define EALREADY 103 -#define EBADMSG 104 -#define ECANCELED 105 -#define ECONNABORTED 106 -#define ECONNREFUSED 107 -#define ECONNRESET 108 -#define EDESTADDRREQ 109 -#define EHOSTUNREACH 110 -#define EIDRM 111 -#define EINPROGRESS 112 -#define EISCONN 113 -#define ELOOP 114 -#define EMSGSIZE 115 -#define ENETDOWN 116 -#define ENETRESET 117 -#define ENETUNREACH 118 -#define ENOBUFS 119 -#define ENODATA 120 -#define ENOLINK 121 -#define ENOMSG 122 -#define ENOPROTOOPT 123 -#define ENOSR 124 -#define ENOSTR 125 -#define ENOTCONN 126 -#define ENOTRECOVERABLE 127 -#define ENOTSOCK 128 -#define ENOTSUP 129 -#define EOPNOTSUPP 130 -#define EOTHER 131 -#define EOVERFLOW 132 -#define EOWNERDEAD 133 -#define EPROTO 134 -#define EPROTONOSUPPORT 135 -#define EPROTOTYPE 136 -#define ETIME 137 -#define ETIMEDOUT 138 -#define ETXTBSY 139 -#define EWOULDBLOCK 140 - -#define ENOTACTIVE 142 -#define ECHRNG 143 -#define EREMOTEIO 144 +#define EADDRINUSE 100 +#define EADDRNOTAVAIL 101 +#define EAFNOSUPPORT 102 +#define EALREADY 103 +#define EBADMSG 104 +#define ECANCELED 105 +#define ECONNABORTED 106 +#define ECONNREFUSED 107 +#define ECONNRESET 108 +#define EDESTADDRREQ 109 +#define EHOSTUNREACH 110 +#define EIDRM 111 +#define EINPROGRESS 112 +#define EISCONN 113 +#define ELOOP 114 +#define EMSGSIZE 115 +#define ENETDOWN 116 +#define ENETRESET 117 +#define ENETUNREACH 118 +#define ENOBUFS 119 +#define ENODATA 120 +#define ENOLINK 121 +#define ENOMSG 122 +#define ENOPROTOOPT 123 +#define ENOSR 124 +#define ENOSTR 125 +#define ENOTCONN 126 +#define ENOTRECOVERABLE 127 +#define ENOTSOCK 128 +#define ENOTSUP 129 +#define EOPNOTSUPP 130 +#define EOTHER 131 +#define EOVERFLOW 132 +#define EOWNERDEAD 133 +#define EPROTO 134 +#define EPROTONOSUPPORT 135 +#define EPROTOTYPE 136 +#define ETIME 137 +#define ETIMEDOUT 138 +#define ETXTBSY 139 +#define EWOULDBLOCK 140 + +#define ENOTACTIVE 142 +#define ECHRNG 143 +#define EREMOTEIO 144 #ifdef __cplusplus } diff --git a/include/os/windows/spl/sys/fcntl.h b/include/os/windows/spl/sys/fcntl.h index 34b3a04c115..d57c873b59c 100644 --- a/include/os/windows/spl/sys/fcntl.h +++ b/include/os/windows/spl/sys/fcntl.h @@ -1,41 +1,61 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ + #ifndef _SPL_FCNTL_H -#define _SPL_FCNTL_H +#define _SPL_FCNTL_H #include -// #if (defined _CRT_DECLARE_NONSTDC_NAMES && _CRT_DECLARE_NONSTDC_NAMES) || (!defined _CRT_DECLARE_NONSTDC_NAMES && !__STDC__) -#define _CRT_DECLARE_NONSTDC_NAMES 1 +#define _CRT_DECLARE_NONSTDC_NAMES 1 #include -#define F_FREESP 11 +#define F_FREESP 11 -#define O_LARGEFILE 0 -#define O_RSYNC 0 -#define O_DIRECT 0 -#define O_SYNC 0 -#define O_DSYNC 0 -#define O_CLOEXEC 0 -#define O_NDELAY 0 +#define O_LARGEFILE 0 +#define O_RSYNC 0 +#define O_DIRECT 0 +#define O_SYNC 0 +#define O_DSYNC 0 +#define O_CLOEXEC 0 +#define O_NDELAY 0 -#define F_RDLCK 1 /* shared or read lock */ -#define F_UNLCK 2 /* unlock */ -#define F_WRLCK 3 /* exclusive or write lock */ +#define F_RDLCK 1 /* shared or read lock */ +#define F_UNLCK 2 /* unlock */ +#define F_WRLCK 3 /* exclusive or write lock */ #ifdef KERNEL -#define F_WAIT 0x010 /* Wait until lock is granted */ -#define F_FLOCK 0x020 /* Use flock(2) semantics for lock */ -#define F_POSIX 0x040 /* Use POSIX semantics for lock */ -#define F_PROV 0x080 /* Non-coalesced provisional lock */ -#define F_WAKE1_SAFE 0x100 /* its safe to only wake one waiter */ -#define F_ABORT 0x200 /* lock attempt aborted (force umount) */ -#define F_OFD_LOCK 0x400 /* Use "OFD" semantics for lock */ +#define F_WAIT 0x010 /* Wait until lock is granted */ +#define F_FLOCK 0x020 /* Use flock(2) semantics for lock */ +#define F_POSIX 0x040 /* Use POSIX semantics for lock */ +#define F_PROV 0x080 /* Non-coalesced provisional lock */ +#define F_WAKE1_SAFE 0x100 /* its safe to only wake one waiter */ +#define F_ABORT 0x200 /* lock attempt aborted (force umount) */ +#define F_OFD_LOCK 0x400 /* Use "OFD" semantics for lock */ #endif struct flock { - off_t l_start; /* starting offset */ - off_t l_len; /* len = 0 means until end of file */ - pid_t l_pid; /* lock owner */ - short l_type; /* lock type: read/write, etc. */ - short l_whence; /* type of l_start */ + off_t l_start; /* starting offset */ + off_t l_len; /* len = 0 means until end of file */ + pid_t l_pid; /* lock owner */ + short l_type; /* lock type: read/write, etc. */ + short l_whence; /* type of l_start */ }; #endif /* _SPL_FCNTL_H */ diff --git a/include/os/windows/spl/sys/file.h b/include/os/windows/spl/sys/file.h index 692e5325167..d28d4bd3813 100644 --- a/include/os/windows/spl/sys/file.h +++ b/include/os/windows/spl/sys/file.h @@ -1,6 +1,26 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ #ifndef _SPL_FILE_H -#define _SPL_FILE_H +#define _SPL_FILE_H #define FIGNORECASE 0x00080000 #define FKIOCTL 0x80000000 @@ -9,21 +29,20 @@ #include struct spl_fileproc { - void *f_vnode; // this points to the "fd" so we can look it up. - list_node_t f_next; /* next zfsdev_state_t link */ - uint64_t f_fd; - uint64_t f_offset; - void *f_proc; - void *f_fp; - int f_writes; - uint64_t f_file; // Minor of the file - HANDLE f_handle; - void *f_fileobject; - void *f_deviceobject; + void *f_vnode; + list_node_t f_next; + uint64_t f_fd; + uint64_t f_offset; + void *f_proc; + void *f_fp; + int f_writes; + uint64_t f_file; + HANDLE f_handle; + void *f_fileobject; + void *f_deviceobject; }; -//typedef struct spl_fileproc file_t; -#define file_t struct spl_fileproc +#define file_t struct spl_fileproc void *getf(uint64_t fd); void releasef(uint64_t fd); diff --git a/include/os/windows/spl/sys/fs/swapnode.h b/include/os/windows/spl/sys/fs/swapnode.h deleted file mode 100644 index 0a24f21d0c0..00000000000 --- a/include/os/windows/spl/sys/fs/swapnode.h +++ /dev/null @@ -1,5 +0,0 @@ - -#ifndef _SPL_SWAPNODE_H -#define _SPL_SWAPNODE_H - -#endif /* SPL_SWAPNODE_H */ diff --git a/include/os/windows/spl/sys/idmap.h b/include/os/windows/spl/sys/idmap.h index 581d6c8026b..80678fa8fb4 100644 --- a/include/os/windows/spl/sys/idmap.h +++ b/include/os/windows/spl/sys/idmap.h @@ -1,7 +1,27 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ #ifndef _SPL_IDMAP_H -#define _SPL_IDMAP_H +#define _SPL_IDMAP_H -#define IDMAP_WK_CREATOR_OWNER_UID 2147483648U +#define IDMAP_WK_CREATOR_OWNER_UID 2147483648U #endif /* SPL_IDMAP_H */ diff --git a/include/os/windows/spl/sys/int_limits.h b/include/os/windows/spl/sys/int_limits.h index ce860dc9bef..81f5caf9eaf 100644 --- a/include/os/windows/spl/sys/int_limits.h +++ b/include/os/windows/spl/sys/int_limits.h @@ -1,5 +1,25 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ #ifndef _SPL_INT_LIMITS_H -#define _SPL_INT_LIMITS_H +#define _SPL_INT_LIMITS_H #endif /* SPL_INT_LIMITS_H */ diff --git a/include/os/windows/spl/sys/int_types.h b/include/os/windows/spl/sys/int_types.h index 47f96f6635d..1a04d92dfdf 100644 --- a/include/os/windows/spl/sys/int_types.h +++ b/include/os/windows/spl/sys/int_types.h @@ -1,6 +1,26 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ #ifndef _SPL_INT_TYPES_H -#define _SPL_INT_TYPES_H +#define _SPL_INT_TYPES_H #include diff --git a/include/os/windows/spl/sys/inttypes.h b/include/os/windows/spl/sys/inttypes.h index a28d05c8cb0..59d8efdb1ed 100644 --- a/include/os/windows/spl/sys/inttypes.h +++ b/include/os/windows/spl/sys/inttypes.h @@ -1,5 +1,25 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ #ifndef _SPL_INTTYPES_H -#define _SPL_INTTYPES_H +#define _SPL_INTTYPES_H #endif /* SPL_INTTYPES_H */ diff --git a/include/os/windows/spl/sys/ioctl.h b/include/os/windows/spl/sys/ioctl.h index c44def2b236..61b0d9db35d 100644 --- a/include/os/windows/spl/sys/ioctl.h +++ b/include/os/windows/spl/sys/ioctl.h @@ -28,4 +28,3 @@ #endif /* _LIBSPL_SYS_STAT_H */ - diff --git a/include/os/windows/spl/sys/kidmap.h b/include/os/windows/spl/sys/kidmap.h index 63b1ccba0b0..2acae935b42 100644 --- a/include/os/windows/spl/sys/kidmap.h +++ b/include/os/windows/spl/sys/kidmap.h @@ -1,6 +1,26 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ #ifndef _SPL_KIDMAP_H -#define _SPL_KIDMAP_H +#define _SPL_KIDMAP_H #include diff --git a/include/os/windows/spl/sys/kmem.h b/include/os/windows/spl/sys/kmem.h index 072d3187b90..003306d2f7f 100644 --- a/include/os/windows/spl/sys/kmem.h +++ b/include/os/windows/spl/sys/kmem.h @@ -34,7 +34,6 @@ #include #include #include -//#include #include #include @@ -49,9 +48,9 @@ extern uint64_t physmem; #define KM_NOSLEEP 0x0001 /* cannot block for memory; may fail */ #define KM_PANIC 0x0002 /* if memory cannot be allocated, panic */ #define KM_PUSHPAGE 0x0004 /* can block for memory; may use reserve */ -#define KM_NORMALPRI 0x0008 /* with KM_NOSLEEP, lower priority allocation */ -#define KM_NODEBUG 0x0010 /* NOT IMPLEMENTED ON OSX */ -#define KM_NO_VBA 0x0020 /* OSX: don't descend to the bucket layer */ +#define KM_NORMALPRI 0x0008 /* with KM_NOSLEEP, lower priority allocation */ +#define KM_NODEBUG 0x0010 /* NOT IMPLEMENTED ON OSX */ +#define KM_NO_VBA 0x0020 /* OSX: don't descend to the bucket layer */ #define KM_VMFLAGS 0x00ff /* flags that must match VM_* flags */ #define KM_FLAGS 0xffff /* all settable kmem flags */ @@ -60,86 +59,85 @@ extern uint64_t physmem; * Kernel memory allocator: DDI interfaces. * See kmem_alloc(9F) for details. */ - //MALLOC(fs, struct free_slab *, sizeof(struct free_slab), - // M_TEMP, M_WAITOK); -#define MALLOC(A,C,S,T,F) \ + +#define MALLOC(A, C, S, T, F) \ (A) = (C)ExAllocatePoolWithTag(NonPagedPoolNx, (S), '!SFZ') -#define FREE(A,T) \ +#define FREE(A, T) \ ExFreePoolWithTag((A), '!SFZ') // Work around symbol collisions in XNU -#define kmem_alloc(size, kmflags) zfs_kmem_alloc((size), (kmflags)) -#define kmem_zalloc(size, kmflags) zfs_kmem_zalloc((size), (kmflags)) -#define kmem_free(buf, size) zfs_kmem_free((buf), (size)) - - void* zfs_kmem_alloc(size_t size, int kmflags); - void* zfs_kmem_zalloc(size_t size, int kmflags); - void zfs_kmem_free(void *buf, size_t size); - - void spl_kmem_init(uint64_t); - void spl_kmem_thread_init(); - void spl_kmem_mp_init(); - void spl_kmem_thread_fini(); - void spl_kmem_fini(); - - uint64_t kmem_size(void); - uint64_t kmem_used(void); - int64_t kmem_avail(void); - uint64_t kmem_num_pages_wanted(); - int spl_vm_pool_low(void); - int64_t spl_minimal_physmem_p(void); - int64_t spl_adjust_pressure(int64_t); - int64_t spl_free_wrapper(void); - int64_t spl_free_manual_pressure_wrapper(void); - boolean_t spl_free_fast_pressure_wrapper(void); - void spl_free_set_pressure(int64_t); - void spl_free_set_fast_pressure(boolean_t); - uint64_t spl_free_last_pressure_wrapper(void); - -#define KMC_NOTOUCH 0x00010000 -#define KMC_NODEBUG 0x00020000 -#define KMC_NOMAGAZINE 0x00040000 -#define KMC_NOHASH 0x00080000 -#define KMC_QCACHE 0x00100000 -#define KMC_KMEM_ALLOC 0x00200000 /* internal use only */ -#define KMC_IDENTIFIER 0x00400000 /* internal use only */ -#define KMC_PREFILL 0x00800000 -#define KMC_ARENA_SLAB 0x01000000 /* use a bigger kmem cache */ - - struct kmem_cache; - - typedef struct kmem_cache kmem_cache_t; - - /* Client response to kmem move callback */ - typedef enum kmem_cbrc { - KMEM_CBRC_YES, - KMEM_CBRC_NO, - KMEM_CBRC_LATER, - KMEM_CBRC_DONT_NEED, - KMEM_CBRC_DONT_KNOW - } kmem_cbrc_t; - -#define POINTER_IS_VALID(p) (!((uintptr_t)(p) & 0x3)) -#define POINTER_INVALIDATE(pp) (*(pp) = (void *)((uintptr_t)(*(pp)) | 0x1)) - - kmem_cache_t *kmem_cache_create(char *name, uint32_t bufsize, uint32_t align, - int (*constructor)(void *, void *, int), - void (*destructor)(void *, void *), - void (*reclaim)(void *), - void *_private, struct vmem *vmp, int cflags); - void kmem_cache_destroy(kmem_cache_t *cache); - void *kmem_cache_alloc(kmem_cache_t *cache, int flags); - void kmem_cache_free(kmem_cache_t *cache, void *buf); - void kmem_cache_free_to_slab(kmem_cache_t *cache, void *buf); - void kmem_cache_reap_now(kmem_cache_t *cache); - void kmem_depot_ws_zero(kmem_cache_t *cache); - void kmem_reap(void); - void kmem_reap_idspace(void); - kmem_cache_t *kmem_cache_buf_in_cache(kmem_cache_t *, void *); - - int kmem_debugging(void); - void kmem_cache_set_move(kmem_cache_t *, - kmem_cbrc_t (*)(void *, void *, uint32_t, void *)); +#define kmem_alloc(size, kmflags) zfs_kmem_alloc((size), (kmflags)) +#define kmem_zalloc(size, kmflags) zfs_kmem_zalloc((size), (kmflags)) +#define kmem_free(buf, size) zfs_kmem_free((buf), (size)) + +void *zfs_kmem_alloc(size_t size, int kmflags); +void *zfs_kmem_zalloc(size_t size, int kmflags); +void zfs_kmem_free(void *buf, size_t size); + +void spl_kmem_init(uint64_t); +void spl_kmem_thread_init(); +void spl_kmem_mp_init(); +void spl_kmem_thread_fini(); +void spl_kmem_fini(); + +uint64_t kmem_size(void); +uint64_t kmem_used(void); +int64_t kmem_avail(void); +uint64_t kmem_num_pages_wanted(); +int spl_vm_pool_low(void); +int64_t spl_minimal_physmem_p(void); +int64_t spl_adjust_pressure(int64_t); +int64_t spl_free_wrapper(void); +int64_t spl_free_manual_pressure_wrapper(void); +boolean_t spl_free_fast_pressure_wrapper(void); +void spl_free_set_pressure(int64_t); +void spl_free_set_fast_pressure(boolean_t); +uint64_t spl_free_last_pressure_wrapper(void); + +#define KMC_NOTOUCH 0x00010000 +#define KMC_NODEBUG 0x00020000 +#define KMC_NOMAGAZINE 0x00040000 +#define KMC_NOHASH 0x00080000 +#define KMC_QCACHE 0x00100000 +#define KMC_KMEM_ALLOC 0x00200000 /* internal use only */ +#define KMC_IDENTIFIER 0x00400000 /* internal use only */ +#define KMC_PREFILL 0x00800000 +#define KMC_ARENA_SLAB 0x01000000 /* use a bigger kmem cache */ + +struct kmem_cache; + +typedef struct kmem_cache kmem_cache_t; + +/* Client response to kmem move callback */ +typedef enum kmem_cbrc { + KMEM_CBRC_YES, + KMEM_CBRC_NO, + KMEM_CBRC_LATER, + KMEM_CBRC_DONT_NEED, + KMEM_CBRC_DONT_KNOW +} kmem_cbrc_t; + +#define POINTER_IS_VALID(p) (!((uintptr_t)(p) & 0x3)) +#define POINTER_INVALIDATE(pp) (*(pp) = (void *)((uintptr_t)(*(pp)) | 0x1)) + +kmem_cache_t *kmem_cache_create(char *name, uint32_t bufsize, uint32_t align, + int (*constructor)(void *, void *, int), + void (*destructor)(void *, void *), + void (*reclaim)(void *), + void *_private, struct vmem *vmp, int cflags); +void kmem_cache_destroy(kmem_cache_t *cache); +void *kmem_cache_alloc(kmem_cache_t *cache, int flags); +void kmem_cache_free(kmem_cache_t *cache, void *buf); +void kmem_cache_free_to_slab(kmem_cache_t *cache, void *buf); +void kmem_cache_reap_now(kmem_cache_t *cache); +void kmem_depot_ws_zero(kmem_cache_t *cache); +void kmem_reap(void); +void kmem_reap_idspace(void); +kmem_cache_t *kmem_cache_buf_in_cache(kmem_cache_t *, void *); + +int kmem_debugging(void); +void kmem_cache_set_move(kmem_cache_t *, + kmem_cbrc_t (*)(void *, void *, uint32_t, void *)); extern char *kmem_asprintf(const char *fmt, ...); extern char *kmem_strdup(const char *str); diff --git a/include/os/windows/spl/sys/kmem_cache.h b/include/os/windows/spl/sys/kmem_cache.h index 7dec9c4358b..2dc08b17126 100644 --- a/include/os/windows/spl/sys/kmem_cache.h +++ b/include/os/windows/spl/sys/kmem_cache.h @@ -1,4 +1,3 @@ - /* * CDDL HEADER START * @@ -21,6 +20,6 @@ * CDDL HEADER END */ #ifndef _SPL_KMEM_CACHE_H -#define _SPL_KMEM_CACHE_H +#define _SPL_KMEM_CACHE_H #endif diff --git a/include/os/windows/spl/sys/kmem_impl.h b/include/os/windows/spl/sys/kmem_impl.h index 36b97e8b8a6..61bc5fc4896 100644 --- a/include/os/windows/spl/sys/kmem_impl.h +++ b/include/os/windows/spl/sys/kmem_impl.h @@ -29,15 +29,12 @@ #include #include #include -#include #include #include #include #include -//#include #include #include -//#include #ifdef __cplusplus extern "C" { @@ -45,33 +42,33 @@ extern "C" { #pragma pack(2) - /* - * kernel memory allocator: implementation-private data structures - * - * Lock order: - * 1. cache_lock - * 2. cc_lock in order by CPU ID - * 3. cache_depot_lock - * - * Do not call kmem_cache_alloc() or taskq_dispatch() while holding any of the - * above locks. - */ - -#define KMF_AUDIT 0x00000001 /* transaction auditing */ +/* + * kernel memory allocator: implementation-private data structures + * + * Lock order: + * 1. cache_lock + * 2. cc_lock in order by CPU ID + * 3. cache_depot_lock + * + * Do not call kmem_cache_alloc() or taskq_dispatch() while holding any of the + * above locks. + */ + +#define KMF_AUDIT 0x00000001 /* transaction auditing */ #define KMF_DEADBEEF 0x00000002 /* deadbeef checking */ -#define KMF_REDZONE 0x00000004 /* redzone checking */ +#define KMF_REDZONE 0x00000004 /* redzone checking */ #define KMF_CONTENTS 0x00000008 /* freed-buffer content logging */ -#define KMF_STICKY 0x00000010 /* if set, override /etc/system */ +#define KMF_STICKY 0x00000010 /* if set, override /etc/system */ #define KMF_NOMAGAZINE 0x00000020 /* disable per-cpu magazines */ #define KMF_FIREWALL 0x00000040 /* put all bufs before unmapped pages */ -#define KMF_LITE 0x00000100 /* lightweight debugging */ +#define KMF_LITE 0x00000100 /* lightweight debugging */ -#define KMF_HASH 0x00000200 /* cache has hash table */ +#define KMF_HASH 0x00000200 /* cache has hash table */ #define KMF_RANDOMIZE 0x00000400 /* randomize other kmem_flags */ #define KMF_DUMPDIVERT 0x00001000 /* use alternate memory at dump time */ #define KMF_DUMPUNSAFE 0x00002000 /* flag caches used at dump time */ -#define KMF_PREFILL 0x00004000 /* Prefill the slab when created. */ +#define KMF_PREFILL 0x00004000 /* Prefill the slab when created. */ #define KMF_BUFTAG (KMF_DEADBEEF | KMF_REDZONE) #define KMF_TOUCH (KMF_BUFTAG | KMF_LITE | KMF_CONTENTS) @@ -80,422 +77,419 @@ extern "C" { #define KMEM_STACK_DEPTH 15 -#define KMEM_FREE_PATTERN 0xdeadbeefdeadbeefULL +#define KMEM_FREE_PATTERN 0xdeadbeefdeadbeefULL #define KMEM_UNINITIALIZED_PATTERN 0xbaddcafebaddcafeULL #define KMEM_REDZONE_PATTERN 0xfeedfacefeedfaceULL -#define KMEM_REDZONE_BYTE 0xbb - - /* - * Upstream platforms handle size == 0 as valid alloc, we - * can not return NULL, as that invalidates KM_SLEEP. So - * we return a valid hardcoded address, instead of actually taking up - * memory by fudging size to 1 byte. If read/writes are - * attempted, we will get page fault (which is correct, they - * asked for zero bytes after all) - */ -#define KMEM_ZERO_SIZE_PTR ((void *)16) - - /* - * Redzone size encodings for kmem_alloc() / kmem_free(). We encode the - * allocation size, rather than storing it directly, so that kmem_free() - * can distinguish frees of the wrong size from redzone violations. - * - * A size of zero is never valid. - */ +#define KMEM_REDZONE_BYTE 0xbb + +/* + * Upstream platforms handle size == 0 as valid alloc, we + * can not return NULL, as that invalidates KM_SLEEP. So + * we return a valid hardcoded address, instead of actually taking up + * memory by fudging size to 1 byte. If read/writes are + * attempted, we will get page fault (which is correct, they + * asked for zero bytes after all) + */ +#define KMEM_ZERO_SIZE_PTR ((void *)16) + +/* + * Redzone size encodings for kmem_alloc() / kmem_free(). We encode the + * allocation size, rather than storing it directly, so that kmem_free() + * can distinguish frees of the wrong size from redzone violations. + * + * A size of zero is never valid. + */ #define KMEM_SIZE_ENCODE(x) (251 * (x) + 1) #define KMEM_SIZE_DECODE(x) ((x) / 251) #define KMEM_SIZE_VALID(x) ((x) % 251 == 1 && (x) != 1) - -#define KMEM_ALIGN 8 /* min guaranteed alignment */ +#define KMEM_ALIGN 8 /* min guaranteed alignment */ #define KMEM_ALIGN_SHIFT 3 /* log2(KMEM_ALIGN) */ #define KMEM_VOID_FRACTION 8 /* never waste more than 1/8 of slab */ -#define KMEM_SLAB_IS_PARTIAL(sp) \ -((sp)->slab_refcnt > 0 && (sp)->slab_refcnt < (sp)->slab_chunks) -#define KMEM_SLAB_IS_ALL_USED(sp) \ -((sp)->slab_refcnt == (sp)->slab_chunks) - - /* - * The bufctl (buffer control) structure keeps some minimal information - * about each buffer: its address, its slab, and its current linkage, - * which is either on the slab's freelist (if the buffer is free), or - * on the cache's buf-to-bufctl hash table (if the buffer is allocated). - * In the case of non-hashed, or "raw", caches (the common case), only - * the freelist linkage is necessary: the buffer address is at a fixed - * offset from the bufctl address, and the slab is at the end of the page. - * - * NOTE: bc_next must be the first field; raw buffers have linkage only. - */ - typedef struct kmem_bufctl { - struct kmem_bufctl *bc_next; /* next bufctl struct */ - void *bc_addr; /* address of buffer */ - struct kmem_slab *bc_slab; /* controlling slab */ - } kmem_bufctl_t; - - /* - * The KMF_AUDIT version of the bufctl structure. The beginning of this - * structure must be identical to the normal bufctl structure so that - * pointers are interchangeable. - */ - typedef struct kmem_bufctl_audit { - struct kmem_bufctl *bc_next; /* next bufctl struct */ - void *bc_addr; /* address of buffer */ - struct kmem_slab *bc_slab; /* controlling slab */ - kmem_cache_t *bc_cache; /* controlling cache */ - hrtime_t bc_timestamp; /* transaction time */ - kthread_t *bc_thread; /* thread doing transaction */ - struct kmem_bufctl *bc_lastlog; /* last log entry */ - void *bc_contents; /* contents at last free */ - int bc_depth; /* stack depth */ - pc_t bc_stack[KMEM_STACK_DEPTH]; /* pc stack */ - } kmem_bufctl_audit_t; - - /* - * A kmem_buftag structure is appended to each buffer whenever any of the - * KMF_BUFTAG flags (KMF_DEADBEEF, KMF_REDZONE, KMF_VERIFY) are set. - */ - typedef struct kmem_buftag { - uint64_t bt_redzone; /* 64-bit redzone pattern */ - kmem_bufctl_t *bt_bufctl; /* bufctl */ - intptr_t bt_bxstat; /* bufctl ^ (alloc/free) */ - } kmem_buftag_t; - - /* - * A variant of the kmem_buftag structure used for KMF_LITE caches. - * Previous callers are stored in reverse chronological order. (i.e. most - * recent first) - */ - typedef struct kmem_buftag_lite { - kmem_buftag_t bt_buftag; /* a normal buftag */ - pc_t bt_history[1]; /* zero or more callers */ - } kmem_buftag_lite_t; +#define KMEM_SLAB_IS_PARTIAL(sp) \ + ((sp)->slab_refcnt > 0 && (sp)->slab_refcnt < (sp)->slab_chunks) +#define KMEM_SLAB_IS_ALL_USED(sp) \ + ((sp)->slab_refcnt == (sp)->slab_chunks) + +/* + * The bufctl (buffer control) structure keeps some minimal information + * about each buffer: its address, its slab, and its current linkage, + * which is either on the slab's freelist (if the buffer is free), or + * on the cache's buf-to-bufctl hash table (if the buffer is allocated). + * In the case of non-hashed, or "raw", caches (the common case), only + * the freelist linkage is necessary: the buffer address is at a fixed + * offset from the bufctl address, and the slab is at the end of the page. + * + * NOTE: bc_next must be the first field; raw buffers have linkage only. + */ +typedef struct kmem_bufctl { + struct kmem_bufctl *bc_next; /* next bufctl struct */ + void *bc_addr; /* address of buffer */ + struct kmem_slab *bc_slab; /* controlling slab */ +} kmem_bufctl_t; + +/* + * The KMF_AUDIT version of the bufctl structure. The beginning of this + * structure must be identical to the normal bufctl structure so that + * pointers are interchangeable. + */ +typedef struct kmem_bufctl_audit { + struct kmem_bufctl *bc_next; /* next bufctl struct */ + void *bc_addr; /* address of buffer */ + struct kmem_slab *bc_slab; /* controlling slab */ + kmem_cache_t *bc_cache; /* controlling cache */ + hrtime_t bc_timestamp; /* transaction time */ + kthread_t *bc_thread; /* thread doing transaction */ + struct kmem_bufctl *bc_lastlog; /* last log entry */ + void *bc_contents; /* contents at last free */ + int bc_depth; /* stack depth */ + pc_t bc_stack[KMEM_STACK_DEPTH]; /* pc stack */ +} kmem_bufctl_audit_t; + +/* + * A kmem_buftag structure is appended to each buffer whenever any of the + * KMF_BUFTAG flags (KMF_DEADBEEF, KMF_REDZONE, KMF_VERIFY) are set. + */ +typedef struct kmem_buftag { + uint64_t bt_redzone; /* 64-bit redzone pattern */ + kmem_bufctl_t *bt_bufctl; /* bufctl */ + intptr_t bt_bxstat; /* bufctl ^ (alloc/free) */ +} kmem_buftag_t; + +/* + * A variant of the kmem_buftag structure used for KMF_LITE caches. + * Previous callers are stored in reverse chronological order. (i.e. most + * recent first) + */ +typedef struct kmem_buftag_lite { + kmem_buftag_t bt_buftag; /* a normal buftag */ + pc_t bt_history[1]; /* zero or more callers */ +} kmem_buftag_lite_t; #define KMEM_BUFTAG_LITE_SIZE(f) \ -(offsetof(kmem_buftag_lite_t, bt_history[f])) + (offsetof(kmem_buftag_lite_t, bt_history[f])) #define KMEM_BUFTAG(cp, buf) \ -((kmem_buftag_t *)((char *)(buf) + (cp)->cache_buftag)) + ((kmem_buftag_t *)((char *)(buf) + (cp)->cache_buftag)) #define KMEM_BUFCTL(cp, buf) \ -((kmem_bufctl_t *)((char *)(buf) + (cp)->cache_bufctl)) + ((kmem_bufctl_t *)((char *)(buf) + (cp)->cache_bufctl)) #define KMEM_BUF(cp, bcp) \ -((void *)((char *)(bcp) - (cp)->cache_bufctl)) + ((void *)((char *)(bcp) - (cp)->cache_bufctl)) #define KMEM_SLAB(cp, buf) \ -((kmem_slab_t *)P2END((uintptr_t)(buf), (cp)->cache_slabsize) - 1) + ((kmem_slab_t *)P2END((uintptr_t)(buf), (cp)->cache_slabsize) - 1) - /* - * Test for using alternate memory at dump time. - */ +/* + * Test for using alternate memory at dump time. + */ #define KMEM_DUMP(cp) ((cp)->cache_flags & KMF_DUMPDIVERT) #define KMEM_DUMPCC(ccp) ((ccp)->cc_flags & KMF_DUMPDIVERT) - /* - * The "CPU" macro loads a cpu_t that refers to the cpu that the current - * thread is running on at the time the macro is executed. A context switch - * may occur immediately after loading this data structure, leaving this - * thread pointing at the cpu_t for the previous cpu. This is not a problem; - * we'd just end up checking the previous cpu's per-cpu cache, and then check - * the other layers of the kmem cache if need be. - * - * It's not even a problem if the old cpu gets DR'ed out during the context - * switch. The cpu-remove DR operation bzero()s the cpu_t, but doesn't free - * it. So the cpu_t's cpu_cache_offset would read as 0, causing us to use - * cpu 0's per-cpu cache. - * - * So, there is no need to disable kernel preemption while using the CPU macro - * below since if we have been context switched, there will not be any - * correctness problem, just a momentary use of a different per-cpu cache. - */ - -#define KMEM_CPU_CACHE(cp) \ -(&cp->cache_cpu[cpu_number()]) +/* + * The "CPU" macro loads a cpu_t that refers to the cpu that the current + * thread is running on at the time the macro is executed. A context switch + * may occur immediately after loading this data structure, leaving this + * thread pointing at the cpu_t for the previous cpu. This is not a problem; + * we'd just end up checking the previous cpu's per-cpu cache, and then check + * the other layers of the kmem cache if need be. + * + * It's not even a problem if the old cpu gets DR'ed out during the context + * switch. The cpu-remove DR operation bzero()s the cpu_t, but doesn't free + * it. So the cpu_t's cpu_cache_offset would read as 0, causing us to use + * cpu 0's per-cpu cache. + * + * So, there is no need to disable kernel preemption while using the CPU macro + * below since if we have been context switched, there will not be any + * correctness problem, just a momentary use of a different per-cpu cache. + */ + +#define KMEM_CPU_CACHE(cp) \ + (&cp->cache_cpu[cpu_number()]) #define KMOM_MAGAZINE_VALID(cp, mp) \ -(((kmem_slab_t *)P2END((uintptr_t)(mp), PAGESIZE) - 1)->slab_cache == \ -(cp)->cache_magtype->mt_cache) + (((kmem_slab_t *)P2END((uintptr_t)(mp), PAGESIZE) - 1)->slab_cache == \ + (cp)->cache_magtype->mt_cache) #define KMEM_MAGAZINE_VALID(cp, mp) \ -(((kmem_slab_t *)P2END((uintptr_t)(mp), PAGESIZE) - 1)->slab_cache == \ -(cp)->cache_magtype->mt_cache) + (((kmem_slab_t *)P2END((uintptr_t)(mp), PAGESIZE) - 1)->slab_cache == \ + (cp)->cache_magtype->mt_cache) #define KMEM_SLAB_OFFSET(sp, buf) \ -((uint32_t)((uintptr_t)(buf) - (uintptr_t)((sp)->slab_base))) + ((uint32_t)((uintptr_t)(buf) - (uintptr_t)((sp)->slab_base))) #define KMEM_SLAB_MEMBER(sp, buf) \ -(KMEM_SLAB_OFFSET(sp, buf) < (sp)->slab_cache->cache_slabsize) + (KMEM_SLAB_OFFSET(sp, buf) < (sp)->slab_cache->cache_slabsize) #define KMEM_BUFTAG_ALLOC 0xa110c8edUL #define KMEM_BUFTAG_FREE 0xf4eef4eeUL - /* slab_later_count thresholds */ +/* slab_later_count thresholds */ #define KMEM_DISBELIEF 3 - /* slab_flags */ -#define KMEM_SLAB_NOMOVE 0x1 +/* slab_flags */ +#define KMEM_SLAB_NOMOVE 0x1 #define KMEM_SLAB_MOVE_PENDING 0x2 - typedef struct kmem_slab { - struct kmem_cache *slab_cache; /* controlling cache */ - void *slab_base; /* base of allocated memory */ - avl_node_t slab_link; /* slab linkage */ - struct kmem_bufctl *slab_head; /* first free buffer */ - long slab_refcnt; /* outstanding allocations */ - long slab_chunks; /* chunks (bufs) in this slab */ - uint32_t slab_stuck_offset; /* unmoved buffer offset */ - uint16_t slab_later_count; /* cf KMEM_CBRC_LATER */ - uint16_t slab_flags; /* bits to mark the slab */ - hrtime_t slab_create_time; /* when was slab created? */ - } kmem_slab_t; +typedef struct kmem_slab { + struct kmem_cache *slab_cache; /* controlling cache */ + void *slab_base; /* base of allocated memory */ + avl_node_t slab_link; /* slab linkage */ + struct kmem_bufctl *slab_head; /* first free buffer */ + long slab_refcnt; /* outstanding allocations */ + long slab_chunks; /* chunks (bufs) in this slab */ + uint32_t slab_stuck_offset; /* unmoved buffer offset */ + uint16_t slab_later_count; /* cf KMEM_CBRC_LATER */ + uint16_t slab_flags; /* bits to mark the slab */ + hrtime_t slab_create_time; /* when was slab created? */ +} kmem_slab_t; #define KMEM_HASH_INITIAL 64 #define KMEM_HASH(cp, buf) \ -((cp)->cache_hash_table + \ -(((uintptr_t)(buf) >> (cp)->cache_hash_shift) & (cp)->cache_hash_mask)) + ((cp)->cache_hash_table + \ + (((uintptr_t)(buf) >> (cp)->cache_hash_shift) & (cp)->cache_hash_mask)) -#define KMEM_CACHE_NAMELEN 31 +#define KMEM_CACHE_NAMELEN 31 - typedef struct kmem_magazine { - void *mag_next; - void *mag_round[1]; /* one or more rounds */ - } kmem_magazine_t; +typedef struct kmem_magazine { + void *mag_next; + void *mag_round[1]; /* one or more rounds */ +} kmem_magazine_t; - /* - * The magazine types for fast per-cpu allocation - */ - typedef struct kmem_magtype { - short mt_magsize; /* magazine size (number of rounds) */ - int mt_align; /* magazine alignment */ - uint32_t mt_minbuf; /* all smaller buffers qualify */ - uint32_t mt_maxbuf; /* no larger buffers qualify */ - kmem_cache_t *mt_cache; /* magazine cache */ - } kmem_magtype_t; +/* + * The magazine types for fast per-cpu allocation + */ +typedef struct kmem_magtype { + short mt_magsize; /* magazine size (number of rounds) */ + int mt_align; /* magazine alignment */ + uint32_t mt_minbuf; /* all smaller buffers qualify */ + uint32_t mt_maxbuf; /* no larger buffers qualify */ + kmem_cache_t *mt_cache; /* magazine cache */ +} kmem_magtype_t; #define KMEM_CPU_CACHE_SIZE 128 /* must be power of 2 */ -#define KMEM_CPU_PAD (KMEM_CPU_CACHE_SIZE - sizeof (kmutex_t) - \ +#define KMEM_CPU_PAD (KMEM_CPU_CACHE_SIZE - sizeof (kmutex_t) - \ 2 * sizeof (uint64_t) - 2 * sizeof (void *) - sizeof (int) - \ 5 * sizeof (short)) #define KMEM_CACHE_SIZE(ncpus) \ offsetof(kmem_cache_t, cache_cpu[ncpus]) /* Offset from kmem_cache->cache_cpu for per cpu caches */ -#define KMEM_CPU_CACHE_OFFSET(cpuid) \ - offsetof(kmem_cache_t, cache_cpu[cpuid]) - \ +#define KMEM_CPU_CACHE_OFFSET(cpuid) \ + offsetof(kmem_cache_t, cache_cpu[cpuid]) - \ offsetof(kmem_cache_t, cache_cpu) -// ((uint32_t)(&((kmem_cache_t *)0)->cache_cpu[cpuid]) - \ -// (uint32_t)(&((kmem_cache_t *)0)->cache_cpu)) - - /* - * Per CPU cache data - */ - typedef struct kmem_cpu_cache { - kmutex_t cc_lock; /* protects this cpu's local cache */ - uint64_t cc_alloc; /* allocations from this cpu */ - uint64_t cc_free; /* frees to this cpu */ - kmem_magazine_t *cc_loaded; /* the currently loaded magazine */ - kmem_magazine_t *cc_ploaded; /* the previously loaded magazine */ - int cc_flags; /* CPU-local copy of cache_flags */ - short cc_rounds; /* number of objects in loaded mag */ - short cc_prounds; /* number of objects in previous mag */ - short cc_magsize; /* number of rounds in a full mag */ - short cc_dump_rounds; /* dump time copy of cc_rounds */ - short cc_dump_prounds; /* dump time copy of cc_prounds */ - char cc_pad[KMEM_CPU_PAD]; /* for nice alignment */ - } kmem_cpu_cache_t; - - /* - * The magazine lists used in the depot. - */ - typedef struct kmem_maglist { - kmem_magazine_t *ml_list; /* magazine list */ - long ml_total; /* number of magazines */ - long ml_min; /* min since last update */ - long ml_reaplimit; /* max reapable magazines */ - uint64_t ml_alloc; /* allocations from this list */ - } kmem_maglist_t; - - typedef struct kmem_defrag { - /* - * Statistics - */ - uint64_t kmd_callbacks; /* move callbacks */ - uint64_t kmd_yes; /* KMEM_CBRC_YES responses */ - uint64_t kmd_no; /* NO responses */ - uint64_t kmd_later; /* LATER responses */ - uint64_t kmd_dont_need; /* DONT_NEED responses */ - uint64_t kmd_dont_know; /* DONT_KNOW responses */ - uint64_t kmd_hunt_found; /* DONT_KNOW: # found in mag */ - uint64_t kmd_slabs_freed; /* slabs freed by moves */ - uint64_t kmd_defrags; /* kmem_cache_defrag() */ - uint64_t kmd_scans; /* kmem_cache_scan() */ - - /* - * Consolidator fields - */ - avl_tree_t kmd_moves_pending; /* buffer moves pending */ - list_t kmd_deadlist; /* deferred slab frees */ - uint32_t kmd_deadcount; /* # of slabs in kmd_deadlist */ - uint8_t kmd_reclaim_numer; /* slab usage threshold */ - uint8_t kmd_pad1; /* compiler padding */ - uint16_t kmd_consolidate; /* triggers consolidator */ - uint32_t kmd_pad2; /* compiler padding */ - uint32_t kmd_slabs_sought; /* reclaimable slabs sought */ - uint32_t kmd_slabs_found; /* reclaimable slabs found */ - uint32_t kmd_tries; /* nth scan interval counter */ - /* - * Fields used to ASSERT that the client does not kmem_cache_free() - * objects passed to the move callback. - */ - void *kmd_from_buf; /* object to move */ - void *kmd_to_buf; /* move destination */ - kthread_t *kmd_thread; /* thread calling move */ - } kmem_defrag_t; - - /* - * Cache callback function types - */ - typedef int (*constructor_fn_t)(void*, void*, int); - typedef void (*destructor_fn_t)(void*, void*); - typedef void (*reclaim_fn_t)(void*); - - /* - * Cache - */ - struct kmem_cache { - - /* - * Statistics - */ - uint64_t cache_slab_create; /* slab creates */ - uint64_t cache_slab_destroy; /* slab destroys */ - uint64_t cache_slab_alloc; /* slab layer allocations */ - uint64_t cache_slab_free; /* slab layer frees */ - uint64_t cache_alloc_fail; /* total failed allocations */ - uint64_t cache_buftotal; /* total buffers */ - uint64_t cache_bufmax; /* max buffers ever */ - uint64_t cache_bufslab; /* buffers free in slab layer */ - uint64_t cache_reap; /* cache reaps */ - uint64_t cache_rescale; /* hash table rescales */ - uint64_t cache_lookup_depth; /* hash lookup depth */ - uint64_t cache_depot_contention; /* mutex contention count */ - uint64_t cache_depot_contention_prev; /* previous snapshot */ - uint64_t cache_alloc_count; /* Number of allocations in cache */ - uint64_t no_vba_success; /* successful calls with KM_NO_VBA flag set */ - uint64_t no_vba_fail; - uint64_t arc_no_grow_set; /* number of times we set arc growth suppression time */ - uint64_t arc_no_grow; /* number of times spl_zio_is_suppressed returned true for this cache */ - - /* - * Cache properties - */ - char cache_name[KMEM_CACHE_NAMELEN + 1]; - uint32_t cache_bufsize; /* object size */ - uint32_t cache_align; /* object alignment */ - int (*cache_constructor)(void *, void *, int); - void (*cache_destructor)(void *, void *); - void (*cache_reclaim)(void *); - kmem_cbrc_t (*cache_move)(void *, void *, uint32_t, void *); - void *cache_private; /* opaque arg to callbacks */ - vmem_t *cache_arena; /* vmem source for slabs */ - int cache_cflags; /* cache creation flags */ - int cache_flags; /* various cache state info */ - uint32_t cache_mtbf; /* induced alloc failure rate */ - uint32_t cache_pad1; /* compiler padding */ - kstat_t *cache_kstat; /* exported statistics */ - list_node_t cache_link; /* cache linkage */ - - /* - * Slab layer - */ - kmutex_t cache_lock; /* protects slab layer */ - - uint32_t cache_chunksize; /* buf + alignment [+ debug] */ - uint32_t cache_slabsize; /* size of a slab */ - uint32_t cache_maxchunks; /* max buffers per slab */ - uint32_t cache_bufctl; /* buf-to-bufctl distance */ - uint32_t cache_buftag; /* buf-to-buftag distance */ - uint32_t cache_verify; /* bytes to verify */ - uint32_t cache_contents; /* bytes of saved content */ - uint32_t cache_color; /* next slab color */ - uint32_t cache_mincolor; /* maximum slab color */ - uint32_t cache_maxcolor; /* maximum slab color */ - uint32_t cache_hash_shift; /* get to interesting bits */ - uint32_t cache_hash_mask; /* hash table mask */ - list_t cache_complete_slabs; /* completely allocated slabs */ - uint32_t cache_complete_slab_count; - avl_tree_t cache_partial_slabs; /* partial slab freelist */ - uint32_t cache_partial_binshift; /* for AVL sort bins */ - kmem_cache_t *cache_bufctl_cache; /* source of bufctls */ - kmem_bufctl_t **cache_hash_table; /* hash table base */ - kmem_defrag_t *cache_defrag; /* slab consolidator fields */ - - /* - * Depot layer - */ - kmutex_t cache_depot_lock; /* protects depot */ - kmem_magtype_t *cache_magtype; /* magazine type */ - kmem_maglist_t cache_full; /* full magazines */ - kmem_maglist_t cache_empty; /* empty magazines */ - void *cache_dumpfreelist; /* heap during crash dump */ - void *cache_dumplog; /* log entry during dump */ - - /* - * Per CPU structures - */ - // XNU adjust to suit offsetof - kmem_cpu_cache_t cache_cpu[1]; /* per-cpu data */ - - } ; - - typedef struct kmem_cpu_log_header { - kmutex_t clh_lock; - char *clh_current; - uint32_t clh_avail; - int clh_chunk; - int clh_hits; -#if defined (SPL_DEBUG_MUTEX) - char clh_pad[128 - sizeof (kmutex_t) - sizeof (char *) - - sizeof (uint32_t) - 2 * sizeof (int)]; +/* + * Per CPU cache data + */ +typedef struct kmem_cpu_cache { + kmutex_t cc_lock; /* protects this cpu's local cache */ + uint64_t cc_alloc; /* allocations from this cpu */ + uint64_t cc_free; /* frees to this cpu */ + kmem_magazine_t *cc_loaded; /* the currently loaded magazine */ + kmem_magazine_t *cc_ploaded; /* the previously loaded magazine */ + int cc_flags; /* CPU-local copy of cache_flags */ + short cc_rounds; /* number of objects in loaded mag */ + short cc_prounds; /* number of objects in previous mag */ + short cc_magsize; /* number of rounds in a full mag */ + short cc_dump_rounds; /* dump time copy of cc_rounds */ + short cc_dump_prounds; /* dump time copy of cc_prounds */ + char cc_pad[KMEM_CPU_PAD]; /* for nice alignment */ +} kmem_cpu_cache_t; + +/* + * The magazine lists used in the depot. + */ +typedef struct kmem_maglist { + kmem_magazine_t *ml_list; /* magazine list */ + long ml_total; /* number of magazines */ + long ml_min; /* min since last update */ + long ml_reaplimit; /* max reapable magazines */ + uint64_t ml_alloc; /* allocations from this list */ +} kmem_maglist_t; + +typedef struct kmem_defrag { + /* + * Statistics + */ + uint64_t kmd_callbacks; /* move callbacks */ + uint64_t kmd_yes; /* KMEM_CBRC_YES responses */ + uint64_t kmd_no; /* NO responses */ + uint64_t kmd_later; /* LATER responses */ + uint64_t kmd_dont_need; /* DONT_NEED responses */ + uint64_t kmd_dont_know; /* DONT_KNOW responses */ + uint64_t kmd_hunt_found; /* DONT_KNOW: # found in mag */ + uint64_t kmd_slabs_freed; /* slabs freed by moves */ + uint64_t kmd_defrags; /* kmem_cache_defrag() */ + uint64_t kmd_scans; /* kmem_cache_scan() */ + + /* + * Consolidator fields + */ + avl_tree_t kmd_moves_pending; /* buffer moves pending */ + list_t kmd_deadlist; /* deferred slab frees */ + uint32_t kmd_deadcount; /* # of slabs in kmd_deadlist */ + uint8_t kmd_reclaim_numer; /* slab usage threshold */ + uint8_t kmd_pad1; /* compiler padding */ + uint16_t kmd_consolidate; /* triggers consolidator */ + uint32_t kmd_pad2; /* compiler padding */ + uint32_t kmd_slabs_sought; /* reclaimable slabs sought */ + uint32_t kmd_slabs_found; /* reclaimable slabs found */ + uint32_t kmd_tries; /* nth scan interval counter */ + /* + * Fields used to ASSERT that the client does not kmem_cache_free() + * objects passed to the move callback. + */ + void *kmd_from_buf; /* object to move */ + void *kmd_to_buf; /* move destination */ + kthread_t *kmd_thread; /* thread calling move */ +} kmem_defrag_t; + +/* + * Cache callback function types + */ +typedef int (*constructor_fn_t)(void*, void*, int); +typedef void (*destructor_fn_t)(void*, void*); +typedef void (*reclaim_fn_t)(void*); + +/* + * Cache + */ +struct kmem_cache { + + /* + * Statistics + */ + uint64_t cache_slab_create; /* slab creates */ + uint64_t cache_slab_destroy; /* slab destroys */ + uint64_t cache_slab_alloc; /* slab layer allocations */ + uint64_t cache_slab_free; /* slab layer frees */ + uint64_t cache_alloc_fail; /* total failed allocations */ + uint64_t cache_buftotal; /* total buffers */ + uint64_t cache_bufmax; /* max buffers ever */ + uint64_t cache_bufslab; /* buffers free in slab layer */ + uint64_t cache_reap; /* cache reaps */ + uint64_t cache_rescale; /* hash table rescales */ + uint64_t cache_lookup_depth; /* hash lookup depth */ + uint64_t cache_depot_contention; /* mutex contention count */ + uint64_t cache_depot_contention_prev; /* previous snapshot */ + uint64_t cache_alloc_count; /* Number of allocations in cache */ + uint64_t no_vba_success; /* successful calls with KM_NO_VBA set */ + uint64_t no_vba_fail; + /* number of times we set arc growth suppression time */ + uint64_t arc_no_grow_set; + /* number of times spl_zio_is_suppressed returned true for this cache */ + uint64_t arc_no_grow; + + /* + * Cache properties + */ + char cache_name[KMEM_CACHE_NAMELEN + 1]; + uint32_t cache_bufsize; /* object size */ + uint32_t cache_align; /* object alignment */ + int (*cache_constructor)(void *, void *, int); + void (*cache_destructor)(void *, void *); + void (*cache_reclaim)(void *); + kmem_cbrc_t (*cache_move)(void *, void *, uint32_t, void *); + void *cache_private; /* opaque arg to callbacks */ + vmem_t *cache_arena; /* vmem source for slabs */ + int cache_cflags; /* cache creation flags */ + int cache_flags; /* various cache state info */ + uint32_t cache_mtbf; /* induced alloc failure rate */ + uint32_t cache_pad1; /* compiler padding */ + kstat_t *cache_kstat; /* exported statistics */ + list_node_t cache_link; /* cache linkage */ + + /* + * Slab layer + */ + kmutex_t cache_lock; /* protects slab layer */ + + uint32_t cache_chunksize; /* buf + alignment [+ debug] */ + uint32_t cache_slabsize; /* size of a slab */ + uint32_t cache_maxchunks; /* max buffers per slab */ + uint32_t cache_bufctl; /* buf-to-bufctl distance */ + uint32_t cache_buftag; /* buf-to-buftag distance */ + uint32_t cache_verify; /* bytes to verify */ + uint32_t cache_contents; /* bytes of saved content */ + uint32_t cache_color; /* next slab color */ + uint32_t cache_mincolor; /* maximum slab color */ + uint32_t cache_maxcolor; /* maximum slab color */ + uint32_t cache_hash_shift; /* get to interesting bits */ + uint32_t cache_hash_mask; /* hash table mask */ + list_t cache_complete_slabs; /* completely allocated slabs */ + uint32_t cache_complete_slab_count; + avl_tree_t cache_partial_slabs; /* partial slab freelist */ + uint32_t cache_partial_binshift; /* for AVL sort bins */ + kmem_cache_t *cache_bufctl_cache; /* source of bufctls */ + kmem_bufctl_t **cache_hash_table; /* hash table base */ + kmem_defrag_t *cache_defrag; /* slab consolidator fields */ + + /* + * Depot layer + */ + kmutex_t cache_depot_lock; /* protects depot */ + kmem_magtype_t *cache_magtype; /* magazine type */ + kmem_maglist_t cache_full; /* full magazines */ + kmem_maglist_t cache_empty; /* empty magazines */ + void *cache_dumpfreelist; /* heap during crash dump */ + void *cache_dumplog; /* log entry during dump */ + + /* + * Per CPU structures + */ + // XNU adjust to suit offsetof + kmem_cpu_cache_t cache_cpu[1]; /* per-cpu data */ +}; + +typedef struct kmem_cpu_log_header { + kmutex_t clh_lock; + char *clh_current; + uint32_t clh_avail; + int clh_chunk; + int clh_hits; +#if defined(SPL_DEBUG_MUTEX) + char clh_pad[128 - sizeof (kmutex_t) - sizeof (char *) - + sizeof (uint32_t) - 2 * sizeof (int)]; #else - char clh_pad[128 - sizeof (kmutex_t) - sizeof (char *) - - sizeof (uint32_t) - 2 * sizeof (int)]; + char clh_pad[128 - sizeof (kmutex_t) - sizeof (char *) - + sizeof (uint32_t) - 2 * sizeof (int)]; #endif - } kmem_cpu_log_header_t; - - typedef struct kmem_log_header { - kmutex_t lh_lock; - char *lh_base; - int *lh_free; - uint32_t lh_chunksize; - int lh_nchunks; - int lh_head; - int lh_tail; - int lh_hits; - kmem_cpu_log_header_t lh_cpu[1]; /* ncpus actually allocated */ - } kmem_log_header_t; +} kmem_cpu_log_header_t; + +typedef struct kmem_log_header { + kmutex_t lh_lock; + char *lh_base; + int *lh_free; + uint32_t lh_chunksize; + int lh_nchunks; + int lh_head; + int lh_tail; + int lh_hits; + kmem_cpu_log_header_t lh_cpu[1]; /* ncpus actually allocated */ +} kmem_log_header_t; /* kmem_move kmm_flags */ #define KMM_DESPERATE 0x1 -#define KMM_NOTIFY 0x2 -#define KMM_DEBUG 0x4 +#define KMM_NOTIFY 0x2 +#define KMM_DEBUG 0x4 - typedef struct kmem_move { - kmem_slab_t *kmm_from_slab; - void *kmm_from_buf; - void *kmm_to_buf; - avl_node_t kmm_entry; - int kmm_flags; - } kmem_move_t; +typedef struct kmem_move { + kmem_slab_t *kmm_from_slab; + void *kmm_from_buf; + void *kmm_to_buf; + avl_node_t kmm_entry; + int kmm_flags; +} kmem_move_t; - /* - * In order to consolidate partial slabs, it must be possible for the cache to - * have partial slabs. - */ -#define KMEM_IS_MOVABLE(cp) \ +/* + * In order to consolidate partial slabs, it must be possible for the cache to + * have partial slabs. + */ +#define KMEM_IS_MOVABLE(cp) \ (((cp)->cache_chunksize * 2) <= (cp)->cache_slabsize) #pragma pack() diff --git a/include/os/windows/spl/sys/kobj.h b/include/os/windows/spl/sys/kobj.h deleted file mode 100644 index fb30531f4fa..00000000000 --- a/include/os/windows/spl/sys/kobj.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - * CDDL HEADER START - * - * The contents of this file are subject to the terms of the - * Common Development and Distribution License (the "License"). - * You may not use this file except in compliance with the License. - * - * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE - * or http://www.opensolaris.org/os/licensing. - * See the License for the specific language governing permissions - * and limitations under the License. - * - * When distributing Covered Code, include this CDDL HEADER in each - * file and include the License file at usr/src/OPENSOLARIS.LICENSE. - * If applicable, add the following below this CDDL HEADER, with the - * fields enclosed by brackets "[]" replaced with your own identifying - * information: Portions Copyright [yyyy] [name of copyright owner] - * - * CDDL HEADER END - */ -/* - * Copyright 2007 Sun Microsystems, Inc. All rights reserved. - * Use is subject to license terms. - */ - -#ifndef _SPL_KOBJ_H -#define _SPL_KOBJ_H - -#include - - -struct _buf { - intptr_t _fd; -}; - -struct bootstat { - uint64_t st_size; -}; - -//typedef struct _buf buf_t; - -extern struct _buf *kobj_open_file(char *name); -extern void kobj_close_file(struct _buf *file); -extern int kobj_read_file(struct _buf *file, char *buf, - ssize_t size, offset_t off); -extern int kobj_get_filesize(struct _buf *file, uint64_t *size); - -#endif /* SPL_KOBJ_H */ diff --git a/include/os/windows/spl/sys/kstat.h b/include/os/windows/spl/sys/kstat.h index bb7d71bc113..fbf364ede75 100644 --- a/include/os/windows/spl/sys/kstat.h +++ b/include/os/windows/spl/sys/kstat.h @@ -24,94 +24,97 @@ */ #ifndef _SPL_KSTAT_H -#define _SPL_KSTAT_H +#define _SPL_KSTAT_H #include #include #include -//#include #include /* -* Kernel statistics driver (/dev/zfs) ioctls -* Defined outside the ZFS ioctls, and handled separately in zfs_vnops_windows.c -*/ + * Kernel statistics driver (/dev/zfs) ioctls + * Defined outside the ZFS ioctls, and handled separately in + * zfs_vnops_windows.c + */ #define SPLIOCTL_TYPE 40000 -#define KSTAT_IOC_CHAIN_ID CTL_CODE(SPLIOCTL_TYPE, 0x7FD, METHOD_NEITHER, FILE_ANY_ACCESS) -#define KSTAT_IOC_READ CTL_CODE(SPLIOCTL_TYPE, 0x7FE, METHOD_NEITHER, FILE_ANY_ACCESS) -#define KSTAT_IOC_WRITE CTL_CODE(SPLIOCTL_TYPE, 0x7FF, METHOD_NEITHER, FILE_ANY_ACCESS) - +#define KSTAT_IOC_CHAIN_ID CTL_CODE(SPLIOCTL_TYPE, 0x7FD, \ + METHOD_NEITHER, FILE_ANY_ACCESS) +#define KSTAT_IOC_READ CTL_CODE(SPLIOCTL_TYPE, 0x7FE, \ + METHOD_NEITHER, FILE_ANY_ACCESS) +#define KSTAT_IOC_WRITE CTL_CODE(SPLIOCTL_TYPE, 0x7FF, \ + METHOD_NEITHER, FILE_ANY_ACCESS) -#define KSTAT_STRLEN 255 -#define KSTAT_RAW_MAX (128*1024) +#define KSTAT_STRLEN 255 +#define KSTAT_RAW_MAX (128*1024) -#if defined(_KERNEL) +#if defined(_KERNEL) -#define KSTAT_ENTER(k) \ - { kmutex_t *lp = (k)->ks_lock; if (lp) mutex_enter(lp); } +#define KSTAT_ENTER(k) \ + { kmutex_t *lp = (k)->ks_lock; if (lp) mutex_enter(lp); } -#define KSTAT_EXIT(k) \ - { kmutex_t *lp = (k)->ks_lock; if (lp) mutex_exit(lp); } +#define KSTAT_EXIT(k) \ + { kmutex_t *lp = (k)->ks_lock; if (lp) mutex_exit(lp); } -#define KSTAT_UPDATE(k, rw) (*(k)->ks_update)((k), (rw)) +#define KSTAT_UPDATE(k, rw) (*(k)->ks_update)((k), (rw)) -#define KSTAT_SNAPSHOT(k, buf, rw) (*(k)->ks_snapshot)((k), (buf), (rw)) +#define KSTAT_SNAPSHOT(k, buf, rw) (*(k)->ks_snapshot)((k), (buf), (rw)) #endif /* defined(_KERNEL) */ -/* For reference valid classes are: +/* + * For reference valid classes are: * disk, tape, net, controller, vm, kvm, hat, streams, kstat, misc */ -#define KSTAT_TYPE_RAW 0 /* can be anything; ks_ndata >= 1 */ -#define KSTAT_TYPE_NAMED 1 /* name/value pair; ks_ndata >= 1 */ -#define KSTAT_TYPE_INTR 2 /* interrupt stats; ks_ndata == 1 */ -#define KSTAT_TYPE_IO 3 /* I/O stats; ks_ndata == 1 */ -#define KSTAT_TYPE_TIMER 4 /* event timer; ks_ndata >= 1 */ -#define KSTAT_TYPE_TXG 5 /* txg sync; ks_ndata >= 1 */ -#define KSTAT_NUM_TYPES 6 - -#define KSTAT_DATA_CHAR 0 -#define KSTAT_DATA_INT32 1 -#define KSTAT_DATA_UINT32 2 -#define KSTAT_DATA_INT64 3 -#define KSTAT_DATA_UINT64 4 -#define KSTAT_DATA_LONG 5 -#define KSTAT_DATA_ULONG 6 -#define KSTAT_DATA_STRING 7 -#define KSTAT_NUM_DATAS 8 - -#define KSTAT_INTR_HARD 0 -#define KSTAT_INTR_SOFT 1 -#define KSTAT_INTR_WATCHDOG 2 -#define KSTAT_INTR_SPURIOUS 3 -#define KSTAT_INTR_MULTSVC 4 -#define KSTAT_NUM_INTRS 5 - -#define KSTAT_FLAG_VIRTUAL 0x01 -#define KSTAT_FLAG_VAR_SIZE 0x02 -#define KSTAT_FLAG_WRITABLE 0x04 -#define KSTAT_FLAG_PERSISTENT 0x08 -#define KSTAT_FLAG_DORMANT 0x10 -#define KSTAT_FLAG_UNSUPPORTED (KSTAT_FLAG_VAR_SIZE | KSTAT_FLAG_WRITABLE | \ -KSTAT_FLAG_PERSISTENT | KSTAT_FLAG_DORMANT) -#define KSTAT_FLAG_INVALID 0x20 +#define KSTAT_TYPE_RAW 0 /* can be anything; ks_ndata >= 1 */ +#define KSTAT_TYPE_NAMED 1 /* name/value pair; ks_ndata >= 1 */ +#define KSTAT_TYPE_INTR 2 /* interrupt stats; ks_ndata == 1 */ +#define KSTAT_TYPE_IO 3 /* I/O stats; ks_ndata == 1 */ +#define KSTAT_TYPE_TIMER 4 /* event timer; ks_ndata >= 1 */ +#define KSTAT_TYPE_TXG 5 /* txg sync; ks_ndata >= 1 */ +#define KSTAT_NUM_TYPES 6 + +#define KSTAT_DATA_CHAR 0 +#define KSTAT_DATA_INT32 1 +#define KSTAT_DATA_UINT32 2 +#define KSTAT_DATA_INT64 3 +#define KSTAT_DATA_UINT64 4 +#define KSTAT_DATA_LONG 5 +#define KSTAT_DATA_ULONG 6 +#define KSTAT_DATA_STRING 7 +#define KSTAT_NUM_DATAS 8 + +#define KSTAT_INTR_HARD 0 +#define KSTAT_INTR_SOFT 1 +#define KSTAT_INTR_WATCHDOG 2 +#define KSTAT_INTR_SPURIOUS 3 +#define KSTAT_INTR_MULTSVC 4 +#define KSTAT_NUM_INTRS 5 + +#define KSTAT_FLAG_VIRTUAL 0x01 +#define KSTAT_FLAG_VAR_SIZE 0x02 +#define KSTAT_FLAG_WRITABLE 0x04 +#define KSTAT_FLAG_PERSISTENT 0x08 +#define KSTAT_FLAG_DORMANT 0x10 +#define KSTAT_FLAG_UNSUPPORTED (KSTAT_FLAG_VAR_SIZE | KSTAT_FLAG_WRITABLE | \ + KSTAT_FLAG_PERSISTENT | KSTAT_FLAG_DORMANT) +#define KSTAT_FLAG_INVALID 0x20 #define KSTAT_FLAG_LONGSTRINGS 0x40 -#define KSTAT_FLAG_NO_HEADERS 0x80 +#define KSTAT_FLAG_NO_HEADERS 0x80 -#define KS_MAGIC 0x9d9d9d9d +#define KS_MAGIC 0x9d9d9d9d -#define KSTAT_NAMED_PTR(kptr) ((kstat_named_t *)(kptr)->ks_data) +#define KSTAT_NAMED_PTR(kptr) ((kstat_named_t *)(kptr)->ks_data) /* Dynamic updates */ -#define KSTAT_READ 0 -#define KSTAT_WRITE 1 +#define KSTAT_READ 0 +#define KSTAT_WRITE 1 struct kstat; -typedef int kid_t; /* unique kstat id */ -typedef int kstat_update_t(struct kstat *, int); /* dynamic update cb */ +typedef int kid_t; /* unique kstat id */ +typedef int kstat_update_t(struct kstat *, int); /* dynamic update cb */ struct seq_file { char *sf_buf; @@ -132,35 +135,35 @@ typedef struct kstat { /* * Fields relevant to both kernel and user */ - hrtime_t ks_crtime; /* creation time (from gethrtime()) */ - struct kstat *ks_next; /* kstat chain linkage */ - kid_t ks_kid; /* unique kstat ID */ - char ks_module[KSTAT_STRLEN]; /* provider module name */ - uchar_t ks_resv; /* reserved, currently just padding */ - int ks_instance; /* provider module's instance */ - char ks_name[KSTAT_STRLEN]; /* kstat name */ - uchar_t ks_type; /* kstat data type */ - char ks_class[KSTAT_STRLEN]; /* kstat class */ - uchar_t ks_flags; /* kstat flags */ - void *ks_data; /* kstat type-specific data */ - uint_t ks_ndata; /* # of type-specific data records */ - size_t ks_data_size; /* total size of kstat data section */ - hrtime_t ks_snaptime; /* time of last data shapshot */ - int ks_returnvalue; - int ks_errnovalue; - - /* - * Fields relevant to kernel only - */ + hrtime_t ks_crtime; /* creation time (from gethrtime()) */ + struct kstat *ks_next; /* kstat chain linkage */ + kid_t ks_kid; /* unique kstat ID */ + char ks_module[KSTAT_STRLEN]; /* provider module name */ + uchar_t ks_resv; /* reserved, currently just padding */ + int ks_instance; /* provider module's instance */ + char ks_name[KSTAT_STRLEN]; /* kstat name */ + uchar_t ks_type; /* kstat data type */ + char ks_class[KSTAT_STRLEN]; /* kstat class */ + uchar_t ks_flags; /* kstat flags */ + void *ks_data; /* kstat type-specific data */ + uint_t ks_ndata; /* # of type-specific data records */ + size_t ks_data_size; /* total size of kstat data section */ + hrtime_t ks_snaptime; /* time of last data shapshot */ + int ks_returnvalue; + int ks_errnovalue; + + /* + * Fields relevant to kernel only + */ int(*ks_update)(struct kstat *, int); /* dynamic update */ - void *ks_private; /* arbitrary provider-private data */ + void *ks_private; /* arbitrary provider-private data */ int(*ks_snapshot)(struct kstat *, void *, int); - void *ks_private1; /* private data */ + void *ks_private1; /* private data */ kmutex_t ks_private_lock; /* kstat private data lock */ - kmutex_t *ks_lock; /* kstat data lock */ + kmutex_t *ks_lock; /* kstat data lock */ kstat_raw_ops_t ks_raw_ops; /* ops table for raw type */ - char *ks_raw_buf; /* buf used for raw ops */ - size_t ks_raw_bufsize; /* size of raw ops buffer */ + char *ks_raw_buf; /* buf used for raw ops */ + size_t ks_raw_bufsize; /* size of raw ops buffer */ } kstat_t; #pragma pack() @@ -182,16 +185,16 @@ typedef struct kstat_named { } addr; uint32_t len; /* # bytes for strlen + '\0' */ } str; - /* - * The int64_t and uint64_t types are not valid for a maximally conformant - * 32-bit compilation environment (cc -Xc) using compilers prior to the - * introduction of C99 conforming compiler (reference ISO/IEC 9899:1990). - * In these cases, the visibility of i64 and ui64 is only permitted for - * 64-bit compilation environments or 32-bit non-maximally conformant - * C89 or C90 ANSI C compilation environments (cc -Xt and cc -Xa). In the - * C99 ANSI C compilation environment, the long long type is supported. - * The _INT64_TYPE is defined by the implementation (see sys/int_types.h). - */ +/* + * The int64_t and uint64_t types are not valid for a maximally conformant + * 32-bit compilation environment (cc -Xc) using compilers prior to the + * introduction of C99 conforming compiler (reference ISO/IEC 9899:1990). + * In these cases, the visibility of i64 and ui64 is only permitted for + * 64-bit compilation environments or 32-bit non-maximally conformant + * C89 or C90 ANSI C compilation environments (cc -Xt and cc -Xa). In the + * C99 ANSI C compilation environment, the long long type is supported. + * The _INT64_TYPE is defined by the implementation (see sys/int_types.h). + */ int64_t i64; uint64_t ui64; @@ -212,14 +215,14 @@ typedef struct kstat_named { #define KSTAT_NAMED_PTR(kptr) ((kstat_named_t *)(kptr)->ks_data) /* -* Retrieve the pointer of the string contained in the given named kstat. -*/ + * Retrieve the pointer of the string contained in the given named kstat. + */ #define KSTAT_NAMED_STR_PTR(knptr) ((knptr)->value.str.addr.ptr) /* -* Retrieve the length of the buffer required to store the string in the given -* named kstat. -*/ + * Retrieve the length of the buffer required to store the string in the given + * named kstat. + */ #define KSTAT_NAMED_STR_BUFLEN(knptr) ((knptr)->value.str.len) typedef struct kstat_intr { @@ -227,35 +230,35 @@ typedef struct kstat_intr { } kstat_intr_t; typedef struct kstat_io { - u_longlong_t nread; /* number of bytes read */ - u_longlong_t nwritten; /* number of bytes written */ - uint_t reads; /* number of read operations */ - uint_t writes; /* number of write operations */ - hrtime_t wtime; /* cumulative wait (pre-service) time */ - hrtime_t wlentime; /* cumulative wait length*time product*/ - hrtime_t wlastupdate; /* last time wait queue changed */ - hrtime_t rtime; /* cumulative run (service) time */ - hrtime_t rlentime; /* cumulative run length*time product */ - hrtime_t rlastupdate; /* last time run queue changed */ - uint_t wcnt; /* count of elements in wait state */ - uint_t rcnt; /* count of elements in run state */ + u_longlong_t nread; /* number of bytes read */ + u_longlong_t nwritten; /* number of bytes written */ + uint_t reads; /* number of read operations */ + uint_t writes; /* number of write operations */ + hrtime_t wtime; /* cumulative wait (pre-service) time */ + hrtime_t wlentime; /* cumulative wait len*time product */ + hrtime_t wlastupdate; /* last time wait queue changed */ + hrtime_t rtime; /* cumulative run (service) time */ + hrtime_t rlentime; /* cumulative run length*time product */ + hrtime_t rlastupdate; /* last time run queue changed */ + uint_t wcnt; /* count of elements in wait state */ + uint_t rcnt; /* count of elements in run state */ } kstat_io_t; typedef struct kstat_timer { - char name[KSTAT_STRLEN+1]; /* event name */ - u_longlong_t num_events; /* number of events */ - hrtime_t elapsed_time; /* cumulative elapsed time */ - hrtime_t min_time; /* shortest event duration */ - hrtime_t max_time; /* longest event duration */ - hrtime_t start_time; /* previous event start time */ - hrtime_t stop_time; /* previous event stop time */ + char name[KSTAT_STRLEN+1]; /* event name */ + u_longlong_t num_events; /* number of events */ + hrtime_t elapsed_time; /* cumulative elapsed time */ + hrtime_t min_time; /* shortest event duration */ + hrtime_t max_time; /* longest event duration */ + hrtime_t start_time; /* previous event start time */ + hrtime_t stop_time; /* previous event stop time */ } kstat_timer_t; void spl_kstat_init(void); void spl_kstat_fini(void); typedef uint64_t zoneid_t; -#define ALL_ZONES 0 +#define ALL_ZONES 0 extern kstat_t *kstat_create(const char *, int, const char *, const char *, uchar_t, uint_t, uchar_t); @@ -295,11 +298,14 @@ extern kstat_t *kstat_hold_bykid(kid_t kid, zoneid_t); extern kstat_t *kstat_hold_byname(const char *, int, const char *, zoneid_t); extern void kstat_rele(kstat_t *); -#define kstat_set_seq_raw_ops(k, h, d, a) __kstat_set_seq_raw_ops(k, h, d, a) -#define kstat_set_raw_ops(k, h, d, a) __kstat_set_raw_ops(k, h, d, a) +#define kstat_set_seq_raw_ops(k, h, d, a) __kstat_set_seq_raw_ops(k, h, d, a) +#define kstat_set_raw_ops(k, h, d, a) __kstat_set_raw_ops(k, h, d, a) -int spl_kstat_chain_id(PDEVICE_OBJECT DiskDevice, PIRP Irp, PIO_STACK_LOCATION IrpSp); -int spl_kstat_read(PDEVICE_OBJECT DiskDevice, PIRP Irp, PIO_STACK_LOCATION IrpSp); -int spl_kstat_write(PDEVICE_OBJECT DiskDevice, PIRP Irp, PIO_STACK_LOCATION IrpSp); +int spl_kstat_chain_id(PDEVICE_OBJECT DiskDevice, PIRP Irp, + PIO_STACK_LOCATION IrpSp); +int spl_kstat_read(PDEVICE_OBJECT DiskDevice, PIRP Irp, + PIO_STACK_LOCATION IrpSp); +int spl_kstat_write(PDEVICE_OBJECT DiskDevice, PIRP Irp, + PIO_STACK_LOCATION IrpSp); #endif /* _SPL_KSTAT_H */ diff --git a/include/os/windows/spl/sys/list.h b/include/os/windows/spl/sys/list.h index cfb9a7a92ab..5dd7276d9d5 100644 --- a/include/os/windows/spl/sys/list.h +++ b/include/os/windows/spl/sys/list.h @@ -23,9 +23,8 @@ * Use is subject to license terms. */ - #ifndef _SPL_LIST_H -#define _SPL_LIST_H +#define _SPL_LIST_H #include @@ -46,21 +45,16 @@ * of the list_link_init() and list_link_active() functions. */ -//typedef struct list_head list_node_t; -//#pragma pack(4) typedef struct list_node { struct list_node *list_next; struct list_node *list_prev; } list_node_t; - - typedef struct list { size_t list_size; size_t list_offset; list_node_t list_head; } list_t; -//#pragma pack() void list_create(list_t *, size_t, size_t); void list_destroy(list_t *); @@ -80,70 +74,70 @@ void *list_prev(list_t *, void *); int list_link_active(list_node_t *); int list_is_empty(list_t *); -#define LIST_POISON1 NULL -#define LIST_POISON2 NULL +#define LIST_POISON1 NULL +#define LIST_POISON2 NULL -//#define list_d2l(a, obj) ((list_node_t *)(((char *)obj) + (a)->list_offset)) -//#define list_object(a, node) ((void *)(((char *)node) - (a)->list_offset)) -#define list_d2l(a, obj) ((list_node_t *)(((uint64_t)obj) + (uint64_t)(a)->list_offset)) -#define list_object(a, node) ((void *)(((uint64_t)node) - (uint64_t)(a)->list_offset)) +#define list_d2l(a, obj) \ + ((list_node_t *)(((uint64_t)obj) + (uint64_t)(a)->list_offset)) +#define list_object(a, node) \ + ((void *)(((uint64_t)node) - (uint64_t)(a)->list_offset)) #define list_empty(a) ((a)->list_head.list_next == &(a)->list_head) static inline void list_link_init(list_node_t *node) { - node->list_next = LIST_POISON1; - node->list_prev = LIST_POISON2; + node->list_next = LIST_POISON1; + node->list_prev = LIST_POISON2; } static inline void -__list_del(list_node_t * prev, list_node_t * next) +__list_del(list_node_t *prev, list_node_t *next) { - next->list_prev = prev; - prev->list_next = next; + next->list_prev = prev; + prev->list_next = next; } static inline void list_del(list_node_t *entry) { - __list_del(entry->list_prev, entry->list_next); - entry->list_next = LIST_POISON1; - entry->list_prev = LIST_POISON2; + __list_del(entry->list_prev, entry->list_next); + entry->list_next = LIST_POISON1; + entry->list_prev = LIST_POISON2; } static inline void * list_remove_head(list_t *list) { - list_node_t *head = list->list_head.list_next; - if (head == &list->list_head) - return NULL; + list_node_t *head = list->list_head.list_next; + if (head == &list->list_head) + return (NULL); - list_del(head); - return list_object(list, head); + list_del(head); + return (list_object(list, head)); } static inline void * list_remove_tail(list_t *list) { - list_node_t *tail = list->list_head.list_prev; - if (tail == &list->list_head) - return NULL; + list_node_t *tail = list->list_head.list_prev; + if (tail == &list->list_head) + return (NULL); - list_del(tail); - return list_object(list, tail); + list_del(tail); + return (list_object(list, tail)); } static inline void list_link_replace(list_node_t *old_node, list_node_t *new_node) { - ASSERT(list_link_active(old_node)); - ASSERT(!list_link_active(new_node)); - - new_node->list_next = old_node->list_next; - new_node->list_prev = old_node->list_prev; - old_node->list_prev->list_next = new_node; - old_node->list_next->list_prev = new_node; - list_link_init(old_node); + ASSERT(list_link_active(old_node)); + ASSERT(!list_link_active(new_node)); + + new_node->list_next = old_node->list_next; + new_node->list_prev = old_node->list_prev; + old_node->list_prev->list_next = new_node; + old_node->list_next->list_prev = new_node; + list_link_init(old_node); } #endif /* SPL_LIST_H */ diff --git a/include/os/windows/spl/sys/mkdev.h b/include/os/windows/spl/sys/mkdev.h deleted file mode 100644 index 5cecac9b6fb..00000000000 --- a/include/os/windows/spl/sys/mkdev.h +++ /dev/null @@ -1,5 +0,0 @@ - -#ifndef _SPL_MKDEV_H -#define _SPL_MKDEV_H - -#endif /* SPL_MKDEV_H */ diff --git a/include/os/windows/spl/sys/mntent.h b/include/os/windows/spl/sys/mntent.h index 6b79d1edf54..73308121f99 100644 --- a/include/os/windows/spl/sys/mntent.h +++ b/include/os/windows/spl/sys/mntent.h @@ -1,5 +1,25 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ #ifndef _SPL_MNTENT_H -#define _SPL_MNTENT_H +#define _SPL_MNTENT_H #endif /* SPL_MNTENT_H */ diff --git a/include/os/windows/spl/sys/mod_os.h b/include/os/windows/spl/sys/mod_os.h index 78ef852e9b3..dc8828fe819 100644 --- a/include/os/windows/spl/sys/mod_os.h +++ b/include/os/windows/spl/sys/mod_os.h @@ -40,7 +40,7 @@ extern "C" { #ifdef _MSC_VER #define __init -#define __exit +#define __exit #else #define __init __attribute__((unused)) #define __exit __attribute__((unused)) diff --git a/include/os/windows/spl/sys/mode.h b/include/os/windows/spl/sys/mode.h deleted file mode 100644 index c2b091d3780..00000000000 --- a/include/os/windows/spl/sys/mode.h +++ /dev/null @@ -1,5 +0,0 @@ - -#ifndef _SPL_MODE_H -#define _SPL_MODE_H - -#endif /* SPL_MODE_H */ diff --git a/include/os/windows/spl/sys/mount.h b/include/os/windows/spl/sys/mount.h index c85bf7afb8f..ea87a3107fa 100644 --- a/include/os/windows/spl/sys/mount.h +++ b/include/os/windows/spl/sys/mount.h @@ -1,77 +1,85 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ #ifndef _SPL_MOUNT_H -#define _SPL_MOUNT_H - -//#undef vnode_t -//#include_next -//#define vnode_t struct vnode -#define MNT_WAIT 1 /* synchronized I/O file integrity completion */ -#define MNT_NOWAIT 2 /* start all I/O, but do not wait for it */ - -#define MNT_RDONLY 0x00000001 /* read only filesystem */ -#define MNT_SYNCHRONOUS 0x00000002 /* file system written synchronously */ -#define MNT_NOEXEC 0x00000004 /* can't exec from filesystem */ -#define MNT_NOSUID 0x00000008 /* don't honor setuid bits on fs */ -#define MNT_NODEV 0x00000010 /* don't interpret special files */ -#define MNT_UNION 0x00000020 /* union with underlying filesystem */ -#define MNT_ASYNC 0x00000040 /* file system written asynchronously */ -#define MNT_CPROTECT 0x00000080 /* file system supports content protection */ - -#define MNT_LOCAL 0x00001000 /* filesystem is stored locally */ -#define MNT_QUOTA 0x00002000 /* quotas are enabled on filesystem */ -#define MNT_ROOTFS 0x00004000 /* identifies the root filesystem */ -#define MNT_DOVOLFS 0x00008000 /* FS supports volfs (deprecated flag in Mac OS X 10.5) */ - -#define MNT_DONTBROWSE 0x00100000 /* file system is not appropriate path to user data */ -#define MNT_IGNORE_OWNERSHIP 0x00200000 /* VFS will ignore ownership information on filesystem objects */ -#define MNT_AUTOMOUNTED 0x00400000 /* filesystem was mounted by automounter */ -#define MNT_JOURNALED 0x00800000 /* filesystem is journaled */ -#define MNT_NOUSERXATTR 0x01000000 /* Don't allow user extended attributes */ -#define MNT_DEFWRITE 0x02000000 /* filesystem should defer writes */ -#define MNT_MULTILABEL 0x04000000 /* MAC support for individual labels */ -#define MNT_NOATIME 0x10000000 /* disable update of file access time */ - -#define MNT_UPDATE 0x00010000 /* not a real mount, just an update */ -#define MNT_NOBLOCK 0x00020000 /* don't block unmount if not responding */ -#define MNT_RELOAD 0x00040000 /* reload filesystem data */ -#define MNT_FORCE 0x00080000 /* force unmount or readonly change */ -#define MNT_CMDFLAGS (MNT_UPDATE|MNT_NOBLOCK|MNT_RELOAD|MNT_FORCE) - -#define MNT_UNKNOWNPERMISSIONS MNT_IGNORE_OWNERSHIP +#define _SPL_MOUNT_H + +#define MNT_WAIT 1 /* synchronized I/O file integrity completion */ +#define MNT_NOWAIT 2 /* start all I/O, but do not wait for it */ + +#define MNT_RDONLY 0x00000001 /* read only filesystem */ +#define MNT_SYNCHRONOUS 0x00000002 /* file system written synchronously */ +#define MNT_NOEXEC 0x00000004 /* can't exec from filesystem */ +#define MNT_NOSUID 0x00000008 /* don't honor setuid bits on fs */ +#define MNT_NODEV 0x00000010 /* don't interpret special files */ +#define MNT_UNION 0x00000020 /* union with underlying filesystem */ +#define MNT_ASYNC 0x00000040 /* file system written asynchronously */ +#define MNT_CPROTECT 0x00000080 /* file system supports content protection */ + +#define MNT_LOCAL 0x00001000 /* filesystem is stored locally */ +#define MNT_QUOTA 0x00002000 /* quotas are enabled on filesystem */ +#define MNT_ROOTFS 0x00004000 /* identifies the root filesystem */ +#define MNT_DOVOLFS 0x00008000 /* FS supports volfs (deprecated 10.5) */ + +#define MNT_DONTBROWSE 0x00100000 /* fs is not appropriate path to user data */ +#define MNT_IGNORE_OWNERSHIP 0x00200000 /* VFS will ignore ownership */ +#define MNT_AUTOMOUNTED 0x00400000 /* filesystem was mounted by automounter */ +#define MNT_JOURNALED 0x00800000 /* filesystem is journaled */ +#define MNT_NOUSERXATTR 0x01000000 /* Don't allow user extended attributes */ +#define MNT_DEFWRITE 0x02000000 /* filesystem should defer writes */ +#define MNT_MULTILABEL 0x04000000 /* MAC support for individual labels */ +#define MNT_NOATIME 0x10000000 /* disable update of file access time */ + +#define MNT_UPDATE 0x00010000 /* not a real mount, just an update */ +#define MNT_NOBLOCK 0x00020000 /* don't block unmount if not responding */ +#define MNT_RELOAD 0x00040000 /* reload filesystem data */ +#define MNT_FORCE 0x00080000 /* force unmount or readonly change */ +#define MNT_CMDFLAGS (MNT_UPDATE|MNT_NOBLOCK|MNT_RELOAD|MNT_FORCE) + +#define MNT_UNKNOWNPERMISSIONS MNT_IGNORE_OWNERSHIP #define MFSTYPENAMELEN 16 // Undo this OSX legacy typedef struct fsid { int32_t val[2]; } fsid_t; -//#pragma pack(4) - struct vfsstatfs { - uint32_t f_bsize; /* fundamental file system block size */ - size_t f_iosize; /* optimal transfer block size */ - uint64_t f_blocks; /* total data blocks in file system */ - uint64_t f_bfree; /* free blocks in fs */ - uint64_t f_bavail; /* free blocks avail to non-superuser */ - uint64_t f_bused; /* free blocks avail to non-superuser */ - uint64_t f_files; /* total file nodes in file system */ - uint64_t f_ffree; /* free file nodes in fs */ - fsid_t f_fsid; /* file system id */ - uid_t f_owner; /* user that mounted the filesystem */ - uint64_t f_flags; /* copy of mount exported flags */ - char f_fstypename[MFSTYPENAMELEN];/* fs type name inclus */ - char f_mntonname[MAXPATHLEN];/* directory on which mounted */ - char f_mntfromname[MAXPATHLEN];/* mounted filesystem */ - uint32_t f_fssubtype; /* fs sub-type (flavor) */ - void *f_reserved[2]; /* For future use == 0 */ + uint32_t f_bsize; /* fundamental file system block size */ + size_t f_iosize; /* optimal transfer block size */ + uint64_t f_blocks; /* total data blocks in file system */ + uint64_t f_bfree; /* free blocks in fs */ + uint64_t f_bavail; /* free blocks avail to non-superuser */ + uint64_t f_bused; /* free blocks avail to non-superuser */ + uint64_t f_files; /* total file nodes in file system */ + uint64_t f_ffree; /* free file nodes in fs */ + fsid_t f_fsid; /* file system id */ + uid_t f_owner; /* user that mounted the filesystem */ + uint64_t f_flags; /* copy of mount exported flags */ + char f_fstypename[MFSTYPENAMELEN]; /* fs type name inclus */ + char f_mntonname[MAXPATHLEN]; /* dir on which mounted */ + char f_mntfromname[MAXPATHLEN]; /* mounted filesystem */ + uint32_t f_fssubtype; /* fs sub-type (flavor) */ + void *f_reserved[2]; /* For future use == 0 */ }; -//#pragma pack() - -//enum mount_type { -// MOUNT_TYPE_DCB = 231, // diskObject (most entries not used, should be own struct?) -// MOUNT_TYPE_VCB // fsObject -//}; - typedef enum _FSD_IDENTIFIER_TYPE { MOUNT_TYPE_DGL = ':DGL', // Dokan Global MOUNT_TYPE_DCB = ':DCB', // Disk Control Block @@ -80,14 +88,12 @@ typedef enum _FSD_IDENTIFIER_TYPE { MOUNT_TYPE_CCB = ':CCB', // Context Control Block } FSD_IDENTIFIER_TYPE; - typedef enum mount_type mount_type_t; struct mount { FSD_IDENTIFIER_TYPE type; ULONG size; -// mount_type_t type; void *fsprivate; void *parent_device; // Only set so vcd can find dcb PDEVICE_OBJECT deviceObject; @@ -111,23 +117,22 @@ struct mount }; typedef struct mount mount_t; typedef struct mount vfsp_t; -#define LK_NOWAIT 1 - -int vfs_busy(mount_t *mp, int flags); -void vfs_unbusy(mount_t *mp); -int vfs_isrdonly(mount_t *mp); -void * vfs_fsprivate(mount_t *mp); -void vfs_setfsprivate(mount_t *mp, void *mntdata); -void vfs_clearflags(mount_t *mp, uint64_t flags); -void vfs_setflags(mount_t *mp, uint64_t flags); +#define LK_NOWAIT 1 + +int vfs_busy(mount_t *mp, int flags); +void vfs_unbusy(mount_t *mp); +int vfs_isrdonly(mount_t *mp); +void *vfs_fsprivate(mount_t *mp); +void vfs_setfsprivate(mount_t *mp, void *mntdata); +void vfs_clearflags(mount_t *mp, uint64_t flags); +void vfs_setflags(mount_t *mp, uint64_t flags); struct vfsstatfs *vfs_statfs(mount_t *mp); uint64_t vfs_flags(mount_t *mp); -void vfs_setlocklocal(mount_t *mp); -int vfs_typenum(mount_t *mp); -void vfs_getnewfsid(struct mount *mp); -int vfs_isunmount(mount_t *mp); -int vfs_iswriteupgrade(mount_t *mp); -void vfs_setextendedsecurity(mount_t *mp); - +void vfs_setlocklocal(mount_t *mp); +int vfs_typenum(mount_t *mp); +void vfs_getnewfsid(struct mount *mp); +int vfs_isunmount(mount_t *mp); +int vfs_iswriteupgrade(mount_t *mp); +void vfs_setextendedsecurity(mount_t *mp); #endif /* SPL_MOUNT_H */ diff --git a/include/os/windows/spl/sys/mutex.h b/include/os/windows/spl/sys/mutex.h index 947a1878075..43a685c8679 100644 --- a/include/os/windows/spl/sys/mutex.h +++ b/include/os/windows/spl/sys/mutex.h @@ -1,29 +1,29 @@ /* -* CDDL HEADER START -* -* The contents of this file are subject to the terms of the -* Common Development and Distribution License (the "License"). -* You may not use this file except in compliance with the License. -* -* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE -* or http://www.opensolaris.org/os/licensing. -* See the License for the specific language governing permissions -* and limitations under the License. -* -* When distributing Covered Code, include this CDDL HEADER in each -* file and include the License file at usr/src/OPENSOLARIS.LICENSE. -* If applicable, add the following below this CDDL HEADER, with the -* fields enclosed by brackets "[]" replaced with your own identifying -* information: Portions Copyright [yyyy] [name of copyright owner] -* -* CDDL HEADER END -*/ + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ /* -* -* Copyright (C) 2017 Jorgen Lundman -* -*/ + * + * Copyright (C) 2017 Jorgen Lundman + * + */ #ifndef WINDOWS_MUTEX_H #define WINDOWS_MUTEX_H @@ -51,10 +51,10 @@ typedef enum { - MUTEX_ADAPTIVE = 0, /* spin if owner is running, otherwise block */ - MUTEX_SPIN = 1, /* block interrupts and spin */ - MUTEX_DRIVER = 4, /* driver (DDI) mutex */ - MUTEX_DEFAULT = 6 /* kernel default mutex */ + MUTEX_ADAPTIVE = 0, /* spin if owner is running, otherwise block */ + MUTEX_SPIN = 1, /* block interrupts and spin */ + MUTEX_DRIVER = 4, /* driver (DDI) mutex */ + MUTEX_DEFAULT = 6 /* kernel default mutex */ } kmutex_type_t; typedef struct { @@ -70,23 +70,22 @@ typedef struct { */ typedef struct kmutex { - mutex_t m_lock; - void *m_owner; - unsigned int initialised; - unsigned int set_event_guard; + mutex_t m_lock; + void *m_owner; + unsigned int m_set_event_guard; + unsigned int m_initialised; } kmutex_t; +#define MUTEX_HELD(x) (mutex_owned(x)) +#define MUTEX_NOT_HELD(x) (!mutex_owned(x)) -#define MUTEX_HELD(x) (mutex_owned(x)) -#define MUTEX_NOT_HELD(x) (!mutex_owned(x)) - -#define mutex_init spl_mutex_init +#define mutex_init spl_mutex_init void spl_mutex_init(kmutex_t *mp, char *name, kmutex_type_t type, void *ibc); -#define mutex_enter spl_mutex_enter +#define mutex_enter spl_mutex_enter void spl_mutex_enter(kmutex_t *mp); -#define mutex_enter_nested(A, B) mutex_enter(A) +#define mutex_enter_nested(A, B) mutex_enter(A) #define MUTEX_NOLOCKDEP 0 #define mutex_destroy spl_mutex_destroy diff --git a/include/os/windows/spl/sys/note.h b/include/os/windows/spl/sys/note.h index 020031e5562..b460b2f71ac 100644 --- a/include/os/windows/spl/sys/note.h +++ b/include/os/windows/spl/sys/note.h @@ -1,5 +1,25 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ #ifndef _SPL_NOTE_H -#define _SPL_NOTE_H +#define _SPL_NOTE_H #endif /* SPL_NOTE_H */ diff --git a/include/os/windows/spl/sys/open.h b/include/os/windows/spl/sys/open.h deleted file mode 100644 index 791791d4e5a..00000000000 --- a/include/os/windows/spl/sys/open.h +++ /dev/null @@ -1,5 +0,0 @@ - -#ifndef _SPL_OPEN_H -#define _SPL_OPEN_H - -#endif /* SPL_OPEN_H */ diff --git a/include/os/windows/spl/sys/param.h b/include/os/windows/spl/sys/param.h index cf1fbf0d26e..bbe6b63c113 100644 --- a/include/os/windows/spl/sys/param.h +++ b/include/os/windows/spl/sys/param.h @@ -1,17 +1,34 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ #ifndef _SPL_PARAM_H -#define _SPL_PARAM_H - -//#include_next -//#include +#define _SPL_PARAM_H /* Pages to bytes and back */ -#define ptob(pages) (pages << PAGE_SHIFT) -#define btop(bytes) (bytes >> PAGE_SHIFT) +#define ptob(pages) (pages << PAGE_SHIFT) +#define btop(bytes) (bytes >> PAGE_SHIFT) #ifndef howmany -#define howmany(x, y) ((((x) % (y)) == 0) ? ((x) / (y)) : (((x) / (y)) + 1)) +#define howmany(x, y) ((((x) % (y)) == 0) ? ((x) / (y)) : (((x) / (y)) + 1)) #endif -#define MAXUID UINT32_MAX +#define MAXUID UINT32_MAX #endif /* SPL_PARAM_H */ diff --git a/include/os/windows/spl/sys/pool.h b/include/os/windows/spl/sys/pool.h deleted file mode 100644 index e8fb9c75ec8..00000000000 --- a/include/os/windows/spl/sys/pool.h +++ /dev/null @@ -1,7 +0,0 @@ - -#ifndef _SPL_POOL_H -#define _SPL_POOL_H - -#include - -#endif /* SPL_POOL_H */ diff --git a/include/os/windows/spl/sys/priv.h b/include/os/windows/spl/sys/priv.h index 8a3ddd54303..a5239bb3ed8 100644 --- a/include/os/windows/spl/sys/priv.h +++ b/include/os/windows/spl/sys/priv.h @@ -1,4 +1,4 @@ -/*- +/* * Copyright (c) 2006 nCircle Network Security, Inc. * All rights reserved. * @@ -33,7 +33,7 @@ * Privilege checking interface for BSD kernel. */ #ifndef _SPL_PRIV_H -#define _SPL_PRIV_H +#define _SPL_PRIV_H /* * Privilege list, sorted loosely by kernel subsystem. @@ -231,10 +231,8 @@ * ZFS-specific privileges. */ #define PRIV_ZFS_POOL_CONFIG 280 /* Can configure ZFS pools. */ -#define PRIV_ZFS_INJECT 281 /* Can inject faults in the ZFS fault - injection framework. */ -#define PRIV_ZFS_JAIL 282 /* Can attach/detach ZFS file systems - to/from jails. */ +#define PRIV_ZFS_INJECT 281 /* Can inject faults to framework. */ +#define PRIV_ZFS_JAIL 282 /* Can attach/detach to/from jails. */ /* * NFS-specific privileges. @@ -269,7 +267,7 @@ #define PRIV_VFS_MKNOD_DEV 331 /* Can mknod() to create dev nodes. */ #define PRIV_VFS_MKNOD_WHT 332 /* Can mknod() to create whiteout. */ #define PRIV_VFS_MOUNT 333 /* Can mount(). */ -#define PRIV_VFS_MOUNT_OWNER 334 /* Can manage other users' file systems. */ +#define PRIV_VFS_MOUNT_OWNER 334 /* Can manage other users' fs. */ #define PRIV_VFS_MOUNT_EXPORTED 335 /* Can set MNT_EXPORTED on mount. */ #define PRIV_VFS_MOUNT_PERM 336 /* Override dev node perms at mount. */ #define PRIV_VFS_MOUNT_SUIDDIR 337 /* Can set MNT_SUIDDIR on mount. */ @@ -287,14 +285,8 @@ #define PRIV_VM_MADV_PROTECT 360 /* Can set MADV_PROTECT. */ #define PRIV_VM_MLOCK 361 /* Can mlock(), mlockall(). */ #define PRIV_VM_MUNLOCK 362 /* Can munlock(), munlockall(). */ -#define PRIV_VM_SWAP_NOQUOTA 363 /* - * Can override the global - * swap reservation limits. - */ -#define PRIV_VM_SWAP_NORLIMIT 364 /* - * Can override the per-uid - * swap reservation limits. - */ +#define PRIV_VM_SWAP_NOQUOTA 363 +#define PRIV_VM_SWAP_NORLIMIT 364 /* * Device file system privileges. @@ -473,8 +465,8 @@ /* * cpuctl(4) privileges. */ -#define PRIV_CPUCTL_WRMSR 640 /* Write model-specific register. */ -#define PRIV_CPUCTL_UPDATE 641 /* Update cpu microcode. */ +#define PRIV_CPUCTL_WRMSR 640 /* Write model-specific register. */ +#define PRIV_CPUCTL_UPDATE 641 /* Update cpu microcode. */ /* * Capi4BSD privileges. diff --git a/include/os/windows/spl/sys/priv_impl.h b/include/os/windows/spl/sys/priv_impl.h deleted file mode 100644 index dadbf32f021..00000000000 --- a/include/os/windows/spl/sys/priv_impl.h +++ /dev/null @@ -1,5 +0,0 @@ - -#ifndef _SPL_PRIV_IMPL_H -#define _SPL_PRIV_IMPL_H - -#endif /* _SPL_PRIV_IMPL_H */ diff --git a/include/os/windows/spl/sys/proc.h b/include/os/windows/spl/sys/proc.h index 189a4e3554e..cf47b6f7473 100644 --- a/include/os/windows/spl/sys/proc.h +++ b/include/os/windows/spl/sys/proc.h @@ -1,6 +1,26 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ #ifndef _SPL_PROC_H -#define _SPL_PROC_H +#define _SPL_PROC_H #include @@ -9,7 +29,7 @@ typedef struct _KPROCESS proc_t; extern proc_t p0; #define current_proc PsGetCurrentProcess -#define getpid() PsGetProcessId(PsGetCurrentProcess()) +#define getpid() PsGetProcessId(PsGetCurrentProcess()) static inline boolean_t zfs_proc_is_caller(proc_t *p) @@ -20,7 +40,7 @@ zfs_proc_is_caller(proc_t *p) static inline char * getcomm(void) { - return "procname"; // WIN32 me + return ("procname"); // WIN32 me } #endif /* SPL_PROC_H */ diff --git a/include/os/windows/spl/sys/pset.h b/include/os/windows/spl/sys/pset.h deleted file mode 100644 index 4406e1c1071..00000000000 --- a/include/os/windows/spl/sys/pset.h +++ /dev/null @@ -1,15 +0,0 @@ - -#ifndef _SPL_PSET_H -#define _SPL_PSET_H - -typedef int psetid_t; - -/* special processor set id's */ -#define PS_NONE -1 -#define PS_QUERY -2 -#define PS_MYID -3 -#define PS_SOFT -4 -#define PS_HARD -5 -#define PS_QUERY_TYPE -6 - -#endif /* SPL_PSET_H */ diff --git a/include/os/windows/spl/sys/random.h b/include/os/windows/spl/sys/random.h index a7070280e51..f1d558986cb 100644 --- a/include/os/windows/spl/sys/random.h +++ b/include/os/windows/spl/sys/random.h @@ -28,10 +28,7 @@ #ifndef _SPL_RANDOM_H #define _SPL_RANDOM_H -//#include_next - - extern int random_get_bytes(uint8_t *ptr, uint32_t len); -#define random_get_pseudo_bytes random_get_bytes +#define random_get_pseudo_bytes random_get_bytes #endif /* _SPL_RANDOM_H */ diff --git a/include/os/windows/spl/sys/refstr.h b/include/os/windows/spl/sys/refstr.h deleted file mode 100644 index 2b640f19357..00000000000 --- a/include/os/windows/spl/sys/refstr.h +++ /dev/null @@ -1,5 +0,0 @@ - -#ifndef _SPL_REFSTR_H -#define _SPL_REFSTR_H - -#endif /* SPL_REFSTR_H */ diff --git a/include/os/windows/spl/sys/resource.h b/include/os/windows/spl/sys/resource.h index e6234c3d014..5e1bf347e61 100644 --- a/include/os/windows/spl/sys/resource.h +++ b/include/os/windows/spl/sys/resource.h @@ -1,7 +1,25 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ #ifndef _SPL_RESOURCE_H -#define _SPL_RESOURCE_H - -//#include_next +#define _SPL_RESOURCE_H #endif /* SPL_RESOURCE_H */ diff --git a/include/os/windows/spl/sys/rwlock.h b/include/os/windows/spl/sys/rwlock.h index 9728e9155f5..222ee3848d6 100644 --- a/include/os/windows/spl/sys/rwlock.h +++ b/include/os/windows/spl/sys/rwlock.h @@ -23,27 +23,26 @@ */ #ifndef _SPL_RWLOCK_H -#define _SPL_RWLOCK_H +#define _SPL_RWLOCK_H #include -//#include typedef enum { - RW_DRIVER = 2, - RW_DEFAULT = 4 + RW_DRIVER = 2, + RW_DEFAULT = 4 } krw_type_t; typedef enum { - RW_NONE = 0, - RW_WRITER = 1, - RW_READER = 2 + RW_NONE = 0, + RW_WRITER = 1, + RW_READER = 2 } krw_t; struct krwlock { - ERESOURCE rw_lock; /* opaque data */ - void *rw_owner; /* writer (exclusive) lock only */ - int rw_readers; /* reader lock only */ - int rw_pad; /* */ + ERESOURCE rw_lock; /* opaque data */ + void *rw_owner; /* writer (exclusive) lock only */ + int rw_readers; /* reader lock only */ + int rw_pad; }; typedef struct krwlock krwlock_t; diff --git a/include/os/windows/spl/sys/sched.h b/include/os/windows/spl/sys/sched.h index 104244a69cd..c4955c20e99 100644 --- a/include/os/windows/spl/sys/sched.h +++ b/include/os/windows/spl/sys/sched.h @@ -1,37 +1,27 @@ -#ifndef OSX_SCHED_H -#define OSX_SCHED_H +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ + +#ifndef WINDOWS_SCHED_H +#define WINDOWS_SCHED_H #include - -#if 0 -typedef void (task_func_t)(void *); - -typedef struct task { - struct task *task_next; - struct task *task_prev; - task_func_t *task_func; - void *task_arg; -} task_t; - -#define TASKQ_ACTIVE 0x00010000 - -struct taskq { - kmutex_t tq_lock; - krwlock_t tq_threadlock; - kcondvar_t tq_dispatch_cv; - kcondvar_t tq_wait_cv; - thread_t *tq_threadlist; - int tq_flags; - int tq_active; - int tq_nthreads; - int tq_nalloc; - int tq_minalloc; - int tq_maxalloc; - task_t *tq_freelist; - task_t tq_task; -}; - -#endif - #endif diff --git a/include/os/windows/spl/sys/sdt.h b/include/os/windows/spl/sys/sdt.h deleted file mode 100644 index d6a826c58c8..00000000000 --- a/include/os/windows/spl/sys/sdt.h +++ /dev/null @@ -1,5 +0,0 @@ - -#ifndef _SPL_SDT_H -#define _SPL_SDT_H - -#endif /* SPL_SDT_H */ diff --git a/include/os/windows/spl/sys/seg_kmem.h b/include/os/windows/spl/sys/seg_kmem.h index a8861d9edd9..bd526a7f4fc 100644 --- a/include/os/windows/spl/sys/seg_kmem.h +++ b/include/os/windows/spl/sys/seg_kmem.h @@ -31,45 +31,22 @@ extern "C" { #endif -//#include -//#include #include -//#include -//#include -//#include - /* - * VM - Kernel Segment Driver - */ +/* + * VM - Kernel Segment Driver + */ #if defined(_KERNEL) - extern uint64_t segkmem_total_allocated; - -// extern char *kernelheap; /* start of primary kernel heap */ -// extern char *ekernelheap; /* end of primary kernel heap */ -// extern char *heap_lp_base; /* start of kernel large page heap arena */ -// extern char *heap_lp_end; /* end of kernel large page heap arena */ -// extern struct seg kvseg; /* primary kernel heap segment */ -// extern struct seg kvseg_core; /* "core" kernel heap segment */ -// extern struct seg kzioseg; /* Segment for zio mappings */ -// extern vmem_t *heap_lp_arena; /* kernel large page heap arena */ -// extern vmem_t *heap_arena; /* primary kernel heap arena */ -// extern vmem_t *hat_memload_arena; /* HAT translation arena */ -// extern struct seg kvseg32; /* 32-bit kernel heap segment */ -// extern vmem_t *heap32_arena; /* 32-bit kernel heap arena */ -// extern vmem_t *heaptext_arena; /* kernel text arena, from heap */ -// extern struct as kas; /* kernel address space */ -// extern int segkmem_reloc; /* enable/disable segkmem relocatable pages */ -// extern vmem_t *static_arena; /* arena for caches to import static memory */ -// extern vmem_t *static_alloc_arena; /* arena for allocating static memory */ - extern vmem_t *zio_arena_parent; /* qcaching for zio arenas and abd arena */ - extern vmem_t *zio_arena; /* arena for zio caches for file blocks */ - extern vmem_t *zio_metadata_arena; /* arena for zio caches for (zfs) metadata blocks */ -// extern struct vnode kvps[]; - /* - * segkmem page vnodes - */ +extern uint64_t segkmem_total_allocated; +extern vmem_t *zio_arena_parent; /* qcaching for zio arenas and abd arena */ +extern vmem_t *zio_arena; /* arena for zio caches for file blocks */ +extern vmem_t *zio_metadata_arena; /* zio caches for (zfs) metadata */ + +/* + * segkmem page vnodes + */ #define kvp (kvps[KV_KVP]) #define zvp (kvps[KV_ZVP]) #if defined(__sparc) @@ -77,69 +54,33 @@ extern "C" { #define promvp (kvps[KV_PROMVP]) #endif /* __sparc */ -// extern int segkmem_create(struct seg *); -// extern page_t *segkmem_page_create(void *, uint32_t, int, void *); -// extern void *segkmem_xalloc(vmem_t *, void *, uint32_t, int, uint_t, -// page_t *(*page_create_func)(void *, uint32_t, int, void *), void *); - void *segkmem_alloc(vmem_t *, uint32_t, int); -// extern void *segkmem_alloc_permanent(vmem_t *, uint32_t, int); - extern void segkmem_free(vmem_t *, void *, uint32_t); -// extern void segkmem_xfree(vmem_t *, void *, uint32_t, void (*)(page_t *)); - -// extern void *boot_alloc(void *, uint32_t, uint_t); -// extern void boot_mapin(caddr_t addr, uint32_t size); - extern void kernelheap_init(void); - extern void kernelheap_fini(void); -// extern void segkmem_gc(void); - - extern void *segkmem_zio_alloc(vmem_t *, uint32_t, int); -// extern int segkmem_zio_create(struct seg *); - extern void segkmem_zio_free(vmem_t *, void *, uint32_t); - extern void segkmem_zio_init(void); - extern void segkmem_zio_fini(void); - - /* - * Flags for segkmem_xalloc(). - * - * SEGKMEM_SHARELOCKED requests pages which are locked SE_SHARED to be - * returned rather than unlocked which is now the default. Note that - * memory returned by SEGKMEM_SHARELOCKED cannot be freed by segkmem_free(). - * This is a hack for seg_dev that should be cleaned up in the future. - */ +void *segkmem_alloc(vmem_t *, uint32_t, int); +extern void segkmem_free(vmem_t *, void *, uint32_t); +extern void kernelheap_init(void); +extern void kernelheap_fini(void); +extern void *segkmem_zio_alloc(vmem_t *, uint32_t, int); +extern void segkmem_zio_free(vmem_t *, void *, uint32_t); +extern void segkmem_zio_init(void); +extern void segkmem_zio_fini(void); + +/* + * Flags for segkmem_xalloc(). + * + * SEGKMEM_SHARELOCKED requests pages which are locked SE_SHARED to be + * returned rather than unlocked which is now the default. Note that + * memory returned by SEGKMEM_SHARELOCKED cannot be freed by segkmem_free(). + * This is a hack for seg_dev that should be cleaned up in the future. + */ #define SEGKMEM_SHARELOCKED 0x20000 - /* - * Large page for kmem caches support - */ -// typedef struct segkmem_lpcb { -// kmutex_t lp_lock; -// kcondvar_t lp_cv; -// uint_t lp_wait; -// uint_t lp_uselp; -// ulong_t lp_throttle; - - /* stats */ -// uint64_t sleep_allocs_failed; -// uint64_t nosleep_allocs_failed; -// uint64_t allocs_throttled; -// uint64_t allocs_limited; -// uint64_t alloc_bytes_failed; -// } segkmem_lpcb_t; - -// extern void *segkmem_alloc_lp(vmem_t *, uint32_t *, uint32_t, int); -// extern void segkmem_free_lp(vmem_t *, void *, uint32_t); -// extern int segkmem_lpsetup(); -// extern void segkmem_heap_lp_init(void); - -// extern uint32_t segkmem_lpsize; -// extern int segkmem_lpszc; -// extern uint32_t segkmem_heaplp_quantum; -// extern uint32_t segkmem_kmemlp_max; +/* + * Large page for kmem caches support + */ #define SEGKMEM_USE_LARGEPAGES (segkmem_lpsize > PAGESIZE) -#define IS_KMEM_VA_LARGEPAGE(vaddr) \ -(((vaddr) >= heap_lp_base) && ((vaddr) < heap_lp_end)) +#define IS_KMEM_VA_LARGEPAGE(vaddr) \ + (((vaddr) >= heap_lp_base) && ((vaddr) < heap_lp_end)) #endif /* _KERNEL */ diff --git a/include/os/windows/spl/sys/sid.h b/include/os/windows/spl/sys/sid.h index cbe9c499e0f..fab1cdf22d1 100644 --- a/include/os/windows/spl/sys/sid.h +++ b/include/os/windows/spl/sys/sid.h @@ -24,9 +24,8 @@ * Use is subject to license terms. */ - #ifndef _SPL_SID_H -#define _SPL_SID_H +#define _SPL_SID_H #ifdef __cplusplus extern "C" { @@ -53,49 +52,49 @@ typedef int32_t idmap_stat; static inline ksiddomain_t * ksid_lookupdomain(const char *dom) { - ksiddomain_t *kd; - int len = strlen(dom); + ksiddomain_t *kd; + int len = strlen(dom); - kd = (ksiddomain_t *)kmem_zalloc(sizeof(ksiddomain_t), KM_SLEEP); - kd->kd_name = (char *)kmem_zalloc(len + 1, KM_SLEEP); + kd = (ksiddomain_t *)kmem_zalloc(sizeof (ksiddomain_t), KM_SLEEP); + kd->kd_name = (char *)kmem_zalloc(len + 1, KM_SLEEP); memcpy(kd->kd_name, dom, len); - return (kd); + return (kd); } static inline void ksiddomain_rele(ksiddomain_t *ksid) { kmem_free(ksid->kd_name, strlen(ksid->kd_name) + 1); - kmem_free(ksid, sizeof(ksiddomain_t)); + kmem_free(ksid, sizeof (ksiddomain_t)); } -#define UID_NOBODY 65534 -#define GID_NOBODY 65534 +#define UID_NOBODY 65534 +#define GID_NOBODY 65534 static __inline uint_t ksid_getid(ksid_t *ks) { - panic("%s has been unexpectedly called", __func__); - return 0; + panic("%s has been unexpectedly called", __func__); + return (0); } static __inline const char * ksid_getdomain(ksid_t *ks) { - panic("%s has been unexpectedly called", __func__); - return 0; + panic("%s has been unexpectedly called", __func__); + return (0); } static __inline uint_t ksid_getrid(ksid_t *ks) { - panic("%s has been unexpectedly called", __func__); - return 0; + panic("%s has been unexpectedly called", __func__); + return (0); } -#define kidmap_getsidbyuid(zone, uid, sid_prefix, rid) (1) -#define kidmap_getsidbygid(zone, gid, sid_prefix, rid) (1) +#define kidmap_getsidbyuid(zone, uid, sid_prefix, rid) (1) +#define kidmap_getsidbygid(zone, gid, sid_prefix, rid) (1) #ifdef __cplusplus } diff --git a/include/os/windows/spl/sys/signal.h b/include/os/windows/spl/sys/signal.h index b0767b6d141..30ff1c4533d 100644 --- a/include/os/windows/spl/sys/signal.h +++ b/include/os/windows/spl/sys/signal.h @@ -39,28 +39,24 @@ #ifndef _SPL_SIGNAL_H -#define _SPL_SIGNAL_H +#define _SPL_SIGNAL_H #include -//#include #include #include -//#include_next #define FORREAL 0 /* Usual side-effects */ #define JUSTLOOKING 1 /* Don't stop the process */ struct proc; -//extern int -//thread_issignal(struct proc *, thread_t, sigset_t); - typedef struct __siginfo { /* Windows version goes here */ void *si_addr; } siginfo_t; -/* The "why" argument indicates the allowable side-effects of the call: +/* + * The "why" argument indicates the allowable side-effects of the call: * * FORREAL: Extract the next pending signal from p_sig into p_cursig; * stop the process if a stop has been requested or if a traced signal @@ -69,19 +65,19 @@ typedef struct __siginfo { * JUSTLOOKING: Don't stop the process, just indicate whether or not * a signal might be pending (FORREAL is needed to tell for sure). */ -#define threadmask (sigmask(SIGILL)|sigmask(SIGTRAP)|\ - sigmask(SIGIOT)|sigmask(SIGEMT)|\ - sigmask(SIGFPE)|sigmask(SIGBUS)|\ - sigmask(SIGSEGV)|sigmask(SIGSYS)|\ - sigmask(SIGPIPE)|sigmask(SIGKILL)|\ - sigmask(SIGTERM)|sigmask(SIGINT)) +#define threadmask (sigmask(SIGILL)|sigmask(SIGTRAP)|\ + sigmask(SIGIOT)|sigmask(SIGEMT)| \ + sigmask(SIGFPE)|sigmask(SIGBUS)| \ + sigmask(SIGSEGV)|sigmask(SIGSYS)| \ + sigmask(SIGPIPE)|sigmask(SIGKILL)| \ + sigmask(SIGTERM)|sigmask(SIGINT)) static inline int issig(int why) { - return 0; + return (0); } -#define signal_pending(p) issig(0) +#define signal_pending(p) issig(0) #endif /* SPL_SIGNAL_H */ diff --git a/include/os/windows/spl/sys/simd.h b/include/os/windows/spl/sys/simd.h index 86413d5d162..a1de04f9410 100644 --- a/include/os/windows/spl/sys/simd.h +++ b/include/os/windows/spl/sys/simd.h @@ -79,7 +79,6 @@ #ifndef __clang__ #include #endif -//#include #ifdef _WIN32 // XNU fpu.h @@ -727,4 +726,3 @@ zfs_avx512vbmi_available(void) #endif /* defined(__x86) */ #endif /* _SIMD_X86_H */ - diff --git a/include/os/windows/spl/sys/stat.h b/include/os/windows/spl/sys/stat.h index 9a842aeccaf..2eff738cd18 100644 --- a/include/os/windows/spl/sys/stat.h +++ b/include/os/windows/spl/sys/stat.h @@ -1,47 +1,66 @@ -#ifndef _SPL_STAT_H -#define _SPL_STAT_H +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ -//#include_next +#ifndef _SPL_STAT_H +#define _SPL_STAT_H #ifndef S_IFMT /* File type */ -#define S_IFMT 0170000 /* [XSI] type of file mask */ -#define S_IFIFO 0010000 /* [XSI] named pipe (fifo) */ -#define S_IFCHR 0020000 /* [XSI] character special */ -#define S_IFDIR 0040000 /* [XSI] directory */ -#define S_IFBLK 0060000 /* [XSI] block special */ -#define S_IFREG 0100000 /* [XSI] regular */ -#define S_IFLNK 0120000 /* [XSI] symbolic link */ -#define S_IFSOCK 0140000 /* [XSI] socket */ -#if !defined(_POSIX_C_SOURCE) -#define S_IFWHT 0160000 /* OBSOLETE: whiteout */ +#define S_IFMT 0170000 /* [XSI] type of file mask */ +#define S_IFIFO 0010000 /* [XSI] named pipe (fifo) */ +#define S_IFCHR 0020000 /* [XSI] character special */ +#define S_IFDIR 0040000 /* [XSI] directory */ +#define S_IFBLK 0060000 /* [XSI] block special */ +#define S_IFREG 0100000 /* [XSI] regular */ +#define S_IFLNK 0120000 /* [XSI] symbolic link */ +#define S_IFSOCK 0140000 /* [XSI] socket */ +#if !defined(_POSIX_C_SOURCE) +#define S_IFWHT 0160000 /* OBSOLETE: whiteout */ #endif /* File mode */ /* Read, write, execute/search by owner */ -#define S_IRWXU 0000700 /* [XSI] RWX mask for owner */ -#define S_IRUSR 0000400 /* [XSI] R for owner */ -#define S_IWUSR 0000200 /* [XSI] W for owner */ -#define S_IXUSR 0000100 /* [XSI] X for owner */ +#define S_IRWXU 0000700 /* [XSI] RWX mask for owner */ +#define S_IRUSR 0000400 /* [XSI] R for owner */ +#define S_IWUSR 0000200 /* [XSI] W for owner */ +#define S_IXUSR 0000100 /* [XSI] X for owner */ /* Read, write, execute/search by group */ -#define S_IRWXG 0000070 /* [XSI] RWX mask for group */ -#define S_IRGRP 0000040 /* [XSI] R for group */ -#define S_IWGRP 0000020 /* [XSI] W for group */ -#define S_IXGRP 0000010 /* [XSI] X for group */ +#define S_IRWXG 0000070 /* [XSI] RWX mask for group */ +#define S_IRGRP 0000040 /* [XSI] R for group */ +#define S_IWGRP 0000020 /* [XSI] W for group */ +#define S_IXGRP 0000010 /* [XSI] X for group */ /* Read, write, execute/search by others */ -#define S_IRWXO 0000007 /* [XSI] RWX mask for other */ -#define S_IROTH 0000004 /* [XSI] R for other */ -#define S_IWOTH 0000002 /* [XSI] W for other */ -#define S_IXOTH 0000001 /* [XSI] X for other */ +#define S_IRWXO 0000007 /* [XSI] RWX mask for other */ +#define S_IROTH 0000004 /* [XSI] R for other */ +#define S_IWOTH 0000002 /* [XSI] W for other */ +#define S_IXOTH 0000001 /* [XSI] X for other */ -#define S_ISUID 0004000 /* [XSI] set user id on execution */ -#define S_ISGID 0002000 /* [XSI] set group id on execution */ -#define S_ISVTX 0001000 /* [XSI] directory restrcted delete */ +#define S_ISUID 0004000 /* [XSI] set user id on execution */ +#define S_ISGID 0002000 /* [XSI] set group id on execution */ +#define S_ISVTX 0001000 /* [XSI] directory restrcted delete */ -#if !defined(_POSIX_C_SOURCE) -#define S_ISTXT S_ISVTX /* sticky bit: not supported */ -#define S_IREAD S_IRUSR /* backward compatability */ -#define S_IWRITE S_IWUSR /* backward compatability */ -#define S_IEXEC S_IXUSR /* backward compatability */ +#if !defined(_POSIX_C_SOURCE) +#define S_ISTXT S_ISVTX /* sticky bit: not supported */ +#define S_IREAD S_IRUSR /* backward compatability */ +#define S_IWRITE S_IWUSR /* backward compatability */ +#define S_IEXEC S_IXUSR /* backward compatability */ #endif #endif /* !S_IFMT */ @@ -51,15 +70,15 @@ * of st_mode from a stat structure. The macro shall evaluate to a non-zero * value if the test is true; 0 if the test is false. */ -#define S_ISBLK(m) (((m)& S_IFMT) == S_IFBLK) /* block special */ -#define S_ISCHR(m) (((m)& S_IFMT) == S_IFCHR) /* char special */ -#define S_ISDIR(m) (((m)& S_IFMT) == S_IFDIR) /* directory */ -#define S_ISFIFO(m) (((m)& S_IFMT) == S_IFIFO) /* fifo or socket */ -#define S_ISREG(m) (((m)& S_IFMT) == S_IFREG) /* regular file */ -#define S_ISLNK(m) (((m)& S_IFMT) == S_IFLNK) /* symbolic link */ -#define S_ISSOCK(m) (((m)& S_IFMT) == S_IFSOCK) /* socket */ +#define S_ISBLK(m) (((m)& S_IFMT) == S_IFBLK) /* block special */ +#define S_ISCHR(m) (((m)& S_IFMT) == S_IFCHR) /* char special */ +#define S_ISDIR(m) (((m)& S_IFMT) == S_IFDIR) /* directory */ +#define S_ISFIFO(m) (((m)& S_IFMT) == S_IFIFO) /* fifo or socket */ +#define S_ISREG(m) (((m)& S_IFMT) == S_IFREG) /* regular file */ +#define S_ISLNK(m) (((m)& S_IFMT) == S_IFLNK) /* symbolic link */ +#define S_ISSOCK(m) (((m)& S_IFMT) == S_IFSOCK) /* socket */ #if !defined(_POSIX_C_SOURCE) || defined(_DARWIN_C_SOURCE) -#define S_ISWHT(m) (((m)& S_IFMT) == S_IFWHT) /* OBSOLETE: whiteout */ +#define S_ISWHT(m) (((m)& S_IFMT) == S_IFWHT) /* OBSOLETE: whiteout */ #endif #endif /* SPL_STAT_H */ diff --git a/include/os/windows/spl/sys/strings.h b/include/os/windows/spl/sys/strings.h index b5599dbc515..24fbb809156 100644 --- a/include/os/windows/spl/sys/strings.h +++ b/include/os/windows/spl/sys/strings.h @@ -20,6 +20,6 @@ * CDDL HEADER END */ #ifndef _SPL_STRINGS_H -#define _SPL_STRINGS_H +#define _SPL_STRINGS_H #endif diff --git a/include/os/windows/spl/sys/stropts.h b/include/os/windows/spl/sys/stropts.h index 6fcb9634d08..41e77010ec1 100644 --- a/include/os/windows/spl/sys/stropts.h +++ b/include/os/windows/spl/sys/stropts.h @@ -25,9 +25,8 @@ * */ - #ifndef _SPL_STROPTS_H -#define _SPL_STROPTS_H +#define _SPL_STROPTS_H #include #include @@ -36,7 +35,7 @@ extern "C" { #endif -#define isprint(c) ((c) >= ' ' && (c) <= '~') +#define isprint(c) ((c) >= ' ' && (c) <= '~') /* * Find highest one bit set. @@ -46,72 +45,72 @@ extern "C" { static inline int highbit64(unsigned long long i) { - register int h = 1; - - if (i == 0) - return (0); - if (i & 0xffffffff00000000ull) { - h += 32; i >>= 32; - } - if (i & 0xffff0000) { - h += 16; i >>= 16; - } - if (i & 0xff00) { - h += 8; i >>= 8; - } - if (i & 0xf0) { - h += 4; i >>= 4; - } - if (i & 0xc) { - h += 2; i >>= 2; - } - if (i & 0x2) { - h += 1; - } - return (h); + register int h = 1; + + if (i == 0) + return (0); + if (i & 0xffffffff00000000ull) { + h += 32; i >>= 32; + } + if (i & 0xffff0000) { + h += 16; i >>= 16; + } + if (i & 0xff00) { + h += 8; i >>= 8; + } + if (i & 0xf0) { + h += 4; i >>= 4; + } + if (i & 0xc) { + h += 2; i >>= 2; + } + if (i & 0x2) { + h += 1; + } + return (h); } static inline int highbit(unsigned long long i) { - register int h = 1; - - if (i == 0) - return (0); - if (i & 0xffffffff00000000ull) { - h += 32; i >>= 32; - } - if (i & 0xffff0000) { - h += 16; i >>= 16; - } - if (i & 0xff00) { - h += 8; i >>= 8; - } - if (i & 0xf0) { - h += 4; i >>= 4; - } - if (i & 0xc) { - h += 2; i >>= 2; - } - if (i & 0x2) { - h += 1; - } - return (h); + register int h = 1; + + if (i == 0) + return (0); + if (i & 0xffffffff00000000ull) { + h += 32; i >>= 32; + } + if (i & 0xffff0000) { + h += 16; i >>= 16; + } + if (i & 0xff00) { + h += 8; i >>= 8; + } + if (i & 0xf0) { + h += 4; i >>= 4; + } + if (i & 0xc) { + h += 2; i >>= 2; + } + if (i & 0x2) { + h += 1; + } + return (h); } /* * Find lowest one bit set. - * Returns bit number + 1 of lowest bit that is set, otherwise returns 0. + * Returns bit number + 1 of lowest bit that is set, otherwise returns 0. * Low order bit is 0. */ static inline int lowbit(unsigned long long i) { register int h = 1; - + if (i == 0) return (0); - + if (!(i & 0xffffffff)) { h += 32; i >>= 32; } @@ -132,39 +131,35 @@ lowbit(unsigned long long i) } return (h); } - - static inline int -is_ascii_str(const char * str) +is_ascii_str(const char *str) { - unsigned char ch; + unsigned char ch; - while ((ch = (unsigned char)*str++) != '\0') { - if (ch >= 0x80) - return (0); - } - return (1); + while ((ch = (unsigned char)*str++) != '\0') { + if (ch >= 0x80) + return (0); + } + return (1); } - static inline void * kmemchr(const void *s, int c, size_t n) { - if (n != 0) { - const unsigned char *p = (const unsigned char *)s; - do { - if (*p++ == (unsigned char)c) - return ((void *)(uintptr_t)(p - 1)); - } while (--n != 0); - } - return (NULL); + if (n != 0) { + const unsigned char *p = (const unsigned char *)s; + do { + if (*p++ == (unsigned char)c) + return ((void *)(uintptr_t)(p - 1)); + } while (--n != 0); + } + return (NULL); } -#define LONG_BIT 64 -#define IDX(c) ((unsigned char)(c) / LONG_BIT) -#define BIT(c) ((unsigned long)1 << ((unsigned char)(c) % LONG_BIT)) - +#define LONG_BIT 64 +#define IDX(c) ((unsigned char)(c) / LONG_BIT) +#define BIT(c) ((unsigned long)1 << ((unsigned char)(c) % LONG_BIT)) #ifdef __cplusplus } diff --git a/include/os/windows/spl/sys/sunddi.h b/include/os/windows/spl/sys/sunddi.h index 56ef7f43704..1646a07a85f 100644 --- a/include/os/windows/spl/sys/sunddi.h +++ b/include/os/windows/spl/sys/sunddi.h @@ -25,10 +25,8 @@ * Copyright (c) 2012 by Delphix. All rights reserved. */ - - #ifndef _SPL_SUNDDI_H -#define _SPL_SUNDDI_H +#define _SPL_SUNDDI_H #include #include @@ -36,9 +34,7 @@ #include #include #include -#include #include -//#include typedef int ddi_devid_t; @@ -52,57 +48,51 @@ typedef int ddi_devid_t; #define DDI_SUCCESS 0 #define DDI_FAILURE -1 -#define ddi_prop_lookup_string(x1,x2,x3,x4,x5) (*x5 = NULL) +#define ddi_prop_lookup_string(x1, x2, x3, x4, x5) (*x5 = NULL) #define ddi_prop_free(x) (void)0 #define ddi_root_node() (void)0 -#define isalnum(ch) (isalpha(ch) || isdigit(ch)) -#define isalpha(ch) (isupper(ch) || islower(ch)) -#define isdigit(ch) ((ch) >= '0' && (ch) <= '9') -#define islower(ch) ((ch) >= 'a' && (ch) <= 'z') -#define isspace(ch) (((ch) == ' ') || ((ch) == '\r') || ((ch) == '\n') || \ - ((ch) == '\t') || ((ch) == '\f')) -#define isupper(ch) ((ch) >= 'A' && (ch) <= 'Z') -#define isxdigit(ch) (isdigit(ch) || ((ch) >= 'a' && (ch) <= 'f') || \ - ((ch) >= 'A' && (ch) <= 'F')) -#define isgraph(C) ((C) >= 0x21 && (C) <= 0x7E) -#define ispunct(C) (((C) >= 0x21 && (C) <= 0x2F) || \ - ((C) >= 0x3A && (C) <= 0x40) || \ - ((C) >= 0x5B && (C) <= 0x60) || \ - ((C) >= 0x7B && (C) <= 0x7E)) - -#define DIGIT(x) \ - (isdigit(x) ? (x) - '0' : islower(x) ? (x) + 10 - 'a' : (x) + 10 - 'A') +#define isalnum(ch) (isalpha(ch) || isdigit(ch)) +#define isalpha(ch) (isupper(ch) || islower(ch)) +#define isdigit(ch) ((ch) >= '0' && (ch) <= '9') +#define islower(ch) ((ch) >= 'a' && (ch) <= 'z') +#define isspace(ch) (((ch) == ' ') || ((ch) == '\r') || ((ch) == '\n') || \ + ((ch) == '\t') || ((ch) == '\f')) +#define isupper(ch) ((ch) >= 'A' && (ch) <= 'Z') +#define isxdigit(ch) (isdigit(ch) || ((ch) >= 'a' && (ch) <= 'f') || \ + ((ch) >= 'A' && (ch) <= 'F')) +#define isgraph(C) ((C) >= 0x21 && (C) <= 0x7E) +#define ispunct(C) (((C) >= 0x21 && (C) <= 0x2F) || \ + ((C) >= 0x3A && (C) <= 0x40) || \ + ((C) >= 0x5B && (C) <= 0x60) || \ + ((C) >= 0x7B && (C) <= 0x7E)) + +#define DIGIT(x) \ + (isdigit(x) ? (x) - '0' : islower(x) ? (x) + 10 - 'a' : (x) + 10 - 'A') #define MBASE ('z' - 'a' + 1 + 10) /* -* The following macro is a version of isalnum() that limits alphabetic -* characters to the ranges a-z and A-Z; locale dependent characters will not -* return 1. The members of a-z and A-Z are assumed to be in ascending order -* and contiguous. -*/ -#define lisalnum(x) \ - (isdigit(x) || ((x) >= 'a' && (x) <= 'z') || ((x) >= 'A' && (x) <= 'Z')) - -//extern int ddi_strtoul(const char *, char **, int, unsigned long *); -//extern int ddi_strtol(const char *, char **, int, long *); -//extern int ddi_strtoull(const char *, char **, int, unsigned long long *); -//extern int ddi_strtoll(const char *, char **, int, long long *); + * The following macro is a version of isalnum() that limits alphabetic + * characters to the ranges a-z and A-Z; locale dependent characters will not + * return 1. The members of a-z and A-Z are assumed to be in ascending order + * and contiguous. + */ +#define lisalnum(x) \ + (isdigit(x) || ((x) >= 'a' && (x) <= 'z') || ((x) >= 'A' && (x) <= 'Z')) // Define proper Solaris API calls, and clean ZFS up to use -#define copyin(from, to, len) ddi_copyin((from), (to), (len), 0) +#define copyin(from, to, len) ddi_copyin((from), (to), (len), 0) int ddi_copyin(const void *from, void *to, size_t len, int flags); -#define copyout(from, to, len) ddi_copyout((from), (to), (len), 0) +#define copyout(from, to, len) ddi_copyout((from), (to), (len), 0) int ddi_copyout(const void *from, void *to, size_t len, int flags); -#define copyinstr(from, to, len, done) ddi_copyinstr((from), (to), (len), (done)) +#define copyinstr(from, to, len, done) \ + ddi_copyinstr((from), (to), (len), (done)) int ddi_copyinstr(const void *uaddr, void *kaddr, size_t len, size_t *done); int ddi_copysetup(void *to, size_t len, void **out_buffer, PMDL *out_mdl); - extern int ddi_strtol(const char *str, char **nptr, int base, long *result); - #ifndef OTYPCNT #define OTYPCNT 5 #define OTYP_BLK 0 @@ -114,7 +104,7 @@ extern int ddi_strtol(const char *str, char **nptr, int base, long *result); #define P2END(x, align) (-(~((uint64_t)x) & -((uint64_t)align))) -#define ddi_name_to_major(name) devsw_name2blk(name, NULL, 0) +#define ddi_name_to_major(name) devsw_name2blk(name, NULL, 0) struct dev_info { dev_t dev; // Major / Minor @@ -123,17 +113,17 @@ struct dev_info { }; typedef struct dev_info dev_info_t; -int ddi_strtoull(const char *, char **, int, unsigned long long *); -int ddi_strtoll(const char *, char **, int, long long *); -int ddi_strtoul(const char *, char **, int, unsigned long *); -int ddi_strtol(const char *, char **, int, long *); -int ddi_soft_state_init(void **, uint32_t, uint32_t); -int ddi_soft_state_zalloc(void *, int); -void *ddi_get_soft_state(void *, int); -void ddi_soft_state_free(void *, int); -void ddi_soft_state_fini(void **); -int ddi_create_minor_node(dev_info_t *, char *, int, - minor_t, char *, int); +int ddi_strtoull(const char *, char **, int, unsigned long long *); +int ddi_strtoll(const char *, char **, int, long long *); +int ddi_strtoul(const char *, char **, int, unsigned long *); +int ddi_strtol(const char *, char **, int, long *); +int ddi_soft_state_init(void **, uint32_t, uint32_t); +int ddi_soft_state_zalloc(void *, int); +void *ddi_get_soft_state(void *, int); +void ddi_soft_state_free(void *, int); +void ddi_soft_state_fini(void **); +int ddi_create_minor_node(dev_info_t *, char *, int, + minor_t, char *, int); void ddi_remove_minor_node(dev_info_t *, char *); int ddi_driver_major(dev_info_t *); @@ -149,10 +139,10 @@ typedef void *ldi_ident_t; #define ddi_prop_update_string(a, b, c, d) DDI_SUCCESS #define bioerror(bp, er) (buf_seterror((bp), (er))) -#define biodone(bp) buf_biodone(bp) +#define biodone(bp) buf_biodone(bp) static inline long ddi_fls(long mask) { \ - /*Algorithm courtesy of Steve Chessin.*/ \ + /* Algorithm courtesy of Steve Chessin. */ \ while (mask) { \ long nx; \ if ((nx = (mask & (mask - 1))) == 0) \ @@ -163,19 +153,21 @@ static inline long ddi_fls(long mask) { \ } // find_first_bits_de_bruijn(unsigned nums[ARRAY_SIZE]) -static inline long ddi_ffs(long mask) { \ - static const int MultiplyDeBruijnBitPosition[32] = { \ - 1, 2, 29, 3, 30, 15, 25, 4, 31, 23, 21, 16, 26, 18, 5, 9, \ - 32, 28, 14, 24, 22, 20, 17, 8, 27, 13, 19, 7, 12, 6, 11, 10 \ - }; \ - return MultiplyDeBruijnBitPosition[ \ - ((unsigned)((mask & -mask) * 0x077CB531U)) >> 27]; \ +static inline long +ddi_ffs(long mask) +{ + static const int MultiplyDeBruijnBitPosition[32] = { + 1, 2, 29, 3, 30, 15, 25, 4, 31, 23, 21, 16, 26, 18, 5, 9, + 32, 28, 14, 24, 22, 20, 17, 8, 27, 13, 19, 7, 12, 6, 11, 10 + }; + return MultiplyDeBruijnBitPosition[ + ((unsigned)((mask & -mask) * 0x077CB531U)) >> 27]; } -#define getminor(X) minor((X)) +#define getminor(X) minor((X)) @@ -196,7 +188,7 @@ extern unsigned long long strlcpy(char *, const char *, unsigned long long); extern size_t strlcat(char *dst, const char *s2, size_t n); uint32_t -ddi_strcspn(const char * __restrict s, const char * __restrict charset); -#define strcspn ddi_strcspn +ddi_strcspn(const char *__restrict s, const char *__restrict charset); +#define strcspn ddi_strcspn #endif /* SPL_SUNDDI_H */ diff --git a/include/os/windows/spl/sys/sunldi.h b/include/os/windows/spl/sys/sunldi.h index 85eb04bd2c2..4b493cc5587 100644 --- a/include/os/windows/spl/sys/sunldi.h +++ b/include/os/windows/spl/sys/sunldi.h @@ -22,13 +22,11 @@ * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved. */ - - #ifndef _SPL_SUNLDI_H -#define _SPL_SUNLDI_H +#define _SPL_SUNLDI_H #include -#define SECTOR_SIZE 512 +#define SECTOR_SIZE 512 #endif /* SPL_SUNLDI_H */ diff --git a/include/os/windows/spl/sys/sysdc.h b/include/os/windows/spl/sys/sysdc.h deleted file mode 100644 index e27f31fdd07..00000000000 --- a/include/os/windows/spl/sys/sysdc.h +++ /dev/null @@ -1,4 +0,0 @@ -#ifndef _SPL_SYSDC_H -#define _SPL_SYSDC_H - -#endif /* SPL_SYSDC_H */ diff --git a/include/os/windows/spl/sys/sysevent.h b/include/os/windows/spl/sys/sysevent.h index 8389ac483bd..6510297d601 100644 --- a/include/os/windows/spl/sys/sysevent.h +++ b/include/os/windows/spl/sys/sysevent.h @@ -1,31 +1,31 @@ /* -* CDDL HEADER START -* -* The contents of this file are subject to the terms of the -* Common Development and Distribution License, Version 1.0 only -* (the "License"). You may not use this file except in compliance -* with the License. -* -* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE -* or http://www.opensolaris.org/os/licensing. -* See the License for the specific language governing permissions -* and limitations under the License. -* -* When distributing Covered Code, include this CDDL HEADER in each -* file and include the License file at usr/src/OPENSOLARIS.LICENSE. -* If applicable, add the following below this CDDL HEADER, with the -* fields enclosed by brackets "[]" replaced with your own identifying -* information: Portions Copyright [yyyy] [name of copyright owner] -* -* CDDL HEADER END -*/ + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License, Version 1.0 only + * (the "License"). You may not use this file except in compliance + * with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ /* -* Copyright 2006 Sun Microsystems, Inc. All rights reserved. -* Use is subject to license terms. -*/ + * Copyright 2006 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ #ifndef _SYS_SYSEVENT_H -#define _SYS_SYSEVENT_H +#define _SYS_SYSEVENT_H #include diff --git a/include/os/windows/spl/sys/sysevent/eventdefs.h b/include/os/windows/spl/sys/sysevent/eventdefs.h index 8ed67c26627..888b5b869c0 100644 --- a/include/os/windows/spl/sys/sysevent/eventdefs.h +++ b/include/os/windows/spl/sys/sysevent/eventdefs.h @@ -1,28 +1,28 @@ /* -* CDDL HEADER START -* -* The contents of this file are subject to the terms of the -* Common Development and Distribution License (the "License"). -* You may not use this file except in compliance with the License. -* -* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE -* or http://www.opensolaris.org/os/licensing. -* See the License for the specific language governing permissions -* and limitations under the License. -* -* When distributing Covered Code, include this CDDL HEADER in each -* file and include the License file at usr/src/OPENSOLARIS.LICENSE. -* If applicable, add the following below this CDDL HEADER, with the -* fields enclosed by brackets "[]" replaced with your own identifying -* information: Portions Copyright [yyyy] [name of copyright owner] -* -* CDDL HEADER END -*/ + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ /* -* Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. -* Copyright 2015 Nexenta Systems, Inc. All rights reserved. -* Copyright 2017 Joyent, Inc. -*/ + * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright 2015 Nexenta Systems, Inc. All rights reserved. + * Copyright 2017 Joyent, Inc. + */ #ifndef _SYS_SYSEVENT_EVENTDEFS_H #define _SYS_SYSEVENT_EVENTDEFS_H @@ -31,13 +31,13 @@ extern "C" { #endif - /* - * eventdefs.h contains public definitions for sysevent types (classes - * and subclasses). All additions/removal/changes are subject - * to PSARC approval. - */ +/* + * eventdefs.h contains public definitions for sysevent types (classes + * and subclasses). All additions/removal/changes are subject + * to PSARC approval. + */ - /* Sysevent Class definitions */ +/* Sysevent Class definitions */ #define EC_NONE "EC_none" #define EC_PRIV "EC_priv" #define EC_PLATFORM "EC_platform" /* events private to platform */ @@ -55,44 +55,44 @@ extern "C" { #define EC_DATALINK "EC_datalink" /* datalink event */ #define EC_VRRP "EC_vrrp" /* VRRP event */ - /* - * EC_DEV_ADD and EC_DEV_REMOVE subclass definitions - supporting attributes - * (name/value pairs) are found in sys/sysevent/dev.h - */ +/* + * EC_DEV_ADD and EC_DEV_REMOVE subclass definitions - supporting attributes + * (name/value pairs) are found in sys/sysevent/dev.h + */ #define ESC_DISK "disk" /* disk device */ #define ESC_NETWORK "network" /* network interface */ #define ESC_PRINTER "printer" /* printer device */ #define ESC_LOFI "lofi" /* lofi device */ - /* - * EC_DEV_BRANCH subclass definitions - supporting attributes (name/value pairs) - * are found in sys/sysevent/dev.h - */ +/* + * EC_DEV_BRANCH subclass definitions:supporting attributes (name/value pairs) + * are found in sys/sysevent/dev.h + */ - /* device tree branch added */ +/* device tree branch added */ #define ESC_DEV_BRANCH_ADD "dev_branch_add" - /* device tree branch removed */ +/* device tree branch removed */ #define ESC_DEV_BRANCH_REMOVE "dev_branch_remove" - /* - * EC_DEV_STATUS subclass definitions - * - * device capacity dynamically changed - */ +/* + * EC_DEV_STATUS subclass definitions + * + * device capacity dynamically changed + */ #define ESC_DEV_DLE "dev_dle" - /* LUN has received an eject request from the user */ +/* LUN has received an eject request from the user */ #define ESC_DEV_EJECT_REQUEST "dev_eject_request" - /* FMA Fault and Error event protocol subclass */ +/* FMA Fault and Error event protocol subclass */ #define ESC_FM_ERROR "error" #define ESC_FM_ERROR_REPLAY "error_replay" - /* - * ZFS subclass definitions. supporting attributes (name/value paris) are found - * in sys/fs/zfs.h - */ +/* + * ZFS subclass definitions: supporting attributes (name/value paris) are found + * in sys/fs/zfs.h + */ #define ESC_ZFS_RESILVER_START "resilver_start" #define ESC_ZFS_RESILVER_FINISH "resilver_finish" #define ESC_ZFS_VDEV_REMOVE "vdev_remove" @@ -118,18 +118,18 @@ extern "C" { #define ESC_ZFS_BOOTFS_VDEV_ATTACH "bootfs_vdev_attach" #define ESC_ZFS_POOL_REGUID "pool_reguid" #define ESC_ZFS_HISTORY_EVENT "history_event" -#define ESC_ZFS_TRIM_START "trim_start" -#define ESC_ZFS_TRIM_FINISH "trim_finish" -#define ESC_ZFS_TRIM_CANCEL "trim_cancel" -#define ESC_ZFS_TRIM_RESUME "trim_resume" -#define ESC_ZFS_TRIM_SUSPEND "trim_suspend" - /* - * datalink subclass definitions. - */ +#define ESC_ZFS_TRIM_START "trim_start" +#define ESC_ZFS_TRIM_FINISH "trim_finish" +#define ESC_ZFS_TRIM_CANCEL "trim_cancel" +#define ESC_ZFS_TRIM_RESUME "trim_resume" +#define ESC_ZFS_TRIM_SUSPEND "trim_suspend" +/* + * datalink subclass definitions. + */ #define ESC_DATALINK_PHYS_ADD "datalink_phys_add" /* new physical link */ #ifdef __cplusplus } #endif -#endif /* _SYS_SYSEVENT_EVENTDEFS_H */ \ No newline at end of file +#endif /* _SYS_SYSEVENT_EVENTDEFS_H */ diff --git a/include/os/windows/spl/sys/sysmacros.h b/include/os/windows/spl/sys/sysmacros.h index a660e6353bc..1febf1850a2 100644 --- a/include/os/windows/spl/sys/sysmacros.h +++ b/include/os/windows/spl/sys/sysmacros.h @@ -26,7 +26,7 @@ */ #ifndef _SPL_SYSMACROS_H -#define _SPL_SYSMACROS_H +#define _SPL_SYSMACROS_H #include #include @@ -35,127 +35,98 @@ #include #ifndef _KERNEL -#define _KERNEL __KERNEL__ +#define _KERNEL __KERNEL__ #endif -#define FALSE 0 -#define TRUE 1 +#define FALSE 0 +#define TRUE 1 -#if 0 -#define INT8_MAX (127) -#define INT8_MIN (-128) -#define UINT8_MAX (255) -#define UINT8_MIN (0) +#define NBBY 8 -#define INT16_MAX (32767) -#define INT16_MIN (-32768) -#define UINT16_MAX (65535) -#define UINT16_MIN (0) +#define MAXMSGLEN 256 +#define MAXNAMELEN 256 +#define MAXPATHLEN 1024 +#define MAXOFFSET_T LLONG_MAX +#define DEV_BSIZE 512 +#define DEV_BSHIFT 9 /* log2(DEV_BSIZE) */ -#define INT32_MAX INT_MAX -#define INT32_MIN INT_MIN -#define UINT32_MAX UINT_MAX -#define UINT32_MIN UINT_MIN +#define proc_pageout NULL +#define curproc (struct proc *)PsGetCurrentProcess() -#define INT64_MAX LLONG_MAX -#define INT64_MIN LLONG_MIN -#define UINT64_MAX ULLONG_MAX -#define UINT64_MIN ULLONG_MIN - -#define NBBY 8 -#define MAXBSIZE 8192 -#endif -#define NBBY 8 - //#define ENOTSUP EOPNOTSUPP - -#define MAXMSGLEN 256 -#define MAXNAMELEN 256 -#define MAXPATHLEN 1024 -#define MAXOFFSET_T LLONG_MAX -#define DEV_BSIZE 512 -#define DEV_BSHIFT 9 /* log2(DEV_BSIZE) */ - -#define proc_pageout NULL -#define curproc (struct proc *)PsGetCurrentProcess() -//#define max_ncpus num_possible_cpus() -//#define CPU_SEQID smp_processor_id() extern uint32_t cpu_number(void); -#define CPU_SEQID (cpu_number()) -#define _NOTE(x) -#define is_system_labeled() 0 +#define CPU_SEQID (cpu_number()) +#define _NOTE(x) +#define is_system_labeled() 0 extern unsigned int max_ncpus; #ifndef RLIM64_INFINITY -#define RLIM64_INFINITY (~0ULL) +#define RLIM64_INFINITY (~0ULL) #endif -/* 0..MAX_PRIO-1: Process priority +/* + * 0..MAX_PRIO-1: Process priority * 0..MAX_RT_PRIO-1: RT priority tasks * MAX_RT_PRIO..MAX_PRIO-1: SCHED_NORMAL tasks * * Treat shim tasks as SCHED_NORMAL tasks */ -//#define minclsyspri (MAX_RT_PRIO) -//#define maxclsyspri (MAX_PRIO-1) + /* * In OSX, the kernel thread priorities start at 81 and goes to * 95 MAXPRI_KERNEL. BASEPRI_REALTIME starts from 96. Since * swap priority is at 92. Most ZFS priorities should probably * stay below this, but kmem_reap needs to be higher. */ -#define minclsyspri 81 /* BASEPRI_KERNEL */ -#define defclsyspri 81 /* BASEPRI_KERNEL */ -#define maxclsyspri 89 +#define minclsyspri 81 /* BASEPRI_KERNEL */ +#define defclsyspri 81 /* BASEPRI_KERNEL */ +#define maxclsyspri 89 +#define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20) +#define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20) -#define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20) -#define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20) - -/* Missing macros +/* + * Missing macros */ -#define PAGESIZE PAGE_SIZE +#define PAGESIZE PAGE_SIZE /* from Solaris sys/byteorder.h */ -#define BSWAP_8(x) ((x) & 0xff) -#define BSWAP_16(x) ((BSWAP_8(x) << 8) | BSWAP_8((x) >> 8)) -#define BSWAP_32(x) ((BSWAP_16(x) << 16) | BSWAP_16((x) >> 16)) -#define BSWAP_64(x) ((BSWAP_32(x) << 32) | BSWAP_32((x) >> 32)) - +#define BSWAP_8(x) ((x) & 0xff) +#define BSWAP_16(x) ((BSWAP_8(x) << 8) | BSWAP_8((x) >> 8)) +#define BSWAP_32(x) ((BSWAP_16(x) << 16) | BSWAP_16((x) >> 16)) +#define BSWAP_64(x) ((BSWAP_32(x) << 32) | BSWAP_32((x) >> 32)) /* Dtrace probes do not exist in the linux kernel */ #ifdef DTRACE_PROBE #undef DTRACE_PROBE #endif /* DTRACE_PROBE */ -#define DTRACE_PROBE(a) ((void)0) +#define DTRACE_PROBE(a) ((void)0) #ifdef DTRACE_PROBE1 #undef DTRACE_PROBE1 #endif /* DTRACE_PROBE1 */ -#define DTRACE_PROBE1(a, b, c) ((void)0) +#define DTRACE_PROBE1(a, b, c) ((void)0) #ifdef DTRACE_PROBE2 #undef DTRACE_PROBE2 #endif /* DTRACE_PROBE2 */ -#define DTRACE_PROBE2(a, b, c, d, e) ((void)0) +#define DTRACE_PROBE2(a, b, c, d, e) ((void)0) #ifdef DTRACE_PROBE3 #undef DTRACE_PROBE3 #endif /* DTRACE_PROBE3 */ -#define DTRACE_PROBE3(a, b, c, d, e, f, g) ((void)0) +#define DTRACE_PROBE3(a, b, c, d, e, f, g) ((void)0) #ifdef DTRACE_PROBE4 #undef DTRACE_PROBE4 #endif /* DTRACE_PROBE4 */ -#define DTRACE_PROBE4(a, b, c, d, e, f, g, h, i) ((void)0) +#define DTRACE_PROBE4(a, b, c, d, e, f, g, h, i) ((void)0) /* Missing globals */ extern char spl_version[32]; extern char hw_serial[11]; /* Missing misc functions */ -//extern int highbit(unsigned long long i); -//extern int lowbit(unsigned long long i); extern uint32_t zone_get_hostid(void *zone); extern void spl_setup(void); extern void spl_cleanup(void); @@ -163,46 +134,49 @@ extern void spl_cleanup(void); #define boot_ncpus max_ncpus #define SET_ERROR(X) (X) -#define NBITSMINOR 20 -#define MINORMASK ((1UL<> NBITSMINOR) -#define minor(x) ((x) & MINORMASK) +#define NBITSMINOR 20 +#define MINORMASK ((1UL<> NBITSMINOR) +#define minor(x) ((x) & MINORMASK) -#define makedev(x, y) (((x) << NBITSMINOR) | ((y) & MINORMASK)) -#define makedevice(maj,min) makedev(maj,min) +#define makedev(x, y) (((x) << NBITSMINOR) | ((y) & MINORMASK)) +#define makedevice(maj, min) makedev(maj, min) /* common macros */ #ifndef MIN -#define MIN(a, b) ((a) < (b) ? (a) : (b)) +#define MIN(a, b) ((a) < (b) ? (a) : (b)) #endif #ifndef MAX -#define MAX(a, b) ((a) < (b) ? (b) : (a)) +#define MAX(a, b) ((a) < (b) ? (b) : (a)) #endif #ifndef ABS -#define ABS(a) ((a) < 0 ? -(a) : (a)) +#define ABS(a) ((a) < 0 ? -(a) : (a)) #endif #ifndef DIV_ROUND_UP -#define DIV_ROUND_UP(n,d) (((n) + (d) - 1) / (d)) +#define DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d)) #endif #ifndef roundup -#define roundup(x, y) ((((x) + ((y) - 1)) / (y)) * (y)) +#define roundup(x, y) ((((x) + ((y) - 1)) / (y)) * (y)) #endif /* * Compatibility macros/typedefs needed for Solaris -> Linux port - * For some reason Windows makes some of these signed, and everything goes to hell. + * For some reason Windows makes some of these signed, and everything + * goes to hell. * But may have put in too many (uint64_t), check this */ -#define P2ALIGN(x, align) (((uint64_t)x) & -((uint64_t)align)) -#define P2CROSS(x, y, align) ((((uint64_t)x) ^ ((uint64_t)y)) > ((uint64_t)align) - 1) -#define P2ROUNDUP(x, align) (-(-((uint64_t)x) & -((uint64_t)align))) -#define P2PHASE(x, align) (((uint64_t)x) & (((uint64_t)align) - 1)) -#define P2NPHASE(x, align) (-((uint64_t)x) & (((uint64_t)align) - 1)) -#define ISP2(x) ((((uint64_t)x) & (((uint64_t)x) - 1)) == 0) -#define IS_P2ALIGNED(v, a) ((((uintptr_t)(v)) & ((uintptr_t)(a) - 1))==0) -#define P2BOUNDARY(off, len, align) \ - ((((uint64_t)off) ^ (((uint64_t)off) + ((uint64_t)len) - 1)) > ((uint64_t)align) - 1) +#define P2ALIGN(x, align) (((uint64_t)x) & -((uint64_t)align)) +#define P2CROSS(x, y, align) \ + ((((uint64_t)x) ^ ((uint64_t)y)) > ((uint64_t)align) - 1) +#define P2ROUNDUP(x, align) (-(-((uint64_t)x) & -((uint64_t)align))) +#define P2PHASE(x, align) (((uint64_t)x) & (((uint64_t)align) - 1)) +#define P2NPHASE(x, align) (-((uint64_t)x) & (((uint64_t)align) - 1)) +#define ISP2(x) ((((uint64_t)x) & (((uint64_t)x) - 1)) == 0) +#define IS_P2ALIGNED(v, a) ((((uintptr_t)(v)) & ((uintptr_t)(a) - 1)) == 0) +#define P2BOUNDARY(off, len, align) \ + ((((uint64_t)off) ^ (((uint64_t)off) + \ + ((uint64_t)len) - 1)) > ((uint64_t)align) - 1) /* * Typed version of the P2* macros. These macros should be used to ensure @@ -216,22 +190,25 @@ extern void spl_cleanup(void); * or * P2ROUNDUP_TYPED(x, PAGESIZE, uint64_t) */ -#define P2ALIGN_TYPED(x, align, type) \ - ((type)((uint64_t)x) & -(type)((uint64_t)align)) -#define P2PHASE_TYPED(x, align, type) \ - ((type)((uint64_t)x) & ((type)((uint64_t)align) - 1)) -#define P2NPHASE_TYPED(x, align, type) \ - (-(type)((uint64_t)x) & ((type)((uint64_t)align) - 1)) -#define P2ROUNDUP_TYPED(x, align, type) \ - (-(-(type)((uint64_t)x) & -(type)((uint64_t)align))) -#define P2END_TYPED(x, align, type) \ - (-(~(type)((uint64_t)x) & -(type)((uint64_t)align))) -#define P2PHASEUP_TYPED(x, align, phase, type) \ - ((type)((uint64_t)phase) - (((type)((uint64_t)phase) - (type)((uint64_t)x)) & -(type)((uint64_t)align))) -#define P2CROSS_TYPED(x, y, align, type) \ - (((type)((uint64_t)x) ^ (type)((uint64_t)y)) > (type)((uint64_t)align) - 1) -#define P2SAMEHIGHBIT_TYPED(x, y, type) \ - (((type)((uint64_t)x) ^ (type)((uint64_t)y)) < ((type)((uint64_t)x) & (type)((uint64_t)y))) +#define P2ALIGN_TYPED(x, align, type) \ + ((type)((uint64_t)x) & -(type)((uint64_t)align)) +#define P2PHASE_TYPED(x, align, type) \ + ((type)((uint64_t)x) & ((type)((uint64_t)align) - 1)) +#define P2NPHASE_TYPED(x, align, type) \ + (-(type)((uint64_t)x) & ((type)((uint64_t)align) - 1)) +#define P2ROUNDUP_TYPED(x, align, type) \ + (-(-(type)((uint64_t)x) & -(type)((uint64_t)align))) +#define P2END_TYPED(x, align, type) \ + (-(~(type)((uint64_t)x) & -(type)((uint64_t)align))) +#define P2PHASEUP_TYPED(x, align, phase, type) \ + ((type)((uint64_t)phase) - (((type)((uint64_t)phase) - \ + (type)((uint64_t)x)) & -(type)((uint64_t)align))) +#define P2CROSS_TYPED(x, y, align, type) \ + (((type)((uint64_t)x) ^ (type)((uint64_t)y)) > \ + (type)((uint64_t)align) - 1) +#define P2SAMEHIGHBIT_TYPED(x, y, type) \ + (((type)((uint64_t)x) ^ (type)((uint64_t)y)) < \ + ((type)((uint64_t)x) & (type)((uint64_t)y))) /* * P2* Macros from Illumos @@ -243,14 +220,17 @@ extern void spl_cleanup(void); * eg, P2PHASEUP(0x1234, 0x100, 0x10) == 0x1310 (0x13*align + phase) * eg, P2PHASEUP(0x5600, 0x100, 0x10) == 0x5610 (0x56*align + phase) */ -#define P2PHASEUP(x, align, phase) (((uint64_t)phase) - ((((uint64_t)phase) - ((uint64_t)x)) & -((uint64_t)align))) +#define P2PHASEUP(x, align, phase) \ + (((uint64_t)phase) - ((((uint64_t)phase) - \ + ((uint64_t)x)) & -((uint64_t)align))) /* * Return TRUE if they have the same highest bit set. * eg, P2SAMEHIGHBIT(0x1234, 0x1001) == TRUE (the high bit is 0x1000) * eg, P2SAMEHIGHBIT(0x1234, 0x3010) == FALSE (high bit of 0x3010 is 0x2000) */ -#define P2SAMEHIGHBIT(x, y) ((((uint64_t)x) ^ ((uint64_t)y)) < (((uint64_t)x) & ((uint64_t)y))) +#define P2SAMEHIGHBIT(x, y) \ + ((((uint64_t)x) ^ ((uint64_t)y)) < (((uint64_t)x) & ((uint64_t)y))) /* * End Illumos copy-fest @@ -258,16 +238,12 @@ extern void spl_cleanup(void); /* avoid any possibility of clashing with version */ #if defined(_KERNEL) && !defined(_KMEMUSER) && !defined(offsetof) - /* Use the correct builtin mechanism. The Traditional macro is - not safe on this platform. */ -// #define offsetof(s, m) __builtin_offsetof(s, m) #include #endif -#define IS_INDEXABLE(arg) (sizeof(arg[0])) -#define IS_ARRAY(arg) (IS_INDEXABLE(arg) && (((void *) &arg) == ((void *) arg))) -#define ARRAY_SIZE(arr) (IS_ARRAY(arr) ? (sizeof(arr) / sizeof(arr[0])) : 0) - -// #define SET_ERROR(X) (X) +#define IS_INDEXABLE(arg) (sizeof (arg[0])) +#define IS_ARRAY(arg) \ + (IS_INDEXABLE(arg) && (((void *) &arg) == ((void *) arg))) +#define ARRAY_SIZE(arr) (IS_ARRAY(arr) ? (sizeof (arr) / sizeof (arr[0])) : 0) #endif /* _SPL_SYSMACROS_H */ diff --git a/include/os/windows/spl/sys/systeminfo.h b/include/os/windows/spl/sys/systeminfo.h index 8076ef9f1ce..95a7511a689 100644 --- a/include/os/windows/spl/sys/systeminfo.h +++ b/include/os/windows/spl/sys/systeminfo.h @@ -1,14 +1,33 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ #ifndef _SPL_SYSTEMINFO_H -#define _SPL_SYSTEMINFO_H +#define _SPL_SYSTEMINFO_H -#define HW_INVALID_HOSTID 0xFFFFFFFF /* an invalid hostid */ -#define HW_HOSTID_LEN 11 /* minimum buffer size needed */ - /* to hold a decimal or hex */ - /* hostid string */ +#define HW_INVALID_HOSTID 0xFFFFFFFF /* an invalid hostid */ + +/* minimum buffer size needed to hold a decimal or hex hostid string */ +#define HW_HOSTID_LEN 11 const char *spl_panicstr(void); int spl_system_inshutdown(void); - #endif /* SPL_SYSTEMINFO_H */ diff --git a/include/os/windows/spl/sys/systm.h b/include/os/windows/spl/sys/systm.h index f94095dc0be..a3376404033 100644 --- a/include/os/windows/spl/sys/systm.h +++ b/include/os/windows/spl/sys/systm.h @@ -1,13 +1,31 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ #ifndef _SPL_SYSTM_H -#define _SPL_SYSTM_H +#define _SPL_SYSTM_H -//#include_next #include typedef uintptr_t pc_t; - // Find a header to place this? struct bsd_timeout_wrapper { uint32_t flag; // Must be first @@ -17,9 +35,10 @@ struct bsd_timeout_wrapper { KTIMER timer; }; -/* bsd_timeout will create a new thread, and the new thread will -* first sleep the desired duration, then call the wanted function -*/ +/* + * bsd_timeout will create a new thread, and the new thread will + * first sleep the desired duration, then call the wanted function + */ static inline void bsd_timeout_handler(void *arg) { struct bsd_timeout_wrapper *btw = arg; @@ -28,20 +47,20 @@ static inline void bsd_timeout_handler(void *arg) thread_exit(); } -#define BSD_TIMEOUT_MAGIC 0x42994299 +#define BSD_TIMEOUT_MAGIC 0x42994299 static inline void bsd_untimeout(void(*func)(void *), void *ID) { - /* - * Unfortunately, calling KeSetTimer() does not Signal (or abort) any thread - * sitting in KeWaitForSingleObject() so they would wait forever. Instead we - * change the timeout to be now, so that the threads can exit. - */ +/* + * Unfortunately, calling KeSetTimer() does not Signal (or abort) any thread + * sitting in KeWaitForSingleObject() so they would wait forever. Instead we + * change the timeout to be now, so that the threads can exit. + */ struct bsd_timeout_wrapper *btw = (struct bsd_timeout_wrapper *)ID; LARGE_INTEGER p = { .QuadPart = -1 }; btw->init = 0; // Investigate why this assert triggers on Unload - //ASSERT(btw->init == BSD_TIMEOUT_MAGIC); // timer was not initialized - if(btw->init == BSD_TIMEOUT_MAGIC) + // ASSERT(btw->init == BSD_TIMEOUT_MAGIC); // timer was not initialized + if (btw->init == BSD_TIMEOUT_MAGIC) KeSetTimer(&btw->timer, p, NULL); } @@ -51,7 +70,8 @@ static inline void bsd_timeout(void *FUNC, void *ID, struct timespec *TIM) struct bsd_timeout_wrapper *btw = (struct bsd_timeout_wrapper *)ID; void(*func)(void *) = FUNC; ASSERT(btw != NULL); - duetime.QuadPart = -((int64_t)(SEC2NSEC100(TIM->tv_sec) + NSEC2NSEC100(TIM->tv_nsec))); + duetime.QuadPart = -((int64_t)(SEC2NSEC100(TIM->tv_sec) + + NSEC2NSEC100(TIM->tv_nsec))); btw->func = func; btw->arg = ID; /* Global vars are guaranteed set to 0, still is this secure enough? */ @@ -62,9 +82,9 @@ static inline void bsd_timeout(void *FUNC, void *ID, struct timespec *TIM) if (!KeSetTimer(&btw->timer, duetime, NULL)) { func((ID)); } else { - /* Another option would have been to use taskq, as it can cancel */ + /* Another option would have been to use taskq, it can cancel */ thread_create(NULL, 0, bsd_timeout_handler, ID, 0, NULL, - TS_RUN, minclsyspri); + TS_RUN, minclsyspri); } } diff --git a/include/os/windows/spl/sys/t_lock.h b/include/os/windows/spl/sys/t_lock.h deleted file mode 100644 index d04712d5778..00000000000 --- a/include/os/windows/spl/sys/t_lock.h +++ /dev/null @@ -1,10 +0,0 @@ - -#ifndef _SPL_T_LOCK_H -#define _SPL_T_LOCK_H - -#include -#include -#include -#include - -#endif /* SPL_T_LOCK_H */ diff --git a/include/os/windows/spl/sys/taskq.h b/include/os/windows/spl/sys/taskq.h index badbdf24399..c5e9c7d85ee 100644 --- a/include/os/windows/spl/sys/taskq.h +++ b/include/os/windows/spl/sys/taskq.h @@ -67,7 +67,7 @@ struct proc; #define TQ_NOALLOC 0x04 /* cannot allocate memory; may fail */ #define TQ_FRONT 0x08 /* Put task at the front of the queue */ -#define TASKQID_INVALID ((taskqid_t)0) +#define TASKQID_INVALID ((taskqid_t)0) #ifdef _KERNEL @@ -90,7 +90,7 @@ extern taskqid_t taskq_dispatch(taskq_t *, task_func_t, void *, uint_t); extern void nulltask(void *); extern void taskq_destroy(taskq_t *); extern void taskq_wait(taskq_t *); -#define HAVE_TASKQ_WAIT_ID +#define HAVE_TASKQ_WAIT_ID extern void taskq_wait_id(taskq_t *, taskqid_t); extern void taskq_suspend(taskq_t *); extern int taskq_suspended(taskq_t *); @@ -101,7 +101,7 @@ extern int taskq_cancel_id(taskq_t *, taskqid_t); extern taskq_t *taskq_of_curthread(void); extern int taskq_empty_ent(struct taskq_ent *); -#define taskq_wait_outstanding(T, D) taskq_wait((T)) +#define taskq_wait_outstanding(T, D) taskq_wait((T)) extern void system_taskq_init(void); extern void system_taskq_fini(void); diff --git a/include/os/windows/spl/sys/taskq_impl.h b/include/os/windows/spl/sys/taskq_impl.h index 32e95e382c0..83776e56496 100644 --- a/include/os/windows/spl/sys/taskq_impl.h +++ b/include/os/windows/spl/sys/taskq_impl.h @@ -60,8 +60,8 @@ typedef struct taskq_ent { kcondvar_t tqent_delay_cv; clock_t tqent_delay_time; /* Used to simulate TS_STOPPED */ - kmutex_t tqent_thread_lock; - kcondvar_t tqent_thread_cv; + kmutex_t tqent_thread_lock; + kcondvar_t tqent_thread_cv; } taskq_ent_t; #define TQENT_FLAG_PREALLOC 0x1 @@ -162,7 +162,6 @@ struct taskq { /* Special form of taskq dispatch that uses preallocated entries. */ void taskq_dispatch_ent(taskq_t *, task_func_t, void *, uint_t, taskq_ent_t *); - #define tq_thread tq_thr._tq_thread #define tq_threadlist tq_thr._tq_threadlist @@ -172,8 +171,7 @@ void taskq_dispatch_ent(taskq_t *, task_func_t, void *, uint_t, taskq_ent_t *); /* Extra ZOL / Apple */ extern void taskq_init_ent(taskq_ent_t *t); extern taskqid_t taskq_dispatch_delay(taskq_t *tq, task_func_t func, void *arg, - uint_t flags, clock_t expire_time); - + uint_t flags, clock_t expire_time); #ifdef __cplusplus } diff --git a/include/os/windows/spl/sys/thread.h b/include/os/windows/spl/sys/thread.h index 8e3cb6289c1..8b921578f5b 100644 --- a/include/os/windows/spl/sys/thread.h +++ b/include/os/windows/spl/sys/thread.h @@ -21,70 +21,64 @@ /* * - * Copyright (C) 2008 MacZFS * Copyright (C) 2013 Jorgen Lundman * */ #ifndef _SPL_THREAD_H -#define _SPL_THREAD_H +#define _SPL_THREAD_H #include #include #include #include -//#include - -//struct kthread { -// void *something; -//}; typedef struct _KTHREAD kthread_t; typedef struct _KTHREAD thread_t; /* * Thread interfaces */ -#define TP_MAGIC 0x53535353 +#define TP_MAGIC 0x53535353 -#define TS_FREE 0x00 /* Thread at loose ends */ -#define TS_SLEEP 0x01 /* Awaiting an event */ -#define TS_RUN 0x02 /* Runnable, but not yet on a processor */ -#define TS_ONPROC 0x04 /* Thread is being run on a processor */ -#define TS_ZOMB 0x08 /* Thread has died but hasn't been reaped */ -#define TS_STOPPED 0x10 /* Stopped, initial state */ -#define TS_WAIT 0x20 /* Waiting to become runnable */ +#define TS_FREE 0x00 /* Thread at loose ends */ +#define TS_SLEEP 0x01 /* Awaiting an event */ +#define TS_RUN 0x02 /* Runnable, but not yet on a processor */ +#define TS_ONPROC 0x04 /* Thread is being run on a processor */ +#define TS_ZOMB 0x08 /* Thread has died but hasn't been reaped */ +#define TS_STOPPED 0x10 /* Stopped, initial state */ +#define TS_WAIT 0x20 /* Waiting to become runnable */ typedef void (*thread_func_t)(void *); -//HANDLE PsGetCurrentThreadId(); - // This should be ThreadId, but that dies in taskq_member, // for now, dsl_pool_sync_context calls it instead. -#define current_thread PsGetCurrentThread -#define curthread ((void *)current_thread()) /* current thread pointer */ -#define curproj (ttoproj(curthread)) /* current project pointer */ +#define current_thread PsGetCurrentThread +#define curthread ((void *)current_thread()) /* current thread pointer */ +#define curproj (ttoproj(curthread)) /* current project pointer */ -#define thread_join(t) VERIFY(0) +#define thread_join(t) VERIFY(0) // Drop the p0 argument, not used. #ifdef SPL_DEBUG_THREAD -#define thread_create(A,B,C,D,E,F,G,H) spl_thread_create(A,B,C,D,E,G,__FILE__, __LINE__, H) +#define thread_create(A, B, C, D, E, F, G, H) \ + spl_thread_create(A, B, C, D, E, G, __FILE__, __LINE__, H) extern kthread_t *spl_thread_create(caddr_t stk, size_t stksize, - void (*proc)(void *), void *arg, size_t len, /*proc_t *pp,*/ int state, - char *, int, pri_t pri); -#define thread_create_named(name, A, B, C, D, E, F, G, H) \ + void (*proc)(void *), void *arg, size_t len, /* proc_t *pp, */ + int state, char *, int, pri_t pri); +#define thread_create_named(name, A, B, C, D, E, F, G, H) \ spl_thread_create(A, B, C, D, E, G, __FILE__, __LINE__, H) #else -#define thread_create(A,B,C,D,E,F,G,H) spl_thread_create(A,B,C,D,E,G,H) +#define thread_create(A, B, C, D, E, F, G, H) \ + spl_thread_create(A, B, C, D, E, G, H) extern kthread_t *spl_thread_create(caddr_t stk, size_t stksize, - void (*proc)(void *), void *arg, size_t len, /*proc_t *pp,*/ int state, - pri_t pri); -#define thread_create_named(name, A, B, C, D, E, F, G, H) \ + void (*proc)(void *), void *arg, size_t len, /* proc_t *pp, */ + int state, pri_t pri); +#define thread_create_named(name, A, B, C, D, E, F, G, H) \ spl_thread_create(A, B, C, D, E, G, H) #endif @@ -94,18 +88,16 @@ extern void spl_thread_exit(void); extern kthread_t *spl_current_thread(void); #define delay windows_delay -#define IOSleep windows_delay +#define IOSleep windows_delay extern void windows_delay(int); - -#define KPREEMPT_SYNC 0 +#define KPREEMPT_SYNC 0 static inline void kpreempt(int flags) { - (void)flags; - //ZwYieldExecution(); - LARGE_INTEGER interval; - interval.QuadPart = 0; - KeDelayExecutionThread(KernelMode, FALSE, &interval); + (void) flags; + LARGE_INTEGER interval; + interval.QuadPart = 0; + KeDelayExecutionThread(KernelMode, FALSE, &interval); } #endif /* _SPL_THREAD_H */ diff --git a/include/os/windows/spl/sys/time.h b/include/os/windows/spl/sys/time.h index 5bdb3a1d426..336f16e845c 100644 --- a/include/os/windows/spl/sys/time.h +++ b/include/os/windows/spl/sys/time.h @@ -27,32 +27,30 @@ */ #ifndef _SPL_TIME_H -#define _SPL_TIME_H +#define _SPL_TIME_H typedef long long hrtime_t; #include -//#include_next #include -//#include #include struct timespec; #if defined(CONFIG_64BIT) -#define TIME_MAX INT64_MAX -#define TIME_MIN INT64_MIN +#define TIME_MAX INT64_MAX +#define TIME_MIN INT64_MIN #else -#define TIME_MAX INT32_MAX -#define TIME_MIN INT32_MIN +#define TIME_MAX INT32_MAX +#define TIME_MIN INT32_MIN #endif -#define SEC 1 -#define MILLISEC 1000 -#define MICROSEC 1000000 -#define NANOSEC 1000000000 +#define SEC 1 +#define MILLISEC 1000 +#define MICROSEC 1000000 +#define NANOSEC 1000000000 -#define NSEC2SEC(n) ((n) / (NANOSEC / SEC)) -#define SEC2NSEC(m) ((hrtime_t)(m) * (NANOSEC / SEC)) +#define NSEC2SEC(n) ((n) / (NANOSEC / SEC)) +#define SEC2NSEC(m) ((hrtime_t)(m) * (NANOSEC / SEC)) /* Already defined in include/linux/time.h */ #undef CLOCK_THREAD_CPUTIME_ID @@ -61,28 +59,19 @@ struct timespec; #undef CLOCK_PROCESS_CPUTIME_ID typedef enum clock_type { - __CLOCK_REALTIME0 = 0, /* obsolete; same as CLOCK_REALTIME */ - CLOCK_VIRTUAL = 1, /* thread's user-level CPU clock */ - CLOCK_THREAD_CPUTIME_ID = 2, /* thread's user+system CPU clock */ - CLOCK_REALTIME = 3, /* wall clock */ - CLOCK_MONOTONIC = 4, /* high resolution monotonic clock */ - CLOCK_PROCESS_CPUTIME_ID = 5, /* process's user+system CPU clock */ - CLOCK_HIGHRES = CLOCK_MONOTONIC, /* alternate name */ - CLOCK_PROF = CLOCK_THREAD_CPUTIME_ID,/* alternate name */ + __CLOCK_REALTIME0 = 0, /* obsolete; same as CLOCK_REALTIME */ + CLOCK_VIRTUAL = 1, /* thread's user-level CPU clock */ + CLOCK_THREAD_CPUTIME_ID = 2, /* thread's user+system CPU clock */ + CLOCK_REALTIME = 3, /* wall clock */ + CLOCK_MONOTONIC = 4, /* high resolution monotonic clock */ + CLOCK_PROCESS_CPUTIME_ID = 5, /* process's user+system CPU clock */ + CLOCK_HIGHRES = CLOCK_MONOTONIC, /* alternate name */ + CLOCK_PROF = CLOCK_THREAD_CPUTIME_ID, /* alternate name */ } clock_type_t; -#if 0 -#define hz \ -({ \ - ASSERT(HZ >= 100 && HZ <= MICROSEC); \ - HZ; \ -}) -#endif - -#define TIMESPEC_OVERFLOW(ts) \ +#define TIMESPEC_OVERFLOW(ts) \ ((ts)->tv_sec < TIME_MIN || (ts)->tv_sec > TIME_MAX) - extern hrtime_t gethrtime(void); extern void gethrestime(struct timespec *); extern time_t gethrestime_sec(void); @@ -93,7 +82,7 @@ extern void hrt2ts(hrtime_t hrt, struct timespec *tsp); #define NSEC2MSEC(n) ((n) / (NANOSEC / MILLISEC)) #define NSEC2USEC(n) ((n) / (NANOSEC / MICROSEC)) -// Windows 100NS +// Windows 100NS #define SEC2NSEC100(n) ((n) * 10000000ULL) #define NSEC2NSEC100(n) ((n) / 100ULL) @@ -102,25 +91,26 @@ extern void hrt2ts(hrtime_t hrt, struct timespec *tsp); #define NSEC2USEC(n) ((n) / (NANOSEC / MICROSEC)) +/* + * ZFS time is 2* 64bit values, which are seconds, and nanoseconds since 1970 + * Windows time is 1 64bit value; representing the number of + * 100-nanosecond intervals since January 1, 1601 (UTC). + * There's 116444736000000000 100ns between 1601 and 1970 + */ - -// ZFS time is 2* 64bit values, which are seconds, and nanoseconds since 1970 -// Windows time is 1 64bit value; representing the number of 100-nanosecond intervals since January 1, 1601 (UTC). -// There's 116444736000000000 100ns between 1601 and 1970 - -// I think these functions handle sec correctly, but nsec should be */100 -#define TIME_WINDOWS_TO_UNIX(WT, UT) do { \ +// I think these functions handle sec correctly, but nsec should be */100 +#define TIME_WINDOWS_TO_UNIX(WT, UT) do { \ uint64_t unixepoch = (WT) - 116444736000000000ULL; \ (UT)[0] = /* seconds */ unixepoch / 10000000ULL; \ (UT)[1] = /* remainding nsec */ unixepoch - ((UT)[0] * 10000000ULL); \ - } while(0) + } while (0) -#define TIME_UNIX_TO_WINDOWS(UT, WT) do { \ +#define TIME_UNIX_TO_WINDOWS(UT, WT) do { \ (WT) = ((UT)[1]) + ((UT)[0] * 10000000ULL) + 116444736000000000ULL; \ - } while(0) + } while (0) -#define TIME_UNIX_TO_WINDOWS_EX(SEC, USEC, WT) do { \ +#define TIME_UNIX_TO_WINDOWS_EX(SEC, USEC, WT) do { \ (WT) = (USEC) + ((SEC) * 10000000ULL) + 116444736000000000ULL; \ - } while(0) + } while (0) #endif /* _SPL_TIME_H */ diff --git a/include/os/windows/spl/sys/timer.h b/include/os/windows/spl/sys/timer.h index 58720030fa1..27ea8e1a2bf 100644 --- a/include/os/windows/spl/sys/timer.h +++ b/include/os/windows/spl/sys/timer.h @@ -27,11 +27,10 @@ */ #ifndef _SPL_TIMER_H -#define _SPL_TIMER_H +#define _SPL_TIMER_H #include - // Typical timespec is smaller, but we need to retain the precision // to copy time between Unix and Windows. struct timespec { @@ -39,42 +38,39 @@ struct timespec { uint64_t tv_nsec; }; -//#define USEC_PER_SEC 1000000 /* microseconds per second */ - - +#define lbolt zfs_lbolt() +#define lbolt64 zfs_lbolt() -#define lbolt zfs_lbolt() -#define lbolt64 zfs_lbolt() +#define ddi_get_lbolt() (zfs_lbolt()) +#define ddi_get_lbolt64() (zfs_lbolt()) -#define ddi_get_lbolt() (zfs_lbolt()) -#define ddi_get_lbolt64() (zfs_lbolt()) - -#define typecheck(type,x) \ - ({ type __dummy; \ - typeof(x) __dummy2; \ - (void)(&__dummy == &__dummy2); \ - 1; \ +#define typecheck(type, x) \ + ( \ + { type __dummy; \ + typeof(x) __dummy2; \ + (void) (&__dummy == &__dummy2); \ + 1; \ }) +#pragma error(disable: 4296) +#define ddi_time_before(a, b) ((a) - (b) < 0) +#define ddi_time_after(a, b) ddi_time_before(b, a) -#pragma error( disable: 4296 ) -#define ddi_time_before(a, b) ((a) - (b) < 0) -#define ddi_time_after(a, b) ddi_time_before(b, a) - -#define ddi_time_before64(a, b) ((a) - (b) < 0) -#define ddi_time_after64(a, b) ddi_time_before64(b, a) -#pragma error( default: 4296 ) +#define ddi_time_before64(a, b) ((a) - (b) < 0) +#define ddi_time_after64(a, b) ddi_time_before64(b, a) +#pragma error(default: 4296) extern uint64_t zfs_lbolt(void); -#define usleep_range(wakeup, whocares) \ - do { \ - hrtime_t delta = wakeup - gethrtime(); \ - if (delta > 0) { \ - LARGE_INTEGER ft; \ - ft.QuadPart = -((__int64)NSEC2NSEC100(delta)); \ - (void) KeWaitForMultipleObjects(0, NULL, WaitAny, Executive, KernelMode, FALSE, &ft, NULL);\ - } \ +#define usleep_range(wakeup, whocares) \ + do { \ + hrtime_t delta = wakeup - gethrtime(); \ + if (delta > 0) { \ + LARGE_INTEGER ft; \ + ft.QuadPart = -((__int64)NSEC2NSEC100(delta)); \ + (void) KeWaitForMultipleObjects(0, NULL, WaitAny, \ + Executive, KernelMode, FALSE, &ft, NULL); \ + } \ } while (0) diff --git a/include/os/windows/spl/sys/trace.h b/include/os/windows/spl/sys/trace.h index bed80eef26c..5e33920c819 100644 --- a/include/os/windows/spl/sys/trace.h +++ b/include/os/windows/spl/sys/trace.h @@ -20,7 +20,6 @@ * CDDL HEADER END */ #ifndef _SPL_TRACE_H -#define _SPL_TRACE_H - +#define _SPL_TRACE_H #endif diff --git a/include/os/windows/spl/sys/trace_zfs.h b/include/os/windows/spl/sys/trace_zfs.h index e69de29bb2d..8337712ea57 100644 --- a/include/os/windows/spl/sys/trace_zfs.h +++ b/include/os/windows/spl/sys/trace_zfs.h @@ -0,0 +1 @@ +// diff --git a/include/os/windows/spl/sys/tsd.h b/include/os/windows/spl/sys/tsd.h index d283622893e..d54c2a30e24 100644 --- a/include/os/windows/spl/sys/tsd.h +++ b/include/os/windows/spl/sys/tsd.h @@ -28,15 +28,15 @@ #ifndef _SPL_TSD_H -#define _SPL_TSD_H +#define _SPL_TSD_H #include #include -#define TSD_HASH_TABLE_BITS_DEFAULT 9 -#define TSD_KEYS_MAX 32768 -#define DTOR_PID (PID_MAX_LIMIT+1) -#define PID_KEY (TSD_KEYS_MAX+1) +#define TSD_HASH_TABLE_BITS_DEFAULT 9 +#define TSD_KEYS_MAX 32768 +#define DTOR_PID (PID_MAX_LIMIT+1) +#define PID_KEY (TSD_KEYS_MAX+1) typedef void (*dtor_func_t)(void *); diff --git a/include/os/windows/spl/sys/types.h b/include/os/windows/spl/sys/types.h index d8c3a8b7415..ff5cdbb1c16 100644 --- a/include/os/windows/spl/sys/types.h +++ b/include/os/windows/spl/sys/types.h @@ -31,13 +31,12 @@ typedef enum { B_FALSE = 0, B_TRUE = 1 } boolean_t; typedef short pri_t; typedef int int32_t; -typedef unsigned long ulong; typedef unsigned long ulong_t; typedef unsigned long long uint64_t; typedef unsigned long long u_longlong_t; typedef unsigned long long rlim64_t; typedef unsigned long long loff_t; -#define _CLOCK_T_DEFINED +#define _CLOCK_T_DEFINED typedef unsigned long long clock_t; typedef long long int64_t; typedef long long longlong_t; @@ -51,17 +50,14 @@ typedef long long off_t; typedef struct timespec timestruc_t; /* definition per SVr4 */ typedef struct timespec timespec_t; typedef ulong_t pgcnt_t; -typedef unsigned int mode_t ; -//typedef uint32_t dev32_t; -#define NODEV32 (dev32_t)(-1) +typedef unsigned int mode_t; +#define NODEV32 (dev32_t)(-1) typedef uint_t minor_t; typedef char *caddr_t; typedef unsigned char uint8_t; typedef char int8_t; typedef short int int16_t; typedef unsigned short int uint16_t; -//#include_next -//#include typedef unsigned long long uid_t; typedef unsigned long long gid_t; typedef unsigned int pid_t; @@ -69,22 +65,21 @@ typedef unsigned int pid_t; typedef int64_t ssize_t; typedef uint64_t vm_offset_t; typedef uint64_t dev_t; -#define NGROUPS 16 +#define NGROUPS 16 typedef unsigned short umode_t; -typedef uint64_t user_addr_t; +typedef uint64_t user_addr_t; typedef uint64_t user_size_t; -typedef uint64_t ino64_t; +typedef uint64_t ino64_t; -typedef unsigned long u_long; -typedef unsigned char uuid_t[16]; +typedef unsigned char uuid_t[16]; // clang spits out "atomics are disabled" - change code to use atomic() calls. -#define _Atomic +#define _Atomic -#define PATH_MAX 1024 -#define Z_OK 0 +#define PATH_MAX 1024 +#define Z_OK 0 struct buf; typedef struct buf buf_t; @@ -101,88 +96,65 @@ typedef uintptr_t pc_t; #include -#define snprintf _snprintf -#define vprintf(...) vKdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, __VA_ARGS__)) -#define vsnprintf _vsnprintf +#define snprintf _snprintf +#define vprintf(...) vKdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, \ + __VA_ARGS__)) +#define vsnprintf _vsnprintf #ifndef ULLONG_MAX -#define ULLONG_MAX (~0ULL) +#define ULLONG_MAX (~0ULL) #endif #ifndef LLONG_MAX -#define LLONG_MAX ((long long)(~0ULL>>1)) -#endif - -#if 0 -typedef unsigned long intptr_t; -typedef unsigned long long u_offset_t; -typedef struct task_struct kthread_t; -typedef struct task_struct proc_t; -typedef struct vmem { } vmem_t; -typedef struct timespec timestruc_t; /* definition per SVr4 */ -typedef struct timespec timespec_t; -typedef u_longlong_t len_t; -typedef longlong_t diskaddr_t; -typedef ushort_t o_bcopy; -typedef uint_t major_t; -typedef ulong_t pfn_t; -typedef long spgcnt_t; -typedef short index_t; -typedef int id_t; -typedef unsigned short mode_t; -extern proc_t p0; +#define LLONG_MAX ((long long)(~0ULL>>1)) #endif #include -#define FREAD 0x0001 -#define FWRITE 0x0002 - -#define FCREAT O_CREAT -#define FTRUNC O_TRUNC -#define FEXCL O_EXCL -#define FNOCTTY O_NOCTTY -//#define FASYNC O_SYNC -#define FNOFOLLOW O_NOFOLLOW -#define FAPPEND O_APPEND - - -#define FSYNC 0x10 /* file (data+inode) integrity while writing */ -#define FDSYNC 0x40 /* file data only integrity while writing */ -#define FRSYNC 0x8000 /* sync read operations at same level of */ - /* integrity as specified for writes by */ - /* FSYNC and FDSYNC flags */ -#define FOFFMAX 0x2000 /* large file */ - -#define EXPORT_SYMBOL(X) -#define module_param(X,Y,Z) -#define MODULE_PARM_DESC(X,Y) - -#define B_WRITE 0x00000000 /* Write buffer (pseudo flag). */ -#define B_READ 0x00000001 /* Read buffer. */ -#define B_ASYNC 0x00000002 /* Start I/O, do not wait. */ -#define B_NOCACHE 0x00000004 /* Do not cache block after use. */ -#define B_PHYS 0x00000020 /* I/O to user memory. */ -#define B_PASSIVE 0x00000800 /* PASSIVE I/Os are ignored by THROTTLE I/O */ -#define B_BUSY B_PHYS +#define FREAD 0x0001 +#define FWRITE 0x0002 + +#define FCREAT O_CREAT +#define FTRUNC O_TRUNC +#define FEXCL O_EXCL +#define FNOCTTY O_NOCTTY +#define FNOFOLLOW O_NOFOLLOW +#define FAPPEND O_APPEND + + +#define FSYNC 0x10 /* file (data+inode) integrity while writing */ +#define FDSYNC 0x40 /* file data only integrity while writing */ +#define FRSYNC 0x8000 /* sync read operations at same level of */ +/* integrity as specified for writes by */ +/* FSYNC and FDSYNC flags */ +#define FOFFMAX 0x2000 /* large file */ + +#define EXPORT_SYMBOL(X) +#define module_param(X, Y, Z) +#define MODULE_PARM_DESC(X, Y) + +#define B_WRITE 0x00000000 /* Write buffer (pseudo flag). */ +#define B_READ 0x00000001 /* Read buffer. */ +#define B_ASYNC 0x00000002 /* Start I/O, do not wait. */ +#define B_NOCACHE 0x00000004 /* Do not cache block after use. */ +#define B_PHYS 0x00000020 /* I/O to user memory. */ +#define B_PASSIVE 0x00000800 /* PASSIVE I/Os are ignored by THROTTLE */ +#define B_BUSY B_PHYS #ifdef __GNUC__ -#define member_type(type, member) __typeof__ (((type *)0)->member) +#define member_type(type, member) __typeof__(((type *)0)->member) #else -#define member_type(type, member) void +#define member_type(type, member) void #endif -#define container_of(ptr, type, member) ((type *)( \ - (char *)(member_type(type, member) *){ ptr } - offsetof(type, member))) - -#define bzero(b,len) (memset((b), '\0', (len))) -#define bcopy(b1,b2,len) (memmove((b2), (b1), (len))) -#define bcmp(b1, b2, len) (memcmp((b2), (b1), (len))) -//int snprintf(char *s, int l, char *fmt, ...); +#define container_of(ptr, type, member) ((type *)\ + ((char *)(member_type(type, member)*)\ + { ptr } - offsetof(type, member))) -// extern uint32_t strlcpy(register char* s, register const char* t, register uint32_t n); -// extern uint32_t strlcat(register char* s, register const char* t, register uint32_t n); -#define strtok_r strtok_s -#define strcasecmp _stricmp +#define bzero(b, len) (memset((b), '\0', (len))) +#define bcopy(b1, b2, len) (memmove((b2), (b1), (len))) +#define bcmp(b1, b2, len) (memcmp((b2), (b1), (len))) +#define strtok_r strtok_s +#define strcasecmp _stricmp struct mount; typedef struct mount mount_t; @@ -191,25 +163,25 @@ struct kauth_cred; typedef struct kauth_cred kauth_cred_t; struct kauth_acl; typedef struct kauth_acl kauth_acl_t; -#define KAUTH_FILESEC_NONE ((kauth_filesec_t)0) +#define KAUTH_FILESEC_NONE ((kauth_filesec_t)0) struct kauth_ace_rights; typedef struct kauth_ace_rights kauth_ace_rights_t; -extern int groupmember(gid_t gid, kauth_cred_t *cred); +extern int groupmember(gid_t gid, kauth_cred_t *cred); typedef struct { -#define KAUTH_GUID_SIZE 16 /* 128-bit identifier */ +#define KAUTH_GUID_SIZE 16 /* 128-bit identifier */ unsigned char g_guid[KAUTH_GUID_SIZE]; } guid_t; -#pragma warning( disable: 4296 ) // expression is always true -#pragma error( disable: 4296 ) // expression is always true -#pragma warning( disable: 4703 ) // potentially uninitialized local pointer variable +#pragma warning(disable: 4296) // expression is always true +#pragma error(disable: 4296) // expression is always true +#pragma warning(disable: 4703) // potentially uninit local pointer variable -#define LINK_MAX 32767 /* max file link count */ +#define LINK_MAX 32767 /* max file link count */ -#define FNV1_32A_INIT ((uint32_t)0x811c9dc5) +#define FNV1_32A_INIT ((uint32_t)0x811c9dc5) uint32_t fnv_32a_str(const char *str, uint32_t hval); uint32_t fnv_32a_buf(void *buf, size_t len, uint32_t hval); diff --git a/include/os/windows/spl/sys/ubc.h b/include/os/windows/spl/sys/ubc.h deleted file mode 100644 index 5aaa3314dc9..00000000000 --- a/include/os/windows/spl/sys/ubc.h +++ /dev/null @@ -1,5 +0,0 @@ -#ifndef UBC_H_INCLUDED -#define UBC_H_INCLUDED - - -#endif diff --git a/include/os/windows/spl/sys/uio.h b/include/os/windows/spl/sys/uio.h index 554819e88f0..950becbc318 100644 --- a/include/os/windows/spl/sys/uio.h +++ b/include/os/windows/spl/sys/uio.h @@ -42,11 +42,10 @@ * contributors. */ - /* +/* * Copyright (c) 2017 Jorgen Lundman */ - #ifndef _SYS_UIO_H #define _SYS_UIO_H @@ -70,8 +69,8 @@ typedef struct iovec { /* -* I/O direction. -*/ + * I/O direction. + */ typedef enum uio_rw { UIO_READ, UIO_WRITE } uio_rw_t; /* @@ -87,9 +86,9 @@ typedef struct uio { uio_seg_t uio_segflg; /* address space (kernel or user) */ loff_t uio_limit; /* u-limit (maximum byte offset) */ ssize_t uio_resid; /* residual count */ - enum uio_rw uio_rw; - int uio_max_iovs; /* max number of iovecs this uio_t can hold */ - uint32_t uio_index; /* Current index */ + enum uio_rw uio_rw; + int uio_max_iovs; /* max # of iovecs uio_t can hold */ + uint32_t uio_index; /* Current index */ } uio_t; @@ -99,7 +98,8 @@ uio_t *uio_create(int iovcount, off_t offset, int spacetype, int iodirection); void uio_free(uio_t *uio); int uio_addiov(uio_t *uio, user_addr_t baseaddr, user_size_t length); int uio_isuserspace(uio_t *uio); -int uio_getiov(uio_t *uio, int index, user_addr_t *baseaddr, user_size_t *length); +int uio_getiov(uio_t *uio, int index, user_addr_t *baseaddr, + user_size_t *length); int uio_iovcnt(uio_t *uio); off_t uio_offset(uio_t *uio); void uio_update(uio_t *uio, user_size_t count); @@ -127,13 +127,13 @@ typedef enum xuio_type { } xuio_type_t; -#define UIOA_IOV_MAX 16 +#define UIOA_IOV_MAX 16 typedef struct uioa_page_s { - int uioa_pfncnt; - void **uioa_ppp; - caddr_t uioa_base; - size_t uioa_len; + int uioa_pfncnt; + void **uioa_ppp; + caddr_t uioa_base; + size_t uioa_len; } uioa_page_t; typedef struct xuio { @@ -155,12 +155,12 @@ typedef struct xuio { } xu_ext; } xuio_t; -#define XUIO_XUZC_PRIV(xuio) xuio->xu_ext.xu_zc.xu_zc_priv -#define XUIO_XUZC_RW(xuio) xuio->xu_ext.xu_zc.xu_zc_rw +#define XUIO_XUZC_PRIV(xuio) xuio->xu_ext.xu_zc.xu_zc_priv +#define XUIO_XUZC_RW(xuio) xuio->xu_ext.xu_zc.xu_zc_rw #define uio_segflg(U) \ (uio_isuserspace((struct uio *)(U))?UIO_USERSPACE:UIO_SYSSPACE) -#define uio_advance(U, N) uio_update((struct uio *)(U), (N)) +#define uio_advance(U, N) uio_update((struct uio *)(U), (N)) static inline uint64_t uio_iovlen(const struct uio *u, unsigned int i) @@ -198,28 +198,28 @@ uio_index_at_offset(struct uio *uio, long long off, unsigned int *vec_idx) } /* -* same as uiomove() but doesn't modify uio structure. -* return in cbytes how many bytes were copied. -*/ -static inline int uiocopy(const uint8_t *p, uint32_t n, enum uio_rw rw, struct uio *uio, uint64_t *cbytes) \ -{ \ - int result; \ - struct uio *nuio = uio_duplicate(uio); \ - unsigned long long x = uio_resid(uio); \ - if (!nuio) \ - return (ENOMEM); \ - uio_setrw(nuio, rw); \ - result = spl_uiomove(p, n, nuio); \ - *cbytes = (x - uio_resid(nuio)); \ - uio_free(nuio); \ - return result; \ + * same as uiomove() but doesn't modify uio structure. + * return in cbytes how many bytes were copied. + */ +static inline int +uiocopy(const uint8_t *p, uint32_t n, enum uio_rw rw, + struct uio *uio, uint64_t *cbytes) +{ + int result; + struct uio *nuio = uio_duplicate(uio); + unsigned long long x = uio_resid(uio); + if (!nuio) + return (ENOMEM); + uio_setrw(nuio, rw); + result = spl_uiomove(p, n, nuio); + *cbytes = (x - uio_resid(nuio)); + uio_free(nuio); + return (result); } // Apple's uiomove puts the uio_rw in uio_create -#define uiomove(A,B,C,D) spl_uiomove((const uint8_t *)(A),(B),(D)) -#define uioskip(A,B) uio_update((A), (B)) - - +#define uiomove(A, B, C, D) spl_uiomove((const uint8_t *)(A), (B), (D)) +#define uioskip(A, B) uio_update((A), (B)) #ifdef __cplusplus } diff --git a/include/os/windows/spl/sys/unistd.h b/include/os/windows/spl/sys/unistd.h index dd7c6c2d883..7f53079756e 100644 --- a/include/os/windows/spl/sys/unistd.h +++ b/include/os/windows/spl/sys/unistd.h @@ -1,7 +1,25 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ #ifndef _SPL_UNISTD_H -#define _SPL_UNISTD_H - -//#include_next +#define _SPL_UNISTD_H #endif /* SPL_UNISTD_H */ diff --git a/include/os/windows/spl/sys/utsname.h b/include/os/windows/spl/sys/utsname.h index 288c6ae5b9f..a500251b79f 100644 --- a/include/os/windows/spl/sys/utsname.h +++ b/include/os/windows/spl/sys/utsname.h @@ -30,15 +30,15 @@ #ifndef _SPL_UTSNAME_H -#define _SPL_UTSNAME_H +#define _SPL_UTSNAME_H -#define _SYS_NMLN 257 +#define _SYS_NMLN 257 struct opensolaris_utsname { - char sysname[_SYS_NMLN]; - char nodename[_SYS_NMLN]; - char release[_SYS_NMLN]; - char version[_SYS_NMLN]; - char machine[_SYS_NMLN]; + char sysname[_SYS_NMLN]; + char nodename[_SYS_NMLN]; + char release[_SYS_NMLN]; + char version[_SYS_NMLN]; + char machine[_SYS_NMLN]; }; typedef struct opensolaris_utsname utsname_t; diff --git a/include/os/windows/spl/sys/va_list.h b/include/os/windows/spl/sys/va_list.h deleted file mode 100644 index a35023cf303..00000000000 --- a/include/os/windows/spl/sys/va_list.h +++ /dev/null @@ -1,5 +0,0 @@ - -#ifndef _SPL_VA_LIST_H -#define _SPL_VA_LIST_H - -#endif /* SPL_VA_LIST_H */ diff --git a/include/os/windows/spl/sys/varargs.h b/include/os/windows/spl/sys/varargs.h index 6a65b9d0657..1b8b1fc16d5 100644 --- a/include/os/windows/spl/sys/varargs.h +++ b/include/os/windows/spl/sys/varargs.h @@ -1,7 +1,27 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ #ifndef _SPL_VARARGS_H -#define _SPL_VARARGS_H +#define _SPL_VARARGS_H -#define __va_list va_list +#define __va_list va_list #endif /* SPL_VARARGS_H */ diff --git a/include/os/windows/spl/sys/vfs.h b/include/os/windows/spl/sys/vfs.h index cf068c2625f..4df14d04f05 100644 --- a/include/os/windows/spl/sys/vfs.h +++ b/include/os/windows/spl/sys/vfs.h @@ -31,7 +31,7 @@ */ #ifndef _SPL_ZFS_H -#define _SPL_ZFS_H +#define _SPL_ZFS_H #include #include @@ -40,13 +40,10 @@ typedef struct mount vfs_t; -//#define LK_NOWAIT 0x00000010 /* do not sleep to await lock */ -#define vn_vfswlock(vp) (0) -#define vn_vfsunlock(vp) -#define VFS_HOLD(vfsp) -#define VFS_RELE(vfsp) - - +#define vn_vfswlock(vp) (0) +#define vn_vfsunlock(vp) +#define VFS_HOLD(vfsp) +#define VFS_RELE(vfsp) /* * File identifier. Should be unique per filesystem on a single @@ -66,20 +63,20 @@ typedef struct mount vfs_t; * Because a fid starts with a short it may not be 4 byte aligned, the * fid_pad will force the alignment. */ -#define MAXFIDSZ 64 -#define OLD_MAXFIDSZ 16 + +#define MAXFIDSZ 64 +#define OLD_MAXFIDSZ 16 typedef struct fid { - union { - long fid_pad; - struct { - ushort_t len; /* length of data in bytes */ - char data[MAXFIDSZ]; /* data (variable len) */ - } _fid; - } un; + union { + long fid_pad; + struct { + ushort_t len; /* length of data in bytes */ + char data[MAXFIDSZ]; /* data (variable len) */ + } _fid; + } un; } fid_t; - extern void (*mountroot_post_hook)(void); #endif /* SPL_ZFS_H */ diff --git a/include/os/windows/spl/sys/vfs_opreg.h b/include/os/windows/spl/sys/vfs_opreg.h index b795ae71d17..ee348904868 100644 --- a/include/os/windows/spl/sys/vfs_opreg.h +++ b/include/os/windows/spl/sys/vfs_opreg.h @@ -1,5 +1,25 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ #ifndef _SPL_OPREG_H -#define _SPL_OPREG_H +#define _SPL_OPREG_H #endif /* SPL_OPREG_H */ diff --git a/include/os/windows/spl/sys/vmem.h b/include/os/windows/spl/sys/vmem.h index 9ff8b26e0d8..3f609585e7f 100644 --- a/include/os/windows/spl/sys/vmem.h +++ b/include/os/windows/spl/sys/vmem.h @@ -32,140 +32,135 @@ extern "C" { #endif +#define KMEM_QUANTUM (PAGESIZE) -// BGH - Back to 512k users reporting glitching, beachballing etc. -//#define KMEM_QUANTUM (PAGESIZE<<7) - -#define KMEM_QUANTUM (PAGESIZE) // (<<5, 128k, has been running for months (as of 23 sept 2015), lower does glitch - - - - /* - * Per-allocation flags - */ +/* + * Per-allocation flags + */ #define VM_SLEEP 0x00000000 /* same as KM_SLEEP */ #define VM_NOSLEEP 0x00000001 /* same as KM_NOSLEEP */ #define VM_PANIC 0x00000002 /* same as KM_PANIC */ #define VM_PUSHPAGE 0x00000004 /* same as KM_PUSHPAGE */ #define VM_NORMALPRI 0x00000008 /* same as KM_NORMALPRI */ -#define VM_NODEBUG 0x00000010 /* matches KM_NODE~BUG, not implemented on OSX */ -#define VM_NO_VBA 0x00000020 /* OSX: do not descend to the bucket layer */ -#define VM_KMFLAGS 0x000000ff /* flags that must match KM_* flags */ - +#define VM_NODEBUG 0x00000010 /* matches KM_NODEBUG */ +#define VM_NO_VBA 0x00000020 /* do not descend to bucket */ +#define VM_KMFLAGS 0x000000ff /* flags to match KM_* flags */ #define VM_BESTFIT 0x00000100 #define VM_FIRSTFIT 0x00000200 #define VM_NEXTFIT 0x00000400 - /* - * The following flags are restricted for use only within the kernel. - * VM_MEMLOAD is for use by the HAT to avoid infinite recursion. - * VM_NORELOC is used by the kernel when static VA->PA mappings are required. - */ +/* + * The following flags are restricted for use only within the kernel. + * VM_MEMLOAD is for use by the HAT to avoid infinite recursion. + * VM_NORELOC is used by the kernel when static VA->PA mappings are required. + */ #define VM_MEMLOAD 0x00000800 #define VM_NORELOC 0x00001000 - /* - * VM_ABORT requests that vmem_alloc() *ignore* the VM_SLEEP/VM_NOSLEEP flags - * and forgo reaping if the allocation or attempted import, fails. This - * flag is a segkmem-specific flag, and should not be used by anyone else. - */ +/* + * VM_ABORT requests that vmem_alloc() *ignore* the VM_SLEEP/VM_NOSLEEP flags + * and forgo reaping if the allocation or attempted import, fails. This + * flag is a segkmem-specific flag, and should not be used by anyone else. + */ #define VM_ABORT 0x00002000 - /* - * VM_ENDALLOC requests that large addresses be preferred in allocations. - * Has no effect if VM_NEXTFIT is active. - */ +/* + * VM_ENDALLOC requests that large addresses be preferred in allocations. + * Has no effect if VM_NEXTFIT is active. + */ #define VM_ENDALLOC 0x00004000 #define VM_FLAGS 0x0000FFFF - /* - * Arena creation flags - */ +/* + * Arena creation flags + */ #define VMC_POPULATOR 0x00010000 #define VMC_NO_QCACHE 0x00020000 /* cannot use quantum caches */ #define VMC_IDENTIFIER 0x00040000 /* not backed by memory */ - // VMC_XALLOC 0x00080000 below - // VMC_XALIGN 0x00100000 below + #define VMC_DUMPSAFE 0x00200000 /* can use alternate dump memory */ - // KMC_IDENTIFIER == 0x00400000 - // KMC_PREFILL == 0x00800000 -#define VMC_TIMEFREE 0x01000000 /* keep span creation time, newest spans to front */ -#define VMC_OLDFIRST 0x02000000 /* must accompany VMC_TIMEFREE, oldest spans to front */ - /* - * internal use only; the import function uses the vmem_ximport_t interface - * and may increase the request size if it so desires. - * VMC_XALIGN, for use with vmem_xcreate, specifies that - * the address returned by the import function will be - * aligned according to the alignment argument. - */ + +/* keep span creation time, newest spans to front */ +#define VMC_TIMEFREE 0x01000000 + +/* must accompany VMC_TIMEFREE, oldest spans to front */ +#define VMC_OLDFIRST 0x02000000 +/* + * internal use only; the import function uses the vmem_ximport_t interface + * and may increase the request size if it so desires. + * VMC_XALIGN, for use with vmem_xcreate, specifies that + * the address returned by the import function will be + * aligned according to the alignment argument. + */ #define VMC_XALLOC 0x00080000 #define VMC_XALIGN 0x00100000 #define VMC_FLAGS 0xFFFF0000 - /* - * Public segment types - */ +/* + * Public segment types + */ #define VMEM_ALLOC 0x01 #define VMEM_FREE 0x02 - /* - * Implementation-private segment types - */ +/* + * Implementation-private segment types + */ #define VMEM_SPAN 0x10 #define VMEM_ROTOR 0x20 #define VMEM_WALKER 0x40 - /* - * VMEM_REENTRANT indicates to vmem_walk() that the callback routine may - * call back into the arena being walked, so vmem_walk() must drop the - * arena lock before each callback. The caveat is that since the arena - * isn't locked, its state can change. Therefore it is up to the callback - * routine to handle cases where the segment isn't of the expected type. - * For example, we use this to walk heap_arena when generating a crash dump; - * see segkmem_dump() for sample usage. - */ +/* + * VMEM_REENTRANT indicates to vmem_walk() that the callback routine may + * call back into the arena being walked, so vmem_walk() must drop the + * arena lock before each callback. The caveat is that since the arena + * isn't locked, its state can change. Therefore it is up to the callback + * routine to handle cases where the segment isn't of the expected type. + * For example, we use this to walk heap_arena when generating a crash dump; + * see segkmem_dump() for sample usage. + */ #define VMEM_REENTRANT 0x80000000 - struct vmem; +struct vmem; - typedef struct vmem vmem_t; - typedef void *(vmem_alloc_t)(vmem_t *, uint32_t, int); - typedef void (vmem_free_t)(vmem_t *, void *, uint32_t); +typedef struct vmem vmem_t; +typedef void *(vmem_alloc_t)(vmem_t *, uint32_t, int); +typedef void (vmem_free_t)(vmem_t *, void *, uint32_t); - /* - * Alternate import style; the requested size is passed in a pointer, - * which can be increased by the import function if desired. - */ - typedef void *(vmem_ximport_t)(vmem_t *, uint32_t *, uint32_t, int); +/* + * Alternate import style; the requested size is passed in a pointer, + * which can be increased by the import function if desired. + */ +typedef void *(vmem_ximport_t)(vmem_t *, uint32_t *, uint32_t, int); #ifdef _KERNEL - extern vmem_t *vmem_init(const char *, void *, uint32_t, uint32_t, - vmem_alloc_t *, vmem_free_t *); - extern void vmem_fini(vmem_t *); - extern void vmem_update(void *); - extern int vmem_is_populator(); - extern uint32_t vmem_seg_size; +extern vmem_t *vmem_init(const char *, void *, uint32_t, uint32_t, + vmem_alloc_t *, vmem_free_t *); +extern void vmem_fini(vmem_t *); +extern void vmem_update(void *); +extern int vmem_is_populator(); +extern uint32_t vmem_seg_size; #endif - extern vmem_t *vmem_create(const char *, void *, uint32_t, uint32_t, - vmem_alloc_t *, vmem_free_t *, vmem_t *, uint32_t, int); - extern vmem_t *vmem_xcreate(const char *, void *, uint32_t, uint32_t, - vmem_ximport_t *, vmem_free_t *, vmem_t *, uint32_t, int); - extern void vmem_destroy(vmem_t *); - extern void *vmem_alloc(vmem_t *, uint32_t, int); - extern void *vmem_xalloc(vmem_t *, uint32_t, uint32_t, uint32_t, uint32_t, - void *, void *, int); - extern void vmem_free(vmem_t *, void *, uint32_t); - extern void vmem_xfree(vmem_t *, void *, uint32_t); - extern void *vmem_add(vmem_t *, void *, uint32_t, int); - extern int vmem_contains(vmem_t *, void *, uint32_t); - extern void vmem_walk(vmem_t *, int, void (*)(void *, void *, uint32_t), void *); - extern uint32_t vmem_size(vmem_t *, int); - extern uint32_t vmem_size_locked(vmem_t *, int); - extern uint32_t vmem_size_semi_atomic(vmem_t *, int); - extern void vmem_qcache_reap(vmem_t *vmp); - extern int64_t vmem_buckets_size(int); +extern vmem_t *vmem_create(const char *, void *, uint32_t, uint32_t, + vmem_alloc_t *, vmem_free_t *, vmem_t *, uint32_t, int); +extern vmem_t *vmem_xcreate(const char *, void *, uint32_t, uint32_t, + vmem_ximport_t *, vmem_free_t *, vmem_t *, uint32_t, int); +extern void vmem_destroy(vmem_t *); +extern void *vmem_alloc(vmem_t *, uint32_t, int); +extern void *vmem_xalloc(vmem_t *, uint32_t, uint32_t, uint32_t, uint32_t, + void *, void *, int); +extern void vmem_free(vmem_t *, void *, uint32_t); +extern void vmem_xfree(vmem_t *, void *, uint32_t); +extern void *vmem_add(vmem_t *, void *, uint32_t, int); +extern int vmem_contains(vmem_t *, void *, uint32_t); +extern void vmem_walk(vmem_t *, int, void (*)(void *, void *, uint32_t), + void *); +extern uint32_t vmem_size(vmem_t *, int); +extern uint32_t vmem_size_locked(vmem_t *, int); +extern uint32_t vmem_size_semi_atomic(vmem_t *, int); +extern void vmem_qcache_reap(vmem_t *vmp); +extern int64_t vmem_buckets_size(int); #ifdef __cplusplus } diff --git a/include/os/windows/spl/sys/vmem_impl.h b/include/os/windows/spl/sys/vmem_impl.h index 95a6777f741..83be8db402a 100644 --- a/include/os/windows/spl/sys/vmem_impl.h +++ b/include/os/windows/spl/sys/vmem_impl.h @@ -42,39 +42,39 @@ extern "C" { #define VMEM_STACK_DEPTH 20 - struct vmem_seg { - /* - * The first four fields must match vmem_freelist_t exactly. - */ - uintptr_t vs_start; /* start of segment (inclusive) */ - uintptr_t vs_end; /* end of segment (exclusive) */ - vmem_seg_t *vs_knext; /* next of kin (alloc, free, span) */ - vmem_seg_t *vs_kprev; /* prev of kin */ - - vmem_seg_t *vs_anext; /* next in arena */ - vmem_seg_t *vs_aprev; /* prev in arena */ - uint8_t vs_type; /* alloc, free, span */ - uint8_t vs_import; /* non-zero if segment was imported */ - uint8_t vs_depth; /* stack depth if KMF_AUDIT active */ - /* - * if VM_FREESORT is set on the arena, then - * this field is set at span creation time. - */ - hrtime_t vs_span_createtime; - /* - * The following fields are present only when KMF_AUDIT is set. - */ - kthread_t *vs_thread; - hrtime_t vs_timestamp; - pc_t vs_stack[VMEM_STACK_DEPTH]; - }; - - typedef struct vmem_freelist { - uintptr_t vs_start; /* always zero */ - uintptr_t vs_end; /* segment size */ - vmem_seg_t *vs_knext; /* next of kin */ - vmem_seg_t *vs_kprev; /* prev of kin */ - } vmem_freelist_t; +struct vmem_seg { + /* + * The first four fields must match vmem_freelist_t exactly. + */ + uintptr_t vs_start; /* start of segment (inclusive) */ + uintptr_t vs_end; /* end of segment (exclusive) */ + vmem_seg_t *vs_knext; /* next of kin (alloc, free, span) */ + vmem_seg_t *vs_kprev; /* prev of kin */ + + vmem_seg_t *vs_anext; /* next in arena */ + vmem_seg_t *vs_aprev; /* prev in arena */ + uint8_t vs_type; /* alloc, free, span */ + uint8_t vs_import; /* non-zero if segment was imported */ + uint8_t vs_depth; /* stack depth if KMF_AUDIT active */ + /* + * if VM_FREESORT is set on the arena, then + * this field is set at span creation time. + */ + hrtime_t vs_span_createtime; + /* + * The following fields are present only when KMF_AUDIT is set. + */ + kthread_t *vs_thread; + hrtime_t vs_timestamp; + pc_t vs_stack[VMEM_STACK_DEPTH]; +}; + +typedef struct vmem_freelist { + uintptr_t vs_start; /* always zero */ + uintptr_t vs_end; /* segment size */ + vmem_seg_t *vs_knext; /* next of kin */ + vmem_seg_t *vs_kprev; /* prev of kin */ +} vmem_freelist_t; #define VS_SIZE(vsp) ((vsp)->vs_end - (vsp)->vs_start) @@ -96,57 +96,58 @@ extern "C" { #define VMEM_NQCACHE_MAX 16 #define VMEM_FREELISTS (sizeof (void *) * 8) - typedef struct vmem_kstat { - kstat_named_t vk_mem_inuse; /* memory in use */ - kstat_named_t vk_mem_import; /* memory imported */ - kstat_named_t vk_mem_total; /* total memory in arena */ - kstat_named_t vk_source_id; /* vmem id of vmem source */ - kstat_named_t vk_alloc; /* number of allocations */ - kstat_named_t vk_free; /* number of frees */ - kstat_named_t vk_wait; /* number of allocations that waited */ - kstat_named_t vk_fail; /* number of allocations that failed */ - kstat_named_t vk_lookup; /* hash lookup count */ - kstat_named_t vk_search; /* freelist search count */ - kstat_named_t vk_populate_fail; /* populates that failed */ - kstat_named_t vk_contains; /* vmem_contains() calls */ - kstat_named_t vk_contains_search; /* vmem_contains() search cnt */ - kstat_named_t vk_parent_alloc; /* called the source allocator */ - kstat_named_t vk_parent_free; /* called the source free function */ - kstat_named_t vk_threads_waiting; /* threads in cv_wait in vmem allocator function */ - kstat_named_t vk_excess; /* count of retained excess imports */ - } vmem_kstat_t; - - struct vmem { - char vm_name[VMEM_NAMELEN]; /* arena name */ - kcondvar_t vm_cv; /* cv for blocking allocations */ - kmutex_t vm_lock; /* arena lock */ - uint32_t vm_id; /* vmem id */ - hrtime_t vm_createtime; - uint32_t vm_mtbf; /* induced alloc failure rate */ - int vm_cflags; /* arena creation flags */ - int vm_qshift; /* log2(vm_quantum) */ - uint32_t vm_quantum; /* vmem quantum */ - uint32_t vm_qcache_max; /* maximum size to front by kmem */ - uint32_t vm_min_import; /* smallest amount to import */ - void *(*vm_source_alloc)(vmem_t *, uint32_t, int); - void (*vm_source_free)(vmem_t *, void *, uint32_t); - vmem_t *vm_source; /* vmem source for imported memory */ - vmem_t *vm_next; /* next in vmem_list */ - kstat_t *vm_ksp; /* kstat */ - ssize_t vm_nsegfree; /* number of free vmem_seg_t's */ - vmem_seg_t *vm_segfree; /* free vmem_seg_t list */ - vmem_seg_t **vm_hash_table; /* allocated-segment hash table */ - uint32_t vm_hash_mask; /* hash_size - 1 */ - uint32_t vm_hash_shift; /* log2(vm_hash_mask + 1) */ - ulong_t vm_freemap; /* bitmap of non-empty freelists */ - vmem_seg_t vm_seg0; /* anchor segment */ - vmem_seg_t vm_rotor; /* rotor for VM_NEXTFIT allocations */ - vmem_seg_t *vm_hash0[VMEM_HASH_INITIAL]; /* initial hash table */ - void *vm_qcache[VMEM_NQCACHE_MAX]; /* quantum caches */ - vmem_freelist_t vm_freelist[VMEM_FREELISTS + 1]; /* power-of-2 flists */ - vmem_kstat_t vm_kstat; /* kstat data */ - }; - typedef struct vmem vmem_t; +typedef struct vmem_kstat { + kstat_named_t vk_mem_inuse; /* memory in use */ + kstat_named_t vk_mem_import; /* memory imported */ + kstat_named_t vk_mem_total; /* total memory in arena */ + kstat_named_t vk_source_id; /* vmem id of vmem source */ + kstat_named_t vk_alloc; /* number of allocations */ + kstat_named_t vk_free; /* number of frees */ + kstat_named_t vk_wait; /* number of allocations that waited */ + kstat_named_t vk_fail; /* number of allocations that failed */ + kstat_named_t vk_lookup; /* hash lookup count */ + kstat_named_t vk_search; /* freelist search count */ + kstat_named_t vk_populate_fail; /* populates that failed */ + kstat_named_t vk_contains; /* vmem_contains() calls */ + kstat_named_t vk_contains_search; /* vmem_contains() search cnt */ + kstat_named_t vk_parent_alloc; /* called the source allocator */ + kstat_named_t vk_parent_free; /* called the source free function */ + kstat_named_t vk_threads_waiting; /* threads in cv_wait in vmem */ + kstat_named_t vk_excess; /* count of retained excess imports */ +} vmem_kstat_t; + +struct vmem { + char vm_name[VMEM_NAMELEN]; /* arena name */ + kcondvar_t vm_cv; /* cv for blocking allocations */ + kmutex_t vm_lock; /* arena lock */ + uint32_t vm_id; /* vmem id */ + hrtime_t vm_createtime; + uint32_t vm_mtbf; /* induced alloc failure rate */ + int vm_cflags; /* arena creation flags */ + int vm_qshift; /* log2(vm_quantum) */ + uint32_t vm_quantum; /* vmem quantum */ + uint32_t vm_qcache_max; /* maximum size to front by kmem */ + uint32_t vm_min_import; /* smallest amount to import */ + void *(*vm_source_alloc)(vmem_t *, uint32_t, int); + void (*vm_source_free)(vmem_t *, void *, uint32_t); + vmem_t *vm_source; /* vmem source for imported memory */ + vmem_t *vm_next; /* next in vmem_list */ + kstat_t *vm_ksp; /* kstat */ + ssize_t vm_nsegfree; /* number of free vmem_seg_t's */ + vmem_seg_t *vm_segfree; /* free vmem_seg_t list */ + vmem_seg_t **vm_hash_table; /* allocated-segment hash table */ + uint32_t vm_hash_mask; /* hash_size - 1 */ + uint32_t vm_hash_shift; /* log2(vm_hash_mask + 1) */ + ulong_t vm_freemap; /* bitmap of non-empty freelists */ + vmem_seg_t vm_seg0; /* anchor segment */ + vmem_seg_t vm_rotor; /* rotor for VM_NEXTFIT allocations */ + vmem_seg_t *vm_hash0[VMEM_HASH_INITIAL]; /* initial hash table */ + void *vm_qcache[VMEM_NQCACHE_MAX]; /* quantum caches */ + vmem_freelist_t vm_freelist[VMEM_FREELISTS + 1]; /* power-of-2 flists */ + vmem_kstat_t vm_kstat; /* kstat data */ +}; +typedef struct vmem vmem_t; + #ifdef __cplusplus } #endif diff --git a/include/os/windows/spl/sys/vmsystm.h b/include/os/windows/spl/sys/vmsystm.h index 404db445f75..3a605a2b9b5 100644 --- a/include/os/windows/spl/sys/vmsystm.h +++ b/include/os/windows/spl/sys/vmsystm.h @@ -20,7 +20,7 @@ */ #ifndef _SPL_VMSYSTM_H -#define _SPL_VMSYSTM_H +#define _SPL_VMSYSTM_H #include diff --git a/include/os/windows/spl/sys/vnode.h b/include/os/windows/spl/sys/vnode.h index 485f364db17..48dc8727de5 100644 --- a/include/os/windows/spl/sys/vnode.h +++ b/include/os/windows/spl/sys/vnode.h @@ -26,7 +26,7 @@ */ #ifndef _SPL_VNODE_H -#define _SPL_VNODE_H +#define _SPL_VNODE_H #include @@ -38,32 +38,30 @@ #include #include #include -#include #include -//#include #include /* Enable to track all IOCOUNT */ -//#define DEBUG_IOCOUNT +// #define DEBUG_IOCOUNT /* * Lets define a vnode struct that will hold everything needed for Windows * request to be handled. */ -#define VNODE_DEAD 1 -#define VNODE_MARKTERM 2 -#define VNODE_NEEDINACTIVE 4 -#define VNODE_MARKROOT 8 -#define VNODE_SIZECHANGE 16 -#define VNODE_EASIZE 32 -#define VNODE_FLUSHING 64 -#define VNODE_VALIDBITS 127 +#define VNODE_DEAD 1 +#define VNODE_MARKTERM 2 +#define VNODE_NEEDINACTIVE 4 +#define VNODE_MARKROOT 8 +#define VNODE_SIZECHANGE 16 +#define VNODE_EASIZE 32 +#define VNODE_FLUSHING 64 +#define VNODE_VALIDBITS 127 /* v_unlink flags */ -#define UNLINK_DELETE_ON_CLOSE (1 << 0) // 1 -#define UNLINK_DELETED (1 << 1) // 2 +#define UNLINK_DELETE_ON_CLOSE (1 << 0) // 1 +#define UNLINK_DELETED (1 << 1) // 2 #include typedef struct vnode_fileobjects { @@ -88,7 +86,7 @@ struct vnode { mount_t *v_mount; uint32_t v_flags; - uint32_t v_iocount; // Short term holds + uint32_t v_iocount; // Short term holds uint32_t v_usecount; // Long term holds uint32_t v_type; uint32_t v_unlink; @@ -96,11 +94,11 @@ struct vnode { void *v_data; uint64_t v_id; uint64_t v_easize; - hrtime_t v_age; // How long since entered DEAD + hrtime_t v_age; // How long since entered DEAD // Other Windows entries // Must be 8byte aligned - ERESOURCE resource; // Holder for FileHeader.Resource + ERESOURCE resource; // Holder for FileHeader.Resource ERESOURCE pageio_resource; // Holder for FileHeader.PageIoResource FILE_LOCK lock; SECURITY_DESCRIPTOR *security_descriptor; @@ -122,16 +120,16 @@ typedef int vcexcl_t; enum vcexcl { NONEXCL, EXCL }; -#define VSUID 0x800 /*04000*/ /* set user id on execution */ -#define VSGID 0x400 /*02000*/ /* set group id on execution */ -#define VSVTX 0x200 /*01000*/ /* save swapped text even after use */ -#define VREAD 0x100 /*00400*/ /* read, write, execute permissions */ -#define VWRITE 0x080 /*00200*/ -#define VEXEC 0x040 /*00100*/ +#define VSUID 0x800 /* 04000 */ /* set user id on execution */ +#define VSGID 0x400 /* 02000 */ /* set group id on execution */ +#define VSVTX 0x200 /* 01000 */ /* save swapped text even after use */ +#define VREAD 0x100 /* 00400 */ /* read, write, execute permissions */ +#define VWRITE 0x080 /* 00200 */ +#define VEXEC 0x040 /* 00100 */ /* -* Vnode types. VNON means no type. -*/ + * Vnode types. VNON means no type. + */ enum vtype { /* 0 */ VNON, @@ -141,367 +139,317 @@ enum vtype { VSOCK, VFIFO, VBAD, VSTR, VCPLX }; -extern enum vtype iftovt_tab[]; -extern int vttoif_tab[]; +extern enum vtype iftovt_tab[]; +extern int vttoif_tab[]; -#define IFTOVT(mode) (iftovt_tab[((mode)& S_IFMT) >> 12]) -#define VTTOIF(indx) (vttoif_tab[(int)(indx)]) -#define MAKEIMODE(indx, mode) (int)(VTTOIF(indx) | (mode)) +#define IFTOVT(mode) (iftovt_tab[((mode)& S_IFMT) >> 12]) +#define VTTOIF(indx) (vttoif_tab[(int)(indx)]) +#define MAKEIMODE(indx, mode) (int)(VTTOIF(indx) | (mode)) +#define ATTR_NOACLCHECK 0x20 /* * Windows uses separate vnop getfileinformation to deal with XATTRs, so * we never get vop&XVATTR set from VFS. All internal checks for it in * ZFS is not required. */ -#define ATTR_XVATTR 0 -#define AT_XVATTR ATTR_XVATTR +#define ATTR_XVATTR 0 +#define AT_XVATTR ATTR_XVATTR -#define B_INVAL 0x01 -#define B_TRUNC 0x02 +#define B_INVAL 0x01 +#define B_TRUNC 0x02 #define CREATE_XATTR_DIR 0x04 /* Create extended attr dir */ -#define DNLC_NO_VNODE (struct vnode *)(-1) - - -#define IS_DEVVP(vp) \ - (vnode_ischr(vp) || vnode_isblk(vp) || vnode_isfifo(vp)) - - - -#define VNODE_ATTR_va_rdev (1LL << 0) /* 00000001 */ -#define VNODE_ATTR_va_nlink (1LL << 1) /* 00000002 */ -#define VNODE_ATTR_va_total_size (1LL << 2) /* 00000004 */ -#define VNODE_ATTR_va_total_alloc (1LL << 3) /* 00000008 */ -#define VNODE_ATTR_va_data_size (1LL << 4) /* 00000010 */ -#define VNODE_ATTR_va_data_alloc (1LL << 5) /* 00000020 */ -#define VNODE_ATTR_va_iosize (1LL << 6) /* 00000040 */ -#define VNODE_ATTR_va_uid (1LL << 7) /* 00000080 */ -#define VNODE_ATTR_va_gid (1LL << 8) /* 00000100 */ -#define VNODE_ATTR_va_mode (1LL << 9) /* 00000200 */ -#define VNODE_ATTR_va_flags (1LL << 10) /* 00000400 */ -#define VNODE_ATTR_va_acl (1LL << 11) /* 00000800 */ -#define VNODE_ATTR_va_create_time (1LL << 12) /* 00001000 */ -#define VNODE_ATTR_va_access_time (1LL << 13) /* 00002000 */ -#define VNODE_ATTR_va_modify_time (1LL << 14) /* 00004000 */ -#define VNODE_ATTR_va_change_time (1LL << 15) /* 00008000 */ -#define VNODE_ATTR_va_backup_time (1LL << 16) /* 00010000 */ -#define VNODE_ATTR_va_fileid (1LL << 17) /* 00020000 */ -#define VNODE_ATTR_va_linkid (1LL << 18) /* 00040000 */ -#define VNODE_ATTR_va_parentid (1LL << 19) /* 00080000 */ -#define VNODE_ATTR_va_fsid (1LL << 20) /* 00100000 */ -#define VNODE_ATTR_va_filerev (1LL << 21) /* 00200000 */ -#define VNODE_ATTR_va_gen (1LL << 22) /* 00400000 */ -#define VNODE_ATTR_va_encoding (1LL << 23) /* 00800000 */ -#define VNODE_ATTR_va_type (1LL << 24) /* 01000000 */ -#define VNODE_ATTR_va_name (1LL << 25) /* 02000000 */ -#define VNODE_ATTR_va_uuuid (1LL << 26) /* 04000000 */ -#define VNODE_ATTR_va_guuid (1LL << 27) /* 08000000 */ -#define VNODE_ATTR_va_nchildren (1LL << 28) /* 10000000 */ -#define VNODE_ATTR_va_dirlinkcount (1LL << 29) /* 20000000 */ -#define VNODE_ATTR_va_addedtime (1LL << 30) /* 40000000 */ - -enum rm { RMFILE, RMDIRECTORY }; /* rm or rmdir (remove) */ -enum create { CRCREAT, CRMKNOD, CRMKDIR }; /* reason for create */ - -#define va_mask va_active -#define va_nodeid va_fileid -#define va_nblocks va_filerev +#define DNLC_NO_VNODE (struct vnode *)(-1) + + +#define IS_DEVVP(vp) \ + (vnode_ischr(vp) || vnode_isblk(vp) || vnode_isfifo(vp)) + +#define VNODE_ATTR_va_rdev (1LL << 0) /* 00000001 */ +#define VNODE_ATTR_va_nlink (1LL << 1) /* 00000002 */ +#define VNODE_ATTR_va_total_size (1LL << 2) /* 00000004 */ +#define VNODE_ATTR_va_total_alloc (1LL << 3) /* 00000008 */ +#define VNODE_ATTR_va_data_size (1LL << 4) /* 00000010 */ +#define VNODE_ATTR_va_data_alloc (1LL << 5) /* 00000020 */ +#define VNODE_ATTR_va_iosize (1LL << 6) /* 00000040 */ +#define VNODE_ATTR_va_uid (1LL << 7) /* 00000080 */ +#define VNODE_ATTR_va_gid (1LL << 8) /* 00000100 */ +#define VNODE_ATTR_va_mode (1LL << 9) /* 00000200 */ +#define VNODE_ATTR_va_flags (1LL << 10) /* 00000400 */ +#define VNODE_ATTR_va_acl (1LL << 11) /* 00000800 */ +#define VNODE_ATTR_va_create_time (1LL << 12) /* 00001000 */ +#define VNODE_ATTR_va_access_time (1LL << 13) /* 00002000 */ +#define VNODE_ATTR_va_modify_time (1LL << 14) /* 00004000 */ +#define VNODE_ATTR_va_change_time (1LL << 15) /* 00008000 */ +#define VNODE_ATTR_va_backup_time (1LL << 16) /* 00010000 */ +#define VNODE_ATTR_va_fileid (1LL << 17) /* 00020000 */ +#define VNODE_ATTR_va_linkid (1LL << 18) /* 00040000 */ +#define VNODE_ATTR_va_parentid (1LL << 19) /* 00080000 */ +#define VNODE_ATTR_va_fsid (1LL << 20) /* 00100000 */ +#define VNODE_ATTR_va_filerev (1LL << 21) /* 00200000 */ +#define VNODE_ATTR_va_gen (1LL << 22) /* 00400000 */ +#define VNODE_ATTR_va_encoding (1LL << 23) /* 00800000 */ +#define VNODE_ATTR_va_type (1LL << 24) /* 01000000 */ +#define VNODE_ATTR_va_name (1LL << 25) /* 02000000 */ +#define VNODE_ATTR_va_uuuid (1LL << 26) /* 04000000 */ +#define VNODE_ATTR_va_guuid (1LL << 27) /* 08000000 */ +#define VNODE_ATTR_va_nchildren (1LL << 28) /* 10000000 */ +#define VNODE_ATTR_va_dirlinkcount (1LL << 29) /* 20000000 */ +#define VNODE_ATTR_va_addedtime (1LL << 30) /* 40000000 */ + +enum rm { RMFILE, RMDIRECTORY }; /* rm or rmdir (remove) */ +enum create { CRCREAT, CRMKNOD, CRMKDIR }; /* reason for create */ + +#define va_mask va_active +#define va_nodeid va_fileid +#define va_nblocks va_filerev /* * vnode attr translations */ -#define ATTR_TYPE VNODE_ATTR_va_type -#define ATTR_MODE VNODE_ATTR_va_mode -#define ATTR_ACL VNODE_ATTR_va_acl -#define ATTR_UID VNODE_ATTR_va_uid -#define ATTR_GID VNODE_ATTR_va_gid -#define ATTR_ATIME VNODE_ATTR_va_access_time -#define ATTR_MTIME VNODE_ATTR_va_modify_time -#define ATTR_CTIME VNODE_ATTR_va_change_time -#define ATTR_CRTIME VNODE_ATTR_va_create_time -#define ATTR_SIZE VNODE_ATTR_va_data_size -#define ATTR_NOSET 0 - -#define va_size va_data_size -#define va_atime va_access_time -#define va_mtime va_modify_time -#define va_ctime va_change_time -#define va_crtime va_create_time -#define va_bytes va_data_size +#define ATTR_TYPE VNODE_ATTR_va_type +#define ATTR_MODE VNODE_ATTR_va_mode +#define ATTR_ACL VNODE_ATTR_va_acl +#define ATTR_UID VNODE_ATTR_va_uid +#define ATTR_GID VNODE_ATTR_va_gid +#define ATTR_ATIME VNODE_ATTR_va_access_time +#define ATTR_MTIME VNODE_ATTR_va_modify_time +#define ATTR_CTIME VNODE_ATTR_va_change_time +#define ATTR_CRTIME VNODE_ATTR_va_create_time +#define ATTR_SIZE VNODE_ATTR_va_data_size +#define ATTR_NOSET 0 + +#define va_size va_data_size +#define va_atime va_access_time +#define va_mtime va_modify_time +#define va_ctime va_change_time +#define va_crtime va_create_time +#define va_bytes va_data_size // TBD - this comes from XNU, to assist with compiling right now, but // this struct should be replaced with whatever we cook up for Windows struct vnode_attr { - uint64_t va_supported; - uint64_t va_active; - int va_vaflags; - dev_t va_rdev; /* device id (device nodes only) */ - uint64_t va_nlink; /* number of references to this file */ - uint64_t va_total_size; /* size in bytes of all forks */ - uint64_t va_total_alloc; /* disk space used by all forks */ - uint64_t va_data_size; /* size in bytes of the fork managed by current vnode */ - uint64_t va_data_alloc; /* disk space used by the fork managed by current vnode */ - uint32_t va_iosize; /* optimal I/O blocksize */ - - /* file security information */ - uid_t va_uid; /* owner UID */ - gid_t va_gid; /* owner GID */ - mode_t va_mode; /* posix permissions */ - uint32_t va_flags; /* file flags */ - struct kauth_acl *va_acl; /* access control list */ - - struct timespec va_create_time; /* time of creation */ - struct timespec va_access_time; /* time of last access */ - struct timespec va_modify_time; /* time of last data modification */ - struct timespec va_change_time; /* time of last metadata change */ - struct timespec va_backup_time; /* time of last backup */ - - uint64_t va_fileid; /* file unique ID in filesystem */ - uint64_t va_linkid; /* file link unique ID */ - uint64_t va_parentid; /* parent ID */ - uint32_t va_fsid; /* filesystem ID */ - uint64_t va_filerev; /* file revision counter */ /* XXX */ - - enum vtype va_type; /* file type (create only) */ - char * va_name; /* Name for ATTR_CMN_NAME; MAXPATHLEN bytes */ + uint64_t va_supported; + uint64_t va_active; + int va_vaflags; + dev_t va_rdev; /* device id (device nodes only) */ + uint64_t va_nlink; /* number of references to this file */ + uint64_t va_total_size; /* size in bytes of all forks */ + uint64_t va_total_alloc; /* disk space used by all forks */ + uint64_t va_data_size; /* size in bytes of the fork */ + uint64_t va_data_alloc; /* disk space used by the fork */ + uint32_t va_iosize; /* optimal I/O blocksize */ + + /* file security information */ + uid_t va_uid; /* owner UID */ + gid_t va_gid; /* owner GID */ + mode_t va_mode; /* posix permissions */ + uint32_t va_flags; /* file flags */ + struct kauth_acl *va_acl; /* access control list */ + + struct timespec va_create_time; /* time of creation */ + struct timespec va_access_time; /* time of last access */ + struct timespec va_modify_time; /* time of last data modification */ + struct timespec va_change_time; /* time of last metadata change */ + struct timespec va_backup_time; /* time of last backup */ + + uint64_t va_fileid; /* file unique ID in filesystem */ + uint64_t va_linkid; /* file link unique ID */ + uint64_t va_parentid; /* parent ID */ + uint32_t va_fsid; /* filesystem ID */ + uint64_t va_filerev; /* file revision counter */ + + enum vtype va_type; /* file type (create only) */ + char *va_name; /* Name for ATTR_CMN_NAME; */ + /* MAXPATHLEN bytes */ }; typedef struct vnode_attr vattr; typedef struct vnode_attr vattr_t; /* vsa_mask values */ -#define VSA_ACL 0x0001 -#define VSA_ACLCNT 0x0002 -#define VSA_DFACL 0x0004 -#define VSA_DFACLCNT 0x0008 -#define VSA_ACE 0x0010 -#define VSA_ACECNT 0x0020 -#define VSA_ACE_ALLTYPES 0x0040 -#define VSA_ACE_ACLFLAGS 0x0080 /* get/set ACE ACL flags */ +#define VSA_ACL 0x0001 +#define VSA_ACLCNT 0x0002 +#define VSA_DFACL 0x0004 +#define VSA_DFACLCNT 0x0008 +#define VSA_ACE 0x0010 +#define VSA_ACECNT 0x0020 +#define VSA_ACE_ALLTYPES 0x0040 +#define VSA_ACE_ACLFLAGS 0x0080 /* get/set ACE ACL flags */ /* * component name operations (for VNOP_LOOKUP) */ // Unfortunately 'DELETE' is a Win32 define as well. // We should consider moving all these to VN_* -#define LOOKUP 0 /* perform name lookup only */ -#define CREATE 1 /* setup for file creation */ -#define VN_DELETE 2 /* setup for file deletion */ -#define RENAME 3 /* setup for file renaming */ -#define OPMASK 3 /* mask for operation */ +#define LOOKUP 0 /* perform name lookup only */ +#define CREATE 1 /* setup for file creation */ +#define VN_DELETE 2 /* setup for file deletion */ +#define RENAME 3 /* setup for file renaming */ +#define OPMASK 3 /* mask for operation */ /* * component name operational modifier flags */ -#define FOLLOW 0x00000040 /* follow symbolic links */ -#define NOTRIGGER 0x10000000 /* don't trigger automounts */ +#define FOLLOW 0x00000040 /* follow symbolic links */ +#define NOTRIGGER 0x10000000 /* don't trigger automounts */ /* * component name parameter descriptors. */ -#define ISDOTDOT 0x00002000 /* current component name is .. */ -#define MAKEENTRY 0x00004000 /* entry is to be added to name cache */ -#define ISLASTCN 0x00008000 /* this is last component of pathname */ -#define ISWHITEOUT 0x00020000 /* OBSOLETE: found whiteout */ -#define DOWHITEOUT 0x00040000 /* OBSOLETE: do whiteouts */ +#define ISDOTDOT 0x00002000 /* current component name is .. */ +#define MAKEENTRY 0x00004000 /* entry is to be added to name cache */ +#define ISLASTCN 0x00008000 /* this is last component of pathname */ +#define ISWHITEOUT 0x00020000 /* OBSOLETE: found whiteout */ +#define DOWHITEOUT 0x00040000 /* OBSOLETE: do whiteouts */ struct componentname { uint32_t cn_nameiop; uint32_t cn_flags; char *cn_pnbuf; - int cn_pnlen; - char *cn_nameptr; - int cn_namelen; + int cn_pnlen; + char *cn_nameptr; + int cn_namelen; }; - - - extern struct vnode *vn_alloc(int flag); extern int vn_open(char *pnamep, enum uio_seg seg, int filemode, - int createmode, - struct vnode **vpp, enum create crwhy, mode_t umask); + int createmode, + struct vnode **vpp, enum create crwhy, mode_t umask); extern int vn_openat(char *pnamep, enum uio_seg seg, int filemode, - int createmode, struct vnode **vpp, enum create crwhy, - mode_t umask, struct vnode *startvp); - -#define vn_renamepath(tdvp, svp, tnm, lentnm) do { } while (0) -#define vn_free(vp) do { } while (0) -#define vn_pages_remove(vp,fl,op) do { } while (0) - + int createmode, struct vnode **vpp, enum create crwhy, + mode_t umask, struct vnode *startvp); +#define vn_renamepath(tdvp, svp, tnm, lentnm) do { } while (0) +#define vn_free(vp) do { } while (0) +#define vn_pages_remove(vp, fl, op) do { } while (0) // OSX kernel has a vn_rdwr, let's work around it. extern int zfs_vn_rdwr(enum uio_rw rw, struct vnode *vp, caddr_t base, - ssize_t len, offset_t offset, enum uio_seg seg, - int ioflag, rlim64_t ulimit, cred_t *cr, - ssize_t *residp); + ssize_t len, offset_t offset, enum uio_seg seg, + int ioflag, rlim64_t ulimit, cred_t *cr, + ssize_t *residp); -#define vn_rdwr(rw, vp, base, len, off, seg, flg, limit, cr, resid) \ - zfs_vn_rdwr((rw), (vp), (base), (len), (off), (seg), (flg), (limit), (cr), (resid)) +#define vn_rdwr(rw, vp, base, len, off, seg, flg, limit, cr, resid) \ + zfs_vn_rdwr((rw), (vp), (base), (len), (off), (seg), (flg),\ + (limit), (cr), (resid)) extern int vn_remove(char *fnamep, enum uio_seg seg, enum rm dirflag); extern int vn_rename(char *from, char *to, enum uio_seg seg); -#define LK_RETRY 0 -#define LK_SHARED 0 -#define VN_UNLOCK( vp ) +#define LK_RETRY 0 +#define LK_SHARED 0 +#define VN_UNLOCK(vp) static inline int vn_lock(struct vnode *vp, int fl) { return 0; } - // KERNEL #ifdef DEBUG_IOCOUNT -#define VN_HOLD(vp) vnode_getwithref(vp, __FILE__, __LINE__) -#define VN_RELE(vp) \ - do { \ - if ((vp) && (vp) != DNLC_NO_VNODE) \ - vnode_put(vp, __FILE__, __LINE__); \ - } while (0) -#define vnode_getwithvid(V, ID) vnode_debug_getwithvid((V), (ID), __FILE__, __LINE__) +#define VN_HOLD(vp) vnode_getwithref(vp, __FILE__, __LINE__) +#define VN_RELE(vp) \ + do { \ + if ((vp) && (vp) != DNLC_NO_VNODE) \ + vnode_put(vp, __FILE__, __LINE__); \ + } while (0) +#define vnode_getwithvid(V, ID) \ + vnode_debug_getwithvid((V), (ID), __FILE__, __LINE__) #else -#define VN_HOLD(vp) vnode_getwithref(vp) -#define VN_RELE(vp) \ - do { \ - if ((vp) && (vp) != DNLC_NO_VNODE) \ - vnode_put(vp); \ - } while (0) +#define VN_HOLD(vp) vnode_getwithref(vp) +#define VN_RELE(vp) vnode_put(vp); #endif - - void spl_rele_async(void *arg); void vn_rele_async(struct vnode *vp, void *taskq); -#define VN_RELE_ASYNC(vp,tq) vn_rele_async((vp),(tq)) +#define VN_RELE_ASYNC(vp, tq) vn_rele_async((vp), (tq)) -#define vn_exists(vp) -#define vn_is_readonly(vp) vnode_vfsisrdonly(vp) +#define vn_exists(vp) +#define vn_is_readonly(vp) vnode_vfsisrdonly(vp) -#define VATTR_NULL(v) do { } while(0) +#define VATTR_NULL(v) do { } while (0) extern int -VOP_CLOSE(struct vnode *vp, int flag, int count, offset_t off, void *cr, void *); +VOP_CLOSE(struct vnode *vp, int flag, int count, offset_t off, + void *cr, void *); extern int VOP_FSYNC(struct vnode *vp, int flags, void* unused, void *); extern int VOP_SPACE(HANDLE h, int cmd, struct flock *fl, int flags, offset_t off, - cred_t *cr, void *ctx); + cred_t *cr, void *ctx); -extern int VOP_GETATTR(struct vnode *vp, vattr_t *vap, int flags, void *x3, void *x4); +extern int VOP_GETATTR(struct vnode *vp, vattr_t *vap, int flags, + void *x3, void *x4); -#define VOP_UNLOCK(vp,fl) do { } while(0) +#define VOP_UNLOCK(vp, fl) do { } while (0) void vfs_mountedfrom(struct mount *vfsp, char *osname); -extern struct vnode *dnlc_lookup ( struct vnode *dvp, char *name ); -extern int dnlc_purge_vfsp ( struct mount *mp, int flags ); -extern void dnlc_remove ( struct vnode *vp, char *name ); -extern void dnlc_update ( struct vnode *vp, char *name, - struct vnode *tp); - -//#define build_path(A, B, C, D, E, F) spl_build_path(A,B,C,D,E,F) -//extern int spl_build_path(struct vnode *vp, char *buff, int buflen, int *outlen, -// int flags, vfs_context_t ctx); - +extern struct vnode *dnlc_lookup(struct vnode *dvp, char *name); +extern int dnlc_purge_vfsp(struct mount *mp, int flags); +extern void dnlc_remove(struct vnode *vp, char *name); +extern void dnlc_update(struct vnode *vp, char *name, + struct vnode *tp); extern struct vnode *rootdir; static inline int -chklock(struct vnode *vp, int iomode, unsigned long long offset, ssize_t len, int fmode, void *ct) +chklock(struct vnode *vp, int iomode, unsigned long long offset, + ssize_t len, int fmode, void *ct) { - return (0); + return (0); } -#define vn_has_cached_data(VP) 0 /*(VTOZ(VP)->z_is_mapped || vnode_isswap(VP) || win_has_cached_data(VP))*/ +#define vn_has_cached_data(VP) 0 +/* (VTOZ(VP)->z_is_mapped || vnode_isswap(VP) || win_has_cached_data(VP)) */ -static inline int win_has_cached_data(struct vnode *vp) +static inline int +win_has_cached_data(struct vnode *vp) { int ret = 0; - PFILE_OBJECT pfo = CcGetFileObjectFromSectionPtrsRef(&vp->SectionObjectPointers); + PFILE_OBJECT pfo = + CcGetFileObjectFromSectionPtrsRef(&vp->SectionObjectPointers); if (pfo) { - // Although peeking in this macro, it only looks at SectionPointers, so maybe - // we should do that directly, and skip the FileObject extra? - ret = CcIsFileCached(pfo); - ObDereferenceObject(pfo); + ret = CcIsFileCached(pfo); + ObDereferenceObject(pfo); } - return ret; + return (ret); } -#if 0 -// Since CcGetFileObjectFromSectionPtrsRef is vista and up, we store FileObject in vp now. -#define vnode_pager_setsize(vp, sz) do { \ - PFILE_OBJECT fileObject = CcGetFileObjectFromSectionPtrsRef(&vp->SectionObjectPointers); \ - if (fileObject != NULL) { \ - CC_FILE_SIZES ccfs; \ - vp->FileHeader.AllocationSize.QuadPart = P2ROUNDUP((sz), PAGE_SIZE); \ - vp->FileHeader.FileSize.QuadPart = (sz); \ - vp->FileHeader.ValidDataLength.QuadPart = (sz); \ - ccfs.AllocationSize = vp->FileHeader.AllocationSize; \ - ccfs.FileSize = vp->FileHeader.FileSize; \ - ccfs.ValidDataLength = vp->FileHeader.ValidDataLength; \ - CcSetFileSizes(fileObject, &ccfs); \ - ObDereferenceObject(fileObject); \ - } \ - } while(0) -#else -#define vnode_pager_setsize(vp, sz) do { \ - vp->FileHeader.AllocationSize.QuadPart = P2ROUNDUP((sz), PAGE_SIZE); \ +#define vnode_pager_setsize(vp, sz) do { \ + vp->FileHeader.AllocationSize.QuadPart = \ + P2ROUNDUP((sz), PAGE_SIZE); \ vp->FileHeader.FileSize.QuadPart = (sz); \ vp->FileHeader.ValidDataLength.QuadPart = (sz); \ vnode_setsizechange(vp, 1); \ - } while(0) -#endif + } while (0) + +#define vn_ismntpt(vp) (vnode_mountedhere(vp) != NULL) -#define vn_ismntpt(vp) (vnode_mountedhere(vp) != NULL) - -#if 0 -extern errno_t VOP_LOOKUP (struct vnode *, struct vnode **, - struct componentname *, vfs_context_t); -extern errno_t VOP_MKDIR (struct vnode *, struct vnode **, - struct componentname *, struct vnode_attr *, - vfs_context_t); -extern errno_t VOP_REMOVE (struct vnode *, struct vnode *, - struct componentname *, int, vfs_context_t); -extern errno_t VOP_SYMLINK (struct vnode *, struct vnode **, - struct componentname *, struct vnode_attr *, - char *, vfs_context_t); -#endif void spl_vnode_fini(void); int spl_vnode_init(void); - extern int spl_vfs_root(mount_t *mount, struct vnode **vp); -#define VFS_ROOT(V, L, VP) spl_vfs_root((V), (VP)) +#define VFS_ROOT(V, L, VP) spl_vfs_root((V), (VP)) extern void cache_purgevfs(mount_t *mp); -int spl_vn_rdwr( - enum uio_rw rw, - struct vnode *vp, - caddr_t base, - ssize_t len, - offset_t offset, - enum uio_seg seg, - int ioflag, - rlim64_t ulimit, /* meaningful only if rw is UIO_WRITE */ - cred_t *cr, - ssize_t *residp); - -//vfs_context_t vfs_context_kernel(void); -//vfs_context_t spl_vfs_context_kernel(void); -extern int spl_vnode_notify(struct vnode *vp, uint32_t type, struct vnode_attr *vap); +int spl_vn_rdwr(enum uio_rw rw, struct vnode *vp, caddr_t base, ssize_t len, + offset_t offset, enum uio_seg seg, int ioflag, rlim64_t ulimit, + cred_t *cr, ssize_t *residp); + +extern int spl_vnode_notify(struct vnode *vp, uint32_t type, + struct vnode_attr *vap); extern int spl_vfs_get_notify_attributes(struct vnode_attr *vap); extern void spl_hijack_mountroot(void *func); extern void spl_setrootvnode(struct vnode *vp); @@ -509,44 +457,45 @@ extern void spl_setrootvnode(struct vnode *vp); struct vnode *getrootdir(void); void spl_vfs_start(void); -int vnode_vfsisrdonly(vnode_t *vp); -uint64_t vnode_vid(vnode_t *vp); -int vnode_isreg(vnode_t *vp); -int vnode_isdir(vnode_t *vp); +int vnode_vfsisrdonly(vnode_t *vp); +uint64_t vnode_vid(vnode_t *vp); +int vnode_isreg(vnode_t *vp); +int vnode_isdir(vnode_t *vp); #ifdef DEBUG_IOCOUNT -int vnode_debug_getwithvid(vnode_t *, uint64_t, char *, int); +int vnode_debug_getwithvid(vnode_t *, uint64_t, char *, int); int vnode_getwithref(vnode_t *vp, char *, int); -int vnode_put(vnode_t *vp, char *, int); +int vnode_put(vnode_t *vp, char *, int); void vnode_check_iocount(void); #else -int vnode_getwithvid(vnode_t *, uint64_t); +int vnode_getwithvid(vnode_t *, uint64_t); int vnode_getwithref(vnode_t *vp); -int vnode_put(vnode_t *vp); +int vnode_put(vnode_t *vp); #endif - void *vnode_fsnode(struct vnode *dvp); -enum vtype vnode_vtype(vnode_t *vp); -int vnode_isblk(vnode_t *vp); -int vnode_ischr(vnode_t *vp); -int vnode_isswap(vnode_t *vp); -int vnode_isfifo(vnode_t *vp); -int vnode_islnk(vnode_t *vp); +enum vtype vnode_vtype(vnode_t *vp); +int vnode_isblk(vnode_t *vp); +int vnode_ischr(vnode_t *vp); +int vnode_isswap(vnode_t *vp); +int vnode_isfifo(vnode_t *vp); +int vnode_islnk(vnode_t *vp); mount_t *vnode_mountedhere(vnode_t *vp); void ubc_setsize(struct vnode *, uint64_t); -int vnode_isinuse(vnode_t *vp, uint64_t refcnt); +int vnode_isinuse(vnode_t *vp, uint64_t refcnt); int vnode_isidle(vnode_t *vp); -int vnode_recycle(vnode_t *vp); -int vnode_isvroot(vnode_t *vp); +int vnode_recycle(vnode_t *vp); +int vnode_isvroot(vnode_t *vp); mount_t *vnode_mount(vnode_t *vp); -void vnode_clearfsnode(vnode_t *vp); -void vnode_create(mount_t *, void *v_data, int type, int flags, struct vnode **vpp); +void vnode_clearfsnode(vnode_t *vp); +void vnode_create(mount_t *, void *v_data, int type, int flags, + struct vnode **vpp); int vnode_ref(vnode_t *vp); void vnode_rele(vnode_t *vp); void *vnode_sectionpointer(vnode_t *vp); void *vnode_security(vnode_t *vp); void vnode_setsecurity(vnode_t *vp, void *sd); -void vnode_couplefileobject(vnode_t *vp, FILE_OBJECT *fileobject, uint64_t size); +void vnode_couplefileobject(vnode_t *vp, FILE_OBJECT *fileobject, + uint64_t size); void vnode_decouplefileobject(vnode_t *vp, FILE_OBJECT *fileobject); void vnode_setsizechange(vnode_t *vp, int set); int vnode_sizechange(vnode_t *vp); @@ -557,17 +506,17 @@ void cache_purge_negatives(vnode_t *vp); int vnode_removefsref(vnode_t *vp); int vnode_iocount(vnode_t *vp); -#define VNODE_READDIR_EXTENDED 1 +#define VNODE_READDIR_EXTENDED 1 -#define SKIPSYSTEM 0x0001 /* vflush: skip vnodes marked VSYSTEM */ -#define FORCECLOSE 0x0002 /* vflush: force file closeure */ -#define WRITECLOSE 0x0004 /* vflush: only close writeable files */ -#define SKIPSWAP 0x0008 /* vflush: skip vnodes marked VSWAP */ -#define SKIPROOT 0x0010 /* vflush: skip root vnodes marked VROOT */ -#define VNODELOCKED 0x0100 /* vflush: vnode already locked call to recycle */ -#define NULLVP NULL +#define SKIPSYSTEM 0x0001 /* vflush: skip vnodes marked VSYSTEM */ +#define FORCECLOSE 0x0002 /* vflush: force file closeure */ +#define WRITECLOSE 0x0004 /* vflush: only close writeable files */ +#define SKIPSWAP 0x0008 /* vflush: skip vnodes marked VSWAP */ +#define SKIPROOT 0x0010 /* vflush: skip root vnodes marked VROOT */ +#define VNODELOCKED 0x0100 /* vflush: vnode already called to recycle */ +#define NULLVP NULL -int vflush(struct mount *mp, struct vnode *skipvp, int flags); +int vflush(struct mount *mp, struct vnode *skipvp, int flags); int vnode_fileobject_add(vnode_t *vp, void *fo); int vnode_fileobject_remove(vnode_t *vp, void *fo); int vnode_fileobject_empty(vnode_t *vp, int locked); @@ -578,15 +527,16 @@ int vnode_drain_delayclose(int); int vnode_easize(struct vnode *vp, uint64_t *size); void vnode_set_easize(struct vnode *vp, uint64_t size); void vnode_clear_easize(struct vnode *vp); -int vnode_flushcache(vnode_t *vp, FILE_OBJECT *fileobject, boolean_t ); +int vnode_flushcache(vnode_t *vp, FILE_OBJECT *fileobject, boolean_t); -int kernel_ioctl(PDEVICE_OBJECT DeviceObject, PFILE_OBJECT, long cmd, void *inbuf, uint32_t inlen, - void *outbuf, uint32_t outlen); +int kernel_ioctl(PDEVICE_OBJECT DeviceObject, PFILE_OBJECT, long cmd, + void *inbuf, uint32_t inlen, void *outbuf, uint32_t outlen); /* Linux TRIM API */ int blk_queue_discard(PDEVICE_OBJECT dev); int blk_queue_discard_secure(PDEVICE_OBJECT dev); int blk_queue_nonrot(PDEVICE_OBJECT dev); -int blkdev_issue_discard_bytes(PDEVICE_OBJECT dev, uint64_t offset, uint64_t size, uint32_t flags); +int blkdev_issue_discard_bytes(PDEVICE_OBJECT dev, uint64_t offset, + uint64_t size, uint32_t flags); #endif /* SPL_VNODE_H */ diff --git a/include/os/windows/spl/sys/w32_types.h b/include/os/windows/spl/sys/w32_types.h deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/include/os/windows/spl/sys/zmod.h b/include/os/windows/spl/sys/zmod.h index 5d9db0a4c03..0a862eacebe 100644 --- a/include/os/windows/spl/sys/zmod.h +++ b/include/os/windows/spl/sys/zmod.h @@ -1,4 +1,4 @@ -/*****************************************************************************\ +/* * zlib.h -- interface of the 'zlib' general purpose compression library * version 1.2.5, April 19th, 2010 * @@ -22,39 +22,37 @@ * * Jean-loup Gailly * Mark Adler -\*****************************************************************************/ + */ #ifndef _SPL_ZMOD_H -#define _SPL_ZMOD_H - +#define _SPL_ZMOD_H #include #include #include - struct _zmemheader { - uint64_t length; - char data[0]; + uint64_t length; + char data[0]; }; static inline void * zfs_zalloc(void* opaque, uInt items, uInt size) { - struct _zmemheader *hdr; - uint32_t alloc_size = (items * size) + sizeof (uint64_t); - hdr = kmem_zalloc(alloc_size, KM_SLEEP); - hdr->length = alloc_size; - return (&hdr->data); + struct _zmemheader *hdr; + uint32_t alloc_size = (items * size) + sizeof (uint64_t); + hdr = kmem_zalloc(alloc_size, KM_SLEEP); + hdr->length = alloc_size; + return (&hdr->data); } static inline void zfs_zfree(void *opaque, void *addr) { - struct _zmemheader *hdr; - hdr = addr; - hdr--; - kmem_free(hdr, (uint32_t)hdr->length); + struct _zmemheader *hdr; + hdr = addr; + hdr--; + kmem_free(hdr, (uint32_t)hdr->length); } /* @@ -66,54 +64,54 @@ zfs_zfree(void *opaque, void *addr) static inline int z_uncompress(void *dst, uint32_t *dstlen, const void *src, uint32_t srclen) { - z_stream zs; - int err; + z_stream zs; + int err; - bzero(&zs, sizeof (zs)); - zs.next_in = (uchar_t *)src; - zs.avail_in = srclen; - zs.next_out = dst; - zs.avail_out = *dstlen; - zs.zalloc = zfs_zalloc; - zs.zfree = zfs_zfree; - if ((err = inflateInit(&zs)) != Z_OK) - return (err); - if ((err = inflate(&zs, Z_FINISH)) != Z_STREAM_END) { - (void) inflateEnd(&zs); - return (err == Z_OK ? Z_BUF_ERROR : err); - } - *dstlen = zs.total_out; - return (inflateEnd(&zs)); + bzero(&zs, sizeof (zs)); + zs.next_in = (uchar_t *)src; + zs.avail_in = srclen; + zs.next_out = dst; + zs.avail_out = *dstlen; + zs.zalloc = zfs_zalloc; + zs.zfree = zfs_zfree; + if ((err = inflateInit(&zs)) != Z_OK) + return (err); + if ((err = inflate(&zs, Z_FINISH)) != Z_STREAM_END) { + (void) inflateEnd(&zs); + return (err == Z_OK ? Z_BUF_ERROR : err); + } + *dstlen = zs.total_out; + return (inflateEnd(&zs)); } static inline int z_compress_level(void *dst, uint32_t *dstlen, const void *src, uint32_t srclen, - int level) + int level) { - z_stream zs; - int err; - bzero(&zs, sizeof (zs)); - zs.next_in = (uchar_t *)src; - zs.avail_in = srclen; - zs.next_out = dst; - zs.avail_out = *dstlen; - zs.zalloc = zfs_zalloc; - zs.zfree = zfs_zfree; - if ((err = deflateInit(&zs, level)) != Z_OK) - return (err); - if ((err = deflate(&zs, Z_FINISH)) != Z_STREAM_END) { - (void) deflateEnd(&zs); - return (err == Z_OK ? Z_BUF_ERROR : err); - } - *dstlen = zs.total_out; - return (deflateEnd(&zs)); + z_stream zs; + int err; + bzero(&zs, sizeof (zs)); + zs.next_in = (uchar_t *)src; + zs.avail_in = srclen; + zs.next_out = dst; + zs.avail_out = *dstlen; + zs.zalloc = zfs_zalloc; + zs.zfree = zfs_zfree; + if ((err = deflateInit(&zs, level)) != Z_OK) + return (err); + if ((err = deflate(&zs, Z_FINISH)) != Z_STREAM_END) { + (void) deflateEnd(&zs); + return (err == Z_OK ? Z_BUF_ERROR : err); + } + *dstlen = zs.total_out; + return (deflateEnd(&zs)); } static inline int z_compress(void *dst, uint32_t *dstlen, const void *src, uint32_t srclen) { - return (z_compress_level(dst, dstlen, src, srclen, - Z_DEFAULT_COMPRESSION)); + return (z_compress_level(dst, dstlen, src, srclen, + Z_DEFAULT_COMPRESSION)); } diff --git a/include/os/windows/spl/sys/zone.h b/include/os/windows/spl/sys/zone.h index 3fc989c1966..6408d493955 100644 --- a/include/os/windows/spl/sys/zone.h +++ b/include/os/windows/spl/sys/zone.h @@ -1,14 +1,34 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ #ifndef _SPL_ZONE_H -#define _SPL_ZONE_H +#define _SPL_ZONE_H #include #define GLOBAL_ZONEID 0 -#define zone_dataset_visible(x, y) (1) -#define INGLOBALZONE(z) (1) +#define zone_dataset_visible(x, y) (1) +#define INGLOBALZONE(z) (1) -#define crgetzoneid(x) (GLOBAL_ZONEID) +#define crgetzoneid(x) (GLOBAL_ZONEID) #endif /* SPL_ZONE_H */ diff --git a/include/os/windows/spl/unistd.h b/include/os/windows/spl/unistd.h index c6b298a342f..241bb2ad7a5 100644 --- a/include/os/windows/spl/unistd.h +++ b/include/os/windows/spl/unistd.h @@ -1,4 +1,4 @@ #ifndef _SPL_UNISTD_H -#define _SPL_UNISTD_H +#define _SPL_UNISTD_H #endif /* SPL_UNISTD_H */ diff --git a/include/os/windows/spl_config.h b/include/os/windows/spl_config.h index 039cb675bc6..162e483bb35 100644 --- a/include/os/windows/spl_config.h +++ b/include/os/windows/spl_config.h @@ -2,7 +2,7 @@ /* spl_config.h.in. Generated from configure.ac by autoheader. */ /* Define to 1 to enable basic kmem accounting */ -#define DEBUG_KMEM 1 +#define DEBUG_KMEM 1 /* Define to 1 to enable detailed kmem tracking */ /* #undef DEBUG_KMEM_TRACKING */ @@ -11,46 +11,46 @@ /* #undef DEBUG_LOG */ /* Define to 1 if you have the header file. */ -#define HAVE_DLFCN_H 1 +#define HAVE_DLFCN_H 1 /* Define to 1 if you have the header file. */ -#define HAVE_INTTYPES_H 1 +#define HAVE_INTTYPES_H 1 /* Define to 1 if you have the header file. */ -#define HAVE_MEMORY_H 1 +#define HAVE_MEMORY_H 1 /* Define to 1 if you have the header file. */ -#define HAVE_STDINT_H 1 +#define HAVE_STDINT_H 1 /* Define to 1 if you have the header file. */ -#define HAVE_STDLIB_H 1 +#define HAVE_STDLIB_H 1 /* Define to 1 if you have the header file. */ -#define HAVE_STRINGS_H 1 +#define HAVE_STRINGS_H 1 /* Define to 1 if you have the header file. */ -#define HAVE_STRING_H 1 +#define HAVE_STRING_H 1 /* Define to 1 if you have the header file. */ -#define HAVE_SYS_STAT_H 1 +#define HAVE_SYS_STAT_H 1 /* Define to 1 if you have the header file. */ -#define HAVE_SYS_TYPES_H 1 +#define HAVE_SYS_TYPES_H 1 /* Define to 1 if you have the header file. */ -#define HAVE_UNISTD_H 1 +#define HAVE_UNISTD_H 1 /* Define to the sub-directory where libtool stores uninstalled libraries. */ -#define LT_OBJDIR ".libs/" +#define LT_OBJDIR ".libs/" /* Define to 1 to enable mutex leak accounting */ /* #undef SPL_DEBUG_MUTEX */ /* Define the kernel dependencies version. */ -#define SPL_KERNEL_DEPENDENCIES "28" +#define SPL_KERNEL_DEPENDENCIES "28" /* Define the project alias string. */ -#define SPL_META_ALIAS "spl-1.6.0-7-gc1b4a00" +#define SPL_META_ALIAS "spl-1.6.0-7-gc1b4a00" /* Define the project author. */ /* #undef SPL_META_AUTHOR */ @@ -68,14 +68,13 @@ /* #undef SPL_META_LT_REVISION */ /* Define the project name. */ -#define SPL_META_NAME "spl" +#define SPL_META_NAME "spl" /* Define the project release. */ -#define SPL_META_RELEASE "7-gc1b4a00" +#define SPL_META_RELEASE "7-gc1b4a00" /* Define the project version. */ -#define SPL_META_VERSION "0.2.3" +#define SPL_META_VERSION "0.2.3" /* Define ZFS_BOOT to enable kext load at boot */ -#define ZFS_BOOT 1 - +#define ZFS_BOOT 1 diff --git a/include/os/windows/zfs/sys/kstat_windows.h b/include/os/windows/zfs/sys/kstat_windows.h index e8e3e34aed4..52ae00352ea 100644 --- a/include/os/windows/zfs/sys/kstat_windows.h +++ b/include/os/windows/zfs/sys/kstat_windows.h @@ -23,7 +23,7 @@ */ #ifndef KSTAT_WINDOWS_INCLUDED -#define KSTAT_WINDOWS_INCLUDED +#define KSTAT_WINDOWS_INCLUDED typedef struct windows_kstat { kstat_named_t spa_version; @@ -31,7 +31,7 @@ typedef struct windows_kstat { kstat_named_t win32_active_vnodes; kstat_named_t win32_debug; - kstat_named_t win32_reclaim_nodes; + kstat_named_t win32_reclaim_nodes; kstat_named_t win32_ignore_negatives; kstat_named_t win32_ignore_positives; kstat_named_t win32_create_negatives; @@ -255,8 +255,8 @@ extern uint64_t zfs_disable_removablemedia; extern uint64_t zfs_initialize_value; extern int zfs_autoimport_disable; -int kstat_windows_init(void *); -void kstat_windows_fini(void); +int kstat_windows_init(void *); +void kstat_windows_fini(void); int arc_kstat_update(kstat_t *ksp, int rw); int arc_kstat_update_windows(kstat_t *ksp, int rw); diff --git a/include/os/windows/zfs/sys/policy.h b/include/os/windows/zfs/sys/policy.h index e69de29bb2d..18a6f40d05a 100644 --- a/include/os/windows/zfs/sys/policy.h +++ b/include/os/windows/zfs/sys/policy.h @@ -0,0 +1,25 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ + +#ifndef POLICY_H_INCLUDED +#define POLICY_H_INCLUDED + +#endif diff --git a/include/os/windows/zfs/sys/wzvol.h b/include/os/windows/zfs/sys/wzvol.h index 075bde2bd4f..8b4c39eee77 100644 --- a/include/os/windows/zfs/sys/wzvol.h +++ b/include/os/windows/zfs/sys/wzvol.h @@ -24,184 +24,192 @@ */ #ifndef _SPL_WZVOL_H -#define _SPL_WZVOL_H +#define _SPL_WZVOL_H -#include -#include +#include +#include #include #include #include - - -#define VENDOR_ID L"OpenZFS " -#define VENDOR_ID_ascii "OpenZFS " -#define PRODUCT_ID L"WinZVOL " -#define PRODUCT_ID_ascii "WinZVOL " -#define PRODUCT_REV L"1.00" -#define PRODUCT_REV_ascii "1.00" -#define MP_TAG_GENERAL 'LOVZ' - -//#define WZOL_MAX_TARGETS SCSI_MAXIMUM_TARGETS // 8! A bit low -#define WZOL_MAX_TARGETS 16 // 8! A bit low - -#define MAX_TARGETS WZOL_MAX_TARGETS -#define MAX_LUNS 24 -#define MP_MAX_TRANSFER_SIZE (32 * 1024) -#define TIME_INTERVAL (1 * 1000 * 1000) //1 second. -#define DEVLIST_BUFFER_SIZE 1024 -#define DEVICE_NOT_FOUND 0xFF -#define SECTOR_NOT_FOUND 0xFFFF - -#define MINIMUM_DISK_SIZE (1540 * 1024) // Minimum size required for Disk Manager -#define MAXIMUM_MAP_DISK_SIZE (256 * 1024) - -#define MP_BLOCK_SIZE (512) -#define BUF_SIZE (1540 * 1024) -#define MAX_BLOCKS (BUF_SIZE / MP_BLOCK_SIZE) - -#define DEFAULT_BREAK_ON_ENTRY 0 // No break -#define DEFAULT_DEBUG_LEVEL 2 -#define DEFAULT_INITIATOR_ID 7 -#define DEFAULT_VIRTUAL_DISK_SIZE (8 * 1024 * 1024) // 8 MB. JAntogni, 03.12.2005. -#define DEFAULT_PHYSICAL_DISK_SIZE DEFAULT_VIRTUAL_DISK_SIZE -#define DEFAULT_USE_LBA_LIST 0 -#define DEFAULT_NUMBER_OF_BUSES 1 -#define DEFAULT_NbrVirtDisks 1 -#define DEFAULT_NbrLUNsperHBA 400 -#define DEFAULT_NbrLUNsperTarget 32 -#define DEFAULT_bCombineVirtDisks FALSE - -#define GET_FLAG(Flags, Bit) ((Flags) & (Bit)) -#define SET_FLAG(Flags, Bit) ((Flags) |= (Bit)) -#define CLEAR_FLAG(Flags, Bit) ((Flags) &= ~(Bit)) - -typedef struct _DEVICE_LIST DEVICE_LIST, *pDEVICE_LIST; -typedef struct _wzvolDriverInfo wzvolDriverInfo, *pwzvolDriverInfo; -typedef struct _MP_REG_INFO MP_REG_INFO, *pMP_REG_INFO; -typedef struct _HW_LU_EXTENSION HW_LU_EXTENSION, *pHW_LU_EXTENSION; -typedef struct _HW_LU_EXTENSION_MPIO HW_LU_EXTENSION_MPIO, *pHW_LU_EXTENSION_MPIO; -typedef struct _LBA_LIST LBA_LIST, *PLBA_LIST; - -extern -wzvolDriverInfo STOR_wzvolDriverInfo; +#define VENDOR_ID L"OpenZFS " +#define VENDOR_ID_ascii "OpenZFS " +#define PRODUCT_ID L"WinZVOL " +#define PRODUCT_ID_ascii "WinZVOL " +#define PRODUCT_REV L"1.00" +#define PRODUCT_REV_ascii "1.00" +#define MP_TAG_GENERAL 'LOVZ' + +#define WZOL_MAX_TARGETS 16 // 8! A bit low + +#define MAX_TARGETS WZOL_MAX_TARGETS +#define MAX_LUNS 24 +#define MP_MAX_TRANSFER_SIZE (32 * 1024) +#define TIME_INTERVAL (1 * 1000 * 1000) // 1 second. +#define DEVLIST_BUFFER_SIZE 1024 +#define DEVICE_NOT_FOUND 0xFF +#define SECTOR_NOT_FOUND 0xFFFF + +// Minimum size required for Disk Manager +#define MINIMUM_DISK_SIZE (1540 * 1024) + +#define MAXIMUM_MAP_DISK_SIZE (256 * 1024) + +#define MP_BLOCK_SIZE (512) +#define BUF_SIZE (1540 * 1024) +#define MAX_BLOCKS (BUF_SIZE / MP_BLOCK_SIZE) + +#define DEFAULT_BREAK_ON_ENTRY 0 +#define DEFAULT_DEBUG_LEVEL 2 +#define DEFAULT_INITIATOR_ID 7 +#define DEFAULT_VIRTUAL_DISK_SIZE (8 * 1024 * 1024) +#define DEFAULT_PHYSICAL_DISK_SIZE DEFAULT_VIRTUAL_DISK_SIZE +#define DEFAULT_USE_LBA_LIST 0 +#define DEFAULT_NUMBER_OF_BUSES 1 +#define DEFAULT_NbrVirtDisks 1 +#define DEFAULT_NbrLUNsperHBA 400 +#define DEFAULT_NbrLUNsperTarget 32 +#define DEFAULT_bCombineVirtDisks FALSE + +#define GET_FLAG(Flags, Bit) ((Flags) & (Bit)) +#define SET_FLAG(Flags, Bit) ((Flags) |= (Bit)) +#define CLEAR_FLAG(Flags, Bit) ((Flags) &= ~(Bit)) + +typedef struct _DEVICE_LIST DEVICE_LIST, *pDEVICE_LIST; +typedef struct _wzvolDriverInfo wzvolDriverInfo, *pwzvolDriverInfo; +typedef struct _MP_REG_INFO MP_REG_INFO, *pMP_REG_INFO; +typedef struct _HW_LU_EXTENSION HW_LU_EXTENSION, *pHW_LU_EXTENSION; +typedef struct _HW_LU_EXTENSION_MPIO + HW_LU_EXTENSION_MPIO, *pHW_LU_EXTENSION_MPIO; +typedef struct _LBA_LIST LBA_LIST, *PLBA_LIST; + +extern wzvolDriverInfo STOR_wzvolDriverInfo; typedef struct _MP_REG_INFO { - UNICODE_STRING VendorId; - UNICODE_STRING ProductId; - UNICODE_STRING ProductRevision; - ULONG BreakOnEntry; // Break into debugger - ULONG DebugLevel; // Debug log level - ULONG InitiatorID; // Adapter's target ID - ULONG VirtualDiskSize; // Disk size to be reported - ULONG PhysicalDiskSize; // Disk size to be allocated - ULONG NbrVirtDisks; // Number of virtual disks. - ULONG NbrLUNsperHBA; // Number of LUNs per HBA : really is the amount of zvols we can present throiugh StorPort - ULONG NbrLUNsperTarget; // Number of LUNs per Target. - ULONG bCombineVirtDisks; // 0 => do not combine virtual disks a la MPIO. + UNICODE_STRING VendorId; + UNICODE_STRING ProductId; + UNICODE_STRING ProductRevision; + ULONG BreakOnEntry; // Break into debugger + ULONG DebugLevel; // Debug log level + ULONG InitiatorID; // Adapter's target ID + ULONG VirtualDiskSize; // Disk size to be reported + ULONG PhysicalDiskSize; // Disk size to be allocated + ULONG NbrVirtDisks; // Number of virtual disks. + ULONG NbrLUNsperHBA; // Number of LUNs per HBA + // really is the amount of zvols we can present through StorPort + + ULONG NbrLUNsperTarget; // Number of LUNs per Target. + ULONG bCombineVirtDisks; // 0 => do not combine virtual/MPIO } WZVOL_REG_INFO, *pWZVOL_REG_INFO; typedef struct _wzvolContext { - PVOID zv; + PVOID zv; PIO_REMOVE_LOCK pIoRemLock; volatile ULONGLONG refCnt; -} wzvolContext, * pwzvolContext; - -typedef struct _wzvolDriverInfo { // The master miniport object. In effect, an extension of the driver object for the miniport. - WZVOL_REG_INFO wzvolRegInfo; - KSPIN_LOCK DrvInfoLock; - KSPIN_LOCK MPIOExtLock; // Lock for ListMPIOExt, header of list of HW_LU_EXTENSION_MPIO objects, - KSPIN_LOCK SrbExtLock; // Lock for ListSrbExt - LIST_ENTRY ListMPHBAObj; // Header of list of HW_HBA_EXT objects. - LIST_ENTRY ListMPIOExt; // Header of list of HW_LU_EXTENSION_MPIO objects. - LIST_ENTRY ListSrbExt; // Heade rof List of HW_SRB_EXTENSION - PDRIVER_OBJECT pDriverObj; - wzvolContext *zvContextArray; - ULONG DrvInfoNbrMPHBAObj;// Count of items in ListMPHBAObj. - ULONG DrvInfoNbrMPIOExtObj; // Count of items in ListMPIOExt. - UCHAR MaximumNumberOfLogicalUnits; - UCHAR MaximumNumberOfTargets; - UCHAR NumberOfBuses; +} wzvolContext, *pwzvolContext; + + +// The master miniport object. In effect, an extension of the driver object +// for the miniport. +typedef struct _wzvolDriverInfo { + WZVOL_REG_INFO wzvolRegInfo; + KSPIN_LOCK DrvInfoLock; + // Lock for ListMPIOExt, header of list of HW_LU_EXTENSION_MPIO objects + KSPIN_LOCK MPIOExtLock; + KSPIN_LOCK SrbExtLock; // Lock for ListSrbExt + LIST_ENTRY ListMPHBAObj; // Header of list of HW_HBA_EXT + LIST_ENTRY ListMPIOExt; // Header HW_LU_EXTENSION_MPIO + LIST_ENTRY ListSrbExt; // Header HW_SRB_EXTENSION + PDRIVER_OBJECT pDriverObj; + wzvolContext *zvContextArray; + ULONG DrvInfoNbrMPHBAObj; // Count of items in ListMPHBAObj. + ULONG DrvInfoNbrMPIOExtObj; // Count of items in ListMPIOExt. + UCHAR MaximumNumberOfLogicalUnits; + UCHAR MaximumNumberOfTargets; + UCHAR NumberOfBuses; } wzvolDriverInfo, *pwzvolDriverInfo; typedef struct _LUNInfo { - UCHAR bReportLUNsDontUse; - UCHAR bIODontUse; + UCHAR bReportLUNsDontUse; + UCHAR bIODontUse; } LUNInfo, *pLUNInfo; - -#define DISK_DEVICE 0x00 +#define DISK_DEVICE 0x00 typedef struct _MP_DEVICE_INFO { - UCHAR DeviceType; - UCHAR TargetID; - UCHAR LunID; + UCHAR DeviceType; + UCHAR TargetID; + UCHAR LunID; } MP_DEVICE_INFO, *pMP_DEVICE_INFO; typedef struct _MP_DEVICE_LIST { - ULONG DeviceCount; - MP_DEVICE_INFO DeviceInfo[1]; + ULONG DeviceCount; + MP_DEVICE_INFO DeviceInfo[1]; } MP_DEVICE_LIST, *pMP_DEVICE_LIST; -#define LUNInfoMax 8 - -typedef struct _HW_HBA_EXT { // Adapter device-object extension allocated by StorPort. - LIST_ENTRY List; // Pointers to next and previous HW_HBA_EXT objects. - LIST_ENTRY LUList; // Pointers to HW_LU_EXTENSION objects. - LIST_ENTRY MPIOLunList; - pwzvolDriverInfo pwzvolDrvObj; - PDRIVER_OBJECT pDrvObj; - SCSI_WMILIB_CONTEXT WmiLibContext; - PIRP pReverseCallIrp; - KSPIN_LOCK WkItemsLock; - KSPIN_LOCK WkRoutinesLock; - KSPIN_LOCK MPHBAObjLock; - KSPIN_LOCK LUListLock; - ULONG SRBsSeen; - ULONG WMISRBsSeen; - ULONG NbrMPIOLuns; - ULONG NbrLUNsperHBA; - ULONG Test; - UCHAR HostTargetId; - UCHAR AdapterState; - UCHAR VendorId[9]; - UCHAR ProductId[17]; - UCHAR ProductRevision[5]; - - - BOOLEAN bDontReport; // TRUE => no Report LUNs. - BOOLEAN bReportAdapterDone; - LUNInfo LUNInfoArray[LUNInfoMax]; // To be set only by a kernel debugger. +#define LUNInfoMax 8 + +// Adapter device-object extension allocated by StorPort. +typedef struct _HW_HBA_EXT { + LIST_ENTRY List; // Pointers to next&prev HW_HBA_EXT. + LIST_ENTRY LUList; // Pointers to HW_LU_EXTENSION. + LIST_ENTRY MPIOLunList; + pwzvolDriverInfo pwzvolDrvObj; + PDRIVER_OBJECT pDrvObj; + SCSI_WMILIB_CONTEXT WmiLibContext; + PIRP pReverseCallIrp; + KSPIN_LOCK WkItemsLock; + KSPIN_LOCK WkRoutinesLock; + KSPIN_LOCK MPHBAObjLock; + KSPIN_LOCK LUListLock; + ULONG SRBsSeen; + ULONG WMISRBsSeen; + ULONG NbrMPIOLuns; + ULONG NbrLUNsperHBA; + ULONG Test; + UCHAR HostTargetId; + UCHAR AdapterState; + UCHAR VendorId[9]; + UCHAR ProductId[17]; + UCHAR ProductRevision[5]; + + BOOLEAN bDontReport; // TRUE => no Report LUNs. + BOOLEAN bReportAdapterDone; + // To be set only by a kernel debugger. + LUNInfo LUNInfoArray[LUNInfoMax]; } HW_HBA_EXT, *pHW_HBA_EXT; -typedef struct _HW_LU_EXTENSION_MPIO { // Collector for LUNs that are represented by MPIO as 1 pseudo-LUN. - LIST_ENTRY List; // Pointers to next and previous HW_LU_EXTENSION_MPIO objects. - LIST_ENTRY LUExtList; // Header of list of HW_LU_EXTENSION objects. - KSPIN_LOCK LUExtMPIOLock; - ULONG NbrRealLUNs; - SCSI_ADDRESS ScsiAddr; - PUCHAR pDiskBuf; - USHORT MaxBlocks; - BOOLEAN bIsMissingOnAnyPath; // At present, this is set only by a kernel debugger, for testing. +// Collector for LUNs that are represented by MPIO as 1 pseudo-LUN. +typedef struct _HW_LU_EXTENSION_MPIO { + LIST_ENTRY List; // Ptrs next&prev HW_LU_EXTENSION_MPIO + LIST_ENTRY LUExtList; // Header of list of HW_LU_EXTENSION. + KSPIN_LOCK LUExtMPIOLock; + ULONG NbrRealLUNs; + SCSI_ADDRESS ScsiAddr; + PUCHAR pDiskBuf; + USHORT MaxBlocks; + // At present, this is set only by a kernel debugger, for testing. + BOOLEAN bIsMissingOnAnyPath; } HW_LU_EXTENSION_MPIO, *pHW_LU_EXTENSION_MPIO; // Flag definitions for LUFlags. -#define LU_DEVICE_INITIALIZED 0x0001 -#define LU_MPIO_MAPPED 0x0004 +#define LU_DEVICE_INITIALIZED 0x0001 +#define LU_MPIO_MAPPED 0x0004 -typedef struct _HW_LU_EXTENSION { // LUN extension allocated by StorPort. - LIST_ENTRY List; // Pointers to next and previous HW_LU_EXTENSION objects, used in HW_HBA_EXT. - LIST_ENTRY MPIOList; // Pointers to next and previous HW_LU_EXTENSION objects, used in HW_LU_EXTENSION_MPIO. +// LUN extension allocated by StorPort. +typedef struct _HW_LU_EXTENSION { + LIST_ENTRY List; + LIST_ENTRY MPIOList; pHW_LU_EXTENSION_MPIO pLUMPIOExt; - PUCHAR pDiskBuf; - ULONG LUFlags; - USHORT MaxBlocks; - USHORT BlocksUsed; - BOOLEAN bIsMissing; // At present, this is set only by a kernel debugger, for testing. - UCHAR DeviceType; - UCHAR TargetId; - UCHAR Lun; + PUCHAR pDiskBuf; + ULONG LUFlags; + USHORT MaxBlocks; + USHORT BlocksUsed; + BOOLEAN bIsMissing; + UCHAR DeviceType; + UCHAR TargetId; + UCHAR Lun; } HW_LU_EXTENSION, *pHW_LU_EXTENSION; @@ -211,20 +219,22 @@ typedef enum { } MpWkRtnAction; typedef struct _MP_WorkRtnParms { - pHW_HBA_EXT pHBAExt; - PSCSI_REQUEST_BLOCK pSrb; - PEPROCESS pReqProcess; - MpWkRtnAction Action; - ULONG SecondsToDelay; - CHAR pQueueWorkItem[1]; // IO_WORKITEM structure: keep at the end of this block (dynamically allocated). + pHW_HBA_EXT pHBAExt; + PSCSI_REQUEST_BLOCK pSrb; + PEPROCESS pReqProcess; + MpWkRtnAction Action; + ULONG SecondsToDelay; + CHAR pQueueWorkItem[1]; + // IO_WORKITEM struct: keep at the end (dynamically allocated). } MP_WorkRtnParms, *pMP_WorkRtnParms; typedef struct _HW_SRB_EXTENSION { - SCSIWMI_REQUEST_CONTEXT WmiRequestContext; - LIST_ENTRY QueuedForProcessing; - volatile ULONG Cancelled; - PSCSI_REQUEST_BLOCK pSrbBackPtr; - MP_WorkRtnParms WkRtnParms; // keep at the end of this block (pQueueWorkItem dynamically allocated). + SCSIWMI_REQUEST_CONTEXT WmiRequestContext; + LIST_ENTRY QueuedForProcessing; + volatile ULONG Cancelled; + PSCSI_REQUEST_BLOCK pSrbBackPtr; + MP_WorkRtnParms WkRtnParms; + // keep at the end of this block (pQueueWorkItem dynamically allocated) } HW_SRB_EXTENSION, *PHW_SRB_EXTENSION; enum ResultType { @@ -232,26 +242,26 @@ enum ResultType { ResultQueued }; -#define RegWkBfrSz 0x1000 +#define RegWkBfrSz 0x1000 typedef struct _RegWorkBuffer { - pHW_HBA_EXT pAdapterExt; - UCHAR Work[256]; + pHW_HBA_EXT pAdapterExt; + UCHAR Work[256]; } RegWorkBuffer, *pRegWorkBuffer; ULONG wzvol_HwFindAdapter( - __in pHW_HBA_EXT DevExt, - __in PVOID HwContext, - __in PVOID BusInfo, - __in PVOID LowerDevice, - __in PCHAR ArgumentString, + __in pHW_HBA_EXT DevExt, + __in PVOID HwContext, + __in PVOID BusInfo, + __in PVOID LowerDevice, + __in PCHAR ArgumentString, __in __out PPORT_CONFIGURATION_INFORMATION ConfigInfo, - __out PBOOLEAN Again + __out PBOOLEAN Again ); -VOID +void wzvol_HwTimer( __in pHW_HBA_EXT DevExt ); @@ -274,7 +284,7 @@ wzvol_HwReportLink( void wzvol_HwReportLog(__in pHW_HBA_EXT); -VOID +void wzvol_HwFreeAdapterResources( __in pHW_HBA_EXT ); @@ -331,31 +341,31 @@ ScsiOpReadCapacity16( UCHAR ScsiOpRead( - IN pHW_HBA_EXT DevExt, - IN PSCSI_REQUEST_BLOCK Srb, - IN PUCHAR Action + IN pHW_HBA_EXT DevExt, + IN PSCSI_REQUEST_BLOCK Srb, + IN PUCHAR Action ); UCHAR ScsiOpWrite( - IN pHW_HBA_EXT DevExt, - IN PSCSI_REQUEST_BLOCK Srb, - IN PUCHAR Action + IN pHW_HBA_EXT DevExt, + IN PSCSI_REQUEST_BLOCK Srb, + IN PUCHAR Action ); UCHAR ScsiOpModeSense( - IN pHW_HBA_EXT DevExt, - IN PSCSI_REQUEST_BLOCK pSrb + IN pHW_HBA_EXT DevExt, + IN PSCSI_REQUEST_BLOCK pSrb ); UCHAR ScsiOpReportLuns( - IN pHW_HBA_EXT DevExt, - IN PSCSI_REQUEST_BLOCK Srb + IN pHW_HBA_EXT DevExt, + IN PSCSI_REQUEST_BLOCK Srb ); -VOID +void wzvol_QueryRegParameters( IN PUNICODE_STRING, IN pMP_REG_INFO @@ -363,8 +373,8 @@ wzvol_QueryRegParameters( NTSTATUS wzvol_CreateDeviceList( - __in pHW_HBA_EXT, - __in ULONG + __in pHW_HBA_EXT, + __in ULONG ); UCHAR @@ -380,26 +390,26 @@ UCHAR wzvol_FindRemovedDevice( __in PSCSI_REQUEST_BLOCK ); -VOID wzvol_StopAdapter( +void wzvol_StopAdapter( __in pHW_HBA_EXT DevExt ); -VOID +void wzvol_TracingInit( __in PVOID, __in PVOID ); -VOID +void wzvol_TracingCleanup(__in PVOID); -VOID +void wzvol_ProcServReq( __in pHW_HBA_EXT, __in PIRP ); -VOID +void wzvol_CompServReq( __in pHW_HBA_EXT ); @@ -416,53 +426,54 @@ InitializeWmiContext(__in pHW_HBA_EXT); BOOLEAN HandleWmiSrb( - __in pHW_HBA_EXT, + __in pHW_HBA_EXT, __in __out PSCSI_WMI_REQUEST_BLOCK ); UCHAR ScsiReadWriteSetup( - __in pHW_HBA_EXT pDevExt, - __in PSCSI_REQUEST_BLOCK pSrb, - __in MpWkRtnAction WkRtnAction, - __in PUCHAR pResult + __in pHW_HBA_EXT pDevExt, + __in PSCSI_REQUEST_BLOCK pSrb, + __in MpWkRtnAction WkRtnAction, + __in PUCHAR pResult ); -VOID +void wzvol_GeneralWkRtn( __in PVOID, __in PVOID ); + ULONG wzvol_ThreadWkRtn(__in PVOID); -VOID +void wzvol_WkRtn(IN PVOID); -VOID +void wzvol_CompleteIrp( __in pHW_HBA_EXT, __in PIRP ); -VOID +void wzvol_QueueServiceIrp( - __in pHW_HBA_EXT pDevExt, - __in PIRP pIrp + __in pHW_HBA_EXT pDevExt, + __in PIRP pIrp ); -VOID +void wzvol_ProcServReq( - __in pHW_HBA_EXT pDevExt, - __in PIRP pIrp + __in pHW_HBA_EXT pDevExt, + __in PIRP pIrp ); -VOID +void wzvol_CompServReq( __in pHW_HBA_EXT pDevExt ); -extern int zvol_start(PDRIVER_OBJECT DriverObject, PUNICODE_STRING pRegistryPath); - +extern int zvol_start(PDRIVER_OBJECT DriverObject, + PUNICODE_STRING pRegistryPath); #endif diff --git a/include/os/windows/zfs/sys/wzvolwmi.h b/include/os/windows/zfs/sys/wzvolwmi.h index fc86f0be8a0..0ee22d856fd 100644 --- a/include/os/windows/zfs/sys/wzvolwmi.h +++ b/include/os/windows/zfs/sys/wzvolwmi.h @@ -1,248 +1,251 @@ #ifndef _mpwmi_h_ -#define _mpwmi_h_ +#define _mpwmi_h_ -// MSFC_HBAPortStatistics - MSFC_HBAPortStatistics - - -//*************************************************************************** +// ************************************************************************** // // hbapiwmi.h -// +// // Module: WDM classes to expose HBA api data from drivers // -// Purpose: Contains WDM classes that specify the HBA data to be exposed -// via the HBA api set. +// Purpose: Contains WDM classes that specify the HBA data to be exposed +// via the HBA api set. // // NOTE: This file contains information that is based upon: -// SM-HBA Version 1.0 and FC-HBA 2.18 specification. +// SM-HBA Version 1.0 and FC-HBA 2.18 specification. // -// Please specify which WMI interfaces the provider will implement by -// defining MS_SM_HBA_API or MSFC_HBA_API before including this file. -// That is: +// Please specify which WMI interfaces the provider will implement by +// defining MS_SM_HBA_API or MSFC_HBA_API before including this file. +// That is: // -// #define MS_SM_HBA_API -// #include +// #define MS_SM_HBA_API +// #include // -// - or - +// - or - // -// #define MSFC_HBA_API -// #include +// #define MSFC_HBA_API +// #include // // // Copyright (c) 2001 Microsoft Corporation // -//*************************************************************************** +// ************************************************************************** -#define MSFC_HBAPortStatisticsGuid \ - { 0x3ce7904f,0x459f,0x480d, { 0x9a,0x3c,0x01,0x3e,0xde,0x3b,0xdd,0xe8 } } +#define MSFC_HBAPortStatisticsGuid \ + { 0x3ce7904f, 0x459f, 0x480d, \ + { 0x9a, 0x3c, 0x01, 0x3e, 0xde, 0x3b, 0xdd, 0xe8 } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(MSFC_HBAPortStatistics_GUID, \ - 0x3ce7904f,0x459f,0x480d,0x9a,0x3c,0x01,0x3e,0xde,0x3b,0xdd,0xe8); + 0x3ce7904f, 0x459f, 0x480d, 0x9a, 0x3c, 0x01, 0x3e, 0xde, 0x3b, \ + 0xdd, 0xe8); #endif - typedef struct _MSFC_HBAPortStatistics { - // - LONGLONG SecondsSinceLastReset; - #define MSFC_HBAPortStatistics_SecondsSinceLastReset_SIZE sizeof(LONGLONG) - #define MSFC_HBAPortStatistics_SecondsSinceLastReset_ID 1 - - // - LONGLONG TxFrames; - #define MSFC_HBAPortStatistics_TxFrames_SIZE sizeof(LONGLONG) - #define MSFC_HBAPortStatistics_TxFrames_ID 2 - - // - LONGLONG TxWords; - #define MSFC_HBAPortStatistics_TxWords_SIZE sizeof(LONGLONG) - #define MSFC_HBAPortStatistics_TxWords_ID 3 - - // - LONGLONG RxFrames; - #define MSFC_HBAPortStatistics_RxFrames_SIZE sizeof(LONGLONG) - #define MSFC_HBAPortStatistics_RxFrames_ID 4 - - // - LONGLONG RxWords; - #define MSFC_HBAPortStatistics_RxWords_SIZE sizeof(LONGLONG) - #define MSFC_HBAPortStatistics_RxWords_ID 5 - - // - LONGLONG LIPCount; - #define MSFC_HBAPortStatistics_LIPCount_SIZE sizeof(LONGLONG) - #define MSFC_HBAPortStatistics_LIPCount_ID 6 - - // - LONGLONG NOSCount; - #define MSFC_HBAPortStatistics_NOSCount_SIZE sizeof(LONGLONG) - #define MSFC_HBAPortStatistics_NOSCount_ID 7 - - // - LONGLONG ErrorFrames; - #define MSFC_HBAPortStatistics_ErrorFrames_SIZE sizeof(LONGLONG) - #define MSFC_HBAPortStatistics_ErrorFrames_ID 8 - - // - LONGLONG DumpedFrames; - #define MSFC_HBAPortStatistics_DumpedFrames_SIZE sizeof(LONGLONG) - #define MSFC_HBAPortStatistics_DumpedFrames_ID 9 - - // - LONGLONG LinkFailureCount; - #define MSFC_HBAPortStatistics_LinkFailureCount_SIZE sizeof(LONGLONG) - #define MSFC_HBAPortStatistics_LinkFailureCount_ID 10 - - // - LONGLONG LossOfSyncCount; - #define MSFC_HBAPortStatistics_LossOfSyncCount_SIZE sizeof(LONGLONG) - #define MSFC_HBAPortStatistics_LossOfSyncCount_ID 11 - - // - LONGLONG LossOfSignalCount; - #define MSFC_HBAPortStatistics_LossOfSignalCount_SIZE sizeof(LONGLONG) - #define MSFC_HBAPortStatistics_LossOfSignalCount_ID 12 - - // - LONGLONG PrimitiveSeqProtocolErrCount; - #define MSFC_HBAPortStatistics_PrimitiveSeqProtocolErrCount_SIZE sizeof(LONGLONG) - #define MSFC_HBAPortStatistics_PrimitiveSeqProtocolErrCount_ID 13 - - // - LONGLONG InvalidTxWordCount; - #define MSFC_HBAPortStatistics_InvalidTxWordCount_SIZE sizeof(LONGLONG) - #define MSFC_HBAPortStatistics_InvalidTxWordCount_ID 14 - - // - LONGLONG InvalidCRCCount; - #define MSFC_HBAPortStatistics_InvalidCRCCount_SIZE sizeof(LONGLONG) - #define MSFC_HBAPortStatistics_InvalidCRCCount_ID 15 + // + LONGLONG SecondsSinceLastReset; +#define MSFC_HBAPortStatistics_SecondsSinceLastReset_SIZE sizeof (LONGLONG) +#define MSFC_HBAPortStatistics_SecondsSinceLastReset_ID 1 + + // + LONGLONG TxFrames; +#define MSFC_HBAPortStatistics_TxFrames_SIZE sizeof (LONGLONG) +#define MSFC_HBAPortStatistics_TxFrames_ID 2 + + // + LONGLONG TxWords; +#define MSFC_HBAPortStatistics_TxWords_SIZE sizeof (LONGLONG) +#define MSFC_HBAPortStatistics_TxWords_ID 3 + + // + LONGLONG RxFrames; +#define MSFC_HBAPortStatistics_RxFrames_SIZE sizeof (LONGLONG) +#define MSFC_HBAPortStatistics_RxFrames_ID 4 + + // + LONGLONG RxWords; +#define MSFC_HBAPortStatistics_RxWords_SIZE sizeof (LONGLONG) +#define MSFC_HBAPortStatistics_RxWords_ID 5 + + // + LONGLONG LIPCount; +#define MSFC_HBAPortStatistics_LIPCount_SIZE sizeof (LONGLONG) +#define MSFC_HBAPortStatistics_LIPCount_ID 6 + + // + LONGLONG NOSCount; +#define MSFC_HBAPortStatistics_NOSCount_SIZE sizeof (LONGLONG) +#define MSFC_HBAPortStatistics_NOSCount_ID 7 + + // + LONGLONG ErrorFrames; +#define MSFC_HBAPortStatistics_ErrorFrames_SIZE sizeof (LONGLONG) +#define MSFC_HBAPortStatistics_ErrorFrames_ID 8 + + // + LONGLONG DumpedFrames; +#define MSFC_HBAPortStatistics_DumpedFrames_SIZE sizeof (LONGLONG) +#define MSFC_HBAPortStatistics_DumpedFrames_ID 9 + + // + LONGLONG LinkFailureCount; +#define MSFC_HBAPortStatistics_LinkFailureCount_SIZE sizeof (LONGLONG) +#define MSFC_HBAPortStatistics_LinkFailureCount_ID 10 + + // + LONGLONG LossOfSyncCount; +#define MSFC_HBAPortStatistics_LossOfSyncCount_SIZE sizeof (LONGLONG) +#define MSFC_HBAPortStatistics_LossOfSyncCount_ID 11 + + // + LONGLONG LossOfSignalCount; +#define MSFC_HBAPortStatistics_LossOfSignalCount_SIZE sizeof (LONGLONG) +#define MSFC_HBAPortStatistics_LossOfSignalCount_ID 12 + + // + LONGLONG PrimitiveSeqProtocolErrCount; +#define MSFC_HBAPortStatistics_PrimitiveSeqProtocolErrCount_SIZE \ + sizeof (LONGLONG) +#define MSFC_HBAPortStatistics_PrimitiveSeqProtocolErrCount_ID 13 + + // + LONGLONG InvalidTxWordCount; +#define MSFC_HBAPortStatistics_InvalidTxWordCount_SIZE sizeof (LONGLONG) +#define MSFC_HBAPortStatistics_InvalidTxWordCount_ID 14 + + // + LONGLONG InvalidCRCCount; +#define MSFC_HBAPortStatistics_InvalidCRCCount_SIZE sizeof (LONGLONG) +#define MSFC_HBAPortStatistics_InvalidCRCCount_ID 15 } MSFC_HBAPortStatistics, *PMSFC_HBAPortStatistics; -#define MSFC_HBAPortStatistics_SIZE (FIELD_OFFSET(MSFC_HBAPortStatistics, InvalidCRCCount) + MSFC_HBAPortStatistics_InvalidCRCCount_SIZE) +#define MSFC_HBAPortStatistics_SIZE (FIELD_OFFSET(MSFC_HBAPortStatistics, \ + InvalidCRCCount) + MSFC_HBAPortStatistics_InvalidCRCCount_SIZE) // HBAFC3MgmtInfo - HBAFC3MgmtInfo -#define HBAFC3MgmtInfoGuid \ - { 0x5966a24f,0x6aa5,0x418e, { 0xb7,0x5c,0x2f,0x21,0x4d,0xfb,0x4b,0x18 } } +#define HBAFC3MgmtInfoGuid \ + { 0x5966a24f, 0x6aa5, 0x418e, \ + { 0xb7, 0x5c, 0x2f, 0x21, 0x4d, 0xfb, 0x4b, 0x18 } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(HBAFC3MgmtInfo_GUID, \ - 0x5966a24f,0x6aa5,0x418e,0xb7,0x5c,0x2f,0x21,0x4d,0xfb,0x4b,0x18); + 0x5966a24f, 0x6aa5, 0x418e, 0xb7, 0x5c, 0x2f, 0x21, + 0x4d, 0xfb, 0x4b, 0x18); #endif typedef struct _HBAFC3MgmtInfo { - // - ULONGLONG UniqueAdapterId; - #define HBAFC3MgmtInfo_UniqueAdapterId_SIZE sizeof(ULONGLONG) - #define HBAFC3MgmtInfo_UniqueAdapterId_ID 1 - - // - UCHAR wwn[8]; - #define HBAFC3MgmtInfo_wwn_SIZE sizeof(UCHAR[8]) - #define HBAFC3MgmtInfo_wwn_ID 2 - - // - ULONG unittype; - #define HBAFC3MgmtInfo_unittype_SIZE sizeof(ULONG) - #define HBAFC3MgmtInfo_unittype_ID 3 - - // - ULONG PortId; - #define HBAFC3MgmtInfo_PortId_SIZE sizeof(ULONG) - #define HBAFC3MgmtInfo_PortId_ID 4 - - // - ULONG NumberOfAttachedNodes; - #define HBAFC3MgmtInfo_NumberOfAttachedNodes_SIZE sizeof(ULONG) - #define HBAFC3MgmtInfo_NumberOfAttachedNodes_ID 5 - - // - USHORT IPVersion; - #define HBAFC3MgmtInfo_IPVersion_SIZE sizeof(USHORT) - #define HBAFC3MgmtInfo_IPVersion_ID 6 - - // - USHORT UDPPort; - #define HBAFC3MgmtInfo_UDPPort_SIZE sizeof(USHORT) - #define HBAFC3MgmtInfo_UDPPort_ID 7 - - // - UCHAR IPAddress[16]; - #define HBAFC3MgmtInfo_IPAddress_SIZE sizeof(UCHAR[16]) - #define HBAFC3MgmtInfo_IPAddress_ID 8 - - // - USHORT reserved; - #define HBAFC3MgmtInfo_reserved_SIZE sizeof(USHORT) - #define HBAFC3MgmtInfo_reserved_ID 9 - - // - USHORT TopologyDiscoveryFlags; - #define HBAFC3MgmtInfo_TopologyDiscoveryFlags_SIZE sizeof(USHORT) - #define HBAFC3MgmtInfo_TopologyDiscoveryFlags_ID 10 - - // - ULONG reserved1; - #define HBAFC3MgmtInfo_reserved1_SIZE sizeof(ULONG) - #define HBAFC3MgmtInfo_reserved1_ID 11 + // + ULONGLONG UniqueAdapterId; +#define HBAFC3MgmtInfo_UniqueAdapterId_SIZE sizeof (ULONGLONG) +#define HBAFC3MgmtInfo_UniqueAdapterId_ID 1 + + // + UCHAR wwn[8]; +#define HBAFC3MgmtInfo_wwn_SIZE sizeof (UCHAR[8]) +#define HBAFC3MgmtInfo_wwn_ID 2 + + // + ULONG unittype; +#define HBAFC3MgmtInfo_unittype_SIZE sizeof (ULONG) +#define HBAFC3MgmtInfo_unittype_ID 3 + + // + ULONG PortId; +#define HBAFC3MgmtInfo_PortId_SIZE sizeof (ULONG) +#define HBAFC3MgmtInfo_PortId_ID 4 + + // + ULONG NumberOfAttachedNodes; +#define HBAFC3MgmtInfo_NumberOfAttachedNodes_SIZE sizeof (ULONG) +#define HBAFC3MgmtInfo_NumberOfAttachedNodes_ID 5 + + // + USHORT IPVersion; +#define HBAFC3MgmtInfo_IPVersion_SIZE sizeof (USHORT) +#define HBAFC3MgmtInfo_IPVersion_ID 6 + + // + USHORT UDPPort; +#define HBAFC3MgmtInfo_UDPPort_SIZE sizeof (USHORT) +#define HBAFC3MgmtInfo_UDPPort_ID 7 + + // + UCHAR IPAddress[16]; +#define HBAFC3MgmtInfo_IPAddress_SIZE sizeof (UCHAR[16]) +#define HBAFC3MgmtInfo_IPAddress_ID 8 + + // + USHORT reserved; +#define HBAFC3MgmtInfo_reserved_SIZE sizeof (USHORT) +#define HBAFC3MgmtInfo_reserved_ID 9 + + // + USHORT TopologyDiscoveryFlags; +#define HBAFC3MgmtInfo_TopologyDiscoveryFlags_SIZE sizeof (USHORT) +#define HBAFC3MgmtInfo_TopologyDiscoveryFlags_ID 10 + + // + ULONG reserved1; +#define HBAFC3MgmtInfo_reserved1_SIZE sizeof (ULONG) +#define HBAFC3MgmtInfo_reserved1_ID 11 } HBAFC3MgmtInfo, *PHBAFC3MgmtInfo; -#define HBAFC3MgmtInfo_SIZE (FIELD_OFFSET(HBAFC3MgmtInfo, reserved1) + HBAFC3MgmtInfo_reserved1_SIZE) +#define HBAFC3MgmtInfo_SIZE (FIELD_OFFSET(HBAFC3MgmtInfo, reserved1) + \ + HBAFC3MgmtInfo_reserved1_SIZE) // HBAScsiID - HBAScsiID -#define HBAScsiIDGuid \ - { 0xa76f5058,0xb1f0,0x4622, { 0x9e,0x88,0x5c,0xc4,0x1e,0x34,0x45,0x4a } } +#define HBAScsiIDGuid \ + { 0xa76f5058, 0xb1f0, 0x4622, \ + { 0x9e, 0x88, 0x5c, 0xc4, 0x1e, 0x34, 0x45, 0x4a } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(HBAScsiID_GUID, \ - 0xa76f5058,0xb1f0,0x4622,0x9e,0x88,0x5c,0xc4,0x1e,0x34,0x45,0x4a); + 0xa76f5058, 0xb1f0, 0x4622, 0x9e, 0x88, 0x5c, 0xc4, \ + 0x1e, 0x34, 0x45, 0x4a); #endif typedef struct _HBAScsiID { - // - ULONG ScsiBusNumber; - #define HBAScsiID_ScsiBusNumber_SIZE sizeof(ULONG) - #define HBAScsiID_ScsiBusNumber_ID 1 - - // - ULONG ScsiTargetNumber; - #define HBAScsiID_ScsiTargetNumber_SIZE sizeof(ULONG) - #define HBAScsiID_ScsiTargetNumber_ID 2 - - // - ULONG ScsiOSLun; - #define HBAScsiID_ScsiOSLun_SIZE sizeof(ULONG) - #define HBAScsiID_ScsiOSLun_ID 3 - - - - //****************************************************************** - // - // This used to be a string type, but we made this a fixed length - // array so the WmiSizeIs() will work correctly for structs that - // contain this type. - // Please note that this should still be treated as a string. - // The first uint16 must hold the length of string (in bytes). - // - //****************************************************************** - - - // - USHORT OSDeviceName[257]; - #define HBAScsiID_OSDeviceName_SIZE sizeof(USHORT[257]) - #define HBAScsiID_OSDeviceName_ID 4 + // + ULONG ScsiBusNumber; +#define HBAScsiID_ScsiBusNumber_SIZE sizeof (ULONG) +#define HBAScsiID_ScsiBusNumber_ID 1 + + // + ULONG ScsiTargetNumber; +#define HBAScsiID_ScsiTargetNumber_SIZE sizeof (ULONG) +#define HBAScsiID_ScsiTargetNumber_ID 2 + + // + ULONG ScsiOSLun; +#define HBAScsiID_ScsiOSLun_SIZE sizeof (ULONG) +#define HBAScsiID_ScsiOSLun_ID 3 + + // ****************************************************************** + // + // This used to be a string type, but we made this a fixed length + // array so the WmiSizeIs() will work correctly for structs that + // contain this type. + // Please note that this should still be treated as a string. + // The first uint16 must hold the length of string (in bytes). + // + // ****************************************************************** + + // + USHORT OSDeviceName[257]; +#define HBAScsiID_OSDeviceName_SIZE sizeof (USHORT[257]) +#define HBAScsiID_OSDeviceName_ID 4 } HBAScsiID, *PHBAScsiID; -#define HBAScsiID_SIZE (FIELD_OFFSET(HBAScsiID, OSDeviceName) + HBAScsiID_OSDeviceName_SIZE) +#define HBAScsiID_SIZE \ + (FIELD_OFFSET(HBAScsiID, OSDeviceName) + HBAScsiID_OSDeviceName_SIZE) // MSFC_LinkEvent - MSFC_LinkEvent @@ -254,1522 +257,1616 @@ typedef struct _HBAScsiID // // These match the definitions in hbaapi.h and must be kept in sync. // - /* Adapter Level Events */ -#define HBA_EVENT_ADAPTER_UNKNOWN 0x100 -#define HBA_EVENT_ADAPTER_ADD 0x101 -#define HBA_EVENT_ADAPTER_REMOVE 0x102 -#define HBA_EVENT_ADAPTER_CHANGE 0x103 - - /* Port Level Events */ -#define HBA_EVENT_PORT_UNKNOWN 0x200 -#define HBA_EVENT_PORT_OFFLINE 0x201 -#define HBA_EVENT_PORT_ONLINE 0x202 -#define HBA_EVENT_PORT_NEW_TARGETS 0x203 -#define HBA_EVENT_PORT_FABRIC 0x204 -#define HBA_EVENT_PORT_BROADCAST_CHANGE 0x205 -#define HBA_EVENT_PORT_BROADCAST_D24_0 0x206 -#define HBA_EVENT_PORT_BROADCAST_D27_4 0x207 -#define HBA_EVENT_PORT_BROADCAST_SES 0x208 -#define HBA_EVENT_PORT_BROADCAST_D01_4 0x209 -#define HBA_EVENT_PORT_BROADCAST_D04_7 0x20a -#define HBA_EVENT_PORT_BROADCAST_D16_7 0x20b -#define HBA_EVENT_PORT_BROADCAST_D29_7 0x20c -#define HBA_EVENT_PORT_ALL 0x2ff - - /* Port Statistics Events */ -#define HBA_EVENT_PORT_STAT_THRESHOLD 0x301 -#define HBA_EVENT_PORT_STAT_GROWTH 0x302 +/* Adapter Level Events */ +#define HBA_EVENT_ADAPTER_UNKNOWN 0x100 +#define HBA_EVENT_ADAPTER_ADD 0x101 +#define HBA_EVENT_ADAPTER_REMOVE 0x102 +#define HBA_EVENT_ADAPTER_CHANGE 0x103 + +/* Port Level Events */ +#define HBA_EVENT_PORT_UNKNOWN 0x200 +#define HBA_EVENT_PORT_OFFLINE 0x201 +#define HBA_EVENT_PORT_ONLINE 0x202 +#define HBA_EVENT_PORT_NEW_TARGETS 0x203 +#define HBA_EVENT_PORT_FABRIC 0x204 +#define HBA_EVENT_PORT_BROADCAST_CHANGE 0x205 +#define HBA_EVENT_PORT_BROADCAST_D24_0 0x206 +#define HBA_EVENT_PORT_BROADCAST_D27_4 0x207 +#define HBA_EVENT_PORT_BROADCAST_SES 0x208 +#define HBA_EVENT_PORT_BROADCAST_D01_4 0x209 +#define HBA_EVENT_PORT_BROADCAST_D04_7 0x20a +#define HBA_EVENT_PORT_BROADCAST_D16_7 0x20b +#define HBA_EVENT_PORT_BROADCAST_D29_7 0x20c +#define HBA_EVENT_PORT_ALL 0x2ff + +/* Port Statistics Events */ +#define HBA_EVENT_PORT_STAT_THRESHOLD 0x301 +#define HBA_EVENT_PORT_STAT_GROWTH 0x302 /* Phy Statistics Events */ -#define HBA_EVENT_PHY_STAT_THRESHOLD 0x351 -#define HBA_EVENT_PHY_STAT_GROWTH 0x352 +#define HBA_EVENT_PHY_STAT_THRESHOLD 0x351 +#define HBA_EVENT_PHY_STAT_GROWTH 0x352 - /* Target Level Events */ -#define HBA_EVENT_TARGET_UNKNOWN 0x400 -#define HBA_EVENT_TARGET_OFFLINE 0x401 -#define HBA_EVENT_TARGET_ONLINE 0x402 -#define HBA_EVENT_TARGET_REMOVED 0x403 +/* Target Level Events */ +#define HBA_EVENT_TARGET_UNKNOWN 0x400 +#define HBA_EVENT_TARGET_OFFLINE 0x401 +#define HBA_EVENT_TARGET_ONLINE 0x402 +#define HBA_EVENT_TARGET_REMOVED 0x403 - /* Fabric Link Events */ -#define HBA_EVENT_LINK_UNKNOWN 0x500 -#define HBA_EVENT_LINK_INCIDENT 0x501 +/* Fabric Link Events */ +#define HBA_EVENT_LINK_UNKNOWN 0x500 +#define HBA_EVENT_LINK_INCIDENT 0x501 -#define MSFC_LinkEventGuid \ - { 0xc66015ee,0x014b,0x498a, { 0x94,0x51,0x99,0xfe,0xad,0x0a,0xb4,0x51 } } +#define MSFC_LinkEventGuid \ + { 0xc66015ee, 0x014b, 0x498a, \ + { 0x94, 0x51, 0x99, 0xfe, 0xad, 0x0a, 0xb4, 0x51 } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(MSFC_LinkEvent_GUID, \ - 0xc66015ee,0x014b,0x498a,0x94,0x51,0x99,0xfe,0xad,0x0a,0xb4,0x51); + 0xc66015ee, 0x014b, 0x498a, 0x94, 0x51, 0x99, 0xfe, \ + 0xad, 0x0a, 0xb4, 0x51); #endif - typedef struct _MSFC_LinkEvent { - // - ULONG EventType; - #define MSFC_LinkEvent_EventType_SIZE sizeof(ULONG) - #define MSFC_LinkEvent_EventType_ID 1 + // + ULONG EventType; +#define MSFC_LinkEvent_EventType_SIZE sizeof (ULONG) +#define MSFC_LinkEvent_EventType_ID 1 - // - UCHAR AdapterWWN[8]; - #define MSFC_LinkEvent_AdapterWWN_SIZE sizeof(UCHAR[8]) - #define MSFC_LinkEvent_AdapterWWN_ID 2 + // + UCHAR AdapterWWN[8]; +#define MSFC_LinkEvent_AdapterWWN_SIZE sizeof (UCHAR[8]) +#define MSFC_LinkEvent_AdapterWWN_ID 2 - // - ULONG RLIRBufferSize; - #define MSFC_LinkEvent_RLIRBufferSize_SIZE sizeof(ULONG) - #define MSFC_LinkEvent_RLIRBufferSize_ID 3 + // + ULONG RLIRBufferSize; +#define MSFC_LinkEvent_RLIRBufferSize_SIZE sizeof (ULONG) +#define MSFC_LinkEvent_RLIRBufferSize_ID 3 - // - UCHAR RLIRBuffer[1]; - #define MSFC_LinkEvent_RLIRBuffer_ID 4 + // + UCHAR RLIRBuffer[1]; +#define MSFC_LinkEvent_RLIRBuffer_ID 4 } MSFC_LinkEvent, *PMSFC_LinkEvent; // MSFC_FCAdapterHBAAttributes - MSFC_FCAdapterHBAAttributes - #ifndef MS_SM_HBA_API #ifndef MSFC_HBA_API // // if neither defined then default to MSFC // -#define MSFC_HBA_API +#define MSFC_HBA_API #endif #endif - #ifdef MSFC_HBA_API -#define MSFC_FCAdapterHBAAttributesGuid \ - { 0xf8f3ea26,0xab2c,0x4593, { 0x8b,0x84,0xc5,0x64,0x28,0xe6,0xbe,0xdb } } +#define MSFC_FCAdapterHBAAttributesGuid \ + { 0xf8f3ea26, 0xab2c, 0x4593, \ + { 0x8b, 0x84, 0xc5, 0x64, 0x28, 0xe6, 0xbe, 0xdb } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(MSFC_FCAdapterHBAAttributes_GUID, \ - 0xf8f3ea26,0xab2c,0x4593,0x8b,0x84,0xc5,0x64,0x28,0xe6,0xbe,0xdb); + 0xf8f3ea26, 0xab2c, 0x4593, 0x8b, 0x84, 0xc5, 0x64,\ + 0x28, 0xe6, 0xbe, 0xdb); #endif typedef struct _MSFC_FCAdapterHBAAttributes { - // - ULONGLONG UniqueAdapterId; - #define MSFC_FCAdapterHBAAttributes_UniqueAdapterId_SIZE sizeof(ULONGLONG) - #define MSFC_FCAdapterHBAAttributes_UniqueAdapterId_ID 1 - - // - ULONG HBAStatus; - #define MSFC_FCAdapterHBAAttributes_HBAStatus_SIZE sizeof(ULONG) - #define MSFC_FCAdapterHBAAttributes_HBAStatus_ID 2 - - // - UCHAR NodeWWN[8]; - #define MSFC_FCAdapterHBAAttributes_NodeWWN_SIZE sizeof(UCHAR[8]) - #define MSFC_FCAdapterHBAAttributes_NodeWWN_ID 3 - - // - ULONG VendorSpecificID; - #define MSFC_FCAdapterHBAAttributes_VendorSpecificID_SIZE sizeof(ULONG) - #define MSFC_FCAdapterHBAAttributes_VendorSpecificID_ID 4 - - // - ULONG NumberOfPorts; - #define MSFC_FCAdapterHBAAttributes_NumberOfPorts_SIZE sizeof(ULONG) - #define MSFC_FCAdapterHBAAttributes_NumberOfPorts_ID 5 - - - - //****************************************************************** - // - // The string type is variable length (up to MaxLen). - // Each string starts with a ushort that holds the strings length - // (in bytes) followed by the WCHARs that make up the string. - // - //****************************************************************** - - - // - WCHAR Manufacturer[64 + 1]; - #define MSFC_FCAdapterHBAAttributes_Manufacturer_ID 6 - - // - WCHAR SerialNumber[64 + 1]; - #define MSFC_FCAdapterHBAAttributes_SerialNumber_ID 7 - - // - WCHAR Model[256 + 1]; - #define MSFC_FCAdapterHBAAttributes_Model_ID 8 - - // - WCHAR ModelDescription[256 + 1]; - #define MSFC_FCAdapterHBAAttributes_ModelDescription_ID 9 - - // - WCHAR NodeSymbolicName[256 + 1]; - #define MSFC_FCAdapterHBAAttributes_NodeSymbolicName_ID 10 - - // - WCHAR HardwareVersion[256 + 1]; - #define MSFC_FCAdapterHBAAttributes_HardwareVersion_ID 11 - - // - WCHAR DriverVersion[256 + 1]; - #define MSFC_FCAdapterHBAAttributes_DriverVersion_ID 12 - - // - WCHAR OptionROMVersion[256 + 1]; - #define MSFC_FCAdapterHBAAttributes_OptionROMVersion_ID 13 - - // - WCHAR FirmwareVersion[256 + 1]; - #define MSFC_FCAdapterHBAAttributes_FirmwareVersion_ID 14 - - // - WCHAR DriverName[256 + 1]; - #define MSFC_FCAdapterHBAAttributes_DriverName_ID 15 - - // - WCHAR MfgDomain[256 + 1]; - #define MSFC_FCAdapterHBAAttributes_MfgDomain_ID 16 + // + ULONGLONG UniqueAdapterId; +#define MSFC_FCAdapterHBAAttributes_UniqueAdapterId_SIZE sizeof (ULONGLONG) +#define MSFC_FCAdapterHBAAttributes_UniqueAdapterId_ID 1 + + // + ULONG HBAStatus; +#define MSFC_FCAdapterHBAAttributes_HBAStatus_SIZE sizeof (ULONG) +#define MSFC_FCAdapterHBAAttributes_HBAStatus_ID 2 + + // + UCHAR NodeWWN[8]; +#define MSFC_FCAdapterHBAAttributes_NodeWWN_SIZE sizeof (UCHAR[8]) +#define MSFC_FCAdapterHBAAttributes_NodeWWN_ID 3 + + // + ULONG VendorSpecificID; +#define MSFC_FCAdapterHBAAttributes_VendorSpecificID_SIZE sizeof (ULONG) +#define MSFC_FCAdapterHBAAttributes_VendorSpecificID_ID 4 + + // + ULONG NumberOfPorts; +#define MSFC_FCAdapterHBAAttributes_NumberOfPorts_SIZE sizeof (ULONG) +#define MSFC_FCAdapterHBAAttributes_NumberOfPorts_ID 5 + + // ****************************************************************** + // + // The string type is variable length (up to MaxLen). + // Each string starts with a ushort that holds the strings length + // (in bytes) followed by the WCHARs that make up the string. + // + // ****************************************************************** + + // + WCHAR Manufacturer[64 + 1]; +#define MSFC_FCAdapterHBAAttributes_Manufacturer_ID 6 + + // + WCHAR SerialNumber[64 + 1]; +#define MSFC_FCAdapterHBAAttributes_SerialNumber_ID 7 + + // + WCHAR Model[256 + 1]; +#define MSFC_FCAdapterHBAAttributes_Model_ID 8 + + // + WCHAR ModelDescription[256 + 1]; +#define MSFC_FCAdapterHBAAttributes_ModelDescription_ID 9 + + // + WCHAR NodeSymbolicName[256 + 1]; +#define MSFC_FCAdapterHBAAttributes_NodeSymbolicName_ID 10 + + // + WCHAR HardwareVersion[256 + 1]; +#define MSFC_FCAdapterHBAAttributes_HardwareVersion_ID 11 + + // + WCHAR DriverVersion[256 + 1]; +#define MSFC_FCAdapterHBAAttributes_DriverVersion_ID 12 + + // + WCHAR OptionROMVersion[256 + 1]; +#define MSFC_FCAdapterHBAAttributes_OptionROMVersion_ID 13 + + // + WCHAR FirmwareVersion[256 + 1]; +#define MSFC_FCAdapterHBAAttributes_FirmwareVersion_ID 14 + + // + WCHAR DriverName[256 + 1]; +#define MSFC_FCAdapterHBAAttributes_DriverName_ID 15 + + // + WCHAR MfgDomain[256 + 1]; +#define MSFC_FCAdapterHBAAttributes_MfgDomain_ID 16 } MSFC_FCAdapterHBAAttributes, *PMSFC_FCAdapterHBAAttributes; // MSFC_HBAPortAttributesResults - MSFC_HBAPortAttributesResults -#define MSFC_HBAPortAttributesResultsGuid \ - { 0xa76bd4e3,0x9961,0x4d9b, { 0xb6,0xbe,0x86,0xe6,0x98,0x26,0x0f,0x68 } } +#define MSFC_HBAPortAttributesResultsGuid \ + { 0xa76bd4e3, 0x9961, 0x4d9b, \ + { 0xb6, 0xbe, 0x86, 0xe6, 0x98, 0x26, 0x0f, 0x68 } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(MSFC_HBAPortAttributesResults_GUID, \ - 0xa76bd4e3,0x9961,0x4d9b,0xb6,0xbe,0x86,0xe6,0x98,0x26,0x0f,0x68); + 0xa76bd4e3, 0x9961, 0x4d9b, 0xb6, 0xbe, 0x86, 0xe6,\ + 0x98, 0x26, 0x0f, 0x68); #endif - typedef struct _MSFC_HBAPortAttributesResults { - // - UCHAR NodeWWN[8]; - #define MSFC_HBAPortAttributesResults_NodeWWN_SIZE sizeof(UCHAR[8]) - #define MSFC_HBAPortAttributesResults_NodeWWN_ID 1 - - // - UCHAR PortWWN[8]; - #define MSFC_HBAPortAttributesResults_PortWWN_SIZE sizeof(UCHAR[8]) - #define MSFC_HBAPortAttributesResults_PortWWN_ID 2 - - // - ULONG PortFcId; - #define MSFC_HBAPortAttributesResults_PortFcId_SIZE sizeof(ULONG) - #define MSFC_HBAPortAttributesResults_PortFcId_ID 3 - - // - ULONG PortType; - #define MSFC_HBAPortAttributesResults_PortType_SIZE sizeof(ULONG) - #define MSFC_HBAPortAttributesResults_PortType_ID 4 - - // - ULONG PortState; - #define MSFC_HBAPortAttributesResults_PortState_SIZE sizeof(ULONG) - #define MSFC_HBAPortAttributesResults_PortState_ID 5 - - // - ULONG PortSupportedClassofService; - #define MSFC_HBAPortAttributesResults_PortSupportedClassofService_SIZE sizeof(ULONG) - #define MSFC_HBAPortAttributesResults_PortSupportedClassofService_ID 6 - - // - UCHAR PortSupportedFc4Types[32]; - #define MSFC_HBAPortAttributesResults_PortSupportedFc4Types_SIZE sizeof(UCHAR[32]) - #define MSFC_HBAPortAttributesResults_PortSupportedFc4Types_ID 7 - - // - UCHAR PortActiveFc4Types[32]; - #define MSFC_HBAPortAttributesResults_PortActiveFc4Types_SIZE sizeof(UCHAR[32]) - #define MSFC_HBAPortAttributesResults_PortActiveFc4Types_ID 8 - - // - ULONG PortSupportedSpeed; - #define MSFC_HBAPortAttributesResults_PortSupportedSpeed_SIZE sizeof(ULONG) - #define MSFC_HBAPortAttributesResults_PortSupportedSpeed_ID 9 - - // - ULONG PortSpeed; - #define MSFC_HBAPortAttributesResults_PortSpeed_SIZE sizeof(ULONG) - #define MSFC_HBAPortAttributesResults_PortSpeed_ID 10 - - // - ULONG PortMaxFrameSize; - #define MSFC_HBAPortAttributesResults_PortMaxFrameSize_SIZE sizeof(ULONG) - #define MSFC_HBAPortAttributesResults_PortMaxFrameSize_ID 11 - - // - UCHAR FabricName[8]; - #define MSFC_HBAPortAttributesResults_FabricName_SIZE sizeof(UCHAR[8]) - #define MSFC_HBAPortAttributesResults_FabricName_ID 12 - - // - ULONG NumberofDiscoveredPorts; - #define MSFC_HBAPortAttributesResults_NumberofDiscoveredPorts_SIZE sizeof(ULONG) - #define MSFC_HBAPortAttributesResults_NumberofDiscoveredPorts_ID 13 + // + UCHAR NodeWWN[8]; +#define MSFC_HBAPortAttributesResults_NodeWWN_SIZE sizeof (UCHAR[8]) +#define MSFC_HBAPortAttributesResults_NodeWWN_ID 1 + + // + UCHAR PortWWN[8]; +#define MSFC_HBAPortAttributesResults_PortWWN_SIZE sizeof (UCHAR[8]) +#define MSFC_HBAPortAttributesResults_PortWWN_ID 2 + + // + ULONG PortFcId; +#define MSFC_HBAPortAttributesResults_PortFcId_SIZE sizeof (ULONG) +#define MSFC_HBAPortAttributesResults_PortFcId_ID 3 + + // + ULONG PortType; +#define MSFC_HBAPortAttributesResults_PortType_SIZE sizeof (ULONG) +#define MSFC_HBAPortAttributesResults_PortType_ID 4 + + // + ULONG PortState; +#define MSFC_HBAPortAttributesResults_PortState_SIZE sizeof (ULONG) +#define MSFC_HBAPortAttributesResults_PortState_ID 5 + + // + ULONG PortSupportedClassofService; +#define MSFC_HBAPortAttributesResults_PortSupportedClassofService_SIZE \ + sizeof (ULONG) +#define MSFC_HBAPortAttributesResults_PortSupportedClassofService_ID 6 + + // + UCHAR PortSupportedFc4Types[32]; +#define MSFC_HBAPortAttributesResults_PortSupportedFc4Types_SIZE \ + sizeof (UCHAR[32]) +#define MSFC_HBAPortAttributesResults_PortSupportedFc4Types_ID 7 + + // + UCHAR PortActiveFc4Types[32]; +#define MSFC_HBAPortAttributesResults_PortActiveFc4Types_SIZE \ + sizeof (UCHAR[32]) +#define MSFC_HBAPortAttributesResults_PortActiveFc4Types_ID 8 + + // + ULONG PortSupportedSpeed; +#define MSFC_HBAPortAttributesResults_PortSupportedSpeed_SIZE sizeof (ULONG) +#define MSFC_HBAPortAttributesResults_PortSupportedSpeed_ID 9 + + // + ULONG PortSpeed; +#define MSFC_HBAPortAttributesResults_PortSpeed_SIZE sizeof (ULONG) +#define MSFC_HBAPortAttributesResults_PortSpeed_ID 10 + + // + ULONG PortMaxFrameSize; +#define MSFC_HBAPortAttributesResults_PortMaxFrameSize_SIZE sizeof (ULONG) +#define MSFC_HBAPortAttributesResults_PortMaxFrameSize_ID 11 + + // + UCHAR FabricName[8]; +#define MSFC_HBAPortAttributesResults_FabricName_SIZE sizeof (UCHAR[8]) +#define MSFC_HBAPortAttributesResults_FabricName_ID 12 + + // + ULONG NumberofDiscoveredPorts; +#define MSFC_HBAPortAttributesResults_NumberofDiscoveredPorts_SIZE \ + sizeof (ULONG) +#define MSFC_HBAPortAttributesResults_NumberofDiscoveredPorts_ID 13 } MSFC_HBAPortAttributesResults, *PMSFC_HBAPortAttributesResults; -#define MSFC_HBAPortAttributesResults_SIZE (FIELD_OFFSET(MSFC_HBAPortAttributesResults, NumberofDiscoveredPorts) + MSFC_HBAPortAttributesResults_NumberofDiscoveredPorts_SIZE) +#define MSFC_HBAPortAttributesResults_SIZE \ + (FIELD_OFFSET(MSFC_HBAPortAttributesResults, NumberofDiscoveredPorts) +\ + MSFC_HBAPortAttributesResults_NumberofDiscoveredPorts_SIZE) // MSFC_FibrePortHBAAttributes - MSFC_FibrePortHBAAttributes -#define MSFC_FibrePortHBAAttributesGuid \ - { 0x61b397fd,0xf5ae,0x4950, { 0x97,0x58,0x0e,0xe5,0x98,0xe3,0xc6,0xe6 } } +#define MSFC_FibrePortHBAAttributesGuid \ + { 0x61b397fd, 0xf5ae, 0x4950, { 0x97, 0x58, 0x0e, 0xe5, 0x98,\ + 0xe3, 0xc6, 0xe6 } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(MSFC_FibrePortHBAAttributes_GUID, \ - 0x61b397fd,0xf5ae,0x4950,0x97,0x58,0x0e,0xe5,0x98,0xe3,0xc6,0xe6); + 0x61b397fd, 0xf5ae, 0x4950, 0x97, 0x58, 0x0e, 0xe5,\ + 0x98, 0xe3, 0xc6, 0xe6); #endif typedef struct _MSFC_FibrePortHBAAttributes { - // - ULONGLONG UniquePortId; - #define MSFC_FibrePortHBAAttributes_UniquePortId_SIZE sizeof(ULONGLONG) - #define MSFC_FibrePortHBAAttributes_UniquePortId_ID 1 + // + ULONGLONG UniquePortId; +#define MSFC_FibrePortHBAAttributes_UniquePortId_SIZE sizeof (ULONGLONG) +#define MSFC_FibrePortHBAAttributes_UniquePortId_ID 1 - // - ULONG HBAStatus; - #define MSFC_FibrePortHBAAttributes_HBAStatus_SIZE sizeof(ULONG) - #define MSFC_FibrePortHBAAttributes_HBAStatus_ID 2 + // + ULONG HBAStatus; +#define MSFC_FibrePortHBAAttributes_HBAStatus_SIZE sizeof (ULONG) +#define MSFC_FibrePortHBAAttributes_HBAStatus_ID 2 - // - MSFC_HBAPortAttributesResults Attributes; - #define MSFC_FibrePortHBAAttributes_Attributes_SIZE sizeof(MSFC_HBAPortAttributesResults) - #define MSFC_FibrePortHBAAttributes_Attributes_ID 3 + // + MSFC_HBAPortAttributesResults Attributes; +#define MSFC_FibrePortHBAAttributes_Attributes_SIZE \ + sizeof (MSFC_HBAPortAttributesResults) +#define MSFC_FibrePortHBAAttributes_Attributes_ID 3 } MSFC_FibrePortHBAAttributes, *PMSFC_FibrePortHBAAttributes; -#define MSFC_FibrePortHBAAttributes_SIZE (FIELD_OFFSET(MSFC_FibrePortHBAAttributes, Attributes) + MSFC_FibrePortHBAAttributes_Attributes_SIZE) +#define MSFC_FibrePortHBAAttributes_SIZE \ + (FIELD_OFFSET(MSFC_FibrePortHBAAttributes, Attributes) + \ + MSFC_FibrePortHBAAttributes_Attributes_SIZE) // MSFC_FibrePortHBAStatistics - MSFC_FibrePortHBAStatistics -#define MSFC_FibrePortHBAStatisticsGuid \ - { 0x27efaba4,0x362a,0x4f20, { 0x92,0x0b,0xed,0x66,0xe2,0x80,0xfc,0xf5 } } +#define MSFC_FibrePortHBAStatisticsGuid \ + { 0x27efaba4, 0x362a, 0x4f20, \ + { 0x92, 0x0b, 0xed, 0x66, 0xe2, 0x80, 0xfc, 0xf5 } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(MSFC_FibrePortHBAStatistics_GUID, \ - 0x27efaba4,0x362a,0x4f20,0x92,0x0b,0xed,0x66,0xe2,0x80,0xfc,0xf5); + 0x27efaba4, 0x362a, 0x4f20, 0x92, 0x0b, 0xed, 0x66,\ + 0xe2, 0x80, 0xfc, 0xf5); #endif typedef struct _MSFC_FibrePortHBAStatistics { - // - ULONGLONG UniquePortId; - #define MSFC_FibrePortHBAStatistics_UniquePortId_SIZE sizeof(ULONGLONG) - #define MSFC_FibrePortHBAStatistics_UniquePortId_ID 1 + // + ULONGLONG UniquePortId; +#define MSFC_FibrePortHBAStatistics_UniquePortId_SIZE sizeof (ULONGLONG) +#define MSFC_FibrePortHBAStatistics_UniquePortId_ID 1 - // - ULONG HBAStatus; - #define MSFC_FibrePortHBAStatistics_HBAStatus_SIZE sizeof(ULONG) - #define MSFC_FibrePortHBAStatistics_HBAStatus_ID 2 + // + ULONG HBAStatus; +#define MSFC_FibrePortHBAStatistics_HBAStatus_SIZE sizeof (ULONG) +#define MSFC_FibrePortHBAStatistics_HBAStatus_ID 2 - // - MSFC_HBAPortStatistics Statistics; - #define MSFC_FibrePortHBAStatistics_Statistics_SIZE sizeof(MSFC_HBAPortStatistics) - #define MSFC_FibrePortHBAStatistics_Statistics_ID 3 + // + MSFC_HBAPortStatistics Statistics; +#define MSFC_FibrePortHBAStatistics_Statistics_SIZE \ + sizeof (MSFC_HBAPortStatistics) +#define MSFC_FibrePortHBAStatistics_Statistics_ID 3 } MSFC_FibrePortHBAStatistics, *PMSFC_FibrePortHBAStatistics; -#define MSFC_FibrePortHBAStatistics_SIZE (FIELD_OFFSET(MSFC_FibrePortHBAStatistics, Statistics) + MSFC_FibrePortHBAStatistics_Statistics_SIZE) +#define MSFC_FibrePortHBAStatistics_SIZE \ + (FIELD_OFFSET(MSFC_FibrePortHBAStatistics, Statistics) + \ + MSFC_FibrePortHBAStatistics_Statistics_SIZE) // MSFC_FibrePortHBAMethods - MSFC_FibrePortHBAMethods -#define MSFC_FibrePortHBAMethodsGuid \ - { 0xe693553e,0xedf6,0x4d57, { 0xbf,0x08,0xef,0xca,0xae,0x1a,0x2e,0x1c } } +#define MSFC_FibrePortHBAMethodsGuid \ + { 0xe693553e, 0xedf6, 0x4d57, \ + { 0xbf, 0x08, 0xef, 0xca, 0xae, 0x1a, 0x2e, 0x1c } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(MSFC_FibrePortHBAMethods_GUID, \ - 0xe693553e,0xedf6,0x4d57,0xbf,0x08,0xef,0xca,0xae,0x1a,0x2e,0x1c); + 0xe693553e, 0xedf6, 0x4d57, 0xbf, 0x08, 0xef, 0xca, \ + 0xae, 0x1a, 0x2e, 0x1c); #endif // // Method id definitions for MSFC_FibrePortHBAMethods -#define ResetStatistics 1 +#define ResetStatistics 1 // MSFC_FC4STATISTICS - MSFC_FC4STATISTICS -#define MSFC_FC4STATISTICSGuid \ - { 0xca8e7fe6,0xb85e,0x497f, { 0x88,0x58,0x9b,0x5d,0x93,0xa6,0x6f,0xe1 } } +#define MSFC_FC4STATISTICSGuid \ + { 0xca8e7fe6, 0xb85e, 0x497f, \ + { 0x88, 0x58, 0x9b, 0x5d, 0x93, 0xa6, 0x6f, 0xe1 } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(MSFC_FC4STATISTICS_GUID, \ - 0xca8e7fe6,0xb85e,0x497f,0x88,0x58,0x9b,0x5d,0x93,0xa6,0x6f,0xe1); + 0xca8e7fe6, 0xb85e, 0x497f, 0x88, 0x58, 0x9b, 0x5d, \ + 0x93, 0xa6, 0x6f, 0xe1); #endif typedef struct _MSFC_FC4STATISTICS { - // - ULONGLONG InputRequests; - #define MSFC_FC4STATISTICS_InputRequests_SIZE sizeof(ULONGLONG) - #define MSFC_FC4STATISTICS_InputRequests_ID 1 + // + ULONGLONG InputRequests; +#define MSFC_FC4STATISTICS_InputRequests_SIZE sizeof (ULONGLONG) +#define MSFC_FC4STATISTICS_InputRequests_ID 1 - // - ULONGLONG OutputRequests; - #define MSFC_FC4STATISTICS_OutputRequests_SIZE sizeof(ULONGLONG) - #define MSFC_FC4STATISTICS_OutputRequests_ID 2 + // + ULONGLONG OutputRequests; +#define MSFC_FC4STATISTICS_OutputRequests_SIZE sizeof (ULONGLONG) +#define MSFC_FC4STATISTICS_OutputRequests_ID 2 - // - ULONGLONG ControlRequests; - #define MSFC_FC4STATISTICS_ControlRequests_SIZE sizeof(ULONGLONG) - #define MSFC_FC4STATISTICS_ControlRequests_ID 3 + // + ULONGLONG ControlRequests; +#define MSFC_FC4STATISTICS_ControlRequests_SIZE sizeof (ULONGLONG) +#define MSFC_FC4STATISTICS_ControlRequests_ID 3 - // - ULONGLONG InputMegabytes; - #define MSFC_FC4STATISTICS_InputMegabytes_SIZE sizeof(ULONGLONG) - #define MSFC_FC4STATISTICS_InputMegabytes_ID 4 + // + ULONGLONG InputMegabytes; +#define MSFC_FC4STATISTICS_InputMegabytes_SIZE sizeof (ULONGLONG) +#define MSFC_FC4STATISTICS_InputMegabytes_ID 4 - // - ULONGLONG OutputMegabytes; - #define MSFC_FC4STATISTICS_OutputMegabytes_SIZE sizeof(ULONGLONG) - #define MSFC_FC4STATISTICS_OutputMegabytes_ID 5 + // + ULONGLONG OutputMegabytes; +#define MSFC_FC4STATISTICS_OutputMegabytes_SIZE sizeof (ULONGLONG) +#define MSFC_FC4STATISTICS_OutputMegabytes_ID 5 } MSFC_FC4STATISTICS, *PMSFC_FC4STATISTICS; -#define MSFC_FC4STATISTICS_SIZE (FIELD_OFFSET(MSFC_FC4STATISTICS, OutputMegabytes) + MSFC_FC4STATISTICS_OutputMegabytes_SIZE) +#define MSFC_FC4STATISTICS_SIZE \ + (FIELD_OFFSET(MSFC_FC4STATISTICS, OutputMegabytes) +\ + MSFC_FC4STATISTICS_OutputMegabytes_SIZE) // MSFC_EventBuffer - MSFC_EventBuffer -#define MSFC_EventBufferGuid \ - { 0x623f4588,0xcf01,0x4f0e, { 0xb1,0x97,0xab,0xbe,0xe5,0xe0,0xcf,0xf3 } } +#define MSFC_EventBufferGuid \ + { 0x623f4588, 0xcf01, 0x4f0e, \ + { 0xb1, 0x97, 0xab, 0xbe, 0xe5, 0xe0, 0xcf, 0xf3 } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(MSFC_EventBuffer_GUID, \ - 0x623f4588,0xcf01,0x4f0e,0xb1,0x97,0xab,0xbe,0xe5,0xe0,0xcf,0xf3); + 0x623f4588, 0xcf01, 0x4f0e, 0xb1, 0x97, 0xab, 0xbe, \ + 0xe5, 0xe0, 0xcf, 0xf3); #endif typedef struct _MSFC_EventBuffer { - // - ULONG EventType; - #define MSFC_EventBuffer_EventType_SIZE sizeof(ULONG) - #define MSFC_EventBuffer_EventType_ID 1 + // + ULONG EventType; +#define MSFC_EventBuffer_EventType_SIZE sizeof (ULONG) +#define MSFC_EventBuffer_EventType_ID 1 - // - ULONG EventInfo[4]; - #define MSFC_EventBuffer_EventInfo_SIZE sizeof(ULONG[4]) - #define MSFC_EventBuffer_EventInfo_ID 2 + // + ULONG EventInfo[4]; +#define MSFC_EventBuffer_EventInfo_SIZE sizeof (ULONG[4]) +#define MSFC_EventBuffer_EventInfo_ID 2 } MSFC_EventBuffer, *PMSFC_EventBuffer; -#define MSFC_EventBuffer_SIZE (FIELD_OFFSET(MSFC_EventBuffer, EventInfo) + MSFC_EventBuffer_EventInfo_SIZE) +#define MSFC_EventBuffer_SIZE \ + (FIELD_OFFSET(MSFC_EventBuffer, EventInfo) + \ + MSFC_EventBuffer_EventInfo_SIZE) // MSFC_HBAAdapterMethods - MSFC_HBAAdapterMethods -#define MSFC_HBAAdapterMethodsGuid \ - { 0xdf87d4ed,0x4612,0x4d12, { 0x85,0xfb,0x83,0x57,0x4e,0xc3,0x4b,0x7c } } +#define MSFC_HBAAdapterMethodsGuid \ + { 0xdf87d4ed, 0x4612, 0x4d12, \ + { 0x85, 0xfb, 0x83, 0x57, 0x4e, 0xc3, 0x4b, 0x7c } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(MSFC_HBAAdapterMethods_GUID, \ - 0xdf87d4ed,0x4612,0x4d12,0x85,0xfb,0x83,0x57,0x4e,0xc3,0x4b,0x7c); + 0xdf87d4ed, 0x4612, 0x4d12, 0x85, 0xfb, 0x83, 0x57, \ + 0x4e, 0xc3, 0x4b, 0x7c); #endif // // Method id definitions for MSFC_HBAAdapterMethods -#define GetDiscoveredPortAttributes 1 +#define GetDiscoveredPortAttributes 1 typedef struct _GetDiscoveredPortAttributes_IN { - // - ULONG PortIndex; - #define GetDiscoveredPortAttributes_IN_PortIndex_SIZE sizeof(ULONG) - #define GetDiscoveredPortAttributes_IN_PortIndex_ID 1 + // + ULONG PortIndex; +#define GetDiscoveredPortAttributes_IN_PortIndex_SIZE sizeof (ULONG) +#define GetDiscoveredPortAttributes_IN_PortIndex_ID 1 - // - ULONG DiscoveredPortIndex; - #define GetDiscoveredPortAttributes_IN_DiscoveredPortIndex_SIZE sizeof(ULONG) - #define GetDiscoveredPortAttributes_IN_DiscoveredPortIndex_ID 2 + // + ULONG DiscoveredPortIndex; +#define GetDiscoveredPortAttributes_IN_DiscoveredPortIndex_SIZE sizeof (ULONG) +#define GetDiscoveredPortAttributes_IN_DiscoveredPortIndex_ID 2 } GetDiscoveredPortAttributes_IN, *PGetDiscoveredPortAttributes_IN; -#define GetDiscoveredPortAttributes_IN_SIZE (FIELD_OFFSET(GetDiscoveredPortAttributes_IN, DiscoveredPortIndex) + GetDiscoveredPortAttributes_IN_DiscoveredPortIndex_SIZE) +#define GetDiscoveredPortAttributes_IN_SIZE \ + (FIELD_OFFSET(GetDiscoveredPortAttributes_IN, DiscoveredPortIndex) +\ + GetDiscoveredPortAttributes_IN_DiscoveredPortIndex_SIZE) typedef struct _GetDiscoveredPortAttributes_OUT { - // - ULONG HBAStatus; - #define GetDiscoveredPortAttributes_OUT_HBAStatus_SIZE sizeof(ULONG) - #define GetDiscoveredPortAttributes_OUT_HBAStatus_ID 3 + // + ULONG HBAStatus; +#define GetDiscoveredPortAttributes_OUT_HBAStatus_SIZE sizeof (ULONG) +#define GetDiscoveredPortAttributes_OUT_HBAStatus_ID 3 - // + // MSFC_HBAPortAttributesResults PortAttributes; - #define GetDiscoveredPortAttributes_OUT_PortAttributes_SIZE sizeof(MSFC_HBAPortAttributesResults) - #define GetDiscoveredPortAttributes_OUT_PortAttributes_ID 4 +#define GetDiscoveredPortAttributes_OUT_PortAttributes_SIZE \ + sizeof (MSFC_HBAPortAttributesResults) +#define GetDiscoveredPortAttributes_OUT_PortAttributes_ID 4 } GetDiscoveredPortAttributes_OUT, *PGetDiscoveredPortAttributes_OUT; -#define GetDiscoveredPortAttributes_OUT_SIZE (FIELD_OFFSET(GetDiscoveredPortAttributes_OUT, PortAttributes) + GetDiscoveredPortAttributes_OUT_PortAttributes_SIZE) +#define GetDiscoveredPortAttributes_OUT_SIZE \ + (FIELD_OFFSET(GetDiscoveredPortAttributes_OUT, PortAttributes) + \ + GetDiscoveredPortAttributes_OUT_PortAttributes_SIZE) -#define GetPortAttributesByWWN 2 +#define GetPortAttributesByWWN 2 typedef struct _GetPortAttributesByWWN_IN { - // + // UCHAR wwn[8]; - #define GetPortAttributesByWWN_IN_wwn_SIZE sizeof(UCHAR[8]) - #define GetPortAttributesByWWN_IN_wwn_ID 1 +#define GetPortAttributesByWWN_IN_wwn_SIZE sizeof (UCHAR[8]) +#define GetPortAttributesByWWN_IN_wwn_ID 1 } GetPortAttributesByWWN_IN, *PGetPortAttributesByWWN_IN; -#define GetPortAttributesByWWN_IN_SIZE (FIELD_OFFSET(GetPortAttributesByWWN_IN, wwn) + GetPortAttributesByWWN_IN_wwn_SIZE) +#define GetPortAttributesByWWN_IN_SIZE \ + (FIELD_OFFSET(GetPortAttributesByWWN_IN, wwn) + \ + GetPortAttributesByWWN_IN_wwn_SIZE) typedef struct _GetPortAttributesByWWN_OUT { - // - ULONG HBAStatus; - #define GetPortAttributesByWWN_OUT_HBAStatus_SIZE sizeof(ULONG) - #define GetPortAttributesByWWN_OUT_HBAStatus_ID 2 + // + ULONG HBAStatus; +#define GetPortAttributesByWWN_OUT_HBAStatus_SIZE sizeof (ULONG) +#define GetPortAttributesByWWN_OUT_HBAStatus_ID 2 - // + // MSFC_HBAPortAttributesResults PortAttributes; - #define GetPortAttributesByWWN_OUT_PortAttributes_SIZE sizeof(MSFC_HBAPortAttributesResults) - #define GetPortAttributesByWWN_OUT_PortAttributes_ID 3 +#define GetPortAttributesByWWN_OUT_PortAttributes_SIZE \ + sizeof (MSFC_HBAPortAttributesResults) +#define GetPortAttributesByWWN_OUT_PortAttributes_ID 3 } GetPortAttributesByWWN_OUT, *PGetPortAttributesByWWN_OUT; -#define GetPortAttributesByWWN_OUT_SIZE (FIELD_OFFSET(GetPortAttributesByWWN_OUT, PortAttributes) + GetPortAttributesByWWN_OUT_PortAttributes_SIZE) +#define GetPortAttributesByWWN_OUT_SIZE \ + (FIELD_OFFSET(GetPortAttributesByWWN_OUT, PortAttributes) +\ + GetPortAttributesByWWN_OUT_PortAttributes_SIZE) -#define RefreshInformation 3 -#define SendCTPassThru 4 +#define RefreshInformation 3 +#define SendCTPassThru 4 typedef struct _SendCTPassThru_IN { - // + // UCHAR PortWWN[8]; - #define SendCTPassThru_IN_PortWWN_SIZE sizeof(UCHAR[8]) - #define SendCTPassThru_IN_PortWWN_ID 1 +#define SendCTPassThru_IN_PortWWN_SIZE sizeof (UCHAR[8]) +#define SendCTPassThru_IN_PortWWN_ID 1 - // - ULONG RequestBufferCount; - #define SendCTPassThru_IN_RequestBufferCount_SIZE sizeof(ULONG) - #define SendCTPassThru_IN_RequestBufferCount_ID 2 + // + ULONG RequestBufferCount; +#define SendCTPassThru_IN_RequestBufferCount_SIZE sizeof (ULONG) +#define SendCTPassThru_IN_RequestBufferCount_ID 2 - // + // UCHAR RequestBuffer[1]; - #define SendCTPassThru_IN_RequestBuffer_ID 3 +#define SendCTPassThru_IN_RequestBuffer_ID 3 } SendCTPassThru_IN, *PSendCTPassThru_IN; typedef struct _SendCTPassThru_OUT { - // - ULONG HBAStatus; - #define SendCTPassThru_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SendCTPassThru_OUT_HBAStatus_ID 4 + // + ULONG HBAStatus; +#define SendCTPassThru_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SendCTPassThru_OUT_HBAStatus_ID 4 - // - ULONG TotalResponseBufferCount; - #define SendCTPassThru_OUT_TotalResponseBufferCount_SIZE sizeof(ULONG) - #define SendCTPassThru_OUT_TotalResponseBufferCount_ID 5 + // + ULONG TotalResponseBufferCount; +#define SendCTPassThru_OUT_TotalResponseBufferCount_SIZE sizeof (ULONG) +#define SendCTPassThru_OUT_TotalResponseBufferCount_ID 5 - // - ULONG ActualResponseBufferCount; - #define SendCTPassThru_OUT_ActualResponseBufferCount_SIZE sizeof(ULONG) - #define SendCTPassThru_OUT_ActualResponseBufferCount_ID 6 + // + ULONG ActualResponseBufferCount; +#define SendCTPassThru_OUT_ActualResponseBufferCount_SIZE sizeof (ULONG) +#define SendCTPassThru_OUT_ActualResponseBufferCount_ID 6 -#define SendCTPassThru_OUT_ResponseBuffer_SIZE_HINT 768 +#define SendCTPassThru_OUT_ResponseBuffer_SIZE_HINT 768 - // + // UCHAR ResponseBuffer[1]; - #define SendCTPassThru_OUT_ResponseBuffer_ID 7 +#define SendCTPassThru_OUT_ResponseBuffer_ID 7 } SendCTPassThru_OUT, *PSendCTPassThru_OUT; -#define SendRNID 5 +#define SendRNID 5 typedef struct _SendRNID_IN { - // + // UCHAR wwn[8]; - #define SendRNID_IN_wwn_SIZE sizeof(UCHAR[8]) - #define SendRNID_IN_wwn_ID 1 +#define SendRNID_IN_wwn_SIZE sizeof (UCHAR[8]) +#define SendRNID_IN_wwn_ID 1 - // - ULONG wwntype; - #define SendRNID_IN_wwntype_SIZE sizeof(ULONG) - #define SendRNID_IN_wwntype_ID 2 + // + ULONG wwntype; +#define SendRNID_IN_wwntype_SIZE sizeof (ULONG) +#define SendRNID_IN_wwntype_ID 2 } SendRNID_IN, *PSendRNID_IN; -#define SendRNID_IN_SIZE (FIELD_OFFSET(SendRNID_IN, wwntype) + SendRNID_IN_wwntype_SIZE) +#define SendRNID_IN_SIZE \ + (FIELD_OFFSET(SendRNID_IN, wwntype) + SendRNID_IN_wwntype_SIZE) typedef struct _SendRNID_OUT { - // - ULONG HBAStatus; - #define SendRNID_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SendRNID_OUT_HBAStatus_ID 3 + // + ULONG HBAStatus; +#define SendRNID_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SendRNID_OUT_HBAStatus_ID 3 - // - ULONG ResponseBufferCount; - #define SendRNID_OUT_ResponseBufferCount_SIZE sizeof(ULONG) - #define SendRNID_OUT_ResponseBufferCount_ID 4 + // + ULONG ResponseBufferCount; +#define SendRNID_OUT_ResponseBufferCount_SIZE sizeof (ULONG) +#define SendRNID_OUT_ResponseBufferCount_ID 4 -#define SendRNID_OUT_ResponseBuffer_SIZE_HINT 76 +#define SendRNID_OUT_ResponseBuffer_SIZE_HINT 76 - // + // UCHAR ResponseBuffer[1]; - #define SendRNID_OUT_ResponseBuffer_ID 5 +#define SendRNID_OUT_ResponseBuffer_ID 5 } SendRNID_OUT, *PSendRNID_OUT; -#define SendRNIDV2 6 +#define SendRNIDV2 6 typedef struct _SendRNIDV2_IN { - // + // UCHAR PortWWN[8]; - #define SendRNIDV2_IN_PortWWN_SIZE sizeof(UCHAR[8]) - #define SendRNIDV2_IN_PortWWN_ID 1 +#define SendRNIDV2_IN_PortWWN_SIZE sizeof (UCHAR[8]) +#define SendRNIDV2_IN_PortWWN_ID 1 - // + // UCHAR DestWWN[8]; - #define SendRNIDV2_IN_DestWWN_SIZE sizeof(UCHAR[8]) - #define SendRNIDV2_IN_DestWWN_ID 2 +#define SendRNIDV2_IN_DestWWN_SIZE sizeof (UCHAR[8]) +#define SendRNIDV2_IN_DestWWN_ID 2 - // - ULONG DestFCID; - #define SendRNIDV2_IN_DestFCID_SIZE sizeof(ULONG) - #define SendRNIDV2_IN_DestFCID_ID 3 + // + ULONG DestFCID; +#define SendRNIDV2_IN_DestFCID_SIZE sizeof (ULONG) +#define SendRNIDV2_IN_DestFCID_ID 3 - // - ULONG NodeIdDataFormat; - #define SendRNIDV2_IN_NodeIdDataFormat_SIZE sizeof(ULONG) - #define SendRNIDV2_IN_NodeIdDataFormat_ID 4 + // + ULONG NodeIdDataFormat; +#define SendRNIDV2_IN_NodeIdDataFormat_SIZE sizeof (ULONG) +#define SendRNIDV2_IN_NodeIdDataFormat_ID 4 } SendRNIDV2_IN, *PSendRNIDV2_IN; -#define SendRNIDV2_IN_SIZE (FIELD_OFFSET(SendRNIDV2_IN, NodeIdDataFormat) + SendRNIDV2_IN_NodeIdDataFormat_SIZE) +#define SendRNIDV2_IN_SIZE \ + (FIELD_OFFSET(SendRNIDV2_IN, NodeIdDataFormat) + \ + SendRNIDV2_IN_NodeIdDataFormat_SIZE) typedef struct _SendRNIDV2_OUT { - // - ULONG HBAStatus; - #define SendRNIDV2_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SendRNIDV2_OUT_HBAStatus_ID 5 + // + ULONG HBAStatus; +#define SendRNIDV2_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SendRNIDV2_OUT_HBAStatus_ID 5 - // - ULONG TotalRspBufferSize; - #define SendRNIDV2_OUT_TotalRspBufferSize_SIZE sizeof(ULONG) - #define SendRNIDV2_OUT_TotalRspBufferSize_ID 6 + // + ULONG TotalRspBufferSize; +#define SendRNIDV2_OUT_TotalRspBufferSize_SIZE sizeof (ULONG) +#define SendRNIDV2_OUT_TotalRspBufferSize_ID 6 - // - ULONG ActualRspBufferSize; - #define SendRNIDV2_OUT_ActualRspBufferSize_SIZE sizeof(ULONG) - #define SendRNIDV2_OUT_ActualRspBufferSize_ID 7 + // + ULONG ActualRspBufferSize; +#define SendRNIDV2_OUT_ActualRspBufferSize_SIZE sizeof (ULONG) +#define SendRNIDV2_OUT_ActualRspBufferSize_ID 7 -#define SendRNIDV2_OUT_RspBuffer_SIZE_HINT 76 +#define SendRNIDV2_OUT_RspBuffer_SIZE_HINT 76 - // + // UCHAR RspBuffer[1]; - #define SendRNIDV2_OUT_RspBuffer_ID 8 +#define SendRNIDV2_OUT_RspBuffer_ID 8 } SendRNIDV2_OUT, *PSendRNIDV2_OUT; -#define GetFC3MgmtInfo 7 +#define GetFC3MgmtInfo 7 typedef struct _GetFC3MgmtInfo_OUT { - // - ULONG HBAStatus; - #define GetFC3MgmtInfo_OUT_HBAStatus_SIZE sizeof(ULONG) - #define GetFC3MgmtInfo_OUT_HBAStatus_ID 1 + // + ULONG HBAStatus; +#define GetFC3MgmtInfo_OUT_HBAStatus_SIZE sizeof (ULONG) +#define GetFC3MgmtInfo_OUT_HBAStatus_ID 1 - // + // HBAFC3MgmtInfo MgmtInfo; - #define GetFC3MgmtInfo_OUT_MgmtInfo_SIZE sizeof(HBAFC3MgmtInfo) - #define GetFC3MgmtInfo_OUT_MgmtInfo_ID 2 +#define GetFC3MgmtInfo_OUT_MgmtInfo_SIZE sizeof (HBAFC3MgmtInfo) +#define GetFC3MgmtInfo_OUT_MgmtInfo_ID 2 } GetFC3MgmtInfo_OUT, *PGetFC3MgmtInfo_OUT; -#define GetFC3MgmtInfo_OUT_SIZE (FIELD_OFFSET(GetFC3MgmtInfo_OUT, MgmtInfo) + GetFC3MgmtInfo_OUT_MgmtInfo_SIZE) +#define GetFC3MgmtInfo_OUT_SIZE \ + (FIELD_OFFSET(GetFC3MgmtInfo_OUT, MgmtInfo) + \ + GetFC3MgmtInfo_OUT_MgmtInfo_SIZE) -#define SetFC3MgmtInfo 8 +#define SetFC3MgmtInfo 8 typedef struct _SetFC3MgmtInfo_IN { - // + // HBAFC3MgmtInfo MgmtInfo; - #define SetFC3MgmtInfo_IN_MgmtInfo_SIZE sizeof(HBAFC3MgmtInfo) - #define SetFC3MgmtInfo_IN_MgmtInfo_ID 1 +#define SetFC3MgmtInfo_IN_MgmtInfo_SIZE sizeof (HBAFC3MgmtInfo) +#define SetFC3MgmtInfo_IN_MgmtInfo_ID 1 } SetFC3MgmtInfo_IN, *PSetFC3MgmtInfo_IN; -#define SetFC3MgmtInfo_IN_SIZE (FIELD_OFFSET(SetFC3MgmtInfo_IN, MgmtInfo) + SetFC3MgmtInfo_IN_MgmtInfo_SIZE) +#define SetFC3MgmtInfo_IN_SIZE \ + (FIELD_OFFSET(SetFC3MgmtInfo_IN, MgmtInfo) + \ + SetFC3MgmtInfo_IN_MgmtInfo_SIZE) typedef struct _SetFC3MgmtInfo_OUT { - // - ULONG HBAStatus; - #define SetFC3MgmtInfo_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SetFC3MgmtInfo_OUT_HBAStatus_ID 2 + // + ULONG HBAStatus; +#define SetFC3MgmtInfo_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SetFC3MgmtInfo_OUT_HBAStatus_ID 2 } SetFC3MgmtInfo_OUT, *PSetFC3MgmtInfo_OUT; -#define SetFC3MgmtInfo_OUT_SIZE (FIELD_OFFSET(SetFC3MgmtInfo_OUT, HBAStatus) + SetFC3MgmtInfo_OUT_HBAStatus_SIZE) +#define SetFC3MgmtInfo_OUT_SIZE \ + (FIELD_OFFSET(SetFC3MgmtInfo_OUT, HBAStatus) + \ + SetFC3MgmtInfo_OUT_HBAStatus_SIZE) -#define SendRPL 9 +#define SendRPL 9 typedef struct _SendRPL_IN { - // + // UCHAR PortWWN[8]; - #define SendRPL_IN_PortWWN_SIZE sizeof(UCHAR[8]) - #define SendRPL_IN_PortWWN_ID 1 +#define SendRPL_IN_PortWWN_SIZE sizeof (UCHAR[8]) +#define SendRPL_IN_PortWWN_ID 1 - // + // UCHAR AgentWWN[8]; - #define SendRPL_IN_AgentWWN_SIZE sizeof(UCHAR[8]) - #define SendRPL_IN_AgentWWN_ID 2 +#define SendRPL_IN_AgentWWN_SIZE sizeof (UCHAR[8]) +#define SendRPL_IN_AgentWWN_ID 2 - // - ULONG agent_domain; - #define SendRPL_IN_agent_domain_SIZE sizeof(ULONG) - #define SendRPL_IN_agent_domain_ID 3 + // + ULONG agent_domain; +#define SendRPL_IN_agent_domain_SIZE sizeof (ULONG) +#define SendRPL_IN_agent_domain_ID 3 - // - ULONG portIndex; - #define SendRPL_IN_portIndex_SIZE sizeof(ULONG) - #define SendRPL_IN_portIndex_ID 4 + // + ULONG portIndex; +#define SendRPL_IN_portIndex_SIZE sizeof (ULONG) +#define SendRPL_IN_portIndex_ID 4 } SendRPL_IN, *PSendRPL_IN; -#define SendRPL_IN_SIZE (FIELD_OFFSET(SendRPL_IN, portIndex) + SendRPL_IN_portIndex_SIZE) +#define SendRPL_IN_SIZE \ + (FIELD_OFFSET(SendRPL_IN, portIndex) + SendRPL_IN_portIndex_SIZE) typedef struct _SendRPL_OUT { - // - ULONG HBAStatus; - #define SendRPL_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SendRPL_OUT_HBAStatus_ID 5 + // + ULONG HBAStatus; +#define SendRPL_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SendRPL_OUT_HBAStatus_ID 5 - // - ULONG TotalRspBufferSize; - #define SendRPL_OUT_TotalRspBufferSize_SIZE sizeof(ULONG) - #define SendRPL_OUT_TotalRspBufferSize_ID 6 + // + ULONG TotalRspBufferSize; +#define SendRPL_OUT_TotalRspBufferSize_SIZE sizeof (ULONG) +#define SendRPL_OUT_TotalRspBufferSize_ID 6 - // - ULONG ActualRspBufferSize; - #define SendRPL_OUT_ActualRspBufferSize_SIZE sizeof(ULONG) - #define SendRPL_OUT_ActualRspBufferSize_ID 7 + // + ULONG ActualRspBufferSize; +#define SendRPL_OUT_ActualRspBufferSize_SIZE sizeof (ULONG) +#define SendRPL_OUT_ActualRspBufferSize_ID 7 -#define SendRPL_OUT_RspBuffer_SIZE_HINT 28 // 12+16*n +#define SendRPL_OUT_RspBuffer_SIZE_HINT 28 // 12+16*n - // + // UCHAR RspBuffer[1]; - #define SendRPL_OUT_RspBuffer_ID 8 +#define SendRPL_OUT_RspBuffer_ID 8 } SendRPL_OUT, *PSendRPL_OUT; -#define SendRPS 10 +#define SendRPS 10 typedef struct _SendRPS_IN { - // + // UCHAR PortWWN[8]; - #define SendRPS_IN_PortWWN_SIZE sizeof(UCHAR[8]) - #define SendRPS_IN_PortWWN_ID 1 +#define SendRPS_IN_PortWWN_SIZE sizeof (UCHAR[8]) +#define SendRPS_IN_PortWWN_ID 1 - // + // UCHAR AgentWWN[8]; - #define SendRPS_IN_AgentWWN_SIZE sizeof(UCHAR[8]) - #define SendRPS_IN_AgentWWN_ID 2 +#define SendRPS_IN_AgentWWN_SIZE sizeof (UCHAR[8]) +#define SendRPS_IN_AgentWWN_ID 2 - // + // UCHAR ObjectWWN[8]; - #define SendRPS_IN_ObjectWWN_SIZE sizeof(UCHAR[8]) - #define SendRPS_IN_ObjectWWN_ID 3 +#define SendRPS_IN_ObjectWWN_SIZE sizeof (UCHAR[8]) +#define SendRPS_IN_ObjectWWN_ID 3 - // - ULONG AgentDomain; - #define SendRPS_IN_AgentDomain_SIZE sizeof(ULONG) - #define SendRPS_IN_AgentDomain_ID 4 + // + ULONG AgentDomain; +#define SendRPS_IN_AgentDomain_SIZE sizeof (ULONG) +#define SendRPS_IN_AgentDomain_ID 4 - // - ULONG ObjectPortNumber; - #define SendRPS_IN_ObjectPortNumber_SIZE sizeof(ULONG) - #define SendRPS_IN_ObjectPortNumber_ID 5 + // + ULONG ObjectPortNumber; +#define SendRPS_IN_ObjectPortNumber_SIZE sizeof (ULONG) +#define SendRPS_IN_ObjectPortNumber_ID 5 } SendRPS_IN, *PSendRPS_IN; -#define SendRPS_IN_SIZE (FIELD_OFFSET(SendRPS_IN, ObjectPortNumber) + SendRPS_IN_ObjectPortNumber_SIZE) +#define SendRPS_IN_SIZE \ + (FIELD_OFFSET(SendRPS_IN, ObjectPortNumber) + \ + SendRPS_IN_ObjectPortNumber_SIZE) typedef struct _SendRPS_OUT { - // - ULONG HBAStatus; - #define SendRPS_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SendRPS_OUT_HBAStatus_ID 6 + // + ULONG HBAStatus; +#define SendRPS_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SendRPS_OUT_HBAStatus_ID 6 - // - ULONG TotalRspBufferSize; - #define SendRPS_OUT_TotalRspBufferSize_SIZE sizeof(ULONG) - #define SendRPS_OUT_TotalRspBufferSize_ID 7 + // + ULONG TotalRspBufferSize; +#define SendRPS_OUT_TotalRspBufferSize_SIZE sizeof (ULONG) +#define SendRPS_OUT_TotalRspBufferSize_ID 7 - // - ULONG ActualRspBufferSize; - #define SendRPS_OUT_ActualRspBufferSize_SIZE sizeof(ULONG) - #define SendRPS_OUT_ActualRspBufferSize_ID 8 + // + ULONG ActualRspBufferSize; +#define SendRPS_OUT_ActualRspBufferSize_SIZE sizeof (ULONG) +#define SendRPS_OUT_ActualRspBufferSize_ID 8 +#define SendRPS_OUT_RspBuffer_SIZE_HINT 64 -#define SendRPS_OUT_RspBuffer_SIZE_HINT 64 - - // + // UCHAR RspBuffer[1]; - #define SendRPS_OUT_RspBuffer_ID 9 +#define SendRPS_OUT_RspBuffer_ID 9 } SendRPS_OUT, *PSendRPS_OUT; -#define SendSRL 11 +#define SendSRL 11 typedef struct _SendSRL_IN { - // + // UCHAR PortWWN[8]; - #define SendSRL_IN_PortWWN_SIZE sizeof(UCHAR[8]) - #define SendSRL_IN_PortWWN_ID 1 +#define SendSRL_IN_PortWWN_SIZE sizeof (UCHAR[8]) +#define SendSRL_IN_PortWWN_ID 1 - // + // UCHAR WWN[8]; - #define SendSRL_IN_WWN_SIZE sizeof(UCHAR[8]) - #define SendSRL_IN_WWN_ID 2 +#define SendSRL_IN_WWN_SIZE sizeof (UCHAR[8]) +#define SendSRL_IN_WWN_ID 2 - // - ULONG Domain; - #define SendSRL_IN_Domain_SIZE sizeof(ULONG) - #define SendSRL_IN_Domain_ID 3 + // + ULONG Domain; +#define SendSRL_IN_Domain_SIZE sizeof (ULONG) +#define SendSRL_IN_Domain_ID 3 } SendSRL_IN, *PSendSRL_IN; -#define SendSRL_IN_SIZE (FIELD_OFFSET(SendSRL_IN, Domain) + SendSRL_IN_Domain_SIZE) +#define SendSRL_IN_SIZE \ + (FIELD_OFFSET(SendSRL_IN, Domain) + SendSRL_IN_Domain_SIZE) typedef struct _SendSRL_OUT { - // - ULONG HBAStatus; - #define SendSRL_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SendSRL_OUT_HBAStatus_ID 4 - - // - ULONG TotalRspBufferSize; - #define SendSRL_OUT_TotalRspBufferSize_SIZE sizeof(ULONG) - #define SendSRL_OUT_TotalRspBufferSize_ID 5 + // + ULONG HBAStatus; +#define SendSRL_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SendSRL_OUT_HBAStatus_ID 4 - // - ULONG ActualRspBufferSize; - #define SendSRL_OUT_ActualRspBufferSize_SIZE sizeof(ULONG) - #define SendSRL_OUT_ActualRspBufferSize_ID 6 + // + ULONG TotalRspBufferSize; +#define SendSRL_OUT_TotalRspBufferSize_SIZE sizeof (ULONG) +#define SendSRL_OUT_TotalRspBufferSize_ID 5 + // + ULONG ActualRspBufferSize; +#define SendSRL_OUT_ActualRspBufferSize_SIZE sizeof (ULONG) +#define SendSRL_OUT_ActualRspBufferSize_ID 6 -#define SendSRL_OUT_RspBuffer_SIZE_HINT 8 +#define SendSRL_OUT_RspBuffer_SIZE_HINT 8 - // + // UCHAR RspBuffer[1]; - #define SendSRL_OUT_RspBuffer_ID 7 +#define SendSRL_OUT_RspBuffer_ID 7 } SendSRL_OUT, *PSendSRL_OUT; -#define SendLIRR 12 +#define SendLIRR 12 typedef struct _SendLIRR_IN { - // + // UCHAR SourceWWN[8]; - #define SendLIRR_IN_SourceWWN_SIZE sizeof(UCHAR[8]) - #define SendLIRR_IN_SourceWWN_ID 1 +#define SendLIRR_IN_SourceWWN_SIZE sizeof (UCHAR[8]) +#define SendLIRR_IN_SourceWWN_ID 1 - // + // UCHAR DestWWN[8]; - #define SendLIRR_IN_DestWWN_SIZE sizeof(UCHAR[8]) - #define SendLIRR_IN_DestWWN_ID 2 +#define SendLIRR_IN_DestWWN_SIZE sizeof (UCHAR[8]) +#define SendLIRR_IN_DestWWN_ID 2 - // + // UCHAR Function; - #define SendLIRR_IN_Function_SIZE sizeof(UCHAR) - #define SendLIRR_IN_Function_ID 3 +#define SendLIRR_IN_Function_SIZE sizeof (UCHAR) +#define SendLIRR_IN_Function_ID 3 - // + // UCHAR Type; - #define SendLIRR_IN_Type_SIZE sizeof(UCHAR) - #define SendLIRR_IN_Type_ID 4 +#define SendLIRR_IN_Type_SIZE sizeof (UCHAR) +#define SendLIRR_IN_Type_ID 4 } SendLIRR_IN, *PSendLIRR_IN; -#define SendLIRR_IN_SIZE (FIELD_OFFSET(SendLIRR_IN, Type) + SendLIRR_IN_Type_SIZE) +#define SendLIRR_IN_SIZE \ + (FIELD_OFFSET(SendLIRR_IN, Type) + SendLIRR_IN_Type_SIZE) typedef struct _SendLIRR_OUT { - // - ULONG HBAStatus; - #define SendLIRR_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SendLIRR_OUT_HBAStatus_ID 5 + // + ULONG HBAStatus; +#define SendLIRR_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SendLIRR_OUT_HBAStatus_ID 5 - // - ULONG TotalRspBufferSize; - #define SendLIRR_OUT_TotalRspBufferSize_SIZE sizeof(ULONG) - #define SendLIRR_OUT_TotalRspBufferSize_ID 6 + // + ULONG TotalRspBufferSize; +#define SendLIRR_OUT_TotalRspBufferSize_SIZE sizeof (ULONG) +#define SendLIRR_OUT_TotalRspBufferSize_ID 6 - // - ULONG ActualRspBufferSize; - #define SendLIRR_OUT_ActualRspBufferSize_SIZE sizeof(ULONG) - #define SendLIRR_OUT_ActualRspBufferSize_ID 7 + // + ULONG ActualRspBufferSize; +#define SendLIRR_OUT_ActualRspBufferSize_SIZE sizeof (ULONG) +#define SendLIRR_OUT_ActualRspBufferSize_ID 7 -#define SendLIRR_OUT_RspBuffer_SIZE_HINT 8 +#define SendLIRR_OUT_RspBuffer_SIZE_HINT 8 - // + // UCHAR RspBuffer[1]; - #define SendLIRR_OUT_RspBuffer_ID 8 +#define SendLIRR_OUT_RspBuffer_ID 8 } SendLIRR_OUT, *PSendLIRR_OUT; -#define GetFC4Statistics 13 +#define GetFC4Statistics 13 typedef struct _GetFC4Statistics_IN { - // + // UCHAR PortWWN[8]; - #define GetFC4Statistics_IN_PortWWN_SIZE sizeof(UCHAR[8]) - #define GetFC4Statistics_IN_PortWWN_ID 1 +#define GetFC4Statistics_IN_PortWWN_SIZE sizeof (UCHAR[8]) +#define GetFC4Statistics_IN_PortWWN_ID 1 - // + // UCHAR FC4Type; - #define GetFC4Statistics_IN_FC4Type_SIZE sizeof(UCHAR) - #define GetFC4Statistics_IN_FC4Type_ID 2 +#define GetFC4Statistics_IN_FC4Type_SIZE sizeof (UCHAR) +#define GetFC4Statistics_IN_FC4Type_ID 2 } GetFC4Statistics_IN, *PGetFC4Statistics_IN; -#define GetFC4Statistics_IN_SIZE (FIELD_OFFSET(GetFC4Statistics_IN, FC4Type) + GetFC4Statistics_IN_FC4Type_SIZE) +#define GetFC4Statistics_IN_SIZE \ + (FIELD_OFFSET(GetFC4Statistics_IN, FC4Type) + \ + GetFC4Statistics_IN_FC4Type_SIZE) typedef struct _GetFC4Statistics_OUT { - // - ULONG HBAStatus; - #define GetFC4Statistics_OUT_HBAStatus_SIZE sizeof(ULONG) - #define GetFC4Statistics_OUT_HBAStatus_ID 3 + // + ULONG HBAStatus; +#define GetFC4Statistics_OUT_HBAStatus_SIZE sizeof (ULONG) +#define GetFC4Statistics_OUT_HBAStatus_ID 3 - // + // MSFC_FC4STATISTICS FC4Statistics; - #define GetFC4Statistics_OUT_FC4Statistics_SIZE sizeof(MSFC_FC4STATISTICS) - #define GetFC4Statistics_OUT_FC4Statistics_ID 4 +#define GetFC4Statistics_OUT_FC4Statistics_SIZE sizeof (MSFC_FC4STATISTICS) +#define GetFC4Statistics_OUT_FC4Statistics_ID 4 } GetFC4Statistics_OUT, *PGetFC4Statistics_OUT; -#define GetFC4Statistics_OUT_SIZE (FIELD_OFFSET(GetFC4Statistics_OUT, FC4Statistics) + GetFC4Statistics_OUT_FC4Statistics_SIZE) +#define GetFC4Statistics_OUT_SIZE \ + (FIELD_OFFSET(GetFC4Statistics_OUT, FC4Statistics) + \ + GetFC4Statistics_OUT_FC4Statistics_SIZE) -#define GetFCPStatistics 14 +#define GetFCPStatistics 14 typedef struct _GetFCPStatistics_IN { - // + // HBAScsiID ScsiId; - #define GetFCPStatistics_IN_ScsiId_SIZE sizeof(HBAScsiID) - #define GetFCPStatistics_IN_ScsiId_ID 1 +#define GetFCPStatistics_IN_ScsiId_SIZE sizeof (HBAScsiID) +#define GetFCPStatistics_IN_ScsiId_ID 1 } GetFCPStatistics_IN, *PGetFCPStatistics_IN; -#define GetFCPStatistics_IN_SIZE (FIELD_OFFSET(GetFCPStatistics_IN, ScsiId) + GetFCPStatistics_IN_ScsiId_SIZE) +#define GetFCPStatistics_IN_SIZE \ + (FIELD_OFFSET(GetFCPStatistics_IN, ScsiId) + \ + GetFCPStatistics_IN_ScsiId_SIZE) typedef struct _GetFCPStatistics_OUT { - // - ULONG HBAStatus; - #define GetFCPStatistics_OUT_HBAStatus_SIZE sizeof(ULONG) - #define GetFCPStatistics_OUT_HBAStatus_ID 2 + // + ULONG HBAStatus; +#define GetFCPStatistics_OUT_HBAStatus_SIZE sizeof (ULONG) +#define GetFCPStatistics_OUT_HBAStatus_ID 2 - // + // MSFC_FC4STATISTICS FC4Statistics; - #define GetFCPStatistics_OUT_FC4Statistics_SIZE sizeof(MSFC_FC4STATISTICS) - #define GetFCPStatistics_OUT_FC4Statistics_ID 3 +#define GetFCPStatistics_OUT_FC4Statistics_SIZE sizeof (MSFC_FC4STATISTICS) +#define GetFCPStatistics_OUT_FC4Statistics_ID 3 } GetFCPStatistics_OUT, *PGetFCPStatistics_OUT; -#define GetFCPStatistics_OUT_SIZE (FIELD_OFFSET(GetFCPStatistics_OUT, FC4Statistics) + GetFCPStatistics_OUT_FC4Statistics_SIZE) +#define GetFCPStatistics_OUT_SIZE \ + (FIELD_OFFSET(GetFCPStatistics_OUT, FC4Statistics) + \ + GetFCPStatistics_OUT_FC4Statistics_SIZE) -#define ScsiInquiry 15 +#define ScsiInquiry 15 typedef struct _ScsiInquiry_IN { - // + // UCHAR Cdb[6]; - #define ScsiInquiry_IN_Cdb_SIZE sizeof(UCHAR[6]) - #define ScsiInquiry_IN_Cdb_ID 1 +#define ScsiInquiry_IN_Cdb_SIZE sizeof (UCHAR[6]) +#define ScsiInquiry_IN_Cdb_ID 1 - // + // UCHAR HbaPortWWN[8]; - #define ScsiInquiry_IN_HbaPortWWN_SIZE sizeof(UCHAR[8]) - #define ScsiInquiry_IN_HbaPortWWN_ID 2 +#define ScsiInquiry_IN_HbaPortWWN_SIZE sizeof (UCHAR[8]) +#define ScsiInquiry_IN_HbaPortWWN_ID 2 - // + // UCHAR DiscoveredPortWWN[8]; - #define ScsiInquiry_IN_DiscoveredPortWWN_SIZE sizeof(UCHAR[8]) - #define ScsiInquiry_IN_DiscoveredPortWWN_ID 3 +#define ScsiInquiry_IN_DiscoveredPortWWN_SIZE sizeof (UCHAR[8]) +#define ScsiInquiry_IN_DiscoveredPortWWN_ID 3 - // - ULONGLONG FcLun; - #define ScsiInquiry_IN_FcLun_SIZE sizeof(ULONGLONG) - #define ScsiInquiry_IN_FcLun_ID 4 + // + ULONGLONG FcLun; +#define ScsiInquiry_IN_FcLun_SIZE sizeof (ULONGLONG) +#define ScsiInquiry_IN_FcLun_ID 4 } ScsiInquiry_IN, *PScsiInquiry_IN; -#define ScsiInquiry_IN_SIZE (FIELD_OFFSET(ScsiInquiry_IN, FcLun) + ScsiInquiry_IN_FcLun_SIZE) +#define ScsiInquiry_IN_SIZE \ + (FIELD_OFFSET(ScsiInquiry_IN, FcLun) + ScsiInquiry_IN_FcLun_SIZE) typedef struct _ScsiInquiry_OUT { - // - ULONG HBAStatus; - #define ScsiInquiry_OUT_HBAStatus_SIZE sizeof(ULONG) - #define ScsiInquiry_OUT_HBAStatus_ID 5 + // + ULONG HBAStatus; +#define ScsiInquiry_OUT_HBAStatus_SIZE sizeof (ULONG) +#define ScsiInquiry_OUT_HBAStatus_ID 5 - // - ULONG ResponseBufferSize; - #define ScsiInquiry_OUT_ResponseBufferSize_SIZE sizeof(ULONG) - #define ScsiInquiry_OUT_ResponseBufferSize_ID 6 + // + ULONG ResponseBufferSize; +#define ScsiInquiry_OUT_ResponseBufferSize_SIZE sizeof (ULONG) +#define ScsiInquiry_OUT_ResponseBufferSize_ID 6 - // - ULONG SenseBufferSize; - #define ScsiInquiry_OUT_SenseBufferSize_SIZE sizeof(ULONG) - #define ScsiInquiry_OUT_SenseBufferSize_ID 7 + // + ULONG SenseBufferSize; +#define ScsiInquiry_OUT_SenseBufferSize_SIZE sizeof (ULONG) +#define ScsiInquiry_OUT_SenseBufferSize_ID 7 - // + // UCHAR ScsiStatus; - #define ScsiInquiry_OUT_ScsiStatus_SIZE sizeof(UCHAR) - #define ScsiInquiry_OUT_ScsiStatus_ID 8 +#define ScsiInquiry_OUT_ScsiStatus_SIZE sizeof (UCHAR) +#define ScsiInquiry_OUT_ScsiStatus_ID 8 -#define ScsiInquiry_OUT_ResponseBuffer_SIZE_HINT 96 +#define ScsiInquiry_OUT_ResponseBuffer_SIZE_HINT 96 - // + // UCHAR ResponseBuffer[1]; - #define ScsiInquiry_OUT_ResponseBuffer_ID 9 +#define ScsiInquiry_OUT_ResponseBuffer_ID 9 - // + // // UCHAR SenseBuffer[1]; - #define ScsiInquiry_OUT_SenseBuffer_ID 10 +#define ScsiInquiry_OUT_SenseBuffer_ID 10 } ScsiInquiry_OUT, *PScsiInquiry_OUT; -#define ScsiReadCapacity 16 +#define ScsiReadCapacity 16 typedef struct _ScsiReadCapacity_IN { - // + // UCHAR Cdb[10]; - #define ScsiReadCapacity_IN_Cdb_SIZE sizeof(UCHAR[10]) - #define ScsiReadCapacity_IN_Cdb_ID 1 +#define ScsiReadCapacity_IN_Cdb_SIZE sizeof (UCHAR[10]) +#define ScsiReadCapacity_IN_Cdb_ID 1 - // + // UCHAR HbaPortWWN[8]; - #define ScsiReadCapacity_IN_HbaPortWWN_SIZE sizeof(UCHAR[8]) - #define ScsiReadCapacity_IN_HbaPortWWN_ID 2 +#define ScsiReadCapacity_IN_HbaPortWWN_SIZE sizeof (UCHAR[8]) +#define ScsiReadCapacity_IN_HbaPortWWN_ID 2 - // + // UCHAR DiscoveredPortWWN[8]; - #define ScsiReadCapacity_IN_DiscoveredPortWWN_SIZE sizeof(UCHAR[8]) - #define ScsiReadCapacity_IN_DiscoveredPortWWN_ID 3 +#define ScsiReadCapacity_IN_DiscoveredPortWWN_SIZE sizeof (UCHAR[8]) +#define ScsiReadCapacity_IN_DiscoveredPortWWN_ID 3 - // - ULONGLONG FcLun; - #define ScsiReadCapacity_IN_FcLun_SIZE sizeof(ULONGLONG) - #define ScsiReadCapacity_IN_FcLun_ID 4 + // + ULONGLONG FcLun; +#define ScsiReadCapacity_IN_FcLun_SIZE sizeof (ULONGLONG) +#define ScsiReadCapacity_IN_FcLun_ID 4 } ScsiReadCapacity_IN, *PScsiReadCapacity_IN; -#define ScsiReadCapacity_IN_SIZE (FIELD_OFFSET(ScsiReadCapacity_IN, FcLun) + ScsiReadCapacity_IN_FcLun_SIZE) +#define ScsiReadCapacity_IN_SIZE \ + (FIELD_OFFSET(ScsiReadCapacity_IN, FcLun) + \ + ScsiReadCapacity_IN_FcLun_SIZE) typedef struct _ScsiReadCapacity_OUT { - // - ULONG HBAStatus; - #define ScsiReadCapacity_OUT_HBAStatus_SIZE sizeof(ULONG) - #define ScsiReadCapacity_OUT_HBAStatus_ID 5 + // + ULONG HBAStatus; +#define ScsiReadCapacity_OUT_HBAStatus_SIZE sizeof (ULONG) +#define ScsiReadCapacity_OUT_HBAStatus_ID 5 - // - ULONG ResponseBufferSize; - #define ScsiReadCapacity_OUT_ResponseBufferSize_SIZE sizeof(ULONG) - #define ScsiReadCapacity_OUT_ResponseBufferSize_ID 6 + // + ULONG ResponseBufferSize; +#define ScsiReadCapacity_OUT_ResponseBufferSize_SIZE sizeof (ULONG) +#define ScsiReadCapacity_OUT_ResponseBufferSize_ID 6 - // - ULONG SenseBufferSize; - #define ScsiReadCapacity_OUT_SenseBufferSize_SIZE sizeof(ULONG) - #define ScsiReadCapacity_OUT_SenseBufferSize_ID 7 + // + ULONG SenseBufferSize; +#define ScsiReadCapacity_OUT_SenseBufferSize_SIZE sizeof (ULONG) +#define ScsiReadCapacity_OUT_SenseBufferSize_ID 7 - // + // UCHAR ScsiStatus; - #define ScsiReadCapacity_OUT_ScsiStatus_SIZE sizeof(UCHAR) - #define ScsiReadCapacity_OUT_ScsiStatus_ID 8 +#define ScsiReadCapacity_OUT_ScsiStatus_SIZE sizeof (UCHAR) +#define ScsiReadCapacity_OUT_ScsiStatus_ID 8 -#define ScsiReadCapacity_OUT_ResponseBuffer_SIZE_HINT 16 +#define ScsiReadCapacity_OUT_ResponseBuffer_SIZE_HINT 16 - // + // UCHAR ResponseBuffer[1]; - #define ScsiReadCapacity_OUT_ResponseBuffer_ID 9 +#define ScsiReadCapacity_OUT_ResponseBuffer_ID 9 - // + // // UCHAR SenseBuffer[1]; - #define ScsiReadCapacity_OUT_SenseBuffer_ID 10 +#define ScsiReadCapacity_OUT_SenseBuffer_ID 10 } ScsiReadCapacity_OUT, *PScsiReadCapacity_OUT; -#define ScsiReportLuns 17 +#define ScsiReportLuns 17 typedef struct _ScsiReportLuns_IN { - // + // UCHAR Cdb[12]; - #define ScsiReportLuns_IN_Cdb_SIZE sizeof(UCHAR[12]) - #define ScsiReportLuns_IN_Cdb_ID 1 +#define ScsiReportLuns_IN_Cdb_SIZE sizeof (UCHAR[12]) +#define ScsiReportLuns_IN_Cdb_ID 1 - // + // UCHAR HbaPortWWN[8]; - #define ScsiReportLuns_IN_HbaPortWWN_SIZE sizeof(UCHAR[8]) - #define ScsiReportLuns_IN_HbaPortWWN_ID 2 +#define ScsiReportLuns_IN_HbaPortWWN_SIZE sizeof (UCHAR[8]) +#define ScsiReportLuns_IN_HbaPortWWN_ID 2 - // + // UCHAR DiscoveredPortWWN[8]; - #define ScsiReportLuns_IN_DiscoveredPortWWN_SIZE sizeof(UCHAR[8]) - #define ScsiReportLuns_IN_DiscoveredPortWWN_ID 3 +#define ScsiReportLuns_IN_DiscoveredPortWWN_SIZE sizeof (UCHAR[8]) +#define ScsiReportLuns_IN_DiscoveredPortWWN_ID 3 } ScsiReportLuns_IN, *PScsiReportLuns_IN; -#define ScsiReportLuns_IN_SIZE (FIELD_OFFSET(ScsiReportLuns_IN, DiscoveredPortWWN) + ScsiReportLuns_IN_DiscoveredPortWWN_SIZE) +#define ScsiReportLuns_IN_SIZE \ + (FIELD_OFFSET(ScsiReportLuns_IN, DiscoveredPortWWN) + \ + ScsiReportLuns_IN_DiscoveredPortWWN_SIZE) typedef struct _ScsiReportLuns_OUT { - // - ULONG HBAStatus; - #define ScsiReportLuns_OUT_HBAStatus_SIZE sizeof(ULONG) - #define ScsiReportLuns_OUT_HBAStatus_ID 4 + // + ULONG HBAStatus; +#define ScsiReportLuns_OUT_HBAStatus_SIZE sizeof (ULONG) +#define ScsiReportLuns_OUT_HBAStatus_ID 4 - // - ULONG ResponseBufferSize; - #define ScsiReportLuns_OUT_ResponseBufferSize_SIZE sizeof(ULONG) - #define ScsiReportLuns_OUT_ResponseBufferSize_ID 5 + // + ULONG ResponseBufferSize; +#define ScsiReportLuns_OUT_ResponseBufferSize_SIZE sizeof (ULONG) +#define ScsiReportLuns_OUT_ResponseBufferSize_ID 5 - // - ULONG SenseBufferSize; - #define ScsiReportLuns_OUT_SenseBufferSize_SIZE sizeof(ULONG) - #define ScsiReportLuns_OUT_SenseBufferSize_ID 6 + // + ULONG SenseBufferSize; +#define ScsiReportLuns_OUT_SenseBufferSize_SIZE sizeof (ULONG) +#define ScsiReportLuns_OUT_SenseBufferSize_ID 6 - // + // UCHAR ScsiStatus; - #define ScsiReportLuns_OUT_ScsiStatus_SIZE sizeof(UCHAR) - #define ScsiReportLuns_OUT_ScsiStatus_ID 7 +#define ScsiReportLuns_OUT_ScsiStatus_SIZE sizeof (UCHAR) +#define ScsiReportLuns_OUT_ScsiStatus_ID 7 -#define ScsiReportLuns_OUT_ResponseBuffer_SIZE_HINT 16 // 8+8*number_of_luns +#define ScsiReportLuns_OUT_ResponseBuffer_SIZE_HINT 16 // 8+8*number_of_luns - // + // UCHAR ResponseBuffer[1]; - #define ScsiReportLuns_OUT_ResponseBuffer_ID 8 +#define ScsiReportLuns_OUT_ResponseBuffer_ID 8 - // + // // UCHAR SenseBuffer[1]; - #define ScsiReportLuns_OUT_SenseBuffer_ID 9 +#define ScsiReportLuns_OUT_SenseBuffer_ID 9 } ScsiReportLuns_OUT, *PScsiReportLuns_OUT; -#define GetEventBuffer 18 +#define GetEventBuffer 18 typedef struct _GetEventBuffer_OUT { - // - ULONG HBAStatus; - #define GetEventBuffer_OUT_HBAStatus_SIZE sizeof(ULONG) - #define GetEventBuffer_OUT_HBAStatus_ID 1 + // + ULONG HBAStatus; +#define GetEventBuffer_OUT_HBAStatus_SIZE sizeof (ULONG) +#define GetEventBuffer_OUT_HBAStatus_ID 1 - // - ULONG EventCount; - #define GetEventBuffer_OUT_EventCount_SIZE sizeof(ULONG) - #define GetEventBuffer_OUT_EventCount_ID 2 + // + ULONG EventCount; +#define GetEventBuffer_OUT_EventCount_SIZE sizeof (ULONG) +#define GetEventBuffer_OUT_EventCount_ID 2 - // + // MSFC_EventBuffer Events[1]; - #define GetEventBuffer_OUT_Events_ID 3 +#define GetEventBuffer_OUT_Events_ID 3 } GetEventBuffer_OUT, *PGetEventBuffer_OUT; -#define SendRLS 19 +#define SendRLS 19 typedef struct _SendRLS_IN { - // + // UCHAR PortWWN[8]; - #define SendRLS_IN_PortWWN_SIZE sizeof(UCHAR[8]) - #define SendRLS_IN_PortWWN_ID 1 +#define SendRLS_IN_PortWWN_SIZE sizeof (UCHAR[8]) +#define SendRLS_IN_PortWWN_ID 1 - // + // UCHAR DestWWN[8]; - #define SendRLS_IN_DestWWN_SIZE sizeof(UCHAR[8]) - #define SendRLS_IN_DestWWN_ID 2 +#define SendRLS_IN_DestWWN_SIZE sizeof (UCHAR[8]) +#define SendRLS_IN_DestWWN_ID 2 } SendRLS_IN, *PSendRLS_IN; -#define SendRLS_IN_SIZE (FIELD_OFFSET(SendRLS_IN, DestWWN) + SendRLS_IN_DestWWN_SIZE) +#define SendRLS_IN_SIZE \ + (FIELD_OFFSET(SendRLS_IN, DestWWN) + SendRLS_IN_DestWWN_SIZE) typedef struct _SendRLS_OUT { - // - ULONG HBAStatus; - #define SendRLS_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SendRLS_OUT_HBAStatus_ID 3 + // + ULONG HBAStatus; +#define SendRLS_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SendRLS_OUT_HBAStatus_ID 3 - // - ULONG TotalRspBufferSize; - #define SendRLS_OUT_TotalRspBufferSize_SIZE sizeof(ULONG) - #define SendRLS_OUT_TotalRspBufferSize_ID 4 + // + ULONG TotalRspBufferSize; +#define SendRLS_OUT_TotalRspBufferSize_SIZE sizeof (ULONG) +#define SendRLS_OUT_TotalRspBufferSize_ID 4 - // - ULONG ActualRspBufferSize; - #define SendRLS_OUT_ActualRspBufferSize_SIZE sizeof(ULONG) - #define SendRLS_OUT_ActualRspBufferSize_ID 5 + // + ULONG ActualRspBufferSize; +#define SendRLS_OUT_ActualRspBufferSize_SIZE sizeof (ULONG) +#define SendRLS_OUT_ActualRspBufferSize_ID 5 -#define SendRLS_OUT_RspBuffer_SIZE_HINT 28 +#define SendRLS_OUT_RspBuffer_SIZE_HINT 28 - // + // UCHAR RspBuffer[1]; - #define SendRLS_OUT_RspBuffer_ID 6 +#define SendRLS_OUT_RspBuffer_ID 6 } SendRLS_OUT, *PSendRLS_OUT; // HBAFCPID - HBAFCPID -#define HBAFCPIDGuid \ - { 0xff02bc96,0x7fb0,0x4bac, { 0x8f,0x97,0xc7,0x1e,0x49,0x5f,0xa6,0x98 } } +#define HBAFCPIDGuid \ + { 0xff02bc96, 0x7fb0, 0x4bac, \ + { 0x8f, 0x97, 0xc7, 0x1e, 0x49, 0x5f, 0xa6, 0x98 } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(HBAFCPID_GUID, \ - 0xff02bc96,0x7fb0,0x4bac,0x8f,0x97,0xc7,0x1e,0x49,0x5f,0xa6,0x98); + 0xff02bc96, 0x7fb0, 0x4bac, 0x8f, 0x97, 0xc7, 0x1e, \ + 0x49, 0x5f, 0xa6, 0x98); #endif typedef struct _HBAFCPID { - // - ULONG Fcid; - #define HBAFCPID_Fcid_SIZE sizeof(ULONG) - #define HBAFCPID_Fcid_ID 1 + // + ULONG Fcid; +#define HBAFCPID_Fcid_SIZE sizeof (ULONG) +#define HBAFCPID_Fcid_ID 1 - // + // UCHAR NodeWWN[8]; - #define HBAFCPID_NodeWWN_SIZE sizeof(UCHAR[8]) - #define HBAFCPID_NodeWWN_ID 2 +#define HBAFCPID_NodeWWN_SIZE sizeof (UCHAR[8]) +#define HBAFCPID_NodeWWN_ID 2 - // + // UCHAR PortWWN[8]; - #define HBAFCPID_PortWWN_SIZE sizeof(UCHAR[8]) - #define HBAFCPID_PortWWN_ID 3 +#define HBAFCPID_PortWWN_SIZE sizeof (UCHAR[8]) +#define HBAFCPID_PortWWN_ID 3 - // - ULONGLONG FcpLun; - #define HBAFCPID_FcpLun_SIZE sizeof(ULONGLONG) - #define HBAFCPID_FcpLun_ID 4 + // + ULONGLONG FcpLun; +#define HBAFCPID_FcpLun_SIZE sizeof (ULONGLONG) +#define HBAFCPID_FcpLun_ID 4 } HBAFCPID, *PHBAFCPID; -#define HBAFCPID_SIZE (FIELD_OFFSET(HBAFCPID, FcpLun) + HBAFCPID_FcpLun_SIZE) +#define HBAFCPID_SIZE (FIELD_OFFSET(HBAFCPID, FcpLun) + HBAFCPID_FcpLun_SIZE) // HBAFCPScsiEntry - HBAFCPScsiEntry -#define HBAFCPScsiEntryGuid \ - { 0x77ca1248,0x1505,0x4221, { 0x8e,0xb6,0xbb,0xb6,0xec,0x77,0x1a,0x87 } } +#define HBAFCPScsiEntryGuid \ + { 0x77ca1248, 0x1505, 0x4221, \ + { 0x8e, 0xb6, 0xbb, 0xb6, 0xec, 0x77, 0x1a, 0x87 } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(HBAFCPScsiEntry_GUID, \ - 0x77ca1248,0x1505,0x4221,0x8e,0xb6,0xbb,0xb6,0xec,0x77,0x1a,0x87); + 0x77ca1248, 0x1505, 0x4221, 0x8e, 0xb6, 0xbb, 0xb6, \ + 0xec, 0x77, 0x1a, 0x87); #endif typedef struct _HBAFCPScsiEntry { - // + // HBAFCPID FCPId; - #define HBAFCPScsiEntry_FCPId_SIZE sizeof(HBAFCPID) - #define HBAFCPScsiEntry_FCPId_ID 1 +#define HBAFCPScsiEntry_FCPId_SIZE sizeof (HBAFCPID) +#define HBAFCPScsiEntry_FCPId_ID 1 - // + // UCHAR Luid[256]; - #define HBAFCPScsiEntry_Luid_SIZE sizeof(UCHAR[256]) - #define HBAFCPScsiEntry_Luid_ID 2 +#define HBAFCPScsiEntry_Luid_SIZE sizeof (UCHAR[256]) +#define HBAFCPScsiEntry_Luid_ID 2 - // + // HBAScsiID ScsiId; - #define HBAFCPScsiEntry_ScsiId_SIZE sizeof(HBAScsiID) - #define HBAFCPScsiEntry_ScsiId_ID 3 +#define HBAFCPScsiEntry_ScsiId_SIZE sizeof (HBAScsiID) +#define HBAFCPScsiEntry_ScsiId_ID 3 } HBAFCPScsiEntry, *PHBAFCPScsiEntry; -#define HBAFCPScsiEntry_SIZE (FIELD_OFFSET(HBAFCPScsiEntry, ScsiId) + HBAFCPScsiEntry_ScsiId_SIZE) +#define HBAFCPScsiEntry_SIZE \ + (FIELD_OFFSET(HBAFCPScsiEntry, ScsiId) + HBAFCPScsiEntry_ScsiId_SIZE) // HBAFCPBindingEntry - HBAFCPBindingEntry -#define HBAFCPBindingEntryGuid \ - { 0xfceff8b7,0x9d6b,0x4115, { 0x84,0x22,0x05,0x99,0x24,0x51,0xa6,0x29 } } +#define HBAFCPBindingEntryGuid \ + { 0xfceff8b7, 0x9d6b, 0x4115, \ + { 0x84, 0x22, 0x05, 0x99, 0x24, 0x51, 0xa6, 0x29 } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(HBAFCPBindingEntry_GUID, \ - 0xfceff8b7,0x9d6b,0x4115,0x84,0x22,0x05,0x99,0x24,0x51,0xa6,0x29); + 0xfceff8b7, 0x9d6b, 0x4115, 0x84, 0x22, 0x05, 0x99, \ + 0x24, 0x51, 0xa6, 0x29); #endif typedef struct _HBAFCPBindingEntry { - // - ULONG Type; - #define HBAFCPBindingEntry_Type_SIZE sizeof(ULONG) - #define HBAFCPBindingEntry_Type_ID 1 + // + ULONG Type; +#define HBAFCPBindingEntry_Type_SIZE sizeof (ULONG) +#define HBAFCPBindingEntry_Type_ID 1 - // + // HBAFCPID FCPId; - #define HBAFCPBindingEntry_FCPId_SIZE sizeof(HBAFCPID) - #define HBAFCPBindingEntry_FCPId_ID 2 +#define HBAFCPBindingEntry_FCPId_SIZE sizeof (HBAFCPID) +#define HBAFCPBindingEntry_FCPId_ID 2 - // + // HBAScsiID ScsiId; - #define HBAFCPBindingEntry_ScsiId_SIZE sizeof(HBAScsiID) - #define HBAFCPBindingEntry_ScsiId_ID 3 +#define HBAFCPBindingEntry_ScsiId_SIZE sizeof (HBAScsiID) +#define HBAFCPBindingEntry_ScsiId_ID 3 } HBAFCPBindingEntry, *PHBAFCPBindingEntry; -#define HBAFCPBindingEntry_SIZE (FIELD_OFFSET(HBAFCPBindingEntry, ScsiId) + HBAFCPBindingEntry_ScsiId_SIZE) +#define HBAFCPBindingEntry_SIZE \ + (FIELD_OFFSET(HBAFCPBindingEntry, ScsiId) + \ + HBAFCPBindingEntry_ScsiId_SIZE) // HBAFCPBindingEntry2 - HBAFCPBindingEntry2 -#define HBAFCPBindingEntry2Guid \ - { 0x3a1e7679,0x4b1f,0x4f31, { 0xa8,0xae,0xfe,0x92,0x78,0x73,0x09,0x24 } } +#define HBAFCPBindingEntry2Guid \ + { 0x3a1e7679, 0x4b1f, 0x4f31, \ + { 0xa8, 0xae, 0xfe, 0x92, 0x78, 0x73, 0x09, 0x24 } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(HBAFCPBindingEntry2_GUID, \ - 0x3a1e7679,0x4b1f,0x4f31,0xa8,0xae,0xfe,0x92,0x78,0x73,0x09,0x24); + 0x3a1e7679, 0x4b1f, 0x4f31, 0xa8, 0xae, 0xfe, 0x92, \ + 0x78, 0x73, 0x09, 0x24); #endif typedef struct _HBAFCPBindingEntry2 { - // - ULONG Type; - #define HBAFCPBindingEntry2_Type_SIZE sizeof(ULONG) - #define HBAFCPBindingEntry2_Type_ID 1 + // + ULONG Type; +#define HBAFCPBindingEntry2_Type_SIZE sizeof (ULONG) +#define HBAFCPBindingEntry2_Type_ID 1 - // + // HBAFCPID FCPId; - #define HBAFCPBindingEntry2_FCPId_SIZE sizeof(HBAFCPID) - #define HBAFCPBindingEntry2_FCPId_ID 2 +#define HBAFCPBindingEntry2_FCPId_SIZE sizeof (HBAFCPID) +#define HBAFCPBindingEntry2_FCPId_ID 2 - // + // UCHAR Luid[256]; - #define HBAFCPBindingEntry2_Luid_SIZE sizeof(UCHAR[256]) - #define HBAFCPBindingEntry2_Luid_ID 3 +#define HBAFCPBindingEntry2_Luid_SIZE sizeof (UCHAR[256]) +#define HBAFCPBindingEntry2_Luid_ID 3 - // + // HBAScsiID ScsiId; - #define HBAFCPBindingEntry2_ScsiId_SIZE sizeof(HBAScsiID) - #define HBAFCPBindingEntry2_ScsiId_ID 4 +#define HBAFCPBindingEntry2_ScsiId_SIZE sizeof (HBAScsiID) +#define HBAFCPBindingEntry2_ScsiId_ID 4 } HBAFCPBindingEntry2, *PHBAFCPBindingEntry2; -#define HBAFCPBindingEntry2_SIZE (FIELD_OFFSET(HBAFCPBindingEntry2, ScsiId) + HBAFCPBindingEntry2_ScsiId_SIZE) +#define HBAFCPBindingEntry2_SIZE \ + (FIELD_OFFSET(HBAFCPBindingEntry2, ScsiId) + \ + HBAFCPBindingEntry2_ScsiId_SIZE) // MSFC_HBAFCPInfo - MSFC_HBAFCPInfo -#define MSFC_HBAFCPInfoGuid \ - { 0x7a1fc391,0x5b23,0x4c19, { 0xb0,0xeb,0xb1,0xae,0xf5,0x90,0x50,0xc3 } } +#define MSFC_HBAFCPInfoGuid \ + { 0x7a1fc391, 0x5b23, 0x4c19, \ + { 0xb0, 0xeb, 0xb1, 0xae, 0xf5, 0x90, 0x50, 0xc3 } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(MSFC_HBAFCPInfo_GUID, \ - 0x7a1fc391,0x5b23,0x4c19,0xb0,0xeb,0xb1,0xae,0xf5,0x90,0x50,0xc3); + 0x7a1fc391, 0x5b23, 0x4c19, 0xb0, 0xeb, 0xb1, 0xae, \ + 0xf5, 0x90, 0x50, 0xc3); #endif // // Method id definitions for MSFC_HBAFCPInfo -#define GetFcpTargetMapping 1 +#define GetFcpTargetMapping 1 typedef struct _GetFcpTargetMapping_IN { - // + // UCHAR HbaPortWWN[8]; - #define GetFcpTargetMapping_IN_HbaPortWWN_SIZE sizeof(UCHAR[8]) - #define GetFcpTargetMapping_IN_HbaPortWWN_ID 1 +#define GetFcpTargetMapping_IN_HbaPortWWN_SIZE sizeof (UCHAR[8]) +#define GetFcpTargetMapping_IN_HbaPortWWN_ID 1 - // - ULONG InEntryCount; - #define GetFcpTargetMapping_IN_InEntryCount_SIZE sizeof(ULONG) - #define GetFcpTargetMapping_IN_InEntryCount_ID 2 + // + ULONG InEntryCount; +#define GetFcpTargetMapping_IN_InEntryCount_SIZE sizeof (ULONG) +#define GetFcpTargetMapping_IN_InEntryCount_ID 2 } GetFcpTargetMapping_IN, *PGetFcpTargetMapping_IN; -#define GetFcpTargetMapping_IN_SIZE (FIELD_OFFSET(GetFcpTargetMapping_IN, InEntryCount) + GetFcpTargetMapping_IN_InEntryCount_SIZE) +#define GetFcpTargetMapping_IN_SIZE \ + (FIELD_OFFSET(GetFcpTargetMapping_IN, InEntryCount) + \ + GetFcpTargetMapping_IN_InEntryCount_SIZE) typedef struct _GetFcpTargetMapping_OUT { - // - ULONG HBAStatus; - #define GetFcpTargetMapping_OUT_HBAStatus_SIZE sizeof(ULONG) - #define GetFcpTargetMapping_OUT_HBAStatus_ID 3 + // + ULONG HBAStatus; +#define GetFcpTargetMapping_OUT_HBAStatus_SIZE sizeof (ULONG) +#define GetFcpTargetMapping_OUT_HBAStatus_ID 3 - // - ULONG TotalEntryCount; - #define GetFcpTargetMapping_OUT_TotalEntryCount_SIZE sizeof(ULONG) - #define GetFcpTargetMapping_OUT_TotalEntryCount_ID 4 + // + ULONG TotalEntryCount; +#define GetFcpTargetMapping_OUT_TotalEntryCount_SIZE sizeof (ULONG) +#define GetFcpTargetMapping_OUT_TotalEntryCount_ID 4 - // - ULONG OutEntryCount; - #define GetFcpTargetMapping_OUT_OutEntryCount_SIZE sizeof(ULONG) - #define GetFcpTargetMapping_OUT_OutEntryCount_ID 5 + // + ULONG OutEntryCount; +#define GetFcpTargetMapping_OUT_OutEntryCount_SIZE sizeof (ULONG) +#define GetFcpTargetMapping_OUT_OutEntryCount_ID 5 - // + // HBAFCPScsiEntry Entry[1]; - #define GetFcpTargetMapping_OUT_Entry_ID 6 +#define GetFcpTargetMapping_OUT_Entry_ID 6 } GetFcpTargetMapping_OUT, *PGetFcpTargetMapping_OUT; -#define GetFcpPersistentBinding 2 +#define GetFcpPersistentBinding 2 typedef struct _GetFcpPersistentBinding_IN { - // - ULONG InEntryCount; - #define GetFcpPersistentBinding_IN_InEntryCount_SIZE sizeof(ULONG) - #define GetFcpPersistentBinding_IN_InEntryCount_ID 1 + // + ULONG InEntryCount; +#define GetFcpPersistentBinding_IN_InEntryCount_SIZE sizeof (ULONG) +#define GetFcpPersistentBinding_IN_InEntryCount_ID 1 } GetFcpPersistentBinding_IN, *PGetFcpPersistentBinding_IN; -#define GetFcpPersistentBinding_IN_SIZE (FIELD_OFFSET(GetFcpPersistentBinding_IN, InEntryCount) + GetFcpPersistentBinding_IN_InEntryCount_SIZE) +#define GetFcpPersistentBinding_IN_SIZE \ + (FIELD_OFFSET(GetFcpPersistentBinding_IN, InEntryCount) + \ + GetFcpPersistentBinding_IN_InEntryCount_SIZE) typedef struct _GetFcpPersistentBinding_OUT { - // - ULONG HBAStatus; - #define GetFcpPersistentBinding_OUT_HBAStatus_SIZE sizeof(ULONG) - #define GetFcpPersistentBinding_OUT_HBAStatus_ID 2 + // + ULONG HBAStatus; +#define GetFcpPersistentBinding_OUT_HBAStatus_SIZE sizeof (ULONG) +#define GetFcpPersistentBinding_OUT_HBAStatus_ID 2 - // - ULONG TotalEntryCount; - #define GetFcpPersistentBinding_OUT_TotalEntryCount_SIZE sizeof(ULONG) - #define GetFcpPersistentBinding_OUT_TotalEntryCount_ID 3 + // + ULONG TotalEntryCount; +#define GetFcpPersistentBinding_OUT_TotalEntryCount_SIZE sizeof (ULONG) +#define GetFcpPersistentBinding_OUT_TotalEntryCount_ID 3 - // - ULONG OutEntryCount; - #define GetFcpPersistentBinding_OUT_OutEntryCount_SIZE sizeof(ULONG) - #define GetFcpPersistentBinding_OUT_OutEntryCount_ID 4 + // + ULONG OutEntryCount; +#define GetFcpPersistentBinding_OUT_OutEntryCount_SIZE sizeof (ULONG) +#define GetFcpPersistentBinding_OUT_OutEntryCount_ID 4 - // + // HBAFCPBindingEntry Entry[1]; - #define GetFcpPersistentBinding_OUT_Entry_ID 5 +#define GetFcpPersistentBinding_OUT_Entry_ID 5 } GetFcpPersistentBinding_OUT, *PGetFcpPersistentBinding_OUT; -#define GetBindingCapability 3 +#define GetBindingCapability 3 typedef struct _GetBindingCapability_IN { - // + // UCHAR PortWWN[8]; - #define GetBindingCapability_IN_PortWWN_SIZE sizeof(UCHAR[8]) - #define GetBindingCapability_IN_PortWWN_ID 1 +#define GetBindingCapability_IN_PortWWN_SIZE sizeof (UCHAR[8]) +#define GetBindingCapability_IN_PortWWN_ID 1 } GetBindingCapability_IN, *PGetBindingCapability_IN; -#define GetBindingCapability_IN_SIZE (FIELD_OFFSET(GetBindingCapability_IN, PortWWN) + GetBindingCapability_IN_PortWWN_SIZE) +#define GetBindingCapability_IN_SIZE \ + (FIELD_OFFSET(GetBindingCapability_IN, PortWWN) + \ + GetBindingCapability_IN_PortWWN_SIZE) typedef struct _GetBindingCapability_OUT { - // - ULONG HBAStatus; - #define GetBindingCapability_OUT_HBAStatus_SIZE sizeof(ULONG) - #define GetBindingCapability_OUT_HBAStatus_ID 2 + // + ULONG HBAStatus; +#define GetBindingCapability_OUT_HBAStatus_SIZE sizeof (ULONG) +#define GetBindingCapability_OUT_HBAStatus_ID 2 - // - ULONG BindType; - #define GetBindingCapability_OUT_BindType_SIZE sizeof(ULONG) - #define GetBindingCapability_OUT_BindType_ID 3 + // + ULONG BindType; +#define GetBindingCapability_OUT_BindType_SIZE sizeof (ULONG) +#define GetBindingCapability_OUT_BindType_ID 3 } GetBindingCapability_OUT, *PGetBindingCapability_OUT; -#define GetBindingCapability_OUT_SIZE (FIELD_OFFSET(GetBindingCapability_OUT, BindType) + GetBindingCapability_OUT_BindType_SIZE) +#define GetBindingCapability_OUT_SIZE \ + (FIELD_OFFSET(GetBindingCapability_OUT, BindType) + \ + GetBindingCapability_OUT_BindType_SIZE) -#define GetBindingSupport 4 +#define GetBindingSupport 4 typedef struct _GetBindingSupport_IN { - // + // UCHAR PortWWN[8]; - #define GetBindingSupport_IN_PortWWN_SIZE sizeof(UCHAR[8]) - #define GetBindingSupport_IN_PortWWN_ID 1 +#define GetBindingSupport_IN_PortWWN_SIZE sizeof (UCHAR[8]) +#define GetBindingSupport_IN_PortWWN_ID 1 } GetBindingSupport_IN, *PGetBindingSupport_IN; -#define GetBindingSupport_IN_SIZE (FIELD_OFFSET(GetBindingSupport_IN, PortWWN) + GetBindingSupport_IN_PortWWN_SIZE) +#define GetBindingSupport_IN_SIZE \ + (FIELD_OFFSET(GetBindingSupport_IN, PortWWN) + \ + GetBindingSupport_IN_PortWWN_SIZE) typedef struct _GetBindingSupport_OUT { - // - ULONG HBAStatus; - #define GetBindingSupport_OUT_HBAStatus_SIZE sizeof(ULONG) - #define GetBindingSupport_OUT_HBAStatus_ID 2 + // + ULONG HBAStatus; +#define GetBindingSupport_OUT_HBAStatus_SIZE sizeof (ULONG) +#define GetBindingSupport_OUT_HBAStatus_ID 2 - // - ULONG BindType; - #define GetBindingSupport_OUT_BindType_SIZE sizeof(ULONG) - #define GetBindingSupport_OUT_BindType_ID 3 + // + ULONG BindType; +#define GetBindingSupport_OUT_BindType_SIZE sizeof (ULONG) +#define GetBindingSupport_OUT_BindType_ID 3 } GetBindingSupport_OUT, *PGetBindingSupport_OUT; -#define GetBindingSupport_OUT_SIZE (FIELD_OFFSET(GetBindingSupport_OUT, BindType) + GetBindingSupport_OUT_BindType_SIZE) +#define GetBindingSupport_OUT_SIZE \ + (FIELD_OFFSET(GetBindingSupport_OUT, BindType) + \ + GetBindingSupport_OUT_BindType_SIZE) -#define SetBindingSupport 5 +#define SetBindingSupport 5 typedef struct _SetBindingSupport_IN { - // + // UCHAR PortWWN[8]; - #define SetBindingSupport_IN_PortWWN_SIZE sizeof(UCHAR[8]) - #define SetBindingSupport_IN_PortWWN_ID 1 +#define SetBindingSupport_IN_PortWWN_SIZE sizeof (UCHAR[8]) +#define SetBindingSupport_IN_PortWWN_ID 1 - // - ULONG BindType; - #define SetBindingSupport_IN_BindType_SIZE sizeof(ULONG) - #define SetBindingSupport_IN_BindType_ID 2 + // + ULONG BindType; +#define SetBindingSupport_IN_BindType_SIZE sizeof (ULONG) +#define SetBindingSupport_IN_BindType_ID 2 } SetBindingSupport_IN, *PSetBindingSupport_IN; -#define SetBindingSupport_IN_SIZE (FIELD_OFFSET(SetBindingSupport_IN, BindType) + SetBindingSupport_IN_BindType_SIZE) +#define SetBindingSupport_IN_SIZE \ + (FIELD_OFFSET(SetBindingSupport_IN, BindType) + \ + SetBindingSupport_IN_BindType_SIZE) typedef struct _SetBindingSupport_OUT { - // - ULONG HBAStatus; - #define SetBindingSupport_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SetBindingSupport_OUT_HBAStatus_ID 3 + // + ULONG HBAStatus; +#define SetBindingSupport_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SetBindingSupport_OUT_HBAStatus_ID 3 } SetBindingSupport_OUT, *PSetBindingSupport_OUT; -#define SetBindingSupport_OUT_SIZE (FIELD_OFFSET(SetBindingSupport_OUT, HBAStatus) + SetBindingSupport_OUT_HBAStatus_SIZE) +#define SetBindingSupport_OUT_SIZE \ + (FIELD_OFFSET(SetBindingSupport_OUT, HBAStatus) + \ + SetBindingSupport_OUT_HBAStatus_SIZE) -#define GetPersistentBinding2 6 +#define GetPersistentBinding2 6 typedef struct _GetPersistentBinding2_IN { - // + // UCHAR PortWWN[8]; - #define GetPersistentBinding2_IN_PortWWN_SIZE sizeof(UCHAR[8]) - #define GetPersistentBinding2_IN_PortWWN_ID 1 +#define GetPersistentBinding2_IN_PortWWN_SIZE sizeof (UCHAR[8]) +#define GetPersistentBinding2_IN_PortWWN_ID 1 - // - ULONG InEntryCount; - #define GetPersistentBinding2_IN_InEntryCount_SIZE sizeof(ULONG) - #define GetPersistentBinding2_IN_InEntryCount_ID 2 + // + ULONG InEntryCount; +#define GetPersistentBinding2_IN_InEntryCount_SIZE sizeof (ULONG) +#define GetPersistentBinding2_IN_InEntryCount_ID 2 } GetPersistentBinding2_IN, *PGetPersistentBinding2_IN; -#define GetPersistentBinding2_IN_SIZE (FIELD_OFFSET(GetPersistentBinding2_IN, InEntryCount) + GetPersistentBinding2_IN_InEntryCount_SIZE) +#define GetPersistentBinding2_IN_SIZE \ + (FIELD_OFFSET(GetPersistentBinding2_IN, InEntryCount) + \ + GetPersistentBinding2_IN_InEntryCount_SIZE) typedef struct _GetPersistentBinding2_OUT { - // - ULONG HBAStatus; - #define GetPersistentBinding2_OUT_HBAStatus_SIZE sizeof(ULONG) - #define GetPersistentBinding2_OUT_HBAStatus_ID 3 + // + ULONG HBAStatus; +#define GetPersistentBinding2_OUT_HBAStatus_SIZE sizeof (ULONG) +#define GetPersistentBinding2_OUT_HBAStatus_ID 3 - // - ULONG TotalEntryCount; - #define GetPersistentBinding2_OUT_TotalEntryCount_SIZE sizeof(ULONG) - #define GetPersistentBinding2_OUT_TotalEntryCount_ID 4 + // + ULONG TotalEntryCount; +#define GetPersistentBinding2_OUT_TotalEntryCount_SIZE sizeof (ULONG) +#define GetPersistentBinding2_OUT_TotalEntryCount_ID 4 - // - ULONG OutEntryCount; - #define GetPersistentBinding2_OUT_OutEntryCount_SIZE sizeof(ULONG) - #define GetPersistentBinding2_OUT_OutEntryCount_ID 5 + // + ULONG OutEntryCount; +#define GetPersistentBinding2_OUT_OutEntryCount_SIZE sizeof (ULONG) +#define GetPersistentBinding2_OUT_OutEntryCount_ID 5 - // + // HBAFCPBindingEntry2 Bindings[1]; - #define GetPersistentBinding2_OUT_Bindings_ID 6 +#define GetPersistentBinding2_OUT_Bindings_ID 6 } GetPersistentBinding2_OUT, *PGetPersistentBinding2_OUT; - - -//********************************************************************* +// ********************************************************************* // // A call to HBA_SetPersistentBindingV2 will call SetPersistentEntry // once for each binding entry. @@ -1778,316 +1875,349 @@ typedef struct _GetPersistentBinding2_OUT // // Persistent bindings are stored in the registry under: // -// System\CurrentControlSet\Control\Storage\FC\ +// System\CurrentControlSet\Control\Storage\FC\ // -// under the REG_BINARY key Bindings is the struct: +// under the REG_BINARY key Bindings is the struct: // -// typedef struct { -// ULONG Version; -// HBA_FCPBINDING2 Bindings; -// } HBAP_PERSISTENT_BINDINGS, *PHBAP_PERSISTENT_BINDINGS; +// typedef struct { +// ULONG Version; +// HBA_FCPBINDING2 Bindings; +// } HBAP_PERSISTENT_BINDINGS, *PHBAP_PERSISTENT_BINDINGS; // // This is done so that storport capable drivers may have access to // this information during boot // -//******************************************************************** +// ******************************************************************** -#define HBA_REGISTRY_BINDING_VERSION (1) -#define HBA_REGISTRY_BINDING_RELATIVE_PATH L"System\\CurrentControlSet\\Control\\Storage\\FC" -#define HBA_REGISTRY_BINDING_KEY L"Bindings" +#define HBA_REGISTRY_BINDING_VERSION (1) +#define HBA_REGISTRY_BINDING_RELATIVE_PATH \ + L"System\\CurrentControlSet\\Control\\Storage\\FC" +#define HBA_REGISTRY_BINDING_KEY L"Bindings" -#define SetPersistentEntry 7 +#define SetPersistentEntry 7 typedef struct _SetPersistentEntry_IN { - // + // UCHAR PortWWN[8]; - #define SetPersistentEntry_IN_PortWWN_SIZE sizeof(UCHAR[8]) - #define SetPersistentEntry_IN_PortWWN_ID 1 +#define SetPersistentEntry_IN_PortWWN_SIZE sizeof (UCHAR[8]) +#define SetPersistentEntry_IN_PortWWN_ID 1 - // + // HBAFCPBindingEntry2 Binding; - #define SetPersistentEntry_IN_Binding_SIZE sizeof(HBAFCPBindingEntry2) - #define SetPersistentEntry_IN_Binding_ID 2 +#define SetPersistentEntry_IN_Binding_SIZE sizeof (HBAFCPBindingEntry2) +#define SetPersistentEntry_IN_Binding_ID 2 } SetPersistentEntry_IN, *PSetPersistentEntry_IN; -#define SetPersistentEntry_IN_SIZE (FIELD_OFFSET(SetPersistentEntry_IN, Binding) + SetPersistentEntry_IN_Binding_SIZE) +#define SetPersistentEntry_IN_SIZE \ + (FIELD_OFFSET(SetPersistentEntry_IN, Binding) + \ + SetPersistentEntry_IN_Binding_SIZE) typedef struct _SetPersistentEntry_OUT { - // - ULONG HBAStatus; - #define SetPersistentEntry_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SetPersistentEntry_OUT_HBAStatus_ID 3 + // + ULONG HBAStatus; +#define SetPersistentEntry_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SetPersistentEntry_OUT_HBAStatus_ID 3 } SetPersistentEntry_OUT, *PSetPersistentEntry_OUT; -#define SetPersistentEntry_OUT_SIZE (FIELD_OFFSET(SetPersistentEntry_OUT, HBAStatus) + SetPersistentEntry_OUT_HBAStatus_SIZE) +#define SetPersistentEntry_OUT_SIZE \ + (FIELD_OFFSET(SetPersistentEntry_OUT, HBAStatus) + \ + SetPersistentEntry_OUT_HBAStatus_SIZE) -#define RemovePersistentEntry 8 +#define RemovePersistentEntry 8 typedef struct _RemovePersistentEntry_IN { - // + // UCHAR PortWWN[8]; - #define RemovePersistentEntry_IN_PortWWN_SIZE sizeof(UCHAR[8]) - #define RemovePersistentEntry_IN_PortWWN_ID 1 +#define RemovePersistentEntry_IN_PortWWN_SIZE sizeof (UCHAR[8]) +#define RemovePersistentEntry_IN_PortWWN_ID 1 - // + // HBAFCPBindingEntry2 Binding; - #define RemovePersistentEntry_IN_Binding_SIZE sizeof(HBAFCPBindingEntry2) - #define RemovePersistentEntry_IN_Binding_ID 2 +#define RemovePersistentEntry_IN_Binding_SIZE sizeof (HBAFCPBindingEntry2) +#define RemovePersistentEntry_IN_Binding_ID 2 } RemovePersistentEntry_IN, *PRemovePersistentEntry_IN; -#define RemovePersistentEntry_IN_SIZE (FIELD_OFFSET(RemovePersistentEntry_IN, Binding) + RemovePersistentEntry_IN_Binding_SIZE) +#define RemovePersistentEntry_IN_SIZE \ + (FIELD_OFFSET(RemovePersistentEntry_IN, Binding) + \ + RemovePersistentEntry_IN_Binding_SIZE) typedef struct _RemovePersistentEntry_OUT { - // - ULONG HBAStatus; - #define RemovePersistentEntry_OUT_HBAStatus_SIZE sizeof(ULONG) - #define RemovePersistentEntry_OUT_HBAStatus_ID 3 + // + ULONG HBAStatus; +#define RemovePersistentEntry_OUT_HBAStatus_SIZE sizeof (ULONG) +#define RemovePersistentEntry_OUT_HBAStatus_ID 3 } RemovePersistentEntry_OUT, *PRemovePersistentEntry_OUT; -#define RemovePersistentEntry_OUT_SIZE (FIELD_OFFSET(RemovePersistentEntry_OUT, HBAStatus) + RemovePersistentEntry_OUT_HBAStatus_SIZE) +#define RemovePersistentEntry_OUT_SIZE \ + (FIELD_OFFSET(RemovePersistentEntry_OUT, HBAStatus) + \ + RemovePersistentEntry_OUT_HBAStatus_SIZE) // MSFC_AdapterEvent - MSFC_AdapterEvent -#define MSFC_AdapterEventGuid \ - { 0xe9e47403,0xd1d7,0x43f8, { 0x8e,0xe3,0x53,0xcd,0xbf,0xff,0x56,0x46 } } +#define MSFC_AdapterEventGuid \ + { 0xe9e47403, 0xd1d7, 0x43f8, \ + { 0x8e, 0xe3, 0x53, 0xcd, 0xbf, 0xff, 0x56, 0x46 } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(MSFC_AdapterEvent_GUID, \ - 0xe9e47403,0xd1d7,0x43f8,0x8e,0xe3,0x53,0xcd,0xbf,0xff,0x56,0x46); + 0xe9e47403, 0xd1d7, 0x43f8, 0x8e, 0xe3, 0x53, 0xcd, \ + 0xbf, 0xff, 0x56, 0x46); #endif - typedef struct _MSFC_AdapterEvent { - // - ULONG EventType; - #define MSFC_AdapterEvent_EventType_SIZE sizeof(ULONG) - #define MSFC_AdapterEvent_EventType_ID 1 + // + ULONG EventType; +#define MSFC_AdapterEvent_EventType_SIZE sizeof (ULONG) +#define MSFC_AdapterEvent_EventType_ID 1 - // + // UCHAR PortWWN[8]; - #define MSFC_AdapterEvent_PortWWN_SIZE sizeof(UCHAR[8]) - #define MSFC_AdapterEvent_PortWWN_ID 2 +#define MSFC_AdapterEvent_PortWWN_SIZE sizeof (UCHAR[8]) +#define MSFC_AdapterEvent_PortWWN_ID 2 } MSFC_AdapterEvent, *PMSFC_AdapterEvent; -#define MSFC_AdapterEvent_SIZE (FIELD_OFFSET(MSFC_AdapterEvent, PortWWN) + MSFC_AdapterEvent_PortWWN_SIZE) +#define MSFC_AdapterEvent_SIZE \ + (FIELD_OFFSET(MSFC_AdapterEvent, PortWWN) + \ + MSFC_AdapterEvent_PortWWN_SIZE) // MSFC_PortEvent - MSFC_PortEvent -#define MSFC_PortEventGuid \ - { 0x095fbe97,0x3876,0x48ef, { 0x8a,0x04,0x1c,0x55,0x93,0x5d,0x0d,0xf5 } } +#define MSFC_PortEventGuid \ + { 0x095fbe97, 0x3876, 0x48ef, \ + { 0x8a, 0x04, 0x1c, 0x55, 0x93, 0x5d, 0x0d, 0xf5 } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(MSFC_PortEvent_GUID, \ - 0x095fbe97,0x3876,0x48ef,0x8a,0x04,0x1c,0x55,0x93,0x5d,0x0d,0xf5); + 0x095fbe97, 0x3876, 0x48ef, 0x8a, 0x04, 0x1c, 0x55, \ + 0x93, 0x5d, 0x0d, 0xf5); #endif - typedef struct _MSFC_PortEvent { - // - ULONG EventType; - #define MSFC_PortEvent_EventType_SIZE sizeof(ULONG) - #define MSFC_PortEvent_EventType_ID 1 + // + ULONG EventType; +#define MSFC_PortEvent_EventType_SIZE sizeof (ULONG) +#define MSFC_PortEvent_EventType_ID 1 - // - ULONG FabricPortId; - #define MSFC_PortEvent_FabricPortId_SIZE sizeof(ULONG) - #define MSFC_PortEvent_FabricPortId_ID 2 + // + ULONG FabricPortId; +#define MSFC_PortEvent_FabricPortId_SIZE sizeof (ULONG) +#define MSFC_PortEvent_FabricPortId_ID 2 - // + // UCHAR PortWWN[8]; - #define MSFC_PortEvent_PortWWN_SIZE sizeof(UCHAR[8]) - #define MSFC_PortEvent_PortWWN_ID 3 +#define MSFC_PortEvent_PortWWN_SIZE sizeof (UCHAR[8]) +#define MSFC_PortEvent_PortWWN_ID 3 } MSFC_PortEvent, *PMSFC_PortEvent; -#define MSFC_PortEvent_SIZE (FIELD_OFFSET(MSFC_PortEvent, PortWWN) + MSFC_PortEvent_PortWWN_SIZE) +#define MSFC_PortEvent_SIZE \ + (FIELD_OFFSET(MSFC_PortEvent, PortWWN) + MSFC_PortEvent_PortWWN_SIZE) // MSFC_TargetEvent - MSFC_TargetEvent -#define MSFC_TargetEventGuid \ - { 0xcfa6ef26,0x8675,0x4e27, { 0x9a,0x0b,0xb4,0xa8,0x60,0xdd,0xd0,0xf3 } } +#define MSFC_TargetEventGuid \ + { 0xcfa6ef26, 0x8675, 0x4e27, \ + { 0x9a, 0x0b, 0xb4, 0xa8, 0x60, 0xdd, 0xd0, 0xf3 } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(MSFC_TargetEvent_GUID, \ - 0xcfa6ef26,0x8675,0x4e27,0x9a,0x0b,0xb4,0xa8,0x60,0xdd,0xd0,0xf3); + 0xcfa6ef26, 0x8675, 0x4e27, 0x9a, 0x0b, 0xb4, 0xa8, \ + 0x60, 0xdd, 0xd0, 0xf3); #endif - typedef struct _MSFC_TargetEvent { - // - ULONG EventType; - #define MSFC_TargetEvent_EventType_SIZE sizeof(ULONG) - #define MSFC_TargetEvent_EventType_ID 1 + // + ULONG EventType; +#define MSFC_TargetEvent_EventType_SIZE sizeof (ULONG) +#define MSFC_TargetEvent_EventType_ID 1 - // + // UCHAR PortWWN[8]; - #define MSFC_TargetEvent_PortWWN_SIZE sizeof(UCHAR[8]) - #define MSFC_TargetEvent_PortWWN_ID 2 +#define MSFC_TargetEvent_PortWWN_SIZE sizeof (UCHAR[8]) +#define MSFC_TargetEvent_PortWWN_ID 2 - // + // UCHAR DiscoveredPortWWN[8]; - #define MSFC_TargetEvent_DiscoveredPortWWN_SIZE sizeof(UCHAR[8]) - #define MSFC_TargetEvent_DiscoveredPortWWN_ID 3 +#define MSFC_TargetEvent_DiscoveredPortWWN_SIZE sizeof (UCHAR[8]) +#define MSFC_TargetEvent_DiscoveredPortWWN_ID 3 } MSFC_TargetEvent, *PMSFC_TargetEvent; -#define MSFC_TargetEvent_SIZE (FIELD_OFFSET(MSFC_TargetEvent, DiscoveredPortWWN) + MSFC_TargetEvent_DiscoveredPortWWN_SIZE) +#define MSFC_TargetEvent_SIZE \ + (FIELD_OFFSET(MSFC_TargetEvent, DiscoveredPortWWN) + \ + MSFC_TargetEvent_DiscoveredPortWWN_SIZE) // MSFC_EventControl - MSFC_EventControl -#define MSFC_EventControlGuid \ - { 0xa251ccb3,0x5ab0,0x411b, { 0x87,0x71,0x54,0x30,0xef,0x53,0xa2,0x6c } } +#define MSFC_EventControlGuid \ + { 0xa251ccb3, 0x5ab0, 0x411b, \ + { 0x87, 0x71, 0x54, 0x30, 0xef, 0x53, 0xa2, 0x6c } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(MSFC_EventControl_GUID, \ - 0xa251ccb3,0x5ab0,0x411b,0x87,0x71,0x54,0x30,0xef,0x53,0xa2,0x6c); + 0xa251ccb3, 0x5ab0, 0x411b, 0x87, 0x71, 0x54, 0x30, \ + 0xef, 0x53, 0xa2, 0x6c); #endif // // Method id definitions for MSFC_EventControl -#define AddTarget 10 +#define AddTarget 10 typedef struct _AddTarget_IN { - // + // UCHAR HbaPortWWN[8]; - #define AddTarget_IN_HbaPortWWN_SIZE sizeof(UCHAR[8]) - #define AddTarget_IN_HbaPortWWN_ID 1 +#define AddTarget_IN_HbaPortWWN_SIZE sizeof (UCHAR[8]) +#define AddTarget_IN_HbaPortWWN_ID 1 - // + // UCHAR DiscoveredPortWWN[8]; - #define AddTarget_IN_DiscoveredPortWWN_SIZE sizeof(UCHAR[8]) - #define AddTarget_IN_DiscoveredPortWWN_ID 2 +#define AddTarget_IN_DiscoveredPortWWN_SIZE sizeof (UCHAR[8]) +#define AddTarget_IN_DiscoveredPortWWN_ID 2 - // - ULONG AllTargets; - #define AddTarget_IN_AllTargets_SIZE sizeof(ULONG) - #define AddTarget_IN_AllTargets_ID 3 + // + ULONG AllTargets; +#define AddTarget_IN_AllTargets_SIZE sizeof (ULONG) +#define AddTarget_IN_AllTargets_ID 3 } AddTarget_IN, *PAddTarget_IN; -#define AddTarget_IN_SIZE (FIELD_OFFSET(AddTarget_IN, AllTargets) + AddTarget_IN_AllTargets_SIZE) +#define AddTarget_IN_SIZE \ + (FIELD_OFFSET(AddTarget_IN, AllTargets) + AddTarget_IN_AllTargets_SIZE) typedef struct _AddTarget_OUT { - // - ULONG HBAStatus; - #define AddTarget_OUT_HBAStatus_SIZE sizeof(ULONG) - #define AddTarget_OUT_HBAStatus_ID 4 + // + ULONG HBAStatus; +#define AddTarget_OUT_HBAStatus_SIZE sizeof (ULONG) +#define AddTarget_OUT_HBAStatus_ID 4 } AddTarget_OUT, *PAddTarget_OUT; -#define AddTarget_OUT_SIZE (FIELD_OFFSET(AddTarget_OUT, HBAStatus) + AddTarget_OUT_HBAStatus_SIZE) +#define AddTarget_OUT_SIZE \ + (FIELD_OFFSET(AddTarget_OUT, HBAStatus) + AddTarget_OUT_HBAStatus_SIZE) -#define RemoveTarget 11 +#define RemoveTarget 11 typedef struct _RemoveTarget_IN { - // + // UCHAR HbaPortWWN[8]; - #define RemoveTarget_IN_HbaPortWWN_SIZE sizeof(UCHAR[8]) - #define RemoveTarget_IN_HbaPortWWN_ID 1 +#define RemoveTarget_IN_HbaPortWWN_SIZE sizeof (UCHAR[8]) +#define RemoveTarget_IN_HbaPortWWN_ID 1 - // + // UCHAR DiscoveredPortWWN[8]; - #define RemoveTarget_IN_DiscoveredPortWWN_SIZE sizeof(UCHAR[8]) - #define RemoveTarget_IN_DiscoveredPortWWN_ID 2 +#define RemoveTarget_IN_DiscoveredPortWWN_SIZE sizeof (UCHAR[8]) +#define RemoveTarget_IN_DiscoveredPortWWN_ID 2 - // - ULONG AllTargets; - #define RemoveTarget_IN_AllTargets_SIZE sizeof(ULONG) - #define RemoveTarget_IN_AllTargets_ID 3 + // + ULONG AllTargets; +#define RemoveTarget_IN_AllTargets_SIZE sizeof (ULONG) +#define RemoveTarget_IN_AllTargets_ID 3 } RemoveTarget_IN, *PRemoveTarget_IN; -#define RemoveTarget_IN_SIZE (FIELD_OFFSET(RemoveTarget_IN, AllTargets) + RemoveTarget_IN_AllTargets_SIZE) +#define RemoveTarget_IN_SIZE \ + (FIELD_OFFSET(RemoveTarget_IN, AllTargets) + \ + RemoveTarget_IN_AllTargets_SIZE) typedef struct _RemoveTarget_OUT { - // - ULONG HBAStatus; - #define RemoveTarget_OUT_HBAStatus_SIZE sizeof(ULONG) - #define RemoveTarget_OUT_HBAStatus_ID 4 + // + ULONG HBAStatus; +#define RemoveTarget_OUT_HBAStatus_SIZE sizeof (ULONG) +#define RemoveTarget_OUT_HBAStatus_ID 4 } RemoveTarget_OUT, *PRemoveTarget_OUT; -#define RemoveTarget_OUT_SIZE (FIELD_OFFSET(RemoveTarget_OUT, HBAStatus) + RemoveTarget_OUT_HBAStatus_SIZE) +#define RemoveTarget_OUT_SIZE \ + (FIELD_OFFSET(RemoveTarget_OUT, HBAStatus) + \ + RemoveTarget_OUT_HBAStatus_SIZE) -#define AddPort 20 +#define AddPort 20 typedef struct _AddPort_IN { - // + // UCHAR PortWWN[8]; - #define AddPort_IN_PortWWN_SIZE sizeof(UCHAR[8]) - #define AddPort_IN_PortWWN_ID 1 +#define AddPort_IN_PortWWN_SIZE sizeof (UCHAR[8]) +#define AddPort_IN_PortWWN_ID 1 } AddPort_IN, *PAddPort_IN; -#define AddPort_IN_SIZE (FIELD_OFFSET(AddPort_IN, PortWWN) + AddPort_IN_PortWWN_SIZE) +#define AddPort_IN_SIZE \ + (FIELD_OFFSET(AddPort_IN, PortWWN) + AddPort_IN_PortWWN_SIZE) typedef struct _AddPort_OUT { - // - ULONG HBAStatus; - #define AddPort_OUT_HBAStatus_SIZE sizeof(ULONG) - #define AddPort_OUT_HBAStatus_ID 2 + // + ULONG HBAStatus; +#define AddPort_OUT_HBAStatus_SIZE sizeof (ULONG) +#define AddPort_OUT_HBAStatus_ID 2 } AddPort_OUT, *PAddPort_OUT; -#define AddPort_OUT_SIZE (FIELD_OFFSET(AddPort_OUT, HBAStatus) + AddPort_OUT_HBAStatus_SIZE) +#define AddPort_OUT_SIZE \ + (FIELD_OFFSET(AddPort_OUT, HBAStatus) + AddPort_OUT_HBAStatus_SIZE) -#define RemovePort 21 +#define RemovePort 21 typedef struct _RemovePort_IN { - // + // UCHAR PortWWN[8]; - #define RemovePort_IN_PortWWN_SIZE sizeof(UCHAR[8]) - #define RemovePort_IN_PortWWN_ID 1 +#define RemovePort_IN_PortWWN_SIZE sizeof (UCHAR[8]) +#define RemovePort_IN_PortWWN_ID 1 } RemovePort_IN, *PRemovePort_IN; -#define RemovePort_IN_SIZE (FIELD_OFFSET(RemovePort_IN, PortWWN) + RemovePort_IN_PortWWN_SIZE) +#define RemovePort_IN_SIZE \ + (FIELD_OFFSET(RemovePort_IN, PortWWN) + RemovePort_IN_PortWWN_SIZE) typedef struct _RemovePort_OUT { - // - ULONG HBAStatus; - #define RemovePort_OUT_HBAStatus_SIZE sizeof(ULONG) - #define RemovePort_OUT_HBAStatus_ID 2 + // + ULONG HBAStatus; +#define RemovePort_OUT_HBAStatus_SIZE sizeof (ULONG) +#define RemovePort_OUT_HBAStatus_ID 2 } RemovePort_OUT, *PRemovePort_OUT; -#define RemovePort_OUT_SIZE (FIELD_OFFSET(RemovePort_OUT, HBAStatus) + RemovePort_OUT_HBAStatus_SIZE) +#define RemovePort_OUT_SIZE \ + (FIELD_OFFSET(RemovePort_OUT, HBAStatus) + \ + RemovePort_OUT_HBAStatus_SIZE) -#define AddLink 30 +#define AddLink 30 typedef struct _AddLink_OUT { - // - ULONG HBAStatus; - #define AddLink_OUT_HBAStatus_SIZE sizeof(ULONG) - #define AddLink_OUT_HBAStatus_ID 1 + // + ULONG HBAStatus; +#define AddLink_OUT_HBAStatus_SIZE sizeof (ULONG) +#define AddLink_OUT_HBAStatus_ID 1 } AddLink_OUT, *PAddLink_OUT; -#define AddLink_OUT_SIZE (FIELD_OFFSET(AddLink_OUT, HBAStatus) + AddLink_OUT_HBAStatus_SIZE) +#define AddLink_OUT_SIZE \ + (FIELD_OFFSET(AddLink_OUT, HBAStatus) + AddLink_OUT_HBAStatus_SIZE) -#define RemoveLink 31 +#define RemoveLink 31 typedef struct _RemoveLink_OUT { - // - ULONG HBAStatus; - #define RemoveLink_OUT_HBAStatus_SIZE sizeof(ULONG) - #define RemoveLink_OUT_HBAStatus_ID 1 + // + ULONG HBAStatus; +#define RemoveLink_OUT_HBAStatus_SIZE sizeof (ULONG) +#define RemoveLink_OUT_HBAStatus_ID 1 } RemoveLink_OUT, *PRemoveLink_OUT; -#define RemoveLink_OUT_SIZE (FIELD_OFFSET(RemoveLink_OUT, HBAStatus) + RemoveLink_OUT_HBAStatus_SIZE) +#define RemoveLink_OUT_SIZE \ + (FIELD_OFFSET(RemoveLink_OUT, HBAStatus) + \ + RemoveLink_OUT_HBAStatus_SIZE) // MS_SM_AdapterInformationQuery - MS_SM_AdapterInformationQuery @@ -2097,2462 +2227,2658 @@ typedef struct _RemoveLink_OUT #ifdef MS_SM_HBA_API -#define MS_SM_AdapterInformationQueryGuid \ - { 0xbdc67efa,0xe5e7,0x4777, { 0xb1,0x3c,0x62,0x14,0x59,0x65,0x70,0x99 } } +#define MS_SM_AdapterInformationQueryGuid \ + { 0xbdc67efa, 0xe5e7, 0x4777, \ + { 0xb1, 0x3c, 0x62, 0x14, 0x59, 0x65, 0x70, 0x99 } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(MS_SM_AdapterInformationQuery_GUID, \ - 0xbdc67efa,0xe5e7,0x4777,0xb1,0x3c,0x62,0x14,0x59,0x65,0x70,0x99); + 0xbdc67efa, 0xe5e7, 0x4777, 0xb1, 0x3c, 0x62, 0x14, \ + 0x59, 0x65, 0x70, 0x99); #endif typedef struct _MS_SM_AdapterInformationQuery { - // - ULONGLONG UniqueAdapterId; - #define MS_SM_AdapterInformationQuery_UniqueAdapterId_SIZE sizeof(ULONGLONG) - #define MS_SM_AdapterInformationQuery_UniqueAdapterId_ID 1 + // + ULONGLONG UniqueAdapterId; +#define MS_SM_AdapterInformationQuery_UniqueAdapterId_SIZE sizeof (ULONGLONG) +#define MS_SM_AdapterInformationQuery_UniqueAdapterId_ID 1 - // - ULONG HBAStatus; - #define MS_SM_AdapterInformationQuery_HBAStatus_SIZE sizeof(ULONG) - #define MS_SM_AdapterInformationQuery_HBAStatus_ID 2 + // + ULONG HBAStatus; +#define MS_SM_AdapterInformationQuery_HBAStatus_SIZE sizeof (ULONG) +#define MS_SM_AdapterInformationQuery_HBAStatus_ID 2 - // - ULONG NumberOfPorts; - #define MS_SM_AdapterInformationQuery_NumberOfPorts_SIZE sizeof(ULONG) - #define MS_SM_AdapterInformationQuery_NumberOfPorts_ID 3 + // + ULONG NumberOfPorts; +#define MS_SM_AdapterInformationQuery_NumberOfPorts_SIZE sizeof (ULONG) +#define MS_SM_AdapterInformationQuery_NumberOfPorts_ID 3 - // - ULONG VendorSpecificID; - #define MS_SM_AdapterInformationQuery_VendorSpecificID_SIZE sizeof(ULONG) - #define MS_SM_AdapterInformationQuery_VendorSpecificID_ID 4 + // + ULONG VendorSpecificID; +#define MS_SM_AdapterInformationQuery_VendorSpecificID_SIZE sizeof (ULONG) +#define MS_SM_AdapterInformationQuery_VendorSpecificID_ID 4 - //****************************************************************** - // - // The string type is variable length (up to MaxLen). - // Each string starts with a ushort that holds the strings length - // (in bytes) followed by the WCHARs that make up the string. - // - //****************************************************************** + // ****************************************************************** + // + // The string type is variable length (up to MaxLen). + // Each string starts with a ushort that holds the strings length + // (in bytes) followed by the WCHARs that make up the string. + // + // ****************************************************************** - // + // WCHAR Manufacturer[64 + 1]; - #define MS_SM_AdapterInformationQuery_Manufacturer_ID 5 +#define MS_SM_AdapterInformationQuery_Manufacturer_ID 5 - // + // WCHAR SerialNumber[64 + 1]; - #define MS_SM_AdapterInformationQuery_SerialNumber_ID 6 +#define MS_SM_AdapterInformationQuery_SerialNumber_ID 6 - // + // WCHAR Model[256 + 1]; - #define MS_SM_AdapterInformationQuery_Model_ID 7 +#define MS_SM_AdapterInformationQuery_Model_ID 7 - // + // WCHAR ModelDescription[256 + 1]; - #define MS_SM_AdapterInformationQuery_ModelDescription_ID 8 +#define MS_SM_AdapterInformationQuery_ModelDescription_ID 8 - // + // WCHAR HardwareVersion[256 + 1]; - #define MS_SM_AdapterInformationQuery_HardwareVersion_ID 9 +#define MS_SM_AdapterInformationQuery_HardwareVersion_ID 9 - // + // WCHAR DriverVersion[256 + 1]; - #define MS_SM_AdapterInformationQuery_DriverVersion_ID 10 +#define MS_SM_AdapterInformationQuery_DriverVersion_ID 10 - // + // WCHAR OptionROMVersion[256 + 1]; - #define MS_SM_AdapterInformationQuery_OptionROMVersion_ID 11 +#define MS_SM_AdapterInformationQuery_OptionROMVersion_ID 11 - // + // WCHAR FirmwareVersion[256 + 1]; - #define MS_SM_AdapterInformationQuery_FirmwareVersion_ID 12 +#define MS_SM_AdapterInformationQuery_FirmwareVersion_ID 12 - // + // WCHAR DriverName[256 + 1]; - #define MS_SM_AdapterInformationQuery_DriverName_ID 13 +#define MS_SM_AdapterInformationQuery_DriverName_ID 13 - // + // WCHAR HBASymbolicName[256 + 1]; - #define MS_SM_AdapterInformationQuery_HBASymbolicName_ID 14 +#define MS_SM_AdapterInformationQuery_HBASymbolicName_ID 14 - // + // WCHAR RedundantOptionROMVersion[256 + 1]; - #define MS_SM_AdapterInformationQuery_RedundantOptionROMVersion_ID 15 +#define MS_SM_AdapterInformationQuery_RedundantOptionROMVersion_ID 15 - // + // WCHAR RedundantFirmwareVersion[256 + 1]; - #define MS_SM_AdapterInformationQuery_RedundantFirmwareVersion_ID 16 +#define MS_SM_AdapterInformationQuery_RedundantFirmwareVersion_ID 16 - // + // WCHAR MfgDomain[256 + 1]; - #define MS_SM_AdapterInformationQuery_MfgDomain_ID 17 +#define MS_SM_AdapterInformationQuery_MfgDomain_ID 17 } MS_SM_AdapterInformationQuery, *PMS_SM_AdapterInformationQuery; // MS_SMHBA_FC_Port - MS_SMHBA_FC_Port -#define MS_SMHBA_FC_PortGuid \ - { 0x96b827a7,0x2b4a,0x49c8, { 0x90,0x97,0x07,0x82,0x00,0xc5,0xa5,0xcd } } +#define MS_SMHBA_FC_PortGuid \ + { 0x96b827a7, 0x2b4a, 0x49c8, \ + { 0x90, 0x97, 0x07, 0x82, 0x00, 0xc5, 0xa5, 0xcd } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(MS_SMHBA_FC_Port_GUID, \ - 0x96b827a7,0x2b4a,0x49c8,0x90,0x97,0x07,0x82,0x00,0xc5,0xa5,0xcd); + 0x96b827a7, 0x2b4a, 0x49c8, 0x90, 0x97, 0x07, 0x82, \ + 0x00, 0xc5, 0xa5, 0xcd); #endif typedef struct _MS_SMHBA_FC_Port { - // + // UCHAR NodeWWN[8]; - #define MS_SMHBA_FC_Port_NodeWWN_SIZE sizeof(UCHAR[8]) - #define MS_SMHBA_FC_Port_NodeWWN_ID 1 +#define MS_SMHBA_FC_Port_NodeWWN_SIZE sizeof (UCHAR[8]) +#define MS_SMHBA_FC_Port_NodeWWN_ID 1 - // + // UCHAR PortWWN[8]; - #define MS_SMHBA_FC_Port_PortWWN_SIZE sizeof(UCHAR[8]) - #define MS_SMHBA_FC_Port_PortWWN_ID 2 +#define MS_SMHBA_FC_Port_PortWWN_SIZE sizeof (UCHAR[8]) +#define MS_SMHBA_FC_Port_PortWWN_ID 2 - // - ULONG FcId; - #define MS_SMHBA_FC_Port_FcId_SIZE sizeof(ULONG) - #define MS_SMHBA_FC_Port_FcId_ID 3 + // + ULONG FcId; +#define MS_SMHBA_FC_Port_FcId_SIZE sizeof (ULONG) +#define MS_SMHBA_FC_Port_FcId_ID 3 - // - ULONG PortSupportedClassofService; - #define MS_SMHBA_FC_Port_PortSupportedClassofService_SIZE sizeof(ULONG) - #define MS_SMHBA_FC_Port_PortSupportedClassofService_ID 4 + // + ULONG PortSupportedClassofService; +#define MS_SMHBA_FC_Port_PortSupportedClassofService_SIZE sizeof (ULONG) +#define MS_SMHBA_FC_Port_PortSupportedClassofService_ID 4 - // + // UCHAR PortSupportedFc4Types[32]; - #define MS_SMHBA_FC_Port_PortSupportedFc4Types_SIZE sizeof(UCHAR[32]) - #define MS_SMHBA_FC_Port_PortSupportedFc4Types_ID 5 +#define MS_SMHBA_FC_Port_PortSupportedFc4Types_SIZE sizeof (UCHAR[32]) +#define MS_SMHBA_FC_Port_PortSupportedFc4Types_ID 5 - // + // UCHAR PortActiveFc4Types[32]; - #define MS_SMHBA_FC_Port_PortActiveFc4Types_SIZE sizeof(UCHAR[32]) - #define MS_SMHBA_FC_Port_PortActiveFc4Types_ID 6 +#define MS_SMHBA_FC_Port_PortActiveFc4Types_SIZE sizeof (UCHAR[32]) +#define MS_SMHBA_FC_Port_PortActiveFc4Types_ID 6 - // + // UCHAR FabricName[8]; - #define MS_SMHBA_FC_Port_FabricName_SIZE sizeof(UCHAR[8]) - #define MS_SMHBA_FC_Port_FabricName_ID 7 +#define MS_SMHBA_FC_Port_FabricName_SIZE sizeof (UCHAR[8]) +#define MS_SMHBA_FC_Port_FabricName_ID 7 - // - ULONG NumberofDiscoveredPorts; - #define MS_SMHBA_FC_Port_NumberofDiscoveredPorts_SIZE sizeof(ULONG) - #define MS_SMHBA_FC_Port_NumberofDiscoveredPorts_ID 8 + // + ULONG NumberofDiscoveredPorts; +#define MS_SMHBA_FC_Port_NumberofDiscoveredPorts_SIZE sizeof (ULONG) +#define MS_SMHBA_FC_Port_NumberofDiscoveredPorts_ID 8 - // + // UCHAR NumberofPhys; - #define MS_SMHBA_FC_Port_NumberofPhys_SIZE sizeof(UCHAR) - #define MS_SMHBA_FC_Port_NumberofPhys_ID 9 +#define MS_SMHBA_FC_Port_NumberofPhys_SIZE sizeof (UCHAR) +#define MS_SMHBA_FC_Port_NumberofPhys_ID 9 - // + // WCHAR PortSymbolicName[256 + 1]; - #define MS_SMHBA_FC_Port_PortSymbolicName_ID 10 +#define MS_SMHBA_FC_Port_PortSymbolicName_ID 10 } MS_SMHBA_FC_Port, *PMS_SMHBA_FC_Port; // MS_SMHBA_SAS_Port - MS_SMHBA_SAS_Port -#define MS_SMHBA_SAS_PortGuid \ - { 0xb914e34f,0x7b80,0x46b0, { 0x80,0x34,0x6d,0x9b,0x68,0x9e,0x1d,0xdd } } +#define MS_SMHBA_SAS_PortGuid \ + { 0xb914e34f, 0x7b80, 0x46b0, \ + { 0x80, 0x34, 0x6d, 0x9b, 0x68, 0x9e, 0x1d, 0xdd } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(MS_SMHBA_SAS_Port_GUID, \ - 0xb914e34f,0x7b80,0x46b0,0x80,0x34,0x6d,0x9b,0x68,0x9e,0x1d,0xdd); + 0xb914e34f, 0x7b80, 0x46b0, 0x80, 0x34, 0x6d, 0x9b, \ + 0x68, 0x9e, 0x1d, 0xdd); #endif - typedef struct _MS_SMHBA_SAS_Port { - // - ULONG PortProtocol; - #define MS_SMHBA_SAS_Port_PortProtocol_SIZE sizeof(ULONG) - #define MS_SMHBA_SAS_Port_PortProtocol_ID 1 + // + ULONG PortProtocol; +#define MS_SMHBA_SAS_Port_PortProtocol_SIZE sizeof (ULONG) +#define MS_SMHBA_SAS_Port_PortProtocol_ID 1 - // + // UCHAR LocalSASAddress[8]; - #define MS_SMHBA_SAS_Port_LocalSASAddress_SIZE sizeof(UCHAR[8]) - #define MS_SMHBA_SAS_Port_LocalSASAddress_ID 2 +#define MS_SMHBA_SAS_Port_LocalSASAddress_SIZE sizeof (UCHAR[8]) +#define MS_SMHBA_SAS_Port_LocalSASAddress_ID 2 - // + // UCHAR AttachedSASAddress[8]; - #define MS_SMHBA_SAS_Port_AttachedSASAddress_SIZE sizeof(UCHAR[8]) - #define MS_SMHBA_SAS_Port_AttachedSASAddress_ID 3 +#define MS_SMHBA_SAS_Port_AttachedSASAddress_SIZE sizeof (UCHAR[8]) +#define MS_SMHBA_SAS_Port_AttachedSASAddress_ID 3 - // - ULONG NumberofDiscoveredPorts; - #define MS_SMHBA_SAS_Port_NumberofDiscoveredPorts_SIZE sizeof(ULONG) - #define MS_SMHBA_SAS_Port_NumberofDiscoveredPorts_ID 4 + // + ULONG NumberofDiscoveredPorts; +#define MS_SMHBA_SAS_Port_NumberofDiscoveredPorts_SIZE sizeof (ULONG) +#define MS_SMHBA_SAS_Port_NumberofDiscoveredPorts_ID 4 - // - ULONG NumberofPhys; - #define MS_SMHBA_SAS_Port_NumberofPhys_SIZE sizeof(ULONG) - #define MS_SMHBA_SAS_Port_NumberofPhys_ID 5 + // + ULONG NumberofPhys; +#define MS_SMHBA_SAS_Port_NumberofPhys_SIZE sizeof (ULONG) +#define MS_SMHBA_SAS_Port_NumberofPhys_ID 5 } MS_SMHBA_SAS_Port, *PMS_SMHBA_SAS_Port; -#define MS_SMHBA_SAS_Port_SIZE (FIELD_OFFSET(MS_SMHBA_SAS_Port, NumberofPhys) + MS_SMHBA_SAS_Port_NumberofPhys_SIZE) +#define MS_SMHBA_SAS_Port_SIZE \ + (FIELD_OFFSET(MS_SMHBA_SAS_Port, NumberofPhys) + \ + MS_SMHBA_SAS_Port_NumberofPhys_SIZE) // MS_SMHBA_PORTATTRIBUTES - MS_SMHBA_PORTATTRIBUTES -#define MS_SMHBA_PORTATTRIBUTESGuid \ - { 0x50a97b2d,0x99ad,0x4cf9, { 0x84,0x37,0xb4,0xea,0x0c,0x07,0xbe,0x4c } } +#define MS_SMHBA_PORTATTRIBUTESGuid \ + { 0x50a97b2d, 0x99ad, 0x4cf9, \ + { 0x84, 0x37, 0xb4, 0xea, 0x0c, 0x07, 0xbe, 0x4c } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(MS_SMHBA_PORTATTRIBUTES_GUID, \ - 0x50a97b2d,0x99ad,0x4cf9,0x84,0x37,0xb4,0xea,0x0c,0x07,0xbe,0x4c); + 0x50a97b2d, 0x99ad, 0x4cf9, 0x84, 0x37, 0xb4, 0xea, \ + 0x0c, 0x07, 0xbe, 0x4c); #endif - typedef struct _MS_SMHBA_PORTATTRIBUTES { - // - ULONG PortType; - #define MS_SMHBA_PORTATTRIBUTES_PortType_SIZE sizeof(ULONG) - #define MS_SMHBA_PORTATTRIBUTES_PortType_ID 1 + // + ULONG PortType; +#define MS_SMHBA_PORTATTRIBUTES_PortType_SIZE sizeof (ULONG) +#define MS_SMHBA_PORTATTRIBUTES_PortType_ID 1 - // - ULONG PortState; - #define MS_SMHBA_PORTATTRIBUTES_PortState_SIZE sizeof(ULONG) - #define MS_SMHBA_PORTATTRIBUTES_PortState_ID 2 + // + ULONG PortState; +#define MS_SMHBA_PORTATTRIBUTES_PortState_SIZE sizeof (ULONG) +#define MS_SMHBA_PORTATTRIBUTES_PortState_ID 2 - // - ULONG PortSpecificAttributesSize; - #define MS_SMHBA_PORTATTRIBUTES_PortSpecificAttributesSize_SIZE sizeof(ULONG) - #define MS_SMHBA_PORTATTRIBUTES_PortSpecificAttributesSize_ID 3 + // + ULONG PortSpecificAttributesSize; +#define MS_SMHBA_PORTATTRIBUTES_PortSpecificAttributesSize_SIZE sizeof (ULONG) +#define MS_SMHBA_PORTATTRIBUTES_PortSpecificAttributesSize_ID 3 - // + // WCHAR OSDeviceName[256 + 1]; - #define MS_SMHBA_PORTATTRIBUTES_OSDeviceName_ID 4 +#define MS_SMHBA_PORTATTRIBUTES_OSDeviceName_ID 4 - // - ULONGLONG Reserved; - #define MS_SMHBA_PORTATTRIBUTES_Reserved_SIZE sizeof(ULONGLONG) - #define MS_SMHBA_PORTATTRIBUTES_Reserved_ID 5 + // + ULONGLONG Reserved; +#define MS_SMHBA_PORTATTRIBUTES_Reserved_SIZE sizeof (ULONGLONG) +#define MS_SMHBA_PORTATTRIBUTES_Reserved_ID 5 - // + // UCHAR PortSpecificAttributes[1]; - #define MS_SMHBA_PORTATTRIBUTES_PortSpecificAttributes_ID 6 +#define MS_SMHBA_PORTATTRIBUTES_PortSpecificAttributes_ID 6 } MS_SMHBA_PORTATTRIBUTES, *PMS_SMHBA_PORTATTRIBUTES; // MS_SMHBA_PROTOCOLSTATISTICS - MS_SMHBA_PROTOCOLSTATISTICS -#define MS_SMHBA_PROTOCOLSTATISTICSGuid \ - { 0xb557bd86,0x4128,0x4d5c, { 0xb6,0xe6,0xb6,0x5f,0x9b,0xd6,0x87,0x22 } } +#define MS_SMHBA_PROTOCOLSTATISTICSGuid \ + { 0xb557bd86, 0x4128, 0x4d5c, \ + { 0xb6, 0xe6, 0xb6, 0x5f, 0x9b, 0xd6, 0x87, 0x22 } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(MS_SMHBA_PROTOCOLSTATISTICS_GUID, \ - 0xb557bd86,0x4128,0x4d5c,0xb6,0xe6,0xb6,0x5f,0x9b,0xd6,0x87,0x22); + 0xb557bd86, 0x4128, 0x4d5c, 0xb6, 0xe6, 0xb6, 0x5f, \ + 0x9b, 0xd6, 0x87, 0x22); #endif typedef struct _MS_SMHBA_PROTOCOLSTATISTICS { - // + // LONGLONG SecondsSinceLastReset; - #define MS_SMHBA_PROTOCOLSTATISTICS_SecondsSinceLastReset_SIZE sizeof(LONGLONG) - #define MS_SMHBA_PROTOCOLSTATISTICS_SecondsSinceLastReset_ID 1 +#define MS_SMHBA_PROTOCOLSTATISTICS_SecondsSinceLastReset_SIZE \ + sizeof (LONGLONG) +#define MS_SMHBA_PROTOCOLSTATISTICS_SecondsSinceLastReset_ID 1 - // + // LONGLONG InputRequests; - #define MS_SMHBA_PROTOCOLSTATISTICS_InputRequests_SIZE sizeof(LONGLONG) - #define MS_SMHBA_PROTOCOLSTATISTICS_InputRequests_ID 2 +#define MS_SMHBA_PROTOCOLSTATISTICS_InputRequests_SIZE sizeof (LONGLONG) +#define MS_SMHBA_PROTOCOLSTATISTICS_InputRequests_ID 2 - // + // LONGLONG OutputRequests; - #define MS_SMHBA_PROTOCOLSTATISTICS_OutputRequests_SIZE sizeof(LONGLONG) - #define MS_SMHBA_PROTOCOLSTATISTICS_OutputRequests_ID 3 +#define MS_SMHBA_PROTOCOLSTATISTICS_OutputRequests_SIZE sizeof (LONGLONG) +#define MS_SMHBA_PROTOCOLSTATISTICS_OutputRequests_ID 3 - // + // LONGLONG ControlRequests; - #define MS_SMHBA_PROTOCOLSTATISTICS_ControlRequests_SIZE sizeof(LONGLONG) - #define MS_SMHBA_PROTOCOLSTATISTICS_ControlRequests_ID 4 +#define MS_SMHBA_PROTOCOLSTATISTICS_ControlRequests_SIZE sizeof (LONGLONG) +#define MS_SMHBA_PROTOCOLSTATISTICS_ControlRequests_ID 4 - // + // LONGLONG InputMegabytes; - #define MS_SMHBA_PROTOCOLSTATISTICS_InputMegabytes_SIZE sizeof(LONGLONG) - #define MS_SMHBA_PROTOCOLSTATISTICS_InputMegabytes_ID 5 +#define MS_SMHBA_PROTOCOLSTATISTICS_InputMegabytes_SIZE sizeof (LONGLONG) +#define MS_SMHBA_PROTOCOLSTATISTICS_InputMegabytes_ID 5 - // + // LONGLONG OutputMegabytes; - #define MS_SMHBA_PROTOCOLSTATISTICS_OutputMegabytes_SIZE sizeof(LONGLONG) - #define MS_SMHBA_PROTOCOLSTATISTICS_OutputMegabytes_ID 6 +#define MS_SMHBA_PROTOCOLSTATISTICS_OutputMegabytes_SIZE sizeof (LONGLONG) +#define MS_SMHBA_PROTOCOLSTATISTICS_OutputMegabytes_ID 6 } MS_SMHBA_PROTOCOLSTATISTICS, *PMS_SMHBA_PROTOCOLSTATISTICS; -#define MS_SMHBA_PROTOCOLSTATISTICS_SIZE (FIELD_OFFSET(MS_SMHBA_PROTOCOLSTATISTICS, OutputMegabytes) + MS_SMHBA_PROTOCOLSTATISTICS_OutputMegabytes_SIZE) +#define MS_SMHBA_PROTOCOLSTATISTICS_SIZE \ + (FIELD_OFFSET(MS_SMHBA_PROTOCOLSTATISTICS, OutputMegabytes) + \ + MS_SMHBA_PROTOCOLSTATISTICS_OutputMegabytes_SIZE) // MS_SMHBA_SASPHYSTATISTICS - MS_SMHBA_SASPHYSTATISTICS -#define MS_SMHBA_SASPHYSTATISTICSGuid \ - { 0xbd458e7d,0xc40a,0x4401, { 0xa1,0x79,0x11,0x91,0x9c,0xbc,0xc5,0xc6 } } +#define MS_SMHBA_SASPHYSTATISTICSGuid \ + { 0xbd458e7d, 0xc40a, 0x4401, \ + { 0xa1, 0x79, 0x11, 0x91, 0x9c, 0xbc, 0xc5, 0xc6 } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(MS_SMHBA_SASPHYSTATISTICS_GUID, \ - 0xbd458e7d,0xc40a,0x4401,0xa1,0x79,0x11,0x91,0x9c,0xbc,0xc5,0xc6); + 0xbd458e7d, 0xc40a, 0x4401, 0xa1, 0x79, 0x11, 0x91, \ + 0x9c, 0xbc, 0xc5, 0xc6); #endif typedef struct _MS_SMHBA_SASPHYSTATISTICS { - // + // LONGLONG SecondsSinceLastReset; - #define MS_SMHBA_SASPHYSTATISTICS_SecondsSinceLastReset_SIZE sizeof(LONGLONG) - #define MS_SMHBA_SASPHYSTATISTICS_SecondsSinceLastReset_ID 1 +#define MS_SMHBA_SASPHYSTATISTICS_SecondsSinceLastReset_SIZE sizeof (LONGLONG) +#define MS_SMHBA_SASPHYSTATISTICS_SecondsSinceLastReset_ID 1 - // + // LONGLONG TxFrames; - #define MS_SMHBA_SASPHYSTATISTICS_TxFrames_SIZE sizeof(LONGLONG) - #define MS_SMHBA_SASPHYSTATISTICS_TxFrames_ID 2 +#define MS_SMHBA_SASPHYSTATISTICS_TxFrames_SIZE sizeof (LONGLONG) +#define MS_SMHBA_SASPHYSTATISTICS_TxFrames_ID 2 - // + // LONGLONG TxWords; - #define MS_SMHBA_SASPHYSTATISTICS_TxWords_SIZE sizeof(LONGLONG) - #define MS_SMHBA_SASPHYSTATISTICS_TxWords_ID 3 +#define MS_SMHBA_SASPHYSTATISTICS_TxWords_SIZE sizeof (LONGLONG) +#define MS_SMHBA_SASPHYSTATISTICS_TxWords_ID 3 - // + // LONGLONG RxFrames; - #define MS_SMHBA_SASPHYSTATISTICS_RxFrames_SIZE sizeof(LONGLONG) - #define MS_SMHBA_SASPHYSTATISTICS_RxFrames_ID 4 +#define MS_SMHBA_SASPHYSTATISTICS_RxFrames_SIZE sizeof (LONGLONG) +#define MS_SMHBA_SASPHYSTATISTICS_RxFrames_ID 4 - // + // LONGLONG RxWords; - #define MS_SMHBA_SASPHYSTATISTICS_RxWords_SIZE sizeof(LONGLONG) - #define MS_SMHBA_SASPHYSTATISTICS_RxWords_ID 5 +#define MS_SMHBA_SASPHYSTATISTICS_RxWords_SIZE sizeof (LONGLONG) +#define MS_SMHBA_SASPHYSTATISTICS_RxWords_ID 5 - // + // LONGLONG InvalidDwordCount; - #define MS_SMHBA_SASPHYSTATISTICS_InvalidDwordCount_SIZE sizeof(LONGLONG) - #define MS_SMHBA_SASPHYSTATISTICS_InvalidDwordCount_ID 6 +#define MS_SMHBA_SASPHYSTATISTICS_InvalidDwordCount_SIZE sizeof (LONGLONG) +#define MS_SMHBA_SASPHYSTATISTICS_InvalidDwordCount_ID 6 - // + // LONGLONG RunningDisparityErrorCount; - #define MS_SMHBA_SASPHYSTATISTICS_RunningDisparityErrorCount_SIZE sizeof(LONGLONG) - #define MS_SMHBA_SASPHYSTATISTICS_RunningDisparityErrorCount_ID 7 +#define MS_SMHBA_SASPHYSTATISTICS_RunningDisparityErrorCount_SIZE \ + sizeof (LONGLONG) +#define MS_SMHBA_SASPHYSTATISTICS_RunningDisparityErrorCount_ID 7 - // + // LONGLONG LossofDwordSyncCount; - #define MS_SMHBA_SASPHYSTATISTICS_LossofDwordSyncCount_SIZE sizeof(LONGLONG) - #define MS_SMHBA_SASPHYSTATISTICS_LossofDwordSyncCount_ID 8 +#define MS_SMHBA_SASPHYSTATISTICS_LossofDwordSyncCount_SIZE sizeof (LONGLONG) +#define MS_SMHBA_SASPHYSTATISTICS_LossofDwordSyncCount_ID 8 - // + // LONGLONG PhyResetProblemCount; - #define MS_SMHBA_SASPHYSTATISTICS_PhyResetProblemCount_SIZE sizeof(LONGLONG) - #define MS_SMHBA_SASPHYSTATISTICS_PhyResetProblemCount_ID 9 +#define MS_SMHBA_SASPHYSTATISTICS_PhyResetProblemCount_SIZE sizeof (LONGLONG) +#define MS_SMHBA_SASPHYSTATISTICS_PhyResetProblemCount_ID 9 } MS_SMHBA_SASPHYSTATISTICS, *PMS_SMHBA_SASPHYSTATISTICS; -#define MS_SMHBA_SASPHYSTATISTICS_SIZE (FIELD_OFFSET(MS_SMHBA_SASPHYSTATISTICS, PhyResetProblemCount) + MS_SMHBA_SASPHYSTATISTICS_PhyResetProblemCount_SIZE) +#define MS_SMHBA_SASPHYSTATISTICS_SIZE \ + (FIELD_OFFSET(MS_SMHBA_SASPHYSTATISTICS, PhyResetProblemCount) + \ + MS_SMHBA_SASPHYSTATISTICS_PhyResetProblemCount_SIZE) // MS_SMHBA_FC_PHY - MS_SMHBA_FC_PHY -#define MS_SMHBA_FC_PHYGuid \ - { 0xfb66c8fe,0x1da0,0x48a2, { 0x92,0xdb,0x02,0xc3,0x41,0x14,0x3c,0x46 } } +#define MS_SMHBA_FC_PHYGuid \ + { 0xfb66c8fe, 0x1da0, 0x48a2, \ + { 0x92, 0xdb, 0x02, 0xc3, 0x41, 0x14, 0x3c, 0x46 } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(MS_SMHBA_FC_PHY_GUID, \ - 0xfb66c8fe,0x1da0,0x48a2,0x92,0xdb,0x02,0xc3,0x41,0x14,0x3c,0x46); + 0xfb66c8fe, 0x1da0, 0x48a2, 0x92, 0xdb, 0x02, 0xc3, \ + 0x41, 0x14, 0x3c, 0x46); #endif typedef struct _MS_SMHBA_FC_PHY { - // - ULONG PhySupportSpeed; - #define MS_SMHBA_FC_PHY_PhySupportSpeed_SIZE sizeof(ULONG) - #define MS_SMHBA_FC_PHY_PhySupportSpeed_ID 1 + // + ULONG PhySupportSpeed; +#define MS_SMHBA_FC_PHY_PhySupportSpeed_SIZE sizeof (ULONG) +#define MS_SMHBA_FC_PHY_PhySupportSpeed_ID 1 - // - ULONG PhySpeed; - #define MS_SMHBA_FC_PHY_PhySpeed_SIZE sizeof(ULONG) - #define MS_SMHBA_FC_PHY_PhySpeed_ID 2 + // + ULONG PhySpeed; +#define MS_SMHBA_FC_PHY_PhySpeed_SIZE sizeof (ULONG) +#define MS_SMHBA_FC_PHY_PhySpeed_ID 2 - // + // UCHAR PhyType; - #define MS_SMHBA_FC_PHY_PhyType_SIZE sizeof(UCHAR) - #define MS_SMHBA_FC_PHY_PhyType_ID 3 +#define MS_SMHBA_FC_PHY_PhyType_SIZE sizeof (UCHAR) +#define MS_SMHBA_FC_PHY_PhyType_ID 3 - // - ULONG MaxFrameSize; - #define MS_SMHBA_FC_PHY_MaxFrameSize_SIZE sizeof(ULONG) - #define MS_SMHBA_FC_PHY_MaxFrameSize_ID 4 + // + ULONG MaxFrameSize; +#define MS_SMHBA_FC_PHY_MaxFrameSize_SIZE sizeof (ULONG) +#define MS_SMHBA_FC_PHY_MaxFrameSize_ID 4 } MS_SMHBA_FC_PHY, *PMS_SMHBA_FC_PHY; -#define MS_SMHBA_FC_PHY_SIZE (FIELD_OFFSET(MS_SMHBA_FC_PHY, MaxFrameSize) + MS_SMHBA_FC_PHY_MaxFrameSize_SIZE) +#define MS_SMHBA_FC_PHY_SIZE \ + (FIELD_OFFSET(MS_SMHBA_FC_PHY, MaxFrameSize) + \ + MS_SMHBA_FC_PHY_MaxFrameSize_SIZE) // MS_SMHBA_SAS_PHY - MS_SMHBA_SAS_PHY -#define MS_SMHBA_SAS_PHYGuid \ - { 0xdde0a090,0x96bc,0x452b, { 0x9a,0x64,0x6f,0xbb,0x6a,0x19,0xc4,0x7d } } +#define MS_SMHBA_SAS_PHYGuid \ + { 0xdde0a090, 0x96bc, 0x452b, \ + { 0x9a, 0x64, 0x6f, 0xbb, 0x6a, 0x19, 0xc4, 0x7d } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(MS_SMHBA_SAS_PHY_GUID, \ - 0xdde0a090,0x96bc,0x452b,0x9a,0x64,0x6f,0xbb,0x6a,0x19,0xc4,0x7d); + 0xdde0a090, 0x96bc, 0x452b, 0x9a, 0x64, 0x6f, 0xbb, \ + 0x6a, 0x19, 0xc4, 0x7d); #endif typedef struct _MS_SMHBA_SAS_PHY { - // + // UCHAR PhyIdentifier; - #define MS_SMHBA_SAS_PHY_PhyIdentifier_SIZE sizeof(UCHAR) - #define MS_SMHBA_SAS_PHY_PhyIdentifier_ID 1 - - // - ULONG NegotiatedLinkRate; - #define MS_SMHBA_SAS_PHY_NegotiatedLinkRate_SIZE sizeof(ULONG) - #define MS_SMHBA_SAS_PHY_NegotiatedLinkRate_ID 2 - - // - ULONG ProgrammedMinLinkRate; - #define MS_SMHBA_SAS_PHY_ProgrammedMinLinkRate_SIZE sizeof(ULONG) - #define MS_SMHBA_SAS_PHY_ProgrammedMinLinkRate_ID 3 - - // - ULONG HardwareMinLinkRate; - #define MS_SMHBA_SAS_PHY_HardwareMinLinkRate_SIZE sizeof(ULONG) - #define MS_SMHBA_SAS_PHY_HardwareMinLinkRate_ID 4 - - // - ULONG ProgrammedMaxLinkRate; - #define MS_SMHBA_SAS_PHY_ProgrammedMaxLinkRate_SIZE sizeof(ULONG) - #define MS_SMHBA_SAS_PHY_ProgrammedMaxLinkRate_ID 5 - - // - ULONG HardwareMaxLinkRate; - #define MS_SMHBA_SAS_PHY_HardwareMaxLinkRate_SIZE sizeof(ULONG) - #define MS_SMHBA_SAS_PHY_HardwareMaxLinkRate_ID 6 - - // +#define MS_SMHBA_SAS_PHY_PhyIdentifier_SIZE sizeof (UCHAR) +#define MS_SMHBA_SAS_PHY_PhyIdentifier_ID 1 + + // + ULONG NegotiatedLinkRate; +#define MS_SMHBA_SAS_PHY_NegotiatedLinkRate_SIZE sizeof (ULONG) +#define MS_SMHBA_SAS_PHY_NegotiatedLinkRate_ID 2 + + // + ULONG ProgrammedMinLinkRate; +#define MS_SMHBA_SAS_PHY_ProgrammedMinLinkRate_SIZE sizeof (ULONG) +#define MS_SMHBA_SAS_PHY_ProgrammedMinLinkRate_ID 3 + + // + ULONG HardwareMinLinkRate; +#define MS_SMHBA_SAS_PHY_HardwareMinLinkRate_SIZE sizeof (ULONG) +#define MS_SMHBA_SAS_PHY_HardwareMinLinkRate_ID 4 + + // + ULONG ProgrammedMaxLinkRate; +#define MS_SMHBA_SAS_PHY_ProgrammedMaxLinkRate_SIZE sizeof (ULONG) +#define MS_SMHBA_SAS_PHY_ProgrammedMaxLinkRate_ID 5 + + // + ULONG HardwareMaxLinkRate; +#define MS_SMHBA_SAS_PHY_HardwareMaxLinkRate_SIZE sizeof (ULONG) +#define MS_SMHBA_SAS_PHY_HardwareMaxLinkRate_ID 6 + + // UCHAR domainPortWWN[8]; - #define MS_SMHBA_SAS_PHY_domainPortWWN_SIZE sizeof(UCHAR[8]) - #define MS_SMHBA_SAS_PHY_domainPortWWN_ID 7 +#define MS_SMHBA_SAS_PHY_domainPortWWN_SIZE sizeof (UCHAR[8]) +#define MS_SMHBA_SAS_PHY_domainPortWWN_ID 7 } MS_SMHBA_SAS_PHY, *PMS_SMHBA_SAS_PHY; -#define MS_SMHBA_SAS_PHY_SIZE (FIELD_OFFSET(MS_SMHBA_SAS_PHY, domainPortWWN) + MS_SMHBA_SAS_PHY_domainPortWWN_SIZE) +#define MS_SMHBA_SAS_PHY_SIZE \ + (FIELD_OFFSET(MS_SMHBA_SAS_PHY, domainPortWWN) + \ + MS_SMHBA_SAS_PHY_domainPortWWN_SIZE) // MS_SM_PortInformationMethods - MS_SM_PortInformationMethods -#define MS_SM_PortInformationMethodsGuid \ - { 0x5b6a8b86,0x708d,0x4ec6, { 0x82,0xa6,0x39,0xad,0xcf,0x6f,0x64,0x33 } } +#define MS_SM_PortInformationMethodsGuid \ + { 0x5b6a8b86, 0x708d, 0x4ec6, \ + { 0x82, 0xa6, 0x39, 0xad, 0xcf, 0x6f, 0x64, 0x33 } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(MS_SM_PortInformationMethods_GUID, \ - 0x5b6a8b86,0x708d,0x4ec6,0x82,0xa6,0x39,0xad,0xcf,0x6f,0x64,0x33); + 0x5b6a8b86, 0x708d, 0x4ec6, 0x82, 0xa6, 0x39, 0xad, \ + 0xcf, 0x6f, 0x64, 0x33); #endif // // Method id definitions for MS_SM_PortInformationMethods -#define SM_GetPortType 1 +#define SM_GetPortType 1 typedef struct _SM_GetPortType_IN { - // - ULONG PortIndex; - #define SM_GetPortType_IN_PortIndex_SIZE sizeof(ULONG) - #define SM_GetPortType_IN_PortIndex_ID 1 + // + ULONG PortIndex; +#define SM_GetPortType_IN_PortIndex_SIZE sizeof (ULONG) +#define SM_GetPortType_IN_PortIndex_ID 1 } SM_GetPortType_IN, *PSM_GetPortType_IN; -#define SM_GetPortType_IN_SIZE (FIELD_OFFSET(SM_GetPortType_IN, PortIndex) + SM_GetPortType_IN_PortIndex_SIZE) +#define SM_GetPortType_IN_SIZE \ + (FIELD_OFFSET(SM_GetPortType_IN, PortIndex) + \ + SM_GetPortType_IN_PortIndex_SIZE) typedef struct _SM_GetPortType_OUT { - // - ULONG HBAStatus; - #define SM_GetPortType_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SM_GetPortType_OUT_HBAStatus_ID 2 + // + ULONG HBAStatus; +#define SM_GetPortType_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SM_GetPortType_OUT_HBAStatus_ID 2 - // - ULONG PortType; - #define SM_GetPortType_OUT_PortType_SIZE sizeof(ULONG) - #define SM_GetPortType_OUT_PortType_ID 3 + // + ULONG PortType; +#define SM_GetPortType_OUT_PortType_SIZE sizeof (ULONG) +#define SM_GetPortType_OUT_PortType_ID 3 } SM_GetPortType_OUT, *PSM_GetPortType_OUT; -#define SM_GetPortType_OUT_SIZE (FIELD_OFFSET(SM_GetPortType_OUT, PortType) + SM_GetPortType_OUT_PortType_SIZE) +#define SM_GetPortType_OUT_SIZE \ + (FIELD_OFFSET(SM_GetPortType_OUT, PortType) + \ + SM_GetPortType_OUT_PortType_SIZE) -#define SM_GetAdapterPortAttributes 2 +#define SM_GetAdapterPortAttributes 2 typedef struct _SM_GetAdapterPortAttributes_IN { - // - ULONG PortIndex; - #define SM_GetAdapterPortAttributes_IN_PortIndex_SIZE sizeof(ULONG) - #define SM_GetAdapterPortAttributes_IN_PortIndex_ID 1 + // + ULONG PortIndex; +#define SM_GetAdapterPortAttributes_IN_PortIndex_SIZE sizeof (ULONG) +#define SM_GetAdapterPortAttributes_IN_PortIndex_ID 1 -#define SM_PORT_SPECIFIC_ATTRIBUTES_MAXSIZE max(sizeof(MS_SMHBA_FC_Port), sizeof(MS_SMHBA_SAS_Port)) - // - ULONG PortSpecificAttributesMaxSize; - #define SM_GetAdapterPortAttributes_IN_PortSpecificAttributesMaxSize_SIZE sizeof(ULONG) - #define SM_GetAdapterPortAttributes_IN_PortSpecificAttributesMaxSize_ID 2 +#define SM_PORT_SPECIFIC_ATTRIBUTES_MAXSIZE \ + max(sizeof (MS_SMHBA_FC_Port), sizeof (MS_SMHBA_SAS_Port)) + // + ULONG PortSpecificAttributesMaxSize; +#define SM_GetAdapterPortAttributes_IN_PortSpecificAttributesMaxSize_SIZE \ + sizeof (ULONG) +#define SM_GetAdapterPortAttributes_IN_PortSpecificAttributesMaxSize_ID 2 } SM_GetAdapterPortAttributes_IN, *PSM_GetAdapterPortAttributes_IN; -#define SM_GetAdapterPortAttributes_IN_SIZE (FIELD_OFFSET(SM_GetAdapterPortAttributes_IN, PortSpecificAttributesMaxSize) + SM_GetAdapterPortAttributes_IN_PortSpecificAttributesMaxSize_SIZE) +#define SM_GetAdapterPortAttributes_IN_SIZE \ + (FIELD_OFFSET(SM_GetAdapterPortAttributes_IN, \ + PortSpecificAttributesMaxSize) + \ + SM_GetAdapterPortAttributes_IN_PortSpecificAttributesMaxSize_SIZE) typedef struct _SM_GetAdapterPortAttributes_OUT { - // - ULONG HBAStatus; - #define SM_GetAdapterPortAttributes_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SM_GetAdapterPortAttributes_OUT_HBAStatus_ID 3 + // + ULONG HBAStatus; +#define SM_GetAdapterPortAttributes_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SM_GetAdapterPortAttributes_OUT_HBAStatus_ID 3 - // + // MS_SMHBA_PORTATTRIBUTES PortAttributes; - #define SM_GetAdapterPortAttributes_OUT_PortAttributes_SIZE sizeof(MS_SMHBA_PORTATTRIBUTES) - #define SM_GetAdapterPortAttributes_OUT_PortAttributes_ID 4 +#define SM_GetAdapterPortAttributes_OUT_PortAttributes_SIZE \ + sizeof (MS_SMHBA_PORTATTRIBUTES) +#define SM_GetAdapterPortAttributes_OUT_PortAttributes_ID 4 } SM_GetAdapterPortAttributes_OUT, *PSM_GetAdapterPortAttributes_OUT; -#define SM_GetAdapterPortAttributes_OUT_SIZE (FIELD_OFFSET(SM_GetAdapterPortAttributes_OUT, PortAttributes) + SM_GetAdapterPortAttributes_OUT_PortAttributes_SIZE) +#define SM_GetAdapterPortAttributes_OUT_SIZE \ + (FIELD_OFFSET(SM_GetAdapterPortAttributes_OUT, PortAttributes) + \ + SM_GetAdapterPortAttributes_OUT_PortAttributes_SIZE) -#define SM_GetDiscoveredPortAttributes 3 +#define SM_GetDiscoveredPortAttributes 3 typedef struct _SM_GetDiscoveredPortAttributes_IN { - // - ULONG PortIndex; - #define SM_GetDiscoveredPortAttributes_IN_PortIndex_SIZE sizeof(ULONG) - #define SM_GetDiscoveredPortAttributes_IN_PortIndex_ID 1 + // + ULONG PortIndex; +#define SM_GetDiscoveredPortAttributes_IN_PortIndex_SIZE sizeof (ULONG) +#define SM_GetDiscoveredPortAttributes_IN_PortIndex_ID 1 - // - ULONG DiscoveredPortIndex; - #define SM_GetDiscoveredPortAttributes_IN_DiscoveredPortIndex_SIZE sizeof(ULONG) - #define SM_GetDiscoveredPortAttributes_IN_DiscoveredPortIndex_ID 2 + // + ULONG DiscoveredPortIndex; +#define SM_GetDiscoveredPortAttributes_IN_DiscoveredPortIndex_SIZE \ + sizeof (ULONG) +#define SM_GetDiscoveredPortAttributes_IN_DiscoveredPortIndex_ID 2 - // - ULONG PortSpecificAttributesMaxSize; - #define SM_GetDiscoveredPortAttributes_IN_PortSpecificAttributesMaxSize_SIZE sizeof(ULONG) - #define SM_GetDiscoveredPortAttributes_IN_PortSpecificAttributesMaxSize_ID 3 + // + ULONG PortSpecificAttributesMaxSize; +#define SM_GetDiscoveredPortAttributes_IN_PortSpecificAttributesMaxSize_SIZE \ + sizeof (ULONG) +#define SM_GetDiscoveredPortAttributes_IN_PortSpecificAttributesMaxSize_ID 3 } SM_GetDiscoveredPortAttributes_IN, *PSM_GetDiscoveredPortAttributes_IN; -#define SM_GetDiscoveredPortAttributes_IN_SIZE (FIELD_OFFSET(SM_GetDiscoveredPortAttributes_IN, PortSpecificAttributesMaxSize) + SM_GetDiscoveredPortAttributes_IN_PortSpecificAttributesMaxSize_SIZE) +#define SM_GetDiscoveredPortAttributes_IN_SIZE \ + (FIELD_OFFSET(SM_GetDiscoveredPortAttributes_IN, \ + PortSpecificAttributesMaxSize) + \ + SM_GetDiscoveredPortAttributes_IN_PortSpecificAttributesMaxSize_SIZE) typedef struct _SM_GetDiscoveredPortAttributes_OUT { - // - ULONG HBAStatus; - #define SM_GetDiscoveredPortAttributes_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SM_GetDiscoveredPortAttributes_OUT_HBAStatus_ID 4 + // + ULONG HBAStatus; +#define SM_GetDiscoveredPortAttributes_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SM_GetDiscoveredPortAttributes_OUT_HBAStatus_ID 4 - // + // MS_SMHBA_PORTATTRIBUTES PortAttributes; - #define SM_GetDiscoveredPortAttributes_OUT_PortAttributes_SIZE sizeof(MS_SMHBA_PORTATTRIBUTES) - #define SM_GetDiscoveredPortAttributes_OUT_PortAttributes_ID 5 +#define SM_GetDiscoveredPortAttributes_OUT_PortAttributes_SIZE \ + sizeof (MS_SMHBA_PORTATTRIBUTES) +#define SM_GetDiscoveredPortAttributes_OUT_PortAttributes_ID 5 } SM_GetDiscoveredPortAttributes_OUT, *PSM_GetDiscoveredPortAttributes_OUT; -#define SM_GetDiscoveredPortAttributes_OUT_SIZE (FIELD_OFFSET(SM_GetDiscoveredPortAttributes_OUT, PortAttributes) + SM_GetDiscoveredPortAttributes_OUT_PortAttributes_SIZE) +#define SM_GetDiscoveredPortAttributes_OUT_SIZE \ + (FIELD_OFFSET(SM_GetDiscoveredPortAttributes_OUT, PortAttributes) + \ + SM_GetDiscoveredPortAttributes_OUT_PortAttributes_SIZE) -#define SM_GetPortAttributesByWWN 4 +#define SM_GetPortAttributesByWWN 4 typedef struct _SM_GetPortAttributesByWWN_IN { - // + // UCHAR PortWWN[8]; - #define SM_GetPortAttributesByWWN_IN_PortWWN_SIZE sizeof(UCHAR[8]) - #define SM_GetPortAttributesByWWN_IN_PortWWN_ID 1 +#define SM_GetPortAttributesByWWN_IN_PortWWN_SIZE sizeof (UCHAR[8]) +#define SM_GetPortAttributesByWWN_IN_PortWWN_ID 1 - // + // UCHAR DomainPortWWN[8]; - #define SM_GetPortAttributesByWWN_IN_DomainPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_GetPortAttributesByWWN_IN_DomainPortWWN_ID 2 +#define SM_GetPortAttributesByWWN_IN_DomainPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_GetPortAttributesByWWN_IN_DomainPortWWN_ID 2 - // - ULONG PortSpecificAttributesMaxSize; - #define SM_GetPortAttributesByWWN_IN_PortSpecificAttributesMaxSize_SIZE sizeof(ULONG) - #define SM_GetPortAttributesByWWN_IN_PortSpecificAttributesMaxSize_ID 3 + // + ULONG PortSpecificAttributesMaxSize; +#define SM_GetPortAttributesByWWN_IN_PortSpecificAttributesMaxSize_SIZE \ + sizeof (ULONG) +#define SM_GetPortAttributesByWWN_IN_PortSpecificAttributesMaxSize_ID 3 } SM_GetPortAttributesByWWN_IN, *PSM_GetPortAttributesByWWN_IN; -#define SM_GetPortAttributesByWWN_IN_SIZE (FIELD_OFFSET(SM_GetPortAttributesByWWN_IN, PortSpecificAttributesMaxSize) + SM_GetPortAttributesByWWN_IN_PortSpecificAttributesMaxSize_SIZE) +#define SM_GetPortAttributesByWWN_IN_SIZE \ + (FIELD_OFFSET(SM_GetPortAttributesByWWN_IN, \ + PortSpecificAttributesMaxSize) + \ + SM_GetPortAttributesByWWN_IN_PortSpecificAttributesMaxSize_SIZE) typedef struct _SM_GetPortAttributesByWWN_OUT { - // - ULONG HBAStatus; - #define SM_GetPortAttributesByWWN_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SM_GetPortAttributesByWWN_OUT_HBAStatus_ID 4 + // + ULONG HBAStatus; +#define SM_GetPortAttributesByWWN_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SM_GetPortAttributesByWWN_OUT_HBAStatus_ID 4 - // + // MS_SMHBA_PORTATTRIBUTES PortAttributes; - #define SM_GetPortAttributesByWWN_OUT_PortAttributes_SIZE sizeof(MS_SMHBA_PORTATTRIBUTES) - #define SM_GetPortAttributesByWWN_OUT_PortAttributes_ID 5 +#define SM_GetPortAttributesByWWN_OUT_PortAttributes_SIZE \ + sizeof (MS_SMHBA_PORTATTRIBUTES) +#define SM_GetPortAttributesByWWN_OUT_PortAttributes_ID 5 } SM_GetPortAttributesByWWN_OUT, *PSM_GetPortAttributesByWWN_OUT; -#define SM_GetPortAttributesByWWN_OUT_SIZE (FIELD_OFFSET(SM_GetPortAttributesByWWN_OUT, PortAttributes) + SM_GetPortAttributesByWWN_OUT_PortAttributes_SIZE) +#define SM_GetPortAttributesByWWN_OUT_SIZE \ + (FIELD_OFFSET(SM_GetPortAttributesByWWN_OUT, PortAttributes) + \ + SM_GetPortAttributesByWWN_OUT_PortAttributes_SIZE) -#define SM_GetProtocolStatistics 5 +#define SM_GetProtocolStatistics 5 typedef struct _SM_GetProtocolStatistics_IN { - // - ULONG PortIndex; - #define SM_GetProtocolStatistics_IN_PortIndex_SIZE sizeof(ULONG) - #define SM_GetProtocolStatistics_IN_PortIndex_ID 1 + // + ULONG PortIndex; +#define SM_GetProtocolStatistics_IN_PortIndex_SIZE sizeof (ULONG) +#define SM_GetProtocolStatistics_IN_PortIndex_ID 1 - // - ULONG ProtocolType; - #define SM_GetProtocolStatistics_IN_ProtocolType_SIZE sizeof(ULONG) - #define SM_GetProtocolStatistics_IN_ProtocolType_ID 2 + // + ULONG ProtocolType; +#define SM_GetProtocolStatistics_IN_ProtocolType_SIZE sizeof (ULONG) +#define SM_GetProtocolStatistics_IN_ProtocolType_ID 2 } SM_GetProtocolStatistics_IN, *PSM_GetProtocolStatistics_IN; -#define SM_GetProtocolStatistics_IN_SIZE (FIELD_OFFSET(SM_GetProtocolStatistics_IN, ProtocolType) + SM_GetProtocolStatistics_IN_ProtocolType_SIZE) +#define SM_GetProtocolStatistics_IN_SIZE \ + (FIELD_OFFSET(SM_GetProtocolStatistics_IN, ProtocolType) + \ + SM_GetProtocolStatistics_IN_ProtocolType_SIZE) typedef struct _SM_GetProtocolStatistics_OUT { - // - ULONG HBAStatus; - #define SM_GetProtocolStatistics_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SM_GetProtocolStatistics_OUT_HBAStatus_ID 3 + // + ULONG HBAStatus; +#define SM_GetProtocolStatistics_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SM_GetProtocolStatistics_OUT_HBAStatus_ID 3 - // + // MS_SMHBA_PROTOCOLSTATISTICS ProtocolStatistics; - #define SM_GetProtocolStatistics_OUT_ProtocolStatistics_SIZE sizeof(MS_SMHBA_PROTOCOLSTATISTICS) - #define SM_GetProtocolStatistics_OUT_ProtocolStatistics_ID 4 +#define SM_GetProtocolStatistics_OUT_ProtocolStatistics_SIZE \ + sizeof (MS_SMHBA_PROTOCOLSTATISTICS) +#define SM_GetProtocolStatistics_OUT_ProtocolStatistics_ID 4 } SM_GetProtocolStatistics_OUT, *PSM_GetProtocolStatistics_OUT; -#define SM_GetProtocolStatistics_OUT_SIZE (FIELD_OFFSET(SM_GetProtocolStatistics_OUT, ProtocolStatistics) + SM_GetProtocolStatistics_OUT_ProtocolStatistics_SIZE) +#define SM_GetProtocolStatistics_OUT_SIZE \ + (FIELD_OFFSET(SM_GetProtocolStatistics_OUT, ProtocolStatistics) + \ + SM_GetProtocolStatistics_OUT_ProtocolStatistics_SIZE) -#define SM_GetPhyStatistics 6 +#define SM_GetPhyStatistics 6 typedef struct _SM_GetPhyStatistics_IN { - // - ULONG PortIndex; - #define SM_GetPhyStatistics_IN_PortIndex_SIZE sizeof(ULONG) - #define SM_GetPhyStatistics_IN_PortIndex_ID 1 + // + ULONG PortIndex; +#define SM_GetPhyStatistics_IN_PortIndex_SIZE sizeof (ULONG) +#define SM_GetPhyStatistics_IN_PortIndex_ID 1 - // - ULONG PhyIndex; - #define SM_GetPhyStatistics_IN_PhyIndex_SIZE sizeof(ULONG) - #define SM_GetPhyStatistics_IN_PhyIndex_ID 2 + // + ULONG PhyIndex; +#define SM_GetPhyStatistics_IN_PhyIndex_SIZE sizeof (ULONG) +#define SM_GetPhyStatistics_IN_PhyIndex_ID 2 - // - ULONG InNumOfPhyCounters; - #define SM_GetPhyStatistics_IN_InNumOfPhyCounters_SIZE sizeof(ULONG) - #define SM_GetPhyStatistics_IN_InNumOfPhyCounters_ID 3 + // + ULONG InNumOfPhyCounters; +#define SM_GetPhyStatistics_IN_InNumOfPhyCounters_SIZE sizeof (ULONG) +#define SM_GetPhyStatistics_IN_InNumOfPhyCounters_ID 3 } SM_GetPhyStatistics_IN, *PSM_GetPhyStatistics_IN; -#define SM_GetPhyStatistics_IN_SIZE (FIELD_OFFSET(SM_GetPhyStatistics_IN, InNumOfPhyCounters) + SM_GetPhyStatistics_IN_InNumOfPhyCounters_SIZE) +#define SM_GetPhyStatistics_IN_SIZE \ + (FIELD_OFFSET(SM_GetPhyStatistics_IN, InNumOfPhyCounters) + \ + SM_GetPhyStatistics_IN_InNumOfPhyCounters_SIZE) typedef struct _SM_GetPhyStatistics_OUT { - // - ULONG HBAStatus; - #define SM_GetPhyStatistics_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SM_GetPhyStatistics_OUT_HBAStatus_ID 4 + // + ULONG HBAStatus; +#define SM_GetPhyStatistics_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SM_GetPhyStatistics_OUT_HBAStatus_ID 4 - // - ULONG TotalNumOfPhyCounters; - #define SM_GetPhyStatistics_OUT_TotalNumOfPhyCounters_SIZE sizeof(ULONG) - #define SM_GetPhyStatistics_OUT_TotalNumOfPhyCounters_ID 5 + // + ULONG TotalNumOfPhyCounters; +#define SM_GetPhyStatistics_OUT_TotalNumOfPhyCounters_SIZE sizeof (ULONG) +#define SM_GetPhyStatistics_OUT_TotalNumOfPhyCounters_ID 5 - // - ULONG OutNumOfPhyCounters; - #define SM_GetPhyStatistics_OUT_OutNumOfPhyCounters_SIZE sizeof(ULONG) - #define SM_GetPhyStatistics_OUT_OutNumOfPhyCounters_ID 6 + // + ULONG OutNumOfPhyCounters; +#define SM_GetPhyStatistics_OUT_OutNumOfPhyCounters_SIZE sizeof (ULONG) +#define SM_GetPhyStatistics_OUT_OutNumOfPhyCounters_ID 6 - // + // LONGLONG PhyCounter[1]; - #define SM_GetPhyStatistics_OUT_PhyCounter_ID 7 +#define SM_GetPhyStatistics_OUT_PhyCounter_ID 7 } SM_GetPhyStatistics_OUT, *PSM_GetPhyStatistics_OUT; -#define SM_GetFCPhyAttributes 7 +#define SM_GetFCPhyAttributes 7 typedef struct _SM_GetFCPhyAttributes_IN { - // - ULONG PortIndex; - #define SM_GetFCPhyAttributes_IN_PortIndex_SIZE sizeof(ULONG) - #define SM_GetFCPhyAttributes_IN_PortIndex_ID 1 + // + ULONG PortIndex; +#define SM_GetFCPhyAttributes_IN_PortIndex_SIZE sizeof (ULONG) +#define SM_GetFCPhyAttributes_IN_PortIndex_ID 1 - // - ULONG PhyIndex; - #define SM_GetFCPhyAttributes_IN_PhyIndex_SIZE sizeof(ULONG) - #define SM_GetFCPhyAttributes_IN_PhyIndex_ID 2 + // + ULONG PhyIndex; +#define SM_GetFCPhyAttributes_IN_PhyIndex_SIZE sizeof (ULONG) +#define SM_GetFCPhyAttributes_IN_PhyIndex_ID 2 } SM_GetFCPhyAttributes_IN, *PSM_GetFCPhyAttributes_IN; -#define SM_GetFCPhyAttributes_IN_SIZE (FIELD_OFFSET(SM_GetFCPhyAttributes_IN, PhyIndex) + SM_GetFCPhyAttributes_IN_PhyIndex_SIZE) +#define SM_GetFCPhyAttributes_IN_SIZE \ + (FIELD_OFFSET(SM_GetFCPhyAttributes_IN, PhyIndex) + \ + SM_GetFCPhyAttributes_IN_PhyIndex_SIZE) typedef struct _SM_GetFCPhyAttributes_OUT { - // - ULONG HBAStatus; - #define SM_GetFCPhyAttributes_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SM_GetFCPhyAttributes_OUT_HBAStatus_ID 3 + // + ULONG HBAStatus; +#define SM_GetFCPhyAttributes_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SM_GetFCPhyAttributes_OUT_HBAStatus_ID 3 - // + // MS_SMHBA_FC_PHY PhyType; - #define SM_GetFCPhyAttributes_OUT_PhyType_SIZE sizeof(MS_SMHBA_FC_PHY) - #define SM_GetFCPhyAttributes_OUT_PhyType_ID 4 +#define SM_GetFCPhyAttributes_OUT_PhyType_SIZE sizeof (MS_SMHBA_FC_PHY) +#define SM_GetFCPhyAttributes_OUT_PhyType_ID 4 } SM_GetFCPhyAttributes_OUT, *PSM_GetFCPhyAttributes_OUT; -#define SM_GetFCPhyAttributes_OUT_SIZE (FIELD_OFFSET(SM_GetFCPhyAttributes_OUT, PhyType) + SM_GetFCPhyAttributes_OUT_PhyType_SIZE) +#define SM_GetFCPhyAttributes_OUT_SIZE \ + (FIELD_OFFSET(SM_GetFCPhyAttributes_OUT, PhyType) + \ + SM_GetFCPhyAttributes_OUT_PhyType_SIZE) -#define SM_GetSASPhyAttributes 8 +#define SM_GetSASPhyAttributes 8 typedef struct _SM_GetSASPhyAttributes_IN { - // - ULONG PortIndex; - #define SM_GetSASPhyAttributes_IN_PortIndex_SIZE sizeof(ULONG) - #define SM_GetSASPhyAttributes_IN_PortIndex_ID 1 + // + ULONG PortIndex; +#define SM_GetSASPhyAttributes_IN_PortIndex_SIZE sizeof (ULONG) +#define SM_GetSASPhyAttributes_IN_PortIndex_ID 1 - // - ULONG PhyIndex; - #define SM_GetSASPhyAttributes_IN_PhyIndex_SIZE sizeof(ULONG) - #define SM_GetSASPhyAttributes_IN_PhyIndex_ID 2 + // + ULONG PhyIndex; +#define SM_GetSASPhyAttributes_IN_PhyIndex_SIZE sizeof (ULONG) +#define SM_GetSASPhyAttributes_IN_PhyIndex_ID 2 } SM_GetSASPhyAttributes_IN, *PSM_GetSASPhyAttributes_IN; -#define SM_GetSASPhyAttributes_IN_SIZE (FIELD_OFFSET(SM_GetSASPhyAttributes_IN, PhyIndex) + SM_GetSASPhyAttributes_IN_PhyIndex_SIZE) +#define SM_GetSASPhyAttributes_IN_SIZE \ + (FIELD_OFFSET(SM_GetSASPhyAttributes_IN, PhyIndex) + \ + SM_GetSASPhyAttributes_IN_PhyIndex_SIZE) typedef struct _SM_GetSASPhyAttributes_OUT { - // - ULONG HBAStatus; - #define SM_GetSASPhyAttributes_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SM_GetSASPhyAttributes_OUT_HBAStatus_ID 3 + // + ULONG HBAStatus; +#define SM_GetSASPhyAttributes_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SM_GetSASPhyAttributes_OUT_HBAStatus_ID 3 - // + // MS_SMHBA_SAS_PHY PhyType; - #define SM_GetSASPhyAttributes_OUT_PhyType_SIZE sizeof(MS_SMHBA_SAS_PHY) - #define SM_GetSASPhyAttributes_OUT_PhyType_ID 4 +#define SM_GetSASPhyAttributes_OUT_PhyType_SIZE sizeof (MS_SMHBA_SAS_PHY) +#define SM_GetSASPhyAttributes_OUT_PhyType_ID 4 } SM_GetSASPhyAttributes_OUT, *PSM_GetSASPhyAttributes_OUT; -#define SM_GetSASPhyAttributes_OUT_SIZE (FIELD_OFFSET(SM_GetSASPhyAttributes_OUT, PhyType) + SM_GetSASPhyAttributes_OUT_PhyType_SIZE) +#define SM_GetSASPhyAttributes_OUT_SIZE \ + (FIELD_OFFSET(SM_GetSASPhyAttributes_OUT, PhyType) + \ + SM_GetSASPhyAttributes_OUT_PhyType_SIZE) -#define SM_RefreshInformation 10 +#define SM_RefreshInformation 10 // MS_SMHBA_PORTLUN - MS_SMHBA_PORTLUN -#define MS_SMHBA_PORTLUNGuid \ - { 0x0669d100,0x066e,0x4e49, { 0xa6,0x8c,0xe0,0x51,0x99,0x59,0x61,0x32 } } +#define MS_SMHBA_PORTLUNGuid \ + { 0x0669d100, 0x066e, 0x4e49, \ + { 0xa6, 0x8c, 0xe0, 0x51, 0x99, 0x59, 0x61, 0x32 } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(MS_SMHBA_PORTLUN_GUID, \ - 0x0669d100,0x066e,0x4e49,0xa6,0x8c,0xe0,0x51,0x99,0x59,0x61,0x32); + 0x0669d100, 0x066e, 0x4e49, 0xa6, 0x8c, 0xe0, 0x51, \ + 0x99, 0x59, 0x61, 0x32); #endif typedef struct _MS_SMHBA_PORTLUN { - // + // UCHAR PortWWN[8]; - #define MS_SMHBA_PORTLUN_PortWWN_SIZE sizeof(UCHAR[8]) - #define MS_SMHBA_PORTLUN_PortWWN_ID 1 +#define MS_SMHBA_PORTLUN_PortWWN_SIZE sizeof (UCHAR[8]) +#define MS_SMHBA_PORTLUN_PortWWN_ID 1 - // + // UCHAR domainPortWWN[8]; - #define MS_SMHBA_PORTLUN_domainPortWWN_SIZE sizeof(UCHAR[8]) - #define MS_SMHBA_PORTLUN_domainPortWWN_ID 2 +#define MS_SMHBA_PORTLUN_domainPortWWN_SIZE sizeof (UCHAR[8]) +#define MS_SMHBA_PORTLUN_domainPortWWN_ID 2 - // - ULONGLONG TargetLun; - #define MS_SMHBA_PORTLUN_TargetLun_SIZE sizeof(ULONGLONG) - #define MS_SMHBA_PORTLUN_TargetLun_ID 3 + // + ULONGLONG TargetLun; +#define MS_SMHBA_PORTLUN_TargetLun_SIZE sizeof (ULONGLONG) +#define MS_SMHBA_PORTLUN_TargetLun_ID 3 } MS_SMHBA_PORTLUN, *PMS_SMHBA_PORTLUN; -#define MS_SMHBA_PORTLUN_SIZE (FIELD_OFFSET(MS_SMHBA_PORTLUN, TargetLun) + MS_SMHBA_PORTLUN_TargetLun_SIZE) +#define MS_SMHBA_PORTLUN_SIZE \ + (FIELD_OFFSET(MS_SMHBA_PORTLUN, TargetLun) + \ + MS_SMHBA_PORTLUN_TargetLun_SIZE) // MS_SMHBA_SCSIENTRY - MS_SMHBA_SCSIENTRY -#define MS_SMHBA_SCSIENTRYGuid \ - { 0x125d41bc,0x7643,0x4155, { 0xb8,0x1c,0xe2,0xf1,0x28,0xad,0x1f,0xb4 } } +#define MS_SMHBA_SCSIENTRYGuid \ + { 0x125d41bc, 0x7643, 0x4155, \ + { 0xb8, 0x1c, 0xe2, 0xf1, 0x28, 0xad, 0x1f, 0xb4 } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(MS_SMHBA_SCSIENTRY_GUID, \ - 0x125d41bc,0x7643,0x4155,0xb8,0x1c,0xe2,0xf1,0x28,0xad,0x1f,0xb4); + 0x125d41bc, 0x7643, 0x4155, 0xb8, 0x1c, 0xe2, 0xf1, \ + 0x28, 0xad, 0x1f, 0xb4); #endif typedef struct _MS_SMHBA_SCSIENTRY { - // + // MS_SMHBA_PORTLUN PortLun; - #define MS_SMHBA_SCSIENTRY_PortLun_SIZE sizeof(MS_SMHBA_PORTLUN) - #define MS_SMHBA_SCSIENTRY_PortLun_ID 1 +#define MS_SMHBA_SCSIENTRY_PortLun_SIZE sizeof (MS_SMHBA_PORTLUN) +#define MS_SMHBA_SCSIENTRY_PortLun_ID 1 - // + // UCHAR LUID[256]; - #define MS_SMHBA_SCSIENTRY_LUID_SIZE sizeof(UCHAR[256]) - #define MS_SMHBA_SCSIENTRY_LUID_ID 2 +#define MS_SMHBA_SCSIENTRY_LUID_SIZE sizeof (UCHAR[256]) +#define MS_SMHBA_SCSIENTRY_LUID_ID 2 - // + // HBAScsiID ScsiId; - #define MS_SMHBA_SCSIENTRY_ScsiId_SIZE sizeof(HBAScsiID) - #define MS_SMHBA_SCSIENTRY_ScsiId_ID 3 +#define MS_SMHBA_SCSIENTRY_ScsiId_SIZE sizeof (HBAScsiID) +#define MS_SMHBA_SCSIENTRY_ScsiId_ID 3 } MS_SMHBA_SCSIENTRY, *PMS_SMHBA_SCSIENTRY; -#define MS_SMHBA_SCSIENTRY_SIZE (FIELD_OFFSET(MS_SMHBA_SCSIENTRY, ScsiId) + MS_SMHBA_SCSIENTRY_ScsiId_SIZE) +#define MS_SMHBA_SCSIENTRY_SIZE \ + (FIELD_OFFSET(MS_SMHBA_SCSIENTRY, ScsiId) + \ + MS_SMHBA_SCSIENTRY_ScsiId_SIZE) // MS_SMHBA_BINDINGENTRY - MS_SMHBA_BINDINGENTRY -#define MS_SMHBA_BINDINGENTRYGuid \ - { 0x65bfb548,0xd00a,0x4d4c, { 0xa3,0x57,0x7d,0xaa,0x23,0xbc,0x2e,0x3d } } +#define MS_SMHBA_BINDINGENTRYGuid \ + { 0x65bfb548, 0xd00a, 0x4d4c, \ + { 0xa3, 0x57, 0x7d, 0xaa, 0x23, 0xbc, 0x2e, 0x3d } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(MS_SMHBA_BINDINGENTRY_GUID, \ - 0x65bfb548,0xd00a,0x4d4c,0xa3,0x57,0x7d,0xaa,0x23,0xbc,0x2e,0x3d); + 0x65bfb548, 0xd00a, 0x4d4c, 0xa3, 0x57, 0x7d, 0xaa, \ + 0x23, 0xbc, 0x2e, 0x3d); #endif typedef struct _MS_SMHBA_BINDINGENTRY { - // - ULONG type; - #define MS_SMHBA_BINDINGENTRY_type_SIZE sizeof(ULONG) - #define MS_SMHBA_BINDINGENTRY_type_ID 1 + // + ULONG type; +#define MS_SMHBA_BINDINGENTRY_type_SIZE sizeof (ULONG) +#define MS_SMHBA_BINDINGENTRY_type_ID 1 - // + // MS_SMHBA_PORTLUN PortLun; - #define MS_SMHBA_BINDINGENTRY_PortLun_SIZE sizeof(MS_SMHBA_PORTLUN) - #define MS_SMHBA_BINDINGENTRY_PortLun_ID 2 +#define MS_SMHBA_BINDINGENTRY_PortLun_SIZE sizeof (MS_SMHBA_PORTLUN) +#define MS_SMHBA_BINDINGENTRY_PortLun_ID 2 - // + // UCHAR LUID[256]; - #define MS_SMHBA_BINDINGENTRY_LUID_SIZE sizeof(UCHAR[256]) - #define MS_SMHBA_BINDINGENTRY_LUID_ID 3 +#define MS_SMHBA_BINDINGENTRY_LUID_SIZE sizeof (UCHAR[256]) +#define MS_SMHBA_BINDINGENTRY_LUID_ID 3 - // - ULONG Status; - #define MS_SMHBA_BINDINGENTRY_Status_SIZE sizeof(ULONG) - #define MS_SMHBA_BINDINGENTRY_Status_ID 4 + // + ULONG Status; +#define MS_SMHBA_BINDINGENTRY_Status_SIZE sizeof (ULONG) +#define MS_SMHBA_BINDINGENTRY_Status_ID 4 - // + // HBAScsiID ScsiId; - #define MS_SMHBA_BINDINGENTRY_ScsiId_SIZE sizeof(HBAScsiID) - #define MS_SMHBA_BINDINGENTRY_ScsiId_ID 5 +#define MS_SMHBA_BINDINGENTRY_ScsiId_SIZE sizeof (HBAScsiID) +#define MS_SMHBA_BINDINGENTRY_ScsiId_ID 5 } MS_SMHBA_BINDINGENTRY, *PMS_SMHBA_BINDINGENTRY; -#define MS_SMHBA_BINDINGENTRY_SIZE (FIELD_OFFSET(MS_SMHBA_BINDINGENTRY, ScsiId) + MS_SMHBA_BINDINGENTRY_ScsiId_SIZE) +#define MS_SMHBA_BINDINGENTRY_SIZE \ + (FIELD_OFFSET(MS_SMHBA_BINDINGENTRY, ScsiId) + \ + MS_SMHBA_BINDINGENTRY_ScsiId_SIZE) // MS_SM_TargetInformationMethods - MS_SM_TargetInformationMethods -#define MS_SM_TargetInformationMethodsGuid \ - { 0x93545055,0xab4c,0x4e80, { 0x84,0xae,0x6a,0x86,0xa2,0xdc,0x4b,0x84 } } +#define MS_SM_TargetInformationMethodsGuid \ + { 0x93545055, 0xab4c, 0x4e80, \ + { 0x84, 0xae, 0x6a, 0x86, 0xa2, 0xdc, 0x4b, 0x84 } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(MS_SM_TargetInformationMethods_GUID, \ - 0x93545055,0xab4c,0x4e80,0x84,0xae,0x6a,0x86,0xa2,0xdc,0x4b,0x84); + 0x93545055, 0xab4c, 0x4e80, 0x84, 0xae, 0x6a, 0x86, \ + 0xa2, 0xdc, 0x4b, 0x84); #endif // // Method id definitions for MS_SM_TargetInformationMethods -#define SM_GetTargetMapping 1 +#define SM_GetTargetMapping 1 typedef struct _SM_GetTargetMapping_IN { - // + // UCHAR HbaPortWWN[8]; - #define SM_GetTargetMapping_IN_HbaPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_GetTargetMapping_IN_HbaPortWWN_ID 1 +#define SM_GetTargetMapping_IN_HbaPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_GetTargetMapping_IN_HbaPortWWN_ID 1 - // + // UCHAR DomainPortWWN[8]; - #define SM_GetTargetMapping_IN_DomainPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_GetTargetMapping_IN_DomainPortWWN_ID 2 +#define SM_GetTargetMapping_IN_DomainPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_GetTargetMapping_IN_DomainPortWWN_ID 2 - // - ULONG InEntryCount; - #define SM_GetTargetMapping_IN_InEntryCount_SIZE sizeof(ULONG) - #define SM_GetTargetMapping_IN_InEntryCount_ID 3 + // + ULONG InEntryCount; +#define SM_GetTargetMapping_IN_InEntryCount_SIZE sizeof (ULONG) +#define SM_GetTargetMapping_IN_InEntryCount_ID 3 } SM_GetTargetMapping_IN, *PSM_GetTargetMapping_IN; -#define SM_GetTargetMapping_IN_SIZE (FIELD_OFFSET(SM_GetTargetMapping_IN, InEntryCount) + SM_GetTargetMapping_IN_InEntryCount_SIZE) +#define SM_GetTargetMapping_IN_SIZE \ + (FIELD_OFFSET(SM_GetTargetMapping_IN, InEntryCount) + \ + SM_GetTargetMapping_IN_InEntryCount_SIZE) typedef struct _SM_GetTargetMapping_OUT { - // - ULONG HBAStatus; - #define SM_GetTargetMapping_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SM_GetTargetMapping_OUT_HBAStatus_ID 4 + // + ULONG HBAStatus; +#define SM_GetTargetMapping_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SM_GetTargetMapping_OUT_HBAStatus_ID 4 - // - ULONG TotalEntryCount; - #define SM_GetTargetMapping_OUT_TotalEntryCount_SIZE sizeof(ULONG) - #define SM_GetTargetMapping_OUT_TotalEntryCount_ID 5 + // + ULONG TotalEntryCount; +#define SM_GetTargetMapping_OUT_TotalEntryCount_SIZE sizeof (ULONG) +#define SM_GetTargetMapping_OUT_TotalEntryCount_ID 5 - // - ULONG OutEntryCount; - #define SM_GetTargetMapping_OUT_OutEntryCount_SIZE sizeof(ULONG) - #define SM_GetTargetMapping_OUT_OutEntryCount_ID 6 + // + ULONG OutEntryCount; +#define SM_GetTargetMapping_OUT_OutEntryCount_SIZE sizeof (ULONG) +#define SM_GetTargetMapping_OUT_OutEntryCount_ID 6 - // + // MS_SMHBA_SCSIENTRY Entry[1]; - #define SM_GetTargetMapping_OUT_Entry_ID 7 +#define SM_GetTargetMapping_OUT_Entry_ID 7 } SM_GetTargetMapping_OUT, *PSM_GetTargetMapping_OUT; -#define SM_GetBindingCapability 2 +#define SM_GetBindingCapability 2 typedef struct _SM_GetBindingCapability_IN { - // + // UCHAR HbaPortWWN[8]; - #define SM_GetBindingCapability_IN_HbaPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_GetBindingCapability_IN_HbaPortWWN_ID 1 +#define SM_GetBindingCapability_IN_HbaPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_GetBindingCapability_IN_HbaPortWWN_ID 1 - // + // UCHAR DomainPortWWN[8]; - #define SM_GetBindingCapability_IN_DomainPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_GetBindingCapability_IN_DomainPortWWN_ID 2 +#define SM_GetBindingCapability_IN_DomainPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_GetBindingCapability_IN_DomainPortWWN_ID 2 } SM_GetBindingCapability_IN, *PSM_GetBindingCapability_IN; -#define SM_GetBindingCapability_IN_SIZE (FIELD_OFFSET(SM_GetBindingCapability_IN, DomainPortWWN) + SM_GetBindingCapability_IN_DomainPortWWN_SIZE) +#define SM_GetBindingCapability_IN_SIZE \ + (FIELD_OFFSET(SM_GetBindingCapability_IN, DomainPortWWN) + \ + SM_GetBindingCapability_IN_DomainPortWWN_SIZE) typedef struct _SM_GetBindingCapability_OUT { - // - ULONG HBAStatus; - #define SM_GetBindingCapability_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SM_GetBindingCapability_OUT_HBAStatus_ID 3 + // + ULONG HBAStatus; +#define SM_GetBindingCapability_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SM_GetBindingCapability_OUT_HBAStatus_ID 3 - // - ULONG Flags; - #define SM_GetBindingCapability_OUT_Flags_SIZE sizeof(ULONG) - #define SM_GetBindingCapability_OUT_Flags_ID 4 + // + ULONG Flags; +#define SM_GetBindingCapability_OUT_Flags_SIZE sizeof (ULONG) +#define SM_GetBindingCapability_OUT_Flags_ID 4 } SM_GetBindingCapability_OUT, *PSM_GetBindingCapability_OUT; -#define SM_GetBindingCapability_OUT_SIZE (FIELD_OFFSET(SM_GetBindingCapability_OUT, Flags) + SM_GetBindingCapability_OUT_Flags_SIZE) +#define SM_GetBindingCapability_OUT_SIZE \ + (FIELD_OFFSET(SM_GetBindingCapability_OUT, Flags) + \ + SM_GetBindingCapability_OUT_Flags_SIZE) -#define SM_GetBindingSupport 3 +#define SM_GetBindingSupport 3 typedef struct _SM_GetBindingSupport_IN { - // + // UCHAR HbaPortWWN[8]; - #define SM_GetBindingSupport_IN_HbaPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_GetBindingSupport_IN_HbaPortWWN_ID 1 +#define SM_GetBindingSupport_IN_HbaPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_GetBindingSupport_IN_HbaPortWWN_ID 1 - // + // UCHAR DomainPortWWN[8]; - #define SM_GetBindingSupport_IN_DomainPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_GetBindingSupport_IN_DomainPortWWN_ID 2 +#define SM_GetBindingSupport_IN_DomainPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_GetBindingSupport_IN_DomainPortWWN_ID 2 } SM_GetBindingSupport_IN, *PSM_GetBindingSupport_IN; -#define SM_GetBindingSupport_IN_SIZE (FIELD_OFFSET(SM_GetBindingSupport_IN, DomainPortWWN) + SM_GetBindingSupport_IN_DomainPortWWN_SIZE) +#define SM_GetBindingSupport_IN_SIZE \ + (FIELD_OFFSET(SM_GetBindingSupport_IN, DomainPortWWN) + \ + SM_GetBindingSupport_IN_DomainPortWWN_SIZE) typedef struct _SM_GetBindingSupport_OUT { - // - ULONG HBAStatus; - #define SM_GetBindingSupport_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SM_GetBindingSupport_OUT_HBAStatus_ID 3 + // + ULONG HBAStatus; +#define SM_GetBindingSupport_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SM_GetBindingSupport_OUT_HBAStatus_ID 3 - // - ULONG Flags; - #define SM_GetBindingSupport_OUT_Flags_SIZE sizeof(ULONG) - #define SM_GetBindingSupport_OUT_Flags_ID 4 + // + ULONG Flags; +#define SM_GetBindingSupport_OUT_Flags_SIZE sizeof (ULONG) +#define SM_GetBindingSupport_OUT_Flags_ID 4 } SM_GetBindingSupport_OUT, *PSM_GetBindingSupport_OUT; -#define SM_GetBindingSupport_OUT_SIZE (FIELD_OFFSET(SM_GetBindingSupport_OUT, Flags) + SM_GetBindingSupport_OUT_Flags_SIZE) +#define SM_GetBindingSupport_OUT_SIZE \ + (FIELD_OFFSET(SM_GetBindingSupport_OUT, Flags) + \ + SM_GetBindingSupport_OUT_Flags_SIZE) -#define SM_SetBindingSupport 4 +#define SM_SetBindingSupport 4 typedef struct _SM_SetBindingSupport_IN { - // + // UCHAR HbaPortWWN[8]; - #define SM_SetBindingSupport_IN_HbaPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_SetBindingSupport_IN_HbaPortWWN_ID 1 +#define SM_SetBindingSupport_IN_HbaPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_SetBindingSupport_IN_HbaPortWWN_ID 1 - // + // UCHAR DomainPortWWN[8]; - #define SM_SetBindingSupport_IN_DomainPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_SetBindingSupport_IN_DomainPortWWN_ID 2 +#define SM_SetBindingSupport_IN_DomainPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_SetBindingSupport_IN_DomainPortWWN_ID 2 - // - ULONG Flags; - #define SM_SetBindingSupport_IN_Flags_SIZE sizeof(ULONG) - #define SM_SetBindingSupport_IN_Flags_ID 3 + // + ULONG Flags; +#define SM_SetBindingSupport_IN_Flags_SIZE sizeof (ULONG) +#define SM_SetBindingSupport_IN_Flags_ID 3 } SM_SetBindingSupport_IN, *PSM_SetBindingSupport_IN; -#define SM_SetBindingSupport_IN_SIZE (FIELD_OFFSET(SM_SetBindingSupport_IN, Flags) + SM_SetBindingSupport_IN_Flags_SIZE) +#define SM_SetBindingSupport_IN_SIZE \ + (FIELD_OFFSET(SM_SetBindingSupport_IN, Flags) + \ + SM_SetBindingSupport_IN_Flags_SIZE) typedef struct _SM_SetBindingSupport_OUT { - // - ULONG HBAStatus; - #define SM_SetBindingSupport_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SM_SetBindingSupport_OUT_HBAStatus_ID 4 + // + ULONG HBAStatus; +#define SM_SetBindingSupport_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SM_SetBindingSupport_OUT_HBAStatus_ID 4 } SM_SetBindingSupport_OUT, *PSM_SetBindingSupport_OUT; -#define SM_SetBindingSupport_OUT_SIZE (FIELD_OFFSET(SM_SetBindingSupport_OUT, HBAStatus) + SM_SetBindingSupport_OUT_HBAStatus_SIZE) +#define SM_SetBindingSupport_OUT_SIZE \ + (FIELD_OFFSET(SM_SetBindingSupport_OUT, HBAStatus) + \ + SM_SetBindingSupport_OUT_HBAStatus_SIZE) -#define SM_GetPersistentBinding 5 +#define SM_GetPersistentBinding 5 typedef struct _SM_GetPersistentBinding_IN { - // + // UCHAR HbaPortWWN[8]; - #define SM_GetPersistentBinding_IN_HbaPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_GetPersistentBinding_IN_HbaPortWWN_ID 1 +#define SM_GetPersistentBinding_IN_HbaPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_GetPersistentBinding_IN_HbaPortWWN_ID 1 - // + // UCHAR DomainPortWWN[8]; - #define SM_GetPersistentBinding_IN_DomainPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_GetPersistentBinding_IN_DomainPortWWN_ID 2 +#define SM_GetPersistentBinding_IN_DomainPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_GetPersistentBinding_IN_DomainPortWWN_ID 2 - // - ULONG InEntryCount; - #define SM_GetPersistentBinding_IN_InEntryCount_SIZE sizeof(ULONG) - #define SM_GetPersistentBinding_IN_InEntryCount_ID 3 + // + ULONG InEntryCount; +#define SM_GetPersistentBinding_IN_InEntryCount_SIZE sizeof (ULONG) +#define SM_GetPersistentBinding_IN_InEntryCount_ID 3 } SM_GetPersistentBinding_IN, *PSM_GetPersistentBinding_IN; -#define SM_GetPersistentBinding_IN_SIZE (FIELD_OFFSET(SM_GetPersistentBinding_IN, InEntryCount) + SM_GetPersistentBinding_IN_InEntryCount_SIZE) +#define SM_GetPersistentBinding_IN_SIZE \ + (FIELD_OFFSET(SM_GetPersistentBinding_IN, InEntryCount) + \ + SM_GetPersistentBinding_IN_InEntryCount_SIZE) typedef struct _SM_GetPersistentBinding_OUT { - // - ULONG HBAStatus; - #define SM_GetPersistentBinding_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SM_GetPersistentBinding_OUT_HBAStatus_ID 4 + // + ULONG HBAStatus; +#define SM_GetPersistentBinding_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SM_GetPersistentBinding_OUT_HBAStatus_ID 4 - // - ULONG TotalEntryCount; - #define SM_GetPersistentBinding_OUT_TotalEntryCount_SIZE sizeof(ULONG) - #define SM_GetPersistentBinding_OUT_TotalEntryCount_ID 5 + // + ULONG TotalEntryCount; +#define SM_GetPersistentBinding_OUT_TotalEntryCount_SIZE sizeof (ULONG) +#define SM_GetPersistentBinding_OUT_TotalEntryCount_ID 5 - // - ULONG OutEntryCount; - #define SM_GetPersistentBinding_OUT_OutEntryCount_SIZE sizeof(ULONG) - #define SM_GetPersistentBinding_OUT_OutEntryCount_ID 6 + // + ULONG OutEntryCount; +#define SM_GetPersistentBinding_OUT_OutEntryCount_SIZE sizeof (ULONG) +#define SM_GetPersistentBinding_OUT_OutEntryCount_ID 6 - // + // MS_SMHBA_BINDINGENTRY Entry[1]; - #define SM_GetPersistentBinding_OUT_Entry_ID 7 +#define SM_GetPersistentBinding_OUT_Entry_ID 7 } SM_GetPersistentBinding_OUT, *PSM_GetPersistentBinding_OUT; -#define SM_SetPersistentBinding 6 +#define SM_SetPersistentBinding 6 typedef struct _SM_SetPersistentBinding_IN { - // + // UCHAR HbaPortWWN[8]; - #define SM_SetPersistentBinding_IN_HbaPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_SetPersistentBinding_IN_HbaPortWWN_ID 1 +#define SM_SetPersistentBinding_IN_HbaPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_SetPersistentBinding_IN_HbaPortWWN_ID 1 - // + // UCHAR DomainPortWWN[8]; - #define SM_SetPersistentBinding_IN_DomainPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_SetPersistentBinding_IN_DomainPortWWN_ID 2 +#define SM_SetPersistentBinding_IN_DomainPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_SetPersistentBinding_IN_DomainPortWWN_ID 2 - // - ULONG InEntryCount; - #define SM_SetPersistentBinding_IN_InEntryCount_SIZE sizeof(ULONG) - #define SM_SetPersistentBinding_IN_InEntryCount_ID 3 + // + ULONG InEntryCount; +#define SM_SetPersistentBinding_IN_InEntryCount_SIZE sizeof (ULONG) +#define SM_SetPersistentBinding_IN_InEntryCount_ID 3 - // + // MS_SMHBA_BINDINGENTRY Entry[1]; - #define SM_SetPersistentBinding_IN_Entry_ID 4 +#define SM_SetPersistentBinding_IN_Entry_ID 4 } SM_SetPersistentBinding_IN, *PSM_SetPersistentBinding_IN; typedef struct _SM_SetPersistentBinding_OUT { - // - ULONG HBAStatus; - #define SM_SetPersistentBinding_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SM_SetPersistentBinding_OUT_HBAStatus_ID 5 + // + ULONG HBAStatus; +#define SM_SetPersistentBinding_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SM_SetPersistentBinding_OUT_HBAStatus_ID 5 - // - ULONG OutStatusCount; - #define SM_SetPersistentBinding_OUT_OutStatusCount_SIZE sizeof(ULONG) - #define SM_SetPersistentBinding_OUT_OutStatusCount_ID 6 + // + ULONG OutStatusCount; +#define SM_SetPersistentBinding_OUT_OutStatusCount_SIZE sizeof (ULONG) +#define SM_SetPersistentBinding_OUT_OutStatusCount_ID 6 - // - ULONG EntryStatus[1]; - #define SM_SetPersistentBinding_OUT_EntryStatus_ID 7 + // + ULONG EntryStatus[1]; +#define SM_SetPersistentBinding_OUT_EntryStatus_ID 7 } SM_SetPersistentBinding_OUT, *PSM_SetPersistentBinding_OUT; -#define SM_RemovePersistentBinding 7 +#define SM_RemovePersistentBinding 7 typedef struct _SM_RemovePersistentBinding_IN { - // + // UCHAR HbaPortWWN[8]; - #define SM_RemovePersistentBinding_IN_HbaPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_RemovePersistentBinding_IN_HbaPortWWN_ID 1 +#define SM_RemovePersistentBinding_IN_HbaPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_RemovePersistentBinding_IN_HbaPortWWN_ID 1 - // + // UCHAR DomainPortWWN[8]; - #define SM_RemovePersistentBinding_IN_DomainPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_RemovePersistentBinding_IN_DomainPortWWN_ID 2 +#define SM_RemovePersistentBinding_IN_DomainPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_RemovePersistentBinding_IN_DomainPortWWN_ID 2 - // - ULONG EntryCount; - #define SM_RemovePersistentBinding_IN_EntryCount_SIZE sizeof(ULONG) - #define SM_RemovePersistentBinding_IN_EntryCount_ID 3 + // + ULONG EntryCount; +#define SM_RemovePersistentBinding_IN_EntryCount_SIZE sizeof (ULONG) +#define SM_RemovePersistentBinding_IN_EntryCount_ID 3 - // + // MS_SMHBA_BINDINGENTRY Entry[1]; - #define SM_RemovePersistentBinding_IN_Entry_ID 4 +#define SM_RemovePersistentBinding_IN_Entry_ID 4 } SM_RemovePersistentBinding_IN, *PSM_RemovePersistentBinding_IN; typedef struct _SM_RemovePersistentBinding_OUT { - // - ULONG HBAStatus; - #define SM_RemovePersistentBinding_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SM_RemovePersistentBinding_OUT_HBAStatus_ID 5 + // + ULONG HBAStatus; +#define SM_RemovePersistentBinding_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SM_RemovePersistentBinding_OUT_HBAStatus_ID 5 } SM_RemovePersistentBinding_OUT, *PSM_RemovePersistentBinding_OUT; -#define SM_RemovePersistentBinding_OUT_SIZE (FIELD_OFFSET(SM_RemovePersistentBinding_OUT, HBAStatus) + SM_RemovePersistentBinding_OUT_HBAStatus_SIZE) +#define SM_RemovePersistentBinding_OUT_SIZE \ + (FIELD_OFFSET(SM_RemovePersistentBinding_OUT, HBAStatus) + \ + SM_RemovePersistentBinding_OUT_HBAStatus_SIZE) -#define SM_GetLUNStatistics 8 +#define SM_GetLUNStatistics 8 typedef struct _SM_GetLUNStatistics_IN { - // + // HBAScsiID Lunit; - #define SM_GetLUNStatistics_IN_Lunit_SIZE sizeof(HBAScsiID) - #define SM_GetLUNStatistics_IN_Lunit_ID 1 +#define SM_GetLUNStatistics_IN_Lunit_SIZE sizeof (HBAScsiID) +#define SM_GetLUNStatistics_IN_Lunit_ID 1 } SM_GetLUNStatistics_IN, *PSM_GetLUNStatistics_IN; -#define SM_GetLUNStatistics_IN_SIZE (FIELD_OFFSET(SM_GetLUNStatistics_IN, Lunit) + SM_GetLUNStatistics_IN_Lunit_SIZE) +#define SM_GetLUNStatistics_IN_SIZE \ + (FIELD_OFFSET(SM_GetLUNStatistics_IN, Lunit) + \ + SM_GetLUNStatistics_IN_Lunit_SIZE) typedef struct _SM_GetLUNStatistics_OUT { - // - ULONG HBAStatus; - #define SM_GetLUNStatistics_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SM_GetLUNStatistics_OUT_HBAStatus_ID 2 + // + ULONG HBAStatus; +#define SM_GetLUNStatistics_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SM_GetLUNStatistics_OUT_HBAStatus_ID 2 - // + // MS_SMHBA_PROTOCOLSTATISTICS ProtocolStatistics; - #define SM_GetLUNStatistics_OUT_ProtocolStatistics_SIZE sizeof(MS_SMHBA_PROTOCOLSTATISTICS) - #define SM_GetLUNStatistics_OUT_ProtocolStatistics_ID 3 +#define SM_GetLUNStatistics_OUT_ProtocolStatistics_SIZE \ + sizeof (MS_SMHBA_PROTOCOLSTATISTICS) +#define SM_GetLUNStatistics_OUT_ProtocolStatistics_ID 3 } SM_GetLUNStatistics_OUT, *PSM_GetLUNStatistics_OUT; -#define SM_GetLUNStatistics_OUT_SIZE (FIELD_OFFSET(SM_GetLUNStatistics_OUT, ProtocolStatistics) + SM_GetLUNStatistics_OUT_ProtocolStatistics_SIZE) +#define SM_GetLUNStatistics_OUT_SIZE \ + (FIELD_OFFSET(SM_GetLUNStatistics_OUT, ProtocolStatistics) + \ + SM_GetLUNStatistics_OUT_ProtocolStatistics_SIZE) // MS_SM_ScsiInformationMethods - MS_SM_ScsiInformationMethods -#define MS_SM_ScsiInformationMethodsGuid \ - { 0xb6661e6f,0x075e,0x4209, { 0xae,0x20,0xfe,0x81,0xdb,0x03,0xd9,0x79 } } +#define MS_SM_ScsiInformationMethodsGuid \ + { 0xb6661e6f, 0x075e, 0x4209, \ + { 0xae, 0x20, 0xfe, 0x81, 0xdb, 0x03, 0xd9, 0x79 } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(MS_SM_ScsiInformationMethods_GUID, \ - 0xb6661e6f,0x075e,0x4209,0xae,0x20,0xfe,0x81,0xdb,0x03,0xd9,0x79); + 0xb6661e6f, 0x075e, 0x4209, 0xae, 0x20, 0xfe, 0x81, \ + 0xdb, 0x03, 0xd9, 0x79); #endif // // Method id definitions for MS_SM_ScsiInformationMethods -#define SM_ScsiInquiry 1 +#define SM_ScsiInquiry 1 typedef struct _SM_ScsiInquiry_IN { - // + // UCHAR HbaPortWWN[8]; - #define SM_ScsiInquiry_IN_HbaPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_ScsiInquiry_IN_HbaPortWWN_ID 1 +#define SM_ScsiInquiry_IN_HbaPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_ScsiInquiry_IN_HbaPortWWN_ID 1 - // + // UCHAR DiscoveredPortWWN[8]; - #define SM_ScsiInquiry_IN_DiscoveredPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_ScsiInquiry_IN_DiscoveredPortWWN_ID 2 +#define SM_ScsiInquiry_IN_DiscoveredPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_ScsiInquiry_IN_DiscoveredPortWWN_ID 2 - // + // UCHAR DomainPortWWN[8]; - #define SM_ScsiInquiry_IN_DomainPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_ScsiInquiry_IN_DomainPortWWN_ID 3 +#define SM_ScsiInquiry_IN_DomainPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_ScsiInquiry_IN_DomainPortWWN_ID 3 - // - ULONGLONG SmhbaLUN; - #define SM_ScsiInquiry_IN_SmhbaLUN_SIZE sizeof(ULONGLONG) - #define SM_ScsiInquiry_IN_SmhbaLUN_ID 4 + // + ULONGLONG SmhbaLUN; +#define SM_ScsiInquiry_IN_SmhbaLUN_SIZE sizeof (ULONGLONG) +#define SM_ScsiInquiry_IN_SmhbaLUN_ID 4 - // + // UCHAR Cdb[6]; - #define SM_ScsiInquiry_IN_Cdb_SIZE sizeof(UCHAR[6]) - #define SM_ScsiInquiry_IN_Cdb_ID 5 +#define SM_ScsiInquiry_IN_Cdb_SIZE sizeof (UCHAR[6]) +#define SM_ScsiInquiry_IN_Cdb_ID 5 - // - ULONG InRespBufferMaxSize; - #define SM_ScsiInquiry_IN_InRespBufferMaxSize_SIZE sizeof(ULONG) - #define SM_ScsiInquiry_IN_InRespBufferMaxSize_ID 6 + // + ULONG InRespBufferMaxSize; +#define SM_ScsiInquiry_IN_InRespBufferMaxSize_SIZE sizeof (ULONG) +#define SM_ScsiInquiry_IN_InRespBufferMaxSize_ID 6 - // - ULONG InSenseBufferMaxSize; - #define SM_ScsiInquiry_IN_InSenseBufferMaxSize_SIZE sizeof(ULONG) - #define SM_ScsiInquiry_IN_InSenseBufferMaxSize_ID 7 + // + ULONG InSenseBufferMaxSize; +#define SM_ScsiInquiry_IN_InSenseBufferMaxSize_SIZE sizeof (ULONG) +#define SM_ScsiInquiry_IN_InSenseBufferMaxSize_ID 7 } SM_ScsiInquiry_IN, *PSM_ScsiInquiry_IN; -#define SM_ScsiInquiry_IN_SIZE (FIELD_OFFSET(SM_ScsiInquiry_IN, InSenseBufferMaxSize) + SM_ScsiInquiry_IN_InSenseBufferMaxSize_SIZE) +#define SM_ScsiInquiry_IN_SIZE \ + (FIELD_OFFSET(SM_ScsiInquiry_IN, InSenseBufferMaxSize) + \ + SM_ScsiInquiry_IN_InSenseBufferMaxSize_SIZE) typedef struct _SM_ScsiInquiry_OUT { - // - ULONG HBAStatus; - #define SM_ScsiInquiry_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SM_ScsiInquiry_OUT_HBAStatus_ID 8 + // + ULONG HBAStatus; +#define SM_ScsiInquiry_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SM_ScsiInquiry_OUT_HBAStatus_ID 8 - // + // UCHAR ScsiStatus; - #define SM_ScsiInquiry_OUT_ScsiStatus_SIZE sizeof(UCHAR) - #define SM_ScsiInquiry_OUT_ScsiStatus_ID 9 +#define SM_ScsiInquiry_OUT_ScsiStatus_SIZE sizeof (UCHAR) +#define SM_ScsiInquiry_OUT_ScsiStatus_ID 9 - // - ULONG OutRespBufferSize; - #define SM_ScsiInquiry_OUT_OutRespBufferSize_SIZE sizeof(ULONG) - #define SM_ScsiInquiry_OUT_OutRespBufferSize_ID 10 + // + ULONG OutRespBufferSize; +#define SM_ScsiInquiry_OUT_OutRespBufferSize_SIZE sizeof (ULONG) +#define SM_ScsiInquiry_OUT_OutRespBufferSize_ID 10 - // - ULONG OutSenseBufferSize; - #define SM_ScsiInquiry_OUT_OutSenseBufferSize_SIZE sizeof(ULONG) - #define SM_ScsiInquiry_OUT_OutSenseBufferSize_ID 11 + // + ULONG OutSenseBufferSize; +#define SM_ScsiInquiry_OUT_OutSenseBufferSize_SIZE sizeof (ULONG) +#define SM_ScsiInquiry_OUT_OutSenseBufferSize_ID 11 - // + // UCHAR RespBuffer[1]; - #define SM_ScsiInquiry_OUT_RespBuffer_ID 12 +#define SM_ScsiInquiry_OUT_RespBuffer_ID 12 - // + // // UCHAR SenseBuffer[1]; - #define SM_ScsiInquiry_OUT_SenseBuffer_ID 13 +#define SM_ScsiInquiry_OUT_SenseBuffer_ID 13 } SM_ScsiInquiry_OUT, *PSM_ScsiInquiry_OUT; -#define SM_ScsiReportLuns 2 +#define SM_ScsiReportLuns 2 typedef struct _SM_ScsiReportLuns_IN { - // + // UCHAR HbaPortWWN[8]; - #define SM_ScsiReportLuns_IN_HbaPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_ScsiReportLuns_IN_HbaPortWWN_ID 1 +#define SM_ScsiReportLuns_IN_HbaPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_ScsiReportLuns_IN_HbaPortWWN_ID 1 - // + // UCHAR DiscoveredPortWWN[8]; - #define SM_ScsiReportLuns_IN_DiscoveredPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_ScsiReportLuns_IN_DiscoveredPortWWN_ID 2 +#define SM_ScsiReportLuns_IN_DiscoveredPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_ScsiReportLuns_IN_DiscoveredPortWWN_ID 2 - // + // UCHAR DomainPortWWN[8]; - #define SM_ScsiReportLuns_IN_DomainPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_ScsiReportLuns_IN_DomainPortWWN_ID 3 +#define SM_ScsiReportLuns_IN_DomainPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_ScsiReportLuns_IN_DomainPortWWN_ID 3 - // + // UCHAR Cdb[12]; - #define SM_ScsiReportLuns_IN_Cdb_SIZE sizeof(UCHAR[12]) - #define SM_ScsiReportLuns_IN_Cdb_ID 4 +#define SM_ScsiReportLuns_IN_Cdb_SIZE sizeof (UCHAR[12]) +#define SM_ScsiReportLuns_IN_Cdb_ID 4 - // - ULONG InRespBufferMaxSize; - #define SM_ScsiReportLuns_IN_InRespBufferMaxSize_SIZE sizeof(ULONG) - #define SM_ScsiReportLuns_IN_InRespBufferMaxSize_ID 5 + // + ULONG InRespBufferMaxSize; +#define SM_ScsiReportLuns_IN_InRespBufferMaxSize_SIZE sizeof (ULONG) +#define SM_ScsiReportLuns_IN_InRespBufferMaxSize_ID 5 - // - ULONG InSenseBufferMaxSize; - #define SM_ScsiReportLuns_IN_InSenseBufferMaxSize_SIZE sizeof(ULONG) - #define SM_ScsiReportLuns_IN_InSenseBufferMaxSize_ID 6 + // + ULONG InSenseBufferMaxSize; +#define SM_ScsiReportLuns_IN_InSenseBufferMaxSize_SIZE sizeof (ULONG) +#define SM_ScsiReportLuns_IN_InSenseBufferMaxSize_ID 6 } SM_ScsiReportLuns_IN, *PSM_ScsiReportLuns_IN; -#define SM_ScsiReportLuns_IN_SIZE (FIELD_OFFSET(SM_ScsiReportLuns_IN, InSenseBufferMaxSize) + SM_ScsiReportLuns_IN_InSenseBufferMaxSize_SIZE) +#define SM_ScsiReportLuns_IN_SIZE \ + (FIELD_OFFSET(SM_ScsiReportLuns_IN, InSenseBufferMaxSize) + \ + SM_ScsiReportLuns_IN_InSenseBufferMaxSize_SIZE) typedef struct _SM_ScsiReportLuns_OUT { - // - ULONG HBAStatus; - #define SM_ScsiReportLuns_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SM_ScsiReportLuns_OUT_HBAStatus_ID 7 + // + ULONG HBAStatus; +#define SM_ScsiReportLuns_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SM_ScsiReportLuns_OUT_HBAStatus_ID 7 - // + // UCHAR ScsiStatus; - #define SM_ScsiReportLuns_OUT_ScsiStatus_SIZE sizeof(UCHAR) - #define SM_ScsiReportLuns_OUT_ScsiStatus_ID 8 +#define SM_ScsiReportLuns_OUT_ScsiStatus_SIZE sizeof (UCHAR) +#define SM_ScsiReportLuns_OUT_ScsiStatus_ID 8 - // - ULONG TotalRespBufferSize; - #define SM_ScsiReportLuns_OUT_TotalRespBufferSize_SIZE sizeof(ULONG) - #define SM_ScsiReportLuns_OUT_TotalRespBufferSize_ID 9 + // + ULONG TotalRespBufferSize; +#define SM_ScsiReportLuns_OUT_TotalRespBufferSize_SIZE sizeof (ULONG) +#define SM_ScsiReportLuns_OUT_TotalRespBufferSize_ID 9 - // - ULONG OutRespBufferSize; - #define SM_ScsiReportLuns_OUT_OutRespBufferSize_SIZE sizeof(ULONG) - #define SM_ScsiReportLuns_OUT_OutRespBufferSize_ID 10 + // + ULONG OutRespBufferSize; +#define SM_ScsiReportLuns_OUT_OutRespBufferSize_SIZE sizeof (ULONG) +#define SM_ScsiReportLuns_OUT_OutRespBufferSize_ID 10 - // - ULONG OutSenseBufferSize; - #define SM_ScsiReportLuns_OUT_OutSenseBufferSize_SIZE sizeof(ULONG) - #define SM_ScsiReportLuns_OUT_OutSenseBufferSize_ID 11 + // + ULONG OutSenseBufferSize; +#define SM_ScsiReportLuns_OUT_OutSenseBufferSize_SIZE sizeof (ULONG) +#define SM_ScsiReportLuns_OUT_OutSenseBufferSize_ID 11 - // + // UCHAR RespBuffer[1]; - #define SM_ScsiReportLuns_OUT_RespBuffer_ID 12 +#define SM_ScsiReportLuns_OUT_RespBuffer_ID 12 - // + // // UCHAR SenseBuffer[1]; - #define SM_ScsiReportLuns_OUT_SenseBuffer_ID 13 +#define SM_ScsiReportLuns_OUT_SenseBuffer_ID 13 } SM_ScsiReportLuns_OUT, *PSM_ScsiReportLuns_OUT; -#define SM_ScsiReadCapacity 3 +#define SM_ScsiReadCapacity 3 typedef struct _SM_ScsiReadCapacity_IN { - // + // UCHAR HbaPortWWN[8]; - #define SM_ScsiReadCapacity_IN_HbaPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_ScsiReadCapacity_IN_HbaPortWWN_ID 1 +#define SM_ScsiReadCapacity_IN_HbaPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_ScsiReadCapacity_IN_HbaPortWWN_ID 1 - // + // UCHAR DiscoveredPortWWN[8]; - #define SM_ScsiReadCapacity_IN_DiscoveredPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_ScsiReadCapacity_IN_DiscoveredPortWWN_ID 2 +#define SM_ScsiReadCapacity_IN_DiscoveredPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_ScsiReadCapacity_IN_DiscoveredPortWWN_ID 2 - // + // UCHAR DomainPortWWN[8]; - #define SM_ScsiReadCapacity_IN_DomainPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_ScsiReadCapacity_IN_DomainPortWWN_ID 3 +#define SM_ScsiReadCapacity_IN_DomainPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_ScsiReadCapacity_IN_DomainPortWWN_ID 3 - // - ULONGLONG SmhbaLUN; - #define SM_ScsiReadCapacity_IN_SmhbaLUN_SIZE sizeof(ULONGLONG) - #define SM_ScsiReadCapacity_IN_SmhbaLUN_ID 4 + // + ULONGLONG SmhbaLUN; +#define SM_ScsiReadCapacity_IN_SmhbaLUN_SIZE sizeof (ULONGLONG) +#define SM_ScsiReadCapacity_IN_SmhbaLUN_ID 4 - // + // UCHAR Cdb[16]; - #define SM_ScsiReadCapacity_IN_Cdb_SIZE sizeof(UCHAR[16]) - #define SM_ScsiReadCapacity_IN_Cdb_ID 5 +#define SM_ScsiReadCapacity_IN_Cdb_SIZE sizeof (UCHAR[16]) +#define SM_ScsiReadCapacity_IN_Cdb_ID 5 - // - ULONG InRespBufferMaxSize; - #define SM_ScsiReadCapacity_IN_InRespBufferMaxSize_SIZE sizeof(ULONG) - #define SM_ScsiReadCapacity_IN_InRespBufferMaxSize_ID 6 + // + ULONG InRespBufferMaxSize; +#define SM_ScsiReadCapacity_IN_InRespBufferMaxSize_SIZE sizeof (ULONG) +#define SM_ScsiReadCapacity_IN_InRespBufferMaxSize_ID 6 - // - ULONG InSenseBufferMaxSize; - #define SM_ScsiReadCapacity_IN_InSenseBufferMaxSize_SIZE sizeof(ULONG) - #define SM_ScsiReadCapacity_IN_InSenseBufferMaxSize_ID 7 + // + ULONG InSenseBufferMaxSize; +#define SM_ScsiReadCapacity_IN_InSenseBufferMaxSize_SIZE sizeof (ULONG) +#define SM_ScsiReadCapacity_IN_InSenseBufferMaxSize_ID 7 } SM_ScsiReadCapacity_IN, *PSM_ScsiReadCapacity_IN; -#define SM_ScsiReadCapacity_IN_SIZE (FIELD_OFFSET(SM_ScsiReadCapacity_IN, InSenseBufferMaxSize) + SM_ScsiReadCapacity_IN_InSenseBufferMaxSize_SIZE) +#define SM_ScsiReadCapacity_IN_SIZE \ + (FIELD_OFFSET(SM_ScsiReadCapacity_IN, InSenseBufferMaxSize) + \ + SM_ScsiReadCapacity_IN_InSenseBufferMaxSize_SIZE) typedef struct _SM_ScsiReadCapacity_OUT { - // - ULONG HBAStatus; - #define SM_ScsiReadCapacity_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SM_ScsiReadCapacity_OUT_HBAStatus_ID 8 + // + ULONG HBAStatus; +#define SM_ScsiReadCapacity_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SM_ScsiReadCapacity_OUT_HBAStatus_ID 8 - // + // UCHAR ScsiStatus; - #define SM_ScsiReadCapacity_OUT_ScsiStatus_SIZE sizeof(UCHAR) - #define SM_ScsiReadCapacity_OUT_ScsiStatus_ID 9 +#define SM_ScsiReadCapacity_OUT_ScsiStatus_SIZE sizeof (UCHAR) +#define SM_ScsiReadCapacity_OUT_ScsiStatus_ID 9 - // - ULONG OutRespBufferSize; - #define SM_ScsiReadCapacity_OUT_OutRespBufferSize_SIZE sizeof(ULONG) - #define SM_ScsiReadCapacity_OUT_OutRespBufferSize_ID 10 + // + ULONG OutRespBufferSize; +#define SM_ScsiReadCapacity_OUT_OutRespBufferSize_SIZE sizeof (ULONG) +#define SM_ScsiReadCapacity_OUT_OutRespBufferSize_ID 10 - // - ULONG OutSenseBufferSize; - #define SM_ScsiReadCapacity_OUT_OutSenseBufferSize_SIZE sizeof(ULONG) - #define SM_ScsiReadCapacity_OUT_OutSenseBufferSize_ID 11 + // + ULONG OutSenseBufferSize; +#define SM_ScsiReadCapacity_OUT_OutSenseBufferSize_SIZE sizeof (ULONG) +#define SM_ScsiReadCapacity_OUT_OutSenseBufferSize_ID 11 - // + // UCHAR RespBuffer[1]; - #define SM_ScsiReadCapacity_OUT_RespBuffer_ID 12 +#define SM_ScsiReadCapacity_OUT_RespBuffer_ID 12 - // + // // UCHAR SenseBuffer[1]; - #define SM_ScsiReadCapacity_OUT_SenseBuffer_ID 13 +#define SM_ScsiReadCapacity_OUT_SenseBuffer_ID 13 } SM_ScsiReadCapacity_OUT, *PSM_ScsiReadCapacity_OUT; -// MS_SM_FabricAndDomainManagementMethods - MS_SM_FabricAndDomainManagementMethods -#define MS_SM_FabricAndDomainManagementMethodsGuid \ - { 0x467fea10,0x701b,0x4388, { 0x91,0x7f,0x73,0x06,0x20,0xce,0xa3,0x28 } } +// MS_SM_FabricAndDomainManagementMethods - +// MS_SM_FabricAndDomainManagementMethods +#define MS_SM_FabricAndDomainManagementMethodsGuid \ + { 0x467fea10, 0x701b, 0x4388, \ + { 0x91, 0x7f, 0x73, 0x06, 0x20, 0xce, 0xa3, 0x28 } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(MS_SM_FabricAndDomainManagementMethods_GUID, \ - 0x467fea10,0x701b,0x4388,0x91,0x7f,0x73,0x06,0x20,0xce,0xa3,0x28); + 0x467fea10, 0x701b, 0x4388, 0x91, 0x7f, 0x73, 0x06, \ + 0x20, 0xce, 0xa3, 0x28); #endif // // Method id definitions for MS_SM_FabricAndDomainManagementMethods -#define SM_SendTEST 1 +#define SM_SendTEST 1 typedef struct _SM_SendTEST_IN { - // + // UCHAR HbaPortWWN[8]; - #define SM_SendTEST_IN_HbaPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_SendTEST_IN_HbaPortWWN_ID 1 +#define SM_SendTEST_IN_HbaPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_SendTEST_IN_HbaPortWWN_ID 1 - // + // UCHAR DestWWN[8]; - #define SM_SendTEST_IN_DestWWN_SIZE sizeof(UCHAR[8]) - #define SM_SendTEST_IN_DestWWN_ID 2 +#define SM_SendTEST_IN_DestWWN_SIZE sizeof (UCHAR[8]) +#define SM_SendTEST_IN_DestWWN_ID 2 - // - ULONG DestFCID; - #define SM_SendTEST_IN_DestFCID_SIZE sizeof(ULONG) - #define SM_SendTEST_IN_DestFCID_ID 3 + // + ULONG DestFCID; +#define SM_SendTEST_IN_DestFCID_SIZE sizeof (ULONG) +#define SM_SendTEST_IN_DestFCID_ID 3 - // - ULONG ReqBufferSize; - #define SM_SendTEST_IN_ReqBufferSize_SIZE sizeof(ULONG) - #define SM_SendTEST_IN_ReqBufferSize_ID 4 + // + ULONG ReqBufferSize; +#define SM_SendTEST_IN_ReqBufferSize_SIZE sizeof (ULONG) +#define SM_SendTEST_IN_ReqBufferSize_ID 4 - // + // UCHAR ReqBuffer[1]; - #define SM_SendTEST_IN_ReqBuffer_ID 5 +#define SM_SendTEST_IN_ReqBuffer_ID 5 } SM_SendTEST_IN, *PSM_SendTEST_IN; typedef struct _SM_SendTEST_OUT { - // - ULONG HBAStatus; - #define SM_SendTEST_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SM_SendTEST_OUT_HBAStatus_ID 6 + // + ULONG HBAStatus; +#define SM_SendTEST_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SM_SendTEST_OUT_HBAStatus_ID 6 } SM_SendTEST_OUT, *PSM_SendTEST_OUT; -#define SM_SendTEST_OUT_SIZE (FIELD_OFFSET(SM_SendTEST_OUT, HBAStatus) + SM_SendTEST_OUT_HBAStatus_SIZE) +#define SM_SendTEST_OUT_SIZE \ + (FIELD_OFFSET(SM_SendTEST_OUT, HBAStatus) + \ + SM_SendTEST_OUT_HBAStatus_SIZE) -#define SM_SendECHO 2 +#define SM_SendECHO 2 typedef struct _SM_SendECHO_IN { - // + // UCHAR HbaPortWWN[8]; - #define SM_SendECHO_IN_HbaPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_SendECHO_IN_HbaPortWWN_ID 1 +#define SM_SendECHO_IN_HbaPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_SendECHO_IN_HbaPortWWN_ID 1 - // + // UCHAR DestWWN[8]; - #define SM_SendECHO_IN_DestWWN_SIZE sizeof(UCHAR[8]) - #define SM_SendECHO_IN_DestWWN_ID 2 +#define SM_SendECHO_IN_DestWWN_SIZE sizeof (UCHAR[8]) +#define SM_SendECHO_IN_DestWWN_ID 2 - // - ULONG DestFCID; - #define SM_SendECHO_IN_DestFCID_SIZE sizeof(ULONG) - #define SM_SendECHO_IN_DestFCID_ID 3 + // + ULONG DestFCID; +#define SM_SendECHO_IN_DestFCID_SIZE sizeof (ULONG) +#define SM_SendECHO_IN_DestFCID_ID 3 - // - ULONG InRespBufferMaxSize; - #define SM_SendECHO_IN_InRespBufferMaxSize_SIZE sizeof(ULONG) - #define SM_SendECHO_IN_InRespBufferMaxSize_ID 4 + // + ULONG InRespBufferMaxSize; +#define SM_SendECHO_IN_InRespBufferMaxSize_SIZE sizeof (ULONG) +#define SM_SendECHO_IN_InRespBufferMaxSize_ID 4 - // - ULONG ReqBufferSize; - #define SM_SendECHO_IN_ReqBufferSize_SIZE sizeof(ULONG) - #define SM_SendECHO_IN_ReqBufferSize_ID 5 + // + ULONG ReqBufferSize; +#define SM_SendECHO_IN_ReqBufferSize_SIZE sizeof (ULONG) +#define SM_SendECHO_IN_ReqBufferSize_ID 5 - // + // UCHAR ReqBuffer[1]; - #define SM_SendECHO_IN_ReqBuffer_ID 6 +#define SM_SendECHO_IN_ReqBuffer_ID 6 } SM_SendECHO_IN, *PSM_SendECHO_IN; typedef struct _SM_SendECHO_OUT { - // - ULONG HBAStatus; - #define SM_SendECHO_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SM_SendECHO_OUT_HBAStatus_ID 7 + // + ULONG HBAStatus; +#define SM_SendECHO_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SM_SendECHO_OUT_HBAStatus_ID 7 - // - ULONG OutRespBufferSize; - #define SM_SendECHO_OUT_OutRespBufferSize_SIZE sizeof(ULONG) - #define SM_SendECHO_OUT_OutRespBufferSize_ID 8 + // + ULONG OutRespBufferSize; +#define SM_SendECHO_OUT_OutRespBufferSize_SIZE sizeof (ULONG) +#define SM_SendECHO_OUT_OutRespBufferSize_ID 8 - // + // UCHAR RespBuffer[1]; - #define SM_SendECHO_OUT_RespBuffer_ID 9 +#define SM_SendECHO_OUT_RespBuffer_ID 9 } SM_SendECHO_OUT, *PSM_SendECHO_OUT; -#define SM_SendSMPPassThru 3 +#define SM_SendSMPPassThru 3 typedef struct _SM_SendSMPPassThru_IN { - // + // UCHAR HbaPortWWN[8]; - #define SM_SendSMPPassThru_IN_HbaPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_SendSMPPassThru_IN_HbaPortWWN_ID 1 +#define SM_SendSMPPassThru_IN_HbaPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_SendSMPPassThru_IN_HbaPortWWN_ID 1 - // + // UCHAR DestPortWWN[8]; - #define SM_SendSMPPassThru_IN_DestPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_SendSMPPassThru_IN_DestPortWWN_ID 2 +#define SM_SendSMPPassThru_IN_DestPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_SendSMPPassThru_IN_DestPortWWN_ID 2 - // + // UCHAR DomainPortWWN[8]; - #define SM_SendSMPPassThru_IN_DomainPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_SendSMPPassThru_IN_DomainPortWWN_ID 3 +#define SM_SendSMPPassThru_IN_DomainPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_SendSMPPassThru_IN_DomainPortWWN_ID 3 - // - ULONG InRespBufferMaxSize; - #define SM_SendSMPPassThru_IN_InRespBufferMaxSize_SIZE sizeof(ULONG) - #define SM_SendSMPPassThru_IN_InRespBufferMaxSize_ID 4 + // + ULONG InRespBufferMaxSize; +#define SM_SendSMPPassThru_IN_InRespBufferMaxSize_SIZE sizeof (ULONG) +#define SM_SendSMPPassThru_IN_InRespBufferMaxSize_ID 4 - // - ULONG ReqBufferSize; - #define SM_SendSMPPassThru_IN_ReqBufferSize_SIZE sizeof(ULONG) - #define SM_SendSMPPassThru_IN_ReqBufferSize_ID 5 + // + ULONG ReqBufferSize; +#define SM_SendSMPPassThru_IN_ReqBufferSize_SIZE sizeof (ULONG) +#define SM_SendSMPPassThru_IN_ReqBufferSize_ID 5 - // + // UCHAR ReqBuffer[1]; - #define SM_SendSMPPassThru_IN_ReqBuffer_ID 6 +#define SM_SendSMPPassThru_IN_ReqBuffer_ID 6 } SM_SendSMPPassThru_IN, *PSM_SendSMPPassThru_IN; typedef struct _SM_SendSMPPassThru_OUT { - // - ULONG HBAStatus; - #define SM_SendSMPPassThru_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SM_SendSMPPassThru_OUT_HBAStatus_ID 7 + // + ULONG HBAStatus; +#define SM_SendSMPPassThru_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SM_SendSMPPassThru_OUT_HBAStatus_ID 7 - // - ULONG TotalRespBufferSize; - #define SM_SendSMPPassThru_OUT_TotalRespBufferSize_SIZE sizeof(ULONG) - #define SM_SendSMPPassThru_OUT_TotalRespBufferSize_ID 8 + // + ULONG TotalRespBufferSize; +#define SM_SendSMPPassThru_OUT_TotalRespBufferSize_SIZE sizeof (ULONG) +#define SM_SendSMPPassThru_OUT_TotalRespBufferSize_ID 8 - // - ULONG OutRespBufferSize; - #define SM_SendSMPPassThru_OUT_OutRespBufferSize_SIZE sizeof(ULONG) - #define SM_SendSMPPassThru_OUT_OutRespBufferSize_ID 9 + // + ULONG OutRespBufferSize; +#define SM_SendSMPPassThru_OUT_OutRespBufferSize_SIZE sizeof (ULONG) +#define SM_SendSMPPassThru_OUT_OutRespBufferSize_ID 9 - // + // UCHAR RespBuffer[1]; - #define SM_SendSMPPassThru_OUT_RespBuffer_ID 10 +#define SM_SendSMPPassThru_OUT_RespBuffer_ID 10 } SM_SendSMPPassThru_OUT, *PSM_SendSMPPassThru_OUT; -#define SM_SendCTPassThru 10 +#define SM_SendCTPassThru 10 typedef struct _SM_SendCTPassThru_IN { - // + // UCHAR HbaPortWWN[8]; - #define SM_SendCTPassThru_IN_HbaPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_SendCTPassThru_IN_HbaPortWWN_ID 1 +#define SM_SendCTPassThru_IN_HbaPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_SendCTPassThru_IN_HbaPortWWN_ID 1 - // - ULONG InRespBufferMaxSize; - #define SM_SendCTPassThru_IN_InRespBufferMaxSize_SIZE sizeof(ULONG) - #define SM_SendCTPassThru_IN_InRespBufferMaxSize_ID 2 + // + ULONG InRespBufferMaxSize; +#define SM_SendCTPassThru_IN_InRespBufferMaxSize_SIZE sizeof (ULONG) +#define SM_SendCTPassThru_IN_InRespBufferMaxSize_ID 2 - // - ULONG ReqBufferSize; - #define SM_SendCTPassThru_IN_ReqBufferSize_SIZE sizeof(ULONG) - #define SM_SendCTPassThru_IN_ReqBufferSize_ID 3 + // + ULONG ReqBufferSize; +#define SM_SendCTPassThru_IN_ReqBufferSize_SIZE sizeof (ULONG) +#define SM_SendCTPassThru_IN_ReqBufferSize_ID 3 - // + // UCHAR ReqBuffer[1]; - #define SM_SendCTPassThru_IN_ReqBuffer_ID 4 +#define SM_SendCTPassThru_IN_ReqBuffer_ID 4 } SM_SendCTPassThru_IN, *PSM_SendCTPassThru_IN; typedef struct _SM_SendCTPassThru_OUT { - // - ULONG HBAStatus; - #define SM_SendCTPassThru_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SM_SendCTPassThru_OUT_HBAStatus_ID 5 + // + ULONG HBAStatus; +#define SM_SendCTPassThru_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SM_SendCTPassThru_OUT_HBAStatus_ID 5 - // - ULONG TotalRespBufferSize; - #define SM_SendCTPassThru_OUT_TotalRespBufferSize_SIZE sizeof(ULONG) - #define SM_SendCTPassThru_OUT_TotalRespBufferSize_ID 6 + // + ULONG TotalRespBufferSize; +#define SM_SendCTPassThru_OUT_TotalRespBufferSize_SIZE sizeof (ULONG) +#define SM_SendCTPassThru_OUT_TotalRespBufferSize_ID 6 - // - ULONG OutRespBufferSize; - #define SM_SendCTPassThru_OUT_OutRespBufferSize_SIZE sizeof(ULONG) - #define SM_SendCTPassThru_OUT_OutRespBufferSize_ID 7 + // + ULONG OutRespBufferSize; +#define SM_SendCTPassThru_OUT_OutRespBufferSize_SIZE sizeof (ULONG) +#define SM_SendCTPassThru_OUT_OutRespBufferSize_ID 7 - // + // UCHAR RespBuffer[1]; - #define SM_SendCTPassThru_OUT_RespBuffer_ID 8 +#define SM_SendCTPassThru_OUT_RespBuffer_ID 8 } SM_SendCTPassThru_OUT, *PSM_SendCTPassThru_OUT; -#define SM_GetRNIDMgmtInfo 11 +#define SM_GetRNIDMgmtInfo 11 typedef struct _SM_GetRNIDMgmtInfo_OUT { - // - ULONG HBAStatus; - #define SM_GetRNIDMgmtInfo_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SM_GetRNIDMgmtInfo_OUT_HBAStatus_ID 1 + // + ULONG HBAStatus; +#define SM_GetRNIDMgmtInfo_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SM_GetRNIDMgmtInfo_OUT_HBAStatus_ID 1 - // + // HBAFC3MgmtInfo MgmtInfo; - #define SM_GetRNIDMgmtInfo_OUT_MgmtInfo_SIZE sizeof(HBAFC3MgmtInfo) - #define SM_GetRNIDMgmtInfo_OUT_MgmtInfo_ID 2 +#define SM_GetRNIDMgmtInfo_OUT_MgmtInfo_SIZE sizeof (HBAFC3MgmtInfo) +#define SM_GetRNIDMgmtInfo_OUT_MgmtInfo_ID 2 } SM_GetRNIDMgmtInfo_OUT, *PSM_GetRNIDMgmtInfo_OUT; -#define SM_GetRNIDMgmtInfo_OUT_SIZE (FIELD_OFFSET(SM_GetRNIDMgmtInfo_OUT, MgmtInfo) + SM_GetRNIDMgmtInfo_OUT_MgmtInfo_SIZE) +#define SM_GetRNIDMgmtInfo_OUT_SIZE \ + (FIELD_OFFSET(SM_GetRNIDMgmtInfo_OUT, MgmtInfo) + \ + SM_GetRNIDMgmtInfo_OUT_MgmtInfo_SIZE) -#define SM_SetRNIDMgmtInfo 12 +#define SM_SetRNIDMgmtInfo 12 typedef struct _SM_SetRNIDMgmtInfo_IN { - // + // HBAFC3MgmtInfo MgmtInfo; - #define SM_SetRNIDMgmtInfo_IN_MgmtInfo_SIZE sizeof(HBAFC3MgmtInfo) - #define SM_SetRNIDMgmtInfo_IN_MgmtInfo_ID 1 +#define SM_SetRNIDMgmtInfo_IN_MgmtInfo_SIZE sizeof (HBAFC3MgmtInfo) +#define SM_SetRNIDMgmtInfo_IN_MgmtInfo_ID 1 } SM_SetRNIDMgmtInfo_IN, *PSM_SetRNIDMgmtInfo_IN; -#define SM_SetRNIDMgmtInfo_IN_SIZE (FIELD_OFFSET(SM_SetRNIDMgmtInfo_IN, MgmtInfo) + SM_SetRNIDMgmtInfo_IN_MgmtInfo_SIZE) +#define SM_SetRNIDMgmtInfo_IN_SIZE \ + (FIELD_OFFSET(SM_SetRNIDMgmtInfo_IN, MgmtInfo) + \ + SM_SetRNIDMgmtInfo_IN_MgmtInfo_SIZE) typedef struct _SM_SetRNIDMgmtInfo_OUT { - // - ULONG HBAStatus; - #define SM_SetRNIDMgmtInfo_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SM_SetRNIDMgmtInfo_OUT_HBAStatus_ID 2 + // + ULONG HBAStatus; +#define SM_SetRNIDMgmtInfo_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SM_SetRNIDMgmtInfo_OUT_HBAStatus_ID 2 } SM_SetRNIDMgmtInfo_OUT, *PSM_SetRNIDMgmtInfo_OUT; -#define SM_SetRNIDMgmtInfo_OUT_SIZE (FIELD_OFFSET(SM_SetRNIDMgmtInfo_OUT, HBAStatus) + SM_SetRNIDMgmtInfo_OUT_HBAStatus_SIZE) +#define SM_SetRNIDMgmtInfo_OUT_SIZE \ + (FIELD_OFFSET(SM_SetRNIDMgmtInfo_OUT, HBAStatus) + \ + SM_SetRNIDMgmtInfo_OUT_HBAStatus_SIZE) -#define SM_SendRNID 13 +#define SM_SendRNID 13 typedef struct _SM_SendRNID_IN { - // + // UCHAR HbaPortWWN[8]; - #define SM_SendRNID_IN_HbaPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_SendRNID_IN_HbaPortWWN_ID 1 +#define SM_SendRNID_IN_HbaPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_SendRNID_IN_HbaPortWWN_ID 1 - // + // UCHAR DestWWN[8]; - #define SM_SendRNID_IN_DestWWN_SIZE sizeof(UCHAR[8]) - #define SM_SendRNID_IN_DestWWN_ID 2 +#define SM_SendRNID_IN_DestWWN_SIZE sizeof (UCHAR[8]) +#define SM_SendRNID_IN_DestWWN_ID 2 - // - ULONG DestFCID; - #define SM_SendRNID_IN_DestFCID_SIZE sizeof(ULONG) - #define SM_SendRNID_IN_DestFCID_ID 3 + // + ULONG DestFCID; +#define SM_SendRNID_IN_DestFCID_SIZE sizeof (ULONG) +#define SM_SendRNID_IN_DestFCID_ID 3 - // - ULONG NodeIdDataFormat; - #define SM_SendRNID_IN_NodeIdDataFormat_SIZE sizeof(ULONG) - #define SM_SendRNID_IN_NodeIdDataFormat_ID 4 + // + ULONG NodeIdDataFormat; +#define SM_SendRNID_IN_NodeIdDataFormat_SIZE sizeof (ULONG) +#define SM_SendRNID_IN_NodeIdDataFormat_ID 4 - // - ULONG InRespBufferMaxSize; - #define SM_SendRNID_IN_InRespBufferMaxSize_SIZE sizeof(ULONG) - #define SM_SendRNID_IN_InRespBufferMaxSize_ID 5 + // + ULONG InRespBufferMaxSize; +#define SM_SendRNID_IN_InRespBufferMaxSize_SIZE sizeof (ULONG) +#define SM_SendRNID_IN_InRespBufferMaxSize_ID 5 } SM_SendRNID_IN, *PSM_SendRNID_IN; -#define SM_SendRNID_IN_SIZE (FIELD_OFFSET(SM_SendRNID_IN, InRespBufferMaxSize) + SM_SendRNID_IN_InRespBufferMaxSize_SIZE) +#define SM_SendRNID_IN_SIZE \ + (FIELD_OFFSET(SM_SendRNID_IN, InRespBufferMaxSize) + \ + SM_SendRNID_IN_InRespBufferMaxSize_SIZE) typedef struct _SM_SendRNID_OUT { - // - ULONG HBAStatus; - #define SM_SendRNID_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SM_SendRNID_OUT_HBAStatus_ID 6 + // + ULONG HBAStatus; +#define SM_SendRNID_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SM_SendRNID_OUT_HBAStatus_ID 6 - // - ULONG TotalRespBufferSize; - #define SM_SendRNID_OUT_TotalRespBufferSize_SIZE sizeof(ULONG) - #define SM_SendRNID_OUT_TotalRespBufferSize_ID 7 + // + ULONG TotalRespBufferSize; +#define SM_SendRNID_OUT_TotalRespBufferSize_SIZE sizeof (ULONG) +#define SM_SendRNID_OUT_TotalRespBufferSize_ID 7 - // - ULONG OutRespBufferSize; - #define SM_SendRNID_OUT_OutRespBufferSize_SIZE sizeof(ULONG) - #define SM_SendRNID_OUT_OutRespBufferSize_ID 8 + // + ULONG OutRespBufferSize; +#define SM_SendRNID_OUT_OutRespBufferSize_SIZE sizeof (ULONG) +#define SM_SendRNID_OUT_OutRespBufferSize_ID 8 - // + // UCHAR RespBuffer[1]; - #define SM_SendRNID_OUT_RespBuffer_ID 9 +#define SM_SendRNID_OUT_RespBuffer_ID 9 } SM_SendRNID_OUT, *PSM_SendRNID_OUT; -#define SM_SendRPL 14 +#define SM_SendRPL 14 typedef struct _SM_SendRPL_IN { - // + // UCHAR HbaPortWWN[8]; - #define SM_SendRPL_IN_HbaPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_SendRPL_IN_HbaPortWWN_ID 1 +#define SM_SendRPL_IN_HbaPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_SendRPL_IN_HbaPortWWN_ID 1 - // + // UCHAR AgentWWN[8]; - #define SM_SendRPL_IN_AgentWWN_SIZE sizeof(UCHAR[8]) - #define SM_SendRPL_IN_AgentWWN_ID 2 +#define SM_SendRPL_IN_AgentWWN_SIZE sizeof (UCHAR[8]) +#define SM_SendRPL_IN_AgentWWN_ID 2 - // - ULONG AgentDomain; - #define SM_SendRPL_IN_AgentDomain_SIZE sizeof(ULONG) - #define SM_SendRPL_IN_AgentDomain_ID 3 + // + ULONG AgentDomain; +#define SM_SendRPL_IN_AgentDomain_SIZE sizeof (ULONG) +#define SM_SendRPL_IN_AgentDomain_ID 3 - // - ULONG PortIndex; - #define SM_SendRPL_IN_PortIndex_SIZE sizeof(ULONG) - #define SM_SendRPL_IN_PortIndex_ID 4 + // + ULONG PortIndex; +#define SM_SendRPL_IN_PortIndex_SIZE sizeof (ULONG) +#define SM_SendRPL_IN_PortIndex_ID 4 - // - ULONG InRespBufferMaxSize; - #define SM_SendRPL_IN_InRespBufferMaxSize_SIZE sizeof(ULONG) - #define SM_SendRPL_IN_InRespBufferMaxSize_ID 5 + // + ULONG InRespBufferMaxSize; +#define SM_SendRPL_IN_InRespBufferMaxSize_SIZE sizeof (ULONG) +#define SM_SendRPL_IN_InRespBufferMaxSize_ID 5 } SM_SendRPL_IN, *PSM_SendRPL_IN; -#define SM_SendRPL_IN_SIZE (FIELD_OFFSET(SM_SendRPL_IN, InRespBufferMaxSize) + SM_SendRPL_IN_InRespBufferMaxSize_SIZE) +#define SM_SendRPL_IN_SIZE \ + (FIELD_OFFSET(SM_SendRPL_IN, InRespBufferMaxSize) + \ + SM_SendRPL_IN_InRespBufferMaxSize_SIZE) typedef struct _SM_SendRPL_OUT { - // - ULONG HBAStatus; - #define SM_SendRPL_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SM_SendRPL_OUT_HBAStatus_ID 6 + // + ULONG HBAStatus; +#define SM_SendRPL_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SM_SendRPL_OUT_HBAStatus_ID 6 - // - ULONG TotalRespBufferSize; - #define SM_SendRPL_OUT_TotalRespBufferSize_SIZE sizeof(ULONG) - #define SM_SendRPL_OUT_TotalRespBufferSize_ID 7 + // + ULONG TotalRespBufferSize; +#define SM_SendRPL_OUT_TotalRespBufferSize_SIZE sizeof (ULONG) +#define SM_SendRPL_OUT_TotalRespBufferSize_ID 7 - // - ULONG OutRespBufferSize; - #define SM_SendRPL_OUT_OutRespBufferSize_SIZE sizeof(ULONG) - #define SM_SendRPL_OUT_OutRespBufferSize_ID 8 + // + ULONG OutRespBufferSize; +#define SM_SendRPL_OUT_OutRespBufferSize_SIZE sizeof (ULONG) +#define SM_SendRPL_OUT_OutRespBufferSize_ID 8 - // + // UCHAR RespBuffer[1]; - #define SM_SendRPL_OUT_RespBuffer_ID 9 +#define SM_SendRPL_OUT_RespBuffer_ID 9 } SM_SendRPL_OUT, *PSM_SendRPL_OUT; -#define SM_SendRPS 15 +#define SM_SendRPS 15 typedef struct _SM_SendRPS_IN { - // + // UCHAR HbaPortWWN[8]; - #define SM_SendRPS_IN_HbaPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_SendRPS_IN_HbaPortWWN_ID 1 +#define SM_SendRPS_IN_HbaPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_SendRPS_IN_HbaPortWWN_ID 1 - // + // UCHAR AgentWWN[8]; - #define SM_SendRPS_IN_AgentWWN_SIZE sizeof(UCHAR[8]) - #define SM_SendRPS_IN_AgentWWN_ID 2 +#define SM_SendRPS_IN_AgentWWN_SIZE sizeof (UCHAR[8]) +#define SM_SendRPS_IN_AgentWWN_ID 2 - // + // UCHAR ObjectWWN[8]; - #define SM_SendRPS_IN_ObjectWWN_SIZE sizeof(UCHAR[8]) - #define SM_SendRPS_IN_ObjectWWN_ID 3 +#define SM_SendRPS_IN_ObjectWWN_SIZE sizeof (UCHAR[8]) +#define SM_SendRPS_IN_ObjectWWN_ID 3 - // - ULONG AgentDomain; - #define SM_SendRPS_IN_AgentDomain_SIZE sizeof(ULONG) - #define SM_SendRPS_IN_AgentDomain_ID 4 + // + ULONG AgentDomain; +#define SM_SendRPS_IN_AgentDomain_SIZE sizeof (ULONG) +#define SM_SendRPS_IN_AgentDomain_ID 4 - // - ULONG ObjectPortNumber; - #define SM_SendRPS_IN_ObjectPortNumber_SIZE sizeof(ULONG) - #define SM_SendRPS_IN_ObjectPortNumber_ID 5 + // + ULONG ObjectPortNumber; +#define SM_SendRPS_IN_ObjectPortNumber_SIZE sizeof (ULONG) +#define SM_SendRPS_IN_ObjectPortNumber_ID 5 - // - ULONG InRespBufferMaxSize; - #define SM_SendRPS_IN_InRespBufferMaxSize_SIZE sizeof(ULONG) - #define SM_SendRPS_IN_InRespBufferMaxSize_ID 6 + // + ULONG InRespBufferMaxSize; +#define SM_SendRPS_IN_InRespBufferMaxSize_SIZE sizeof (ULONG) +#define SM_SendRPS_IN_InRespBufferMaxSize_ID 6 } SM_SendRPS_IN, *PSM_SendRPS_IN; -#define SM_SendRPS_IN_SIZE (FIELD_OFFSET(SM_SendRPS_IN, InRespBufferMaxSize) + SM_SendRPS_IN_InRespBufferMaxSize_SIZE) +#define SM_SendRPS_IN_SIZE \ + (FIELD_OFFSET(SM_SendRPS_IN, InRespBufferMaxSize) + \ + SM_SendRPS_IN_InRespBufferMaxSize_SIZE) typedef struct _SM_SendRPS_OUT { - // - ULONG HBAStatus; - #define SM_SendRPS_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SM_SendRPS_OUT_HBAStatus_ID 7 + // + ULONG HBAStatus; +#define SM_SendRPS_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SM_SendRPS_OUT_HBAStatus_ID 7 - // - ULONG TotalRespBufferSize; - #define SM_SendRPS_OUT_TotalRespBufferSize_SIZE sizeof(ULONG) - #define SM_SendRPS_OUT_TotalRespBufferSize_ID 8 + // + ULONG TotalRespBufferSize; +#define SM_SendRPS_OUT_TotalRespBufferSize_SIZE sizeof (ULONG) +#define SM_SendRPS_OUT_TotalRespBufferSize_ID 8 - // - ULONG OutRespBufferSize; - #define SM_SendRPS_OUT_OutRespBufferSize_SIZE sizeof(ULONG) - #define SM_SendRPS_OUT_OutRespBufferSize_ID 9 + // + ULONG OutRespBufferSize; +#define SM_SendRPS_OUT_OutRespBufferSize_SIZE sizeof (ULONG) +#define SM_SendRPS_OUT_OutRespBufferSize_ID 9 - // + // UCHAR RespBuffer[1]; - #define SM_SendRPS_OUT_RespBuffer_ID 10 +#define SM_SendRPS_OUT_RespBuffer_ID 10 } SM_SendRPS_OUT, *PSM_SendRPS_OUT; -#define SM_SendSRL 16 +#define SM_SendSRL 16 typedef struct _SM_SendSRL_IN { - // + // UCHAR HbaPortWWN[8]; - #define SM_SendSRL_IN_HbaPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_SendSRL_IN_HbaPortWWN_ID 1 +#define SM_SendSRL_IN_HbaPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_SendSRL_IN_HbaPortWWN_ID 1 - // + // UCHAR WWN[8]; - #define SM_SendSRL_IN_WWN_SIZE sizeof(UCHAR[8]) - #define SM_SendSRL_IN_WWN_ID 2 +#define SM_SendSRL_IN_WWN_SIZE sizeof (UCHAR[8]) +#define SM_SendSRL_IN_WWN_ID 2 - // - ULONG Domain; - #define SM_SendSRL_IN_Domain_SIZE sizeof(ULONG) - #define SM_SendSRL_IN_Domain_ID 3 + // + ULONG Domain; +#define SM_SendSRL_IN_Domain_SIZE sizeof (ULONG) +#define SM_SendSRL_IN_Domain_ID 3 - // - ULONG InRespBufferMaxSize; - #define SM_SendSRL_IN_InRespBufferMaxSize_SIZE sizeof(ULONG) - #define SM_SendSRL_IN_InRespBufferMaxSize_ID 4 + // + ULONG InRespBufferMaxSize; +#define SM_SendSRL_IN_InRespBufferMaxSize_SIZE sizeof (ULONG) +#define SM_SendSRL_IN_InRespBufferMaxSize_ID 4 } SM_SendSRL_IN, *PSM_SendSRL_IN; -#define SM_SendSRL_IN_SIZE (FIELD_OFFSET(SM_SendSRL_IN, InRespBufferMaxSize) + SM_SendSRL_IN_InRespBufferMaxSize_SIZE) +#define SM_SendSRL_IN_SIZE \ + (FIELD_OFFSET(SM_SendSRL_IN, InRespBufferMaxSize) + \ + SM_SendSRL_IN_InRespBufferMaxSize_SIZE) typedef struct _SM_SendSRL_OUT { - // - ULONG HBAStatus; - #define SM_SendSRL_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SM_SendSRL_OUT_HBAStatus_ID 5 + // + ULONG HBAStatus; +#define SM_SendSRL_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SM_SendSRL_OUT_HBAStatus_ID 5 - // - ULONG TotalRespBufferSize; - #define SM_SendSRL_OUT_TotalRespBufferSize_SIZE sizeof(ULONG) - #define SM_SendSRL_OUT_TotalRespBufferSize_ID 6 + // + ULONG TotalRespBufferSize; +#define SM_SendSRL_OUT_TotalRespBufferSize_SIZE sizeof (ULONG) +#define SM_SendSRL_OUT_TotalRespBufferSize_ID 6 - // - ULONG OutRespBufferSize; - #define SM_SendSRL_OUT_OutRespBufferSize_SIZE sizeof(ULONG) - #define SM_SendSRL_OUT_OutRespBufferSize_ID 7 + // + ULONG OutRespBufferSize; +#define SM_SendSRL_OUT_OutRespBufferSize_SIZE sizeof (ULONG) +#define SM_SendSRL_OUT_OutRespBufferSize_ID 7 - // + // UCHAR RespBuffer[1]; - #define SM_SendSRL_OUT_RespBuffer_ID 8 +#define SM_SendSRL_OUT_RespBuffer_ID 8 } SM_SendSRL_OUT, *PSM_SendSRL_OUT; -#define SM_SendLIRR 17 +#define SM_SendLIRR 17 typedef struct _SM_SendLIRR_IN { - // + // UCHAR SourceWWN[8]; - #define SM_SendLIRR_IN_SourceWWN_SIZE sizeof(UCHAR[8]) - #define SM_SendLIRR_IN_SourceWWN_ID 1 +#define SM_SendLIRR_IN_SourceWWN_SIZE sizeof (UCHAR[8]) +#define SM_SendLIRR_IN_SourceWWN_ID 1 - // + // UCHAR DestWWN[8]; - #define SM_SendLIRR_IN_DestWWN_SIZE sizeof(UCHAR[8]) - #define SM_SendLIRR_IN_DestWWN_ID 2 +#define SM_SendLIRR_IN_DestWWN_SIZE sizeof (UCHAR[8]) +#define SM_SendLIRR_IN_DestWWN_ID 2 - // + // UCHAR Function; - #define SM_SendLIRR_IN_Function_SIZE sizeof(UCHAR) - #define SM_SendLIRR_IN_Function_ID 3 +#define SM_SendLIRR_IN_Function_SIZE sizeof (UCHAR) +#define SM_SendLIRR_IN_Function_ID 3 - // + // UCHAR Type; - #define SM_SendLIRR_IN_Type_SIZE sizeof(UCHAR) - #define SM_SendLIRR_IN_Type_ID 4 +#define SM_SendLIRR_IN_Type_SIZE sizeof (UCHAR) +#define SM_SendLIRR_IN_Type_ID 4 - // - ULONG InRespBufferMaxSize; - #define SM_SendLIRR_IN_InRespBufferMaxSize_SIZE sizeof(ULONG) - #define SM_SendLIRR_IN_InRespBufferMaxSize_ID 5 + // + ULONG InRespBufferMaxSize; +#define SM_SendLIRR_IN_InRespBufferMaxSize_SIZE sizeof (ULONG) +#define SM_SendLIRR_IN_InRespBufferMaxSize_ID 5 } SM_SendLIRR_IN, *PSM_SendLIRR_IN; -#define SM_SendLIRR_IN_SIZE (FIELD_OFFSET(SM_SendLIRR_IN, InRespBufferMaxSize) + SM_SendLIRR_IN_InRespBufferMaxSize_SIZE) +#define SM_SendLIRR_IN_SIZE \ + (FIELD_OFFSET(SM_SendLIRR_IN, InRespBufferMaxSize) + \ + SM_SendLIRR_IN_InRespBufferMaxSize_SIZE) typedef struct _SM_SendLIRR_OUT { - // - ULONG HBAStatus; - #define SM_SendLIRR_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SM_SendLIRR_OUT_HBAStatus_ID 6 + // + ULONG HBAStatus; +#define SM_SendLIRR_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SM_SendLIRR_OUT_HBAStatus_ID 6 - // - ULONG TotalRespBufferSize; - #define SM_SendLIRR_OUT_TotalRespBufferSize_SIZE sizeof(ULONG) - #define SM_SendLIRR_OUT_TotalRespBufferSize_ID 7 + // + ULONG TotalRespBufferSize; +#define SM_SendLIRR_OUT_TotalRespBufferSize_SIZE sizeof (ULONG) +#define SM_SendLIRR_OUT_TotalRespBufferSize_ID 7 - // - ULONG OutRespBufferSize; - #define SM_SendLIRR_OUT_OutRespBufferSize_SIZE sizeof(ULONG) - #define SM_SendLIRR_OUT_OutRespBufferSize_ID 8 + // + ULONG OutRespBufferSize; +#define SM_SendLIRR_OUT_OutRespBufferSize_SIZE sizeof (ULONG) +#define SM_SendLIRR_OUT_OutRespBufferSize_ID 8 - // + // UCHAR RespBuffer[1]; - #define SM_SendLIRR_OUT_RespBuffer_ID 9 +#define SM_SendLIRR_OUT_RespBuffer_ID 9 } SM_SendLIRR_OUT, *PSM_SendLIRR_OUT; -#define SM_SendRLS 18 +#define SM_SendRLS 18 typedef struct _SM_SendRLS_IN { - // + // UCHAR HbaPortWWN[8]; - #define SM_SendRLS_IN_HbaPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_SendRLS_IN_HbaPortWWN_ID 1 +#define SM_SendRLS_IN_HbaPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_SendRLS_IN_HbaPortWWN_ID 1 - // + // UCHAR DestWWN[8]; - #define SM_SendRLS_IN_DestWWN_SIZE sizeof(UCHAR[8]) - #define SM_SendRLS_IN_DestWWN_ID 2 +#define SM_SendRLS_IN_DestWWN_SIZE sizeof (UCHAR[8]) +#define SM_SendRLS_IN_DestWWN_ID 2 - // - ULONG InRespBufferMaxSize; - #define SM_SendRLS_IN_InRespBufferMaxSize_SIZE sizeof(ULONG) - #define SM_SendRLS_IN_InRespBufferMaxSize_ID 3 + // + ULONG InRespBufferMaxSize; +#define SM_SendRLS_IN_InRespBufferMaxSize_SIZE sizeof (ULONG) +#define SM_SendRLS_IN_InRespBufferMaxSize_ID 3 } SM_SendRLS_IN, *PSM_SendRLS_IN; -#define SM_SendRLS_IN_SIZE (FIELD_OFFSET(SM_SendRLS_IN, InRespBufferMaxSize) + SM_SendRLS_IN_InRespBufferMaxSize_SIZE) +#define SM_SendRLS_IN_SIZE \ + (FIELD_OFFSET(SM_SendRLS_IN, InRespBufferMaxSize) + \ + SM_SendRLS_IN_InRespBufferMaxSize_SIZE) typedef struct _SM_SendRLS_OUT { - // - ULONG HBAStatus; - #define SM_SendRLS_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SM_SendRLS_OUT_HBAStatus_ID 4 + // + ULONG HBAStatus; +#define SM_SendRLS_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SM_SendRLS_OUT_HBAStatus_ID 4 - // - ULONG TotalRespBufferSize; - #define SM_SendRLS_OUT_TotalRespBufferSize_SIZE sizeof(ULONG) - #define SM_SendRLS_OUT_TotalRespBufferSize_ID 5 + // + ULONG TotalRespBufferSize; +#define SM_SendRLS_OUT_TotalRespBufferSize_SIZE sizeof (ULONG) +#define SM_SendRLS_OUT_TotalRespBufferSize_ID 5 - // - ULONG OutRespBufferSize; - #define SM_SendRLS_OUT_OutRespBufferSize_SIZE sizeof(ULONG) - #define SM_SendRLS_OUT_OutRespBufferSize_ID 6 + // + ULONG OutRespBufferSize; +#define SM_SendRLS_OUT_OutRespBufferSize_SIZE sizeof (ULONG) +#define SM_SendRLS_OUT_OutRespBufferSize_ID 6 - // + // UCHAR RespBuffer[1]; - #define SM_SendRLS_OUT_RespBuffer_ID 7 +#define SM_SendRLS_OUT_RespBuffer_ID 7 } SM_SendRLS_OUT, *PSM_SendRLS_OUT; // MS_SM_AdapterEvent - MS_SM_AdapterEvent -#define MS_SM_AdapterEventGuid \ - { 0x7944cf67,0x697b,0x4432, { 0x95,0x3e,0x1f,0xda,0xda,0x88,0x43,0x61 } } +#define MS_SM_AdapterEventGuid \ + { 0x7944cf67, 0x697b, 0x4432, \ + { 0x95, 0x3e, 0x1f, 0xda, 0xda, 0x88, 0x43, 0x61 } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(MS_SM_AdapterEvent_GUID, \ - 0x7944cf67,0x697b,0x4432,0x95,0x3e,0x1f,0xda,0xda,0x88,0x43,0x61); + 0x7944cf67, 0x697b, 0x4432, 0x95, 0x3e, 0x1f, 0xda, \ + 0xda, 0x88, 0x43, 0x61); #endif typedef struct _MS_SM_AdapterEvent { - // - ULONG EventType; - #define MS_SM_AdapterEvent_EventType_SIZE sizeof(ULONG) - #define MS_SM_AdapterEvent_EventType_ID 1 + // + ULONG EventType; +#define MS_SM_AdapterEvent_EventType_SIZE sizeof (ULONG) +#define MS_SM_AdapterEvent_EventType_ID 1 - // + // UCHAR PortWWN[8]; - #define MS_SM_AdapterEvent_PortWWN_SIZE sizeof(UCHAR[8]) - #define MS_SM_AdapterEvent_PortWWN_ID 2 +#define MS_SM_AdapterEvent_PortWWN_SIZE sizeof (UCHAR[8]) +#define MS_SM_AdapterEvent_PortWWN_ID 2 } MS_SM_AdapterEvent, *PMS_SM_AdapterEvent; -#define MS_SM_AdapterEvent_SIZE (FIELD_OFFSET(MS_SM_AdapterEvent, PortWWN) + MS_SM_AdapterEvent_PortWWN_SIZE) +#define MS_SM_AdapterEvent_SIZE \ + (FIELD_OFFSET(MS_SM_AdapterEvent, PortWWN) + \ + MS_SM_AdapterEvent_PortWWN_SIZE) // MS_SM_PortEvent - MS_SM_PortEvent -#define MS_SM_PortEventGuid \ - { 0x0f760256,0x8fc6,0x47ad, { 0x9d,0x2e,0xf0,0xd6,0x98,0x01,0xde,0x7c } } +#define MS_SM_PortEventGuid \ + { 0x0f760256, 0x8fc6, 0x47ad, \ + { 0x9d, 0x2e, 0xf0, 0xd6, 0x98, 0x01, 0xde, 0x7c } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(MS_SM_PortEvent_GUID, \ - 0x0f760256,0x8fc6,0x47ad,0x9d,0x2e,0xf0,0xd6,0x98,0x01,0xde,0x7c); + 0x0f760256, 0x8fc6, 0x47ad, 0x9d, 0x2e, 0xf0, 0xd6, \ + 0x98, 0x01, 0xde, 0x7c); #endif typedef struct _MS_SM_PortEvent { - // - ULONG EventType; - #define MS_SM_PortEvent_EventType_SIZE sizeof(ULONG) - #define MS_SM_PortEvent_EventType_ID 1 + // + ULONG EventType; +#define MS_SM_PortEvent_EventType_SIZE sizeof (ULONG) +#define MS_SM_PortEvent_EventType_ID 1 - // - ULONG FabricPortId; - #define MS_SM_PortEvent_FabricPortId_SIZE sizeof(ULONG) - #define MS_SM_PortEvent_FabricPortId_ID 2 + // + ULONG FabricPortId; +#define MS_SM_PortEvent_FabricPortId_SIZE sizeof (ULONG) +#define MS_SM_PortEvent_FabricPortId_ID 2 - // + // UCHAR PortWWN[8]; - #define MS_SM_PortEvent_PortWWN_SIZE sizeof(UCHAR[8]) - #define MS_SM_PortEvent_PortWWN_ID 3 +#define MS_SM_PortEvent_PortWWN_SIZE sizeof (UCHAR[8]) +#define MS_SM_PortEvent_PortWWN_ID 3 } MS_SM_PortEvent, *PMS_SM_PortEvent; -#define MS_SM_PortEvent_SIZE (FIELD_OFFSET(MS_SM_PortEvent, PortWWN) + MS_SM_PortEvent_PortWWN_SIZE) +#define MS_SM_PortEvent_SIZE \ + (FIELD_OFFSET(MS_SM_PortEvent, PortWWN) + MS_SM_PortEvent_PortWWN_SIZE) // MS_SM_TargetEvent - MS_SM_TargetEvent -#define MS_SM_TargetEventGuid \ - { 0x6e2d8b73,0xf928,0x4da9, { 0xbd,0xa1,0xae,0x54,0x18,0x9a,0x38,0x25 } } +#define MS_SM_TargetEventGuid \ + { 0x6e2d8b73, 0xf928, 0x4da9, \ + { 0xbd, 0xa1, 0xae, 0x54, 0x18, 0x9a, 0x38, 0x25 } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(MS_SM_TargetEvent_GUID, \ - 0x6e2d8b73,0xf928,0x4da9,0xbd,0xa1,0xae,0x54,0x18,0x9a,0x38,0x25); + 0x6e2d8b73, 0xf928, 0x4da9, 0xbd, 0xa1, 0xae, 0x54, \ + 0x18, 0x9a, 0x38, 0x25); #endif typedef struct _MS_SM_TargetEvent { - // - ULONG EventType; - #define MS_SM_TargetEvent_EventType_SIZE sizeof(ULONG) - #define MS_SM_TargetEvent_EventType_ID 1 + // + ULONG EventType; +#define MS_SM_TargetEvent_EventType_SIZE sizeof (ULONG) +#define MS_SM_TargetEvent_EventType_ID 1 - // + // UCHAR PortWWN[8]; - #define MS_SM_TargetEvent_PortWWN_SIZE sizeof(UCHAR[8]) - #define MS_SM_TargetEvent_PortWWN_ID 2 +#define MS_SM_TargetEvent_PortWWN_SIZE sizeof (UCHAR[8]) +#define MS_SM_TargetEvent_PortWWN_ID 2 - // + // UCHAR DiscoveredPortWWN[8]; - #define MS_SM_TargetEvent_DiscoveredPortWWN_SIZE sizeof(UCHAR[8]) - #define MS_SM_TargetEvent_DiscoveredPortWWN_ID 3 +#define MS_SM_TargetEvent_DiscoveredPortWWN_SIZE sizeof (UCHAR[8]) +#define MS_SM_TargetEvent_DiscoveredPortWWN_ID 3 - // + // UCHAR DomainPortWWN[8]; - #define MS_SM_TargetEvent_DomainPortWWN_SIZE sizeof(UCHAR[8]) - #define MS_SM_TargetEvent_DomainPortWWN_ID 4 +#define MS_SM_TargetEvent_DomainPortWWN_SIZE sizeof (UCHAR[8]) +#define MS_SM_TargetEvent_DomainPortWWN_ID 4 } MS_SM_TargetEvent, *PMS_SM_TargetEvent; -#define MS_SM_TargetEvent_SIZE (FIELD_OFFSET(MS_SM_TargetEvent, DomainPortWWN) + MS_SM_TargetEvent_DomainPortWWN_SIZE) +#define MS_SM_TargetEvent_SIZE \ + (FIELD_OFFSET(MS_SM_TargetEvent, DomainPortWWN) + \ + MS_SM_TargetEvent_DomainPortWWN_SIZE) // MS_SM_EventControl - MS_SM_EventControl -#define MS_SM_EventControlGuid \ - { 0xd6145693,0x5988,0x457f, { 0x85,0x81,0x9a,0x01,0x57,0xb5,0x86,0x90 } } +#define MS_SM_EventControlGuid \ + { 0xd6145693, 0x5988, 0x457f, \ + { 0x85, 0x81, 0x9a, 0x01, 0x57, 0xb5, 0x86, 0x90 } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(MS_SM_EventControl_GUID, \ - 0xd6145693,0x5988,0x457f,0x85,0x81,0x9a,0x01,0x57,0xb5,0x86,0x90); + 0xd6145693, 0x5988, 0x457f, 0x85, 0x81, 0x9a, 0x01, \ + 0x57, 0xb5, 0x86, 0x90); #endif // // Method id definitions for MS_SM_EventControl -#define SM_AddTarget 1 +#define SM_AddTarget 1 typedef struct _SM_AddTarget_IN { - // + // UCHAR HbaPortWWN[8]; - #define SM_AddTarget_IN_HbaPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_AddTarget_IN_HbaPortWWN_ID 1 +#define SM_AddTarget_IN_HbaPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_AddTarget_IN_HbaPortWWN_ID 1 - // + // UCHAR DiscoveredPortWWN[8]; - #define SM_AddTarget_IN_DiscoveredPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_AddTarget_IN_DiscoveredPortWWN_ID 2 +#define SM_AddTarget_IN_DiscoveredPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_AddTarget_IN_DiscoveredPortWWN_ID 2 - // + // UCHAR DomainPortWWN[8]; - #define SM_AddTarget_IN_DomainPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_AddTarget_IN_DomainPortWWN_ID 3 +#define SM_AddTarget_IN_DomainPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_AddTarget_IN_DomainPortWWN_ID 3 - // - ULONG AllTargets; - #define SM_AddTarget_IN_AllTargets_SIZE sizeof(ULONG) - #define SM_AddTarget_IN_AllTargets_ID 4 + // + ULONG AllTargets; +#define SM_AddTarget_IN_AllTargets_SIZE sizeof (ULONG) +#define SM_AddTarget_IN_AllTargets_ID 4 } SM_AddTarget_IN, *PSM_AddTarget_IN; -#define SM_AddTarget_IN_SIZE (FIELD_OFFSET(SM_AddTarget_IN, AllTargets) + SM_AddTarget_IN_AllTargets_SIZE) +#define SM_AddTarget_IN_SIZE \ + (FIELD_OFFSET(SM_AddTarget_IN, AllTargets) + \ + SM_AddTarget_IN_AllTargets_SIZE) typedef struct _SM_AddTarget_OUT { - // - ULONG HBAStatus; - #define SM_AddTarget_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SM_AddTarget_OUT_HBAStatus_ID 5 + // + ULONG HBAStatus; +#define SM_AddTarget_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SM_AddTarget_OUT_HBAStatus_ID 5 } SM_AddTarget_OUT, *PSM_AddTarget_OUT; -#define SM_AddTarget_OUT_SIZE (FIELD_OFFSET(SM_AddTarget_OUT, HBAStatus) + SM_AddTarget_OUT_HBAStatus_SIZE) +#define SM_AddTarget_OUT_SIZE \ + (FIELD_OFFSET(SM_AddTarget_OUT, HBAStatus) + \ + SM_AddTarget_OUT_HBAStatus_SIZE) -#define SM_RemoveTarget 2 +#define SM_RemoveTarget 2 typedef struct _SM_RemoveTarget_IN { - // + // UCHAR HbaPortWWN[8]; - #define SM_RemoveTarget_IN_HbaPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_RemoveTarget_IN_HbaPortWWN_ID 1 +#define SM_RemoveTarget_IN_HbaPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_RemoveTarget_IN_HbaPortWWN_ID 1 - // + // UCHAR DiscoveredPortWWN[8]; - #define SM_RemoveTarget_IN_DiscoveredPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_RemoveTarget_IN_DiscoveredPortWWN_ID 2 +#define SM_RemoveTarget_IN_DiscoveredPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_RemoveTarget_IN_DiscoveredPortWWN_ID 2 - // + // UCHAR DomainPortWWN[8]; - #define SM_RemoveTarget_IN_DomainPortWWN_SIZE sizeof(UCHAR[8]) - #define SM_RemoveTarget_IN_DomainPortWWN_ID 3 +#define SM_RemoveTarget_IN_DomainPortWWN_SIZE sizeof (UCHAR[8]) +#define SM_RemoveTarget_IN_DomainPortWWN_ID 3 - // - ULONG AllTargets; - #define SM_RemoveTarget_IN_AllTargets_SIZE sizeof(ULONG) - #define SM_RemoveTarget_IN_AllTargets_ID 4 + // + ULONG AllTargets; +#define SM_RemoveTarget_IN_AllTargets_SIZE sizeof (ULONG) +#define SM_RemoveTarget_IN_AllTargets_ID 4 } SM_RemoveTarget_IN, *PSM_RemoveTarget_IN; -#define SM_RemoveTarget_IN_SIZE (FIELD_OFFSET(SM_RemoveTarget_IN, AllTargets) + SM_RemoveTarget_IN_AllTargets_SIZE) +#define SM_RemoveTarget_IN_SIZE \ + (FIELD_OFFSET(SM_RemoveTarget_IN, AllTargets) + \ + SM_RemoveTarget_IN_AllTargets_SIZE) typedef struct _SM_RemoveTarget_OUT { - // - ULONG HBAStatus; - #define SM_RemoveTarget_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SM_RemoveTarget_OUT_HBAStatus_ID 5 + // + ULONG HBAStatus; +#define SM_RemoveTarget_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SM_RemoveTarget_OUT_HBAStatus_ID 5 } SM_RemoveTarget_OUT, *PSM_RemoveTarget_OUT; -#define SM_RemoveTarget_OUT_SIZE (FIELD_OFFSET(SM_RemoveTarget_OUT, HBAStatus) + SM_RemoveTarget_OUT_HBAStatus_SIZE) +#define SM_RemoveTarget_OUT_SIZE \ + (FIELD_OFFSET(SM_RemoveTarget_OUT, HBAStatus) + \ + SM_RemoveTarget_OUT_HBAStatus_SIZE) -#define SM_AddPort 3 +#define SM_AddPort 3 typedef struct _SM_AddPort_IN { - // + // UCHAR PortWWN[8]; - #define SM_AddPort_IN_PortWWN_SIZE sizeof(UCHAR[8]) - #define SM_AddPort_IN_PortWWN_ID 1 +#define SM_AddPort_IN_PortWWN_SIZE sizeof (UCHAR[8]) +#define SM_AddPort_IN_PortWWN_ID 1 - // - ULONG EventType; - #define SM_AddPort_IN_EventType_SIZE sizeof(ULONG) - #define SM_AddPort_IN_EventType_ID 2 + // + ULONG EventType; +#define SM_AddPort_IN_EventType_SIZE sizeof (ULONG) +#define SM_AddPort_IN_EventType_ID 2 } SM_AddPort_IN, *PSM_AddPort_IN; -#define SM_AddPort_IN_SIZE (FIELD_OFFSET(SM_AddPort_IN, EventType) + SM_AddPort_IN_EventType_SIZE) +#define SM_AddPort_IN_SIZE \ + (FIELD_OFFSET(SM_AddPort_IN, EventType) + SM_AddPort_IN_EventType_SIZE) typedef struct _SM_AddPort_OUT { - // - ULONG HBAStatus; - #define SM_AddPort_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SM_AddPort_OUT_HBAStatus_ID 3 + // + ULONG HBAStatus; +#define SM_AddPort_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SM_AddPort_OUT_HBAStatus_ID 3 } SM_AddPort_OUT, *PSM_AddPort_OUT; -#define SM_AddPort_OUT_SIZE (FIELD_OFFSET(SM_AddPort_OUT, HBAStatus) + SM_AddPort_OUT_HBAStatus_SIZE) +#define SM_AddPort_OUT_SIZE \ + (FIELD_OFFSET(SM_AddPort_OUT, HBAStatus) + \ + SM_AddPort_OUT_HBAStatus_SIZE) -#define SM_RemovePort 4 +#define SM_RemovePort 4 typedef struct _SM_RemovePort_IN { - // + // UCHAR PortWWN[8]; - #define SM_RemovePort_IN_PortWWN_SIZE sizeof(UCHAR[8]) - #define SM_RemovePort_IN_PortWWN_ID 1 +#define SM_RemovePort_IN_PortWWN_SIZE sizeof (UCHAR[8]) +#define SM_RemovePort_IN_PortWWN_ID 1 - // - ULONG EventType; - #define SM_RemovePort_IN_EventType_SIZE sizeof(ULONG) - #define SM_RemovePort_IN_EventType_ID 2 + // + ULONG EventType; +#define SM_RemovePort_IN_EventType_SIZE sizeof (ULONG) +#define SM_RemovePort_IN_EventType_ID 2 } SM_RemovePort_IN, *PSM_RemovePort_IN; -#define SM_RemovePort_IN_SIZE (FIELD_OFFSET(SM_RemovePort_IN, EventType) + SM_RemovePort_IN_EventType_SIZE) +#define SM_RemovePort_IN_SIZE \ + (FIELD_OFFSET(SM_RemovePort_IN, EventType) + \ + SM_RemovePort_IN_EventType_SIZE) typedef struct _SM_RemovePort_OUT { - // - ULONG HBAStatus; - #define SM_RemovePort_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SM_RemovePort_OUT_HBAStatus_ID 3 + // + ULONG HBAStatus; +#define SM_RemovePort_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SM_RemovePort_OUT_HBAStatus_ID 3 } SM_RemovePort_OUT, *PSM_RemovePort_OUT; -#define SM_RemovePort_OUT_SIZE (FIELD_OFFSET(SM_RemovePort_OUT, HBAStatus) + SM_RemovePort_OUT_HBAStatus_SIZE) +#define SM_RemovePort_OUT_SIZE \ + (FIELD_OFFSET(SM_RemovePort_OUT, HBAStatus) + \ + SM_RemovePort_OUT_HBAStatus_SIZE) -#define SM_AddLink 10 +#define SM_AddLink 10 typedef struct _SM_AddLink_OUT { - // - ULONG HBAStatus; - #define SM_AddLink_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SM_AddLink_OUT_HBAStatus_ID 1 + // + ULONG HBAStatus; +#define SM_AddLink_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SM_AddLink_OUT_HBAStatus_ID 1 } SM_AddLink_OUT, *PSM_AddLink_OUT; -#define SM_AddLink_OUT_SIZE (FIELD_OFFSET(SM_AddLink_OUT, HBAStatus) + SM_AddLink_OUT_HBAStatus_SIZE) +#define SM_AddLink_OUT_SIZE \ + (FIELD_OFFSET(SM_AddLink_OUT, HBAStatus) + \ + SM_AddLink_OUT_HBAStatus_SIZE) -#define SM_RemoveLink 11 +#define SM_RemoveLink 11 typedef struct _SM_RemoveLink_OUT { - // - ULONG HBAStatus; - #define SM_RemoveLink_OUT_HBAStatus_SIZE sizeof(ULONG) - #define SM_RemoveLink_OUT_HBAStatus_ID 1 + // + ULONG HBAStatus; +#define SM_RemoveLink_OUT_HBAStatus_SIZE sizeof (ULONG) +#define SM_RemoveLink_OUT_HBAStatus_ID 1 } SM_RemoveLink_OUT, *PSM_RemoveLink_OUT; -#define SM_RemoveLink_OUT_SIZE (FIELD_OFFSET(SM_RemoveLink_OUT, HBAStatus) + SM_RemoveLink_OUT_HBAStatus_SIZE) +#define SM_RemoveLink_OUT_SIZE \ + (FIELD_OFFSET(SM_RemoveLink_OUT, HBAStatus) + \ + SM_RemoveLink_OUT_HBAStatus_SIZE) // MSFC_TM - MSFC_TM #endif // MS_SM_HBA_API -#define MSFC_TMGuid \ - { 0x8cf4c7eb,0xa286,0x409d, { 0x9e,0xb9,0x29,0xd7,0xe0,0xe9,0xf4,0xfa } } +#define MSFC_TMGuid \ + { 0x8cf4c7eb, 0xa286, 0x409d, \ + { 0x9e, 0xb9, 0x29, 0xd7, 0xe0, 0xe9, 0xf4, 0xfa } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(MSFC_TM_GUID, \ - 0x8cf4c7eb,0xa286,0x409d,0x9e,0xb9,0x29,0xd7,0xe0,0xe9,0xf4,0xfa); + 0x8cf4c7eb, 0xa286, 0x409d, 0x9e, 0xb9, 0x29, 0xd7, \ + 0xe0, 0xe9, 0xf4, 0xfa); #endif typedef struct _MSFC_TM { - // - ULONG tm_sec; - #define MSFC_TM_tm_sec_SIZE sizeof(ULONG) - #define MSFC_TM_tm_sec_ID 1 - - // - ULONG tm_min; - #define MSFC_TM_tm_min_SIZE sizeof(ULONG) - #define MSFC_TM_tm_min_ID 2 - - // - ULONG tm_hour; - #define MSFC_TM_tm_hour_SIZE sizeof(ULONG) - #define MSFC_TM_tm_hour_ID 3 - - // - ULONG tm_mday; - #define MSFC_TM_tm_mday_SIZE sizeof(ULONG) - #define MSFC_TM_tm_mday_ID 4 - - // - ULONG tm_mon; - #define MSFC_TM_tm_mon_SIZE sizeof(ULONG) - #define MSFC_TM_tm_mon_ID 5 - - // - ULONG tm_year; - #define MSFC_TM_tm_year_SIZE sizeof(ULONG) - #define MSFC_TM_tm_year_ID 6 - - // - ULONG tm_wday; - #define MSFC_TM_tm_wday_SIZE sizeof(ULONG) - #define MSFC_TM_tm_wday_ID 7 - - // - ULONG tm_yday; - #define MSFC_TM_tm_yday_SIZE sizeof(ULONG) - #define MSFC_TM_tm_yday_ID 8 - - // - ULONG tm_isdst; - #define MSFC_TM_tm_isdst_SIZE sizeof(ULONG) - #define MSFC_TM_tm_isdst_ID 9 + // + ULONG tm_sec; +#define MSFC_TM_tm_sec_SIZE sizeof (ULONG) +#define MSFC_TM_tm_sec_ID 1 + + // + ULONG tm_min; +#define MSFC_TM_tm_min_SIZE sizeof (ULONG) +#define MSFC_TM_tm_min_ID 2 + + // + ULONG tm_hour; +#define MSFC_TM_tm_hour_SIZE sizeof (ULONG) +#define MSFC_TM_tm_hour_ID 3 + + // + ULONG tm_mday; +#define MSFC_TM_tm_mday_SIZE sizeof (ULONG) +#define MSFC_TM_tm_mday_ID 4 + + // + ULONG tm_mon; +#define MSFC_TM_tm_mon_SIZE sizeof (ULONG) +#define MSFC_TM_tm_mon_ID 5 + + // + ULONG tm_year; +#define MSFC_TM_tm_year_SIZE sizeof (ULONG) +#define MSFC_TM_tm_year_ID 6 + + // + ULONG tm_wday; +#define MSFC_TM_tm_wday_SIZE sizeof (ULONG) +#define MSFC_TM_tm_wday_ID 7 + + // + ULONG tm_yday; +#define MSFC_TM_tm_yday_SIZE sizeof (ULONG) +#define MSFC_TM_tm_yday_ID 8 + + // + ULONG tm_isdst; +#define MSFC_TM_tm_isdst_SIZE sizeof (ULONG) +#define MSFC_TM_tm_isdst_ID 9 } MSFC_TM, *PMSFC_TM; -#define MSFC_TM_SIZE (FIELD_OFFSET(MSFC_TM, tm_isdst) + MSFC_TM_tm_isdst_SIZE) +#define MSFC_TM_SIZE (FIELD_OFFSET(MSFC_TM, tm_isdst) + MSFC_TM_tm_isdst_SIZE) // GmDemoDriver - GmDemoDriver // GmDemoDriver Schema -#define GmDemoDriverGuid \ - { 0x33168f61,0x67a8,0x408e, { 0xb2,0x62,0x12,0x40,0xaa,0xc0,0x34,0x47 } } +#define GmDemoDriverGuid \ + { 0x33168f61, 0x67a8, 0x408e, \ + { 0xb2, 0x62, 0x12, 0x40, 0xaa, 0xc0, 0x34, 0x47 } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(GmDemoDriver_GUID, \ - 0x33168f61,0x67a8,0x408e,0xb2,0x62,0x12,0x40,0xaa,0xc0,0x34,0x47); + 0x33168f61, 0x67a8, 0x408e, 0xb2, 0x62, 0x12, 0x40,\ + 0xaa, 0xc0, 0x34, 0x47); #endif typedef struct _GmDemoDriver { - // The Answer - ULONG TheAnswer; - #define GmDemoDriver_TheAnswer_SIZE sizeof(ULONG) - #define GmDemoDriver_TheAnswer_ID 1 + // The Answer + ULONG TheAnswer; +#define GmDemoDriver_TheAnswer_SIZE sizeof (ULONG) +#define GmDemoDriver_TheAnswer_ID 1 - // The Next Answer - ULONG TheNextAnswer; - #define GmDemoDriver_TheNextAnswer_SIZE sizeof(ULONG) - #define GmDemoDriver_TheNextAnswer_ID 2 + // The Next Answer + ULONG TheNextAnswer; +#define GmDemoDriver_TheNextAnswer_SIZE sizeof (ULONG) +#define GmDemoDriver_TheNextAnswer_ID 2 - // SRBs seen - ULONG SRBsSeen; - #define GmDemoDriver_SRBsSeen_SIZE sizeof(ULONG) - #define GmDemoDriver_SRBsSeen_ID 3 + // SRBs seen + ULONG SRBsSeen; +#define GmDemoDriver_SRBsSeen_SIZE sizeof (ULONG) +#define GmDemoDriver_SRBsSeen_ID 3 - // WMI SRBs seen - ULONG WMISRBsSeen; - #define GmDemoDriver_WMISRBsSeen_SIZE sizeof(ULONG) - #define GmDemoDriver_WMISRBsSeen_ID 4 + // WMI SRBs seen + ULONG WMISRBsSeen; +#define GmDemoDriver_WMISRBsSeen_SIZE sizeof (ULONG) +#define GmDemoDriver_WMISRBsSeen_ID 4 } GmDemoDriver, *PGmDemoDriver; -#define GmDemoDriver_SIZE (FIELD_OFFSET(GmDemoDriver, WMISRBsSeen) + GmDemoDriver_WMISRBsSeen_SIZE) +#define GmDemoDriver_SIZE \ + (FIELD_OFFSET(GmDemoDriver, WMISRBsSeen) + \ + GmDemoDriver_WMISRBsSeen_SIZE) // GmDemoDriver2 - GmDemoDriver2 // GmDemoDriver Schema2 -#define GmDemoDriver2Guid \ - { 0x33168f62,0x67a8,0x408e, { 0xb2,0x62,0x12,0x40,0xaa,0xc0,0x34,0x47 } } +#define GmDemoDriver2Guid \ + { 0x33168f62, 0x67a8, 0x408e, \ + { 0xb2, 0x62, 0x12, 0x40, 0xaa, 0xc0, 0x34, 0x47 } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(GmDemoDriver2_GUID, \ - 0x33168f62,0x67a8,0x408e,0xb2,0x62,0x12,0x40,0xaa,0xc0,0x34,0x47); + 0x33168f62, 0x67a8, 0x408e, 0xb2, 0x62, 0x12, 0x40, \ + 0xaa, 0xc0, 0x34, 0x47); #endif typedef struct _GmDemoDriver2 { - // Number of array elements - ULONG NumberElements; - #define GmDemoDriver2_NumberElements_SIZE sizeof(ULONG) - #define GmDemoDriver2_NumberElements_ID 1 + // Number of array elements + ULONG NumberElements; +#define GmDemoDriver2_NumberElements_SIZE sizeof (ULONG) +#define GmDemoDriver2_NumberElements_ID 1 - // The array - ULONG UlongArray[1]; - #define GmDemoDriver2_UlongArray_ID 2 + // The array + ULONG UlongArray[1]; +#define GmDemoDriver2_UlongArray_ID 2 } GmDemoDriver2, *PGmDemoDriver2; // GmDemoDriverSrbActivity - GmDemoDriverSrbActivity // Performance counter class that keeps counts of SRBs -#define GmDemoDriverSrbActivityGuid \ - { 0x33168f63,0x67a8,0x408e, { 0xb2,0x62,0x12,0x40,0xaa,0xc0,0x34,0x47 } } +#define GmDemoDriverSrbActivityGuid \ + { 0x33168f63, 0x67a8, 0x408e, \ + { 0xb2, 0x62, 0x12, 0x40, 0xaa, 0xc0, 0x34, 0x47 } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(GmDemoDriverSrbActivity_GUID, \ - 0x33168f63,0x67a8,0x408e,0xb2,0x62,0x12,0x40,0xaa,0xc0,0x34,0x47); + 0x33168f63, 0x67a8, 0x408e, 0xb2, 0x62, 0x12, 0x40, \ + 0xaa, 0xc0, 0x34, 0x47); #endif typedef struct _GmDemoDriverSrbActivity { - // Count of CREATE SRBs received - ULONG TotalCreateSRBs; - #define GmDemoDriverSrbActivity_TotalCreateSRBs_SIZE sizeof(ULONG) - #define GmDemoDriverSrbActivity_TotalCreateSRBs_ID 1 + // Count of CREATE SRBs received + ULONG TotalCreateSRBs; +#define GmDemoDriverSrbActivity_TotalCreateSRBs_SIZE sizeof (ULONG) +#define GmDemoDriverSrbActivity_TotalCreateSRBs_ID 1 - // Count of CLOSE SRBs received - ULONG TotalCloseSRBs; - #define GmDemoDriverSrbActivity_TotalCloseSRBs_SIZE sizeof(ULONG) - #define GmDemoDriverSrbActivity_TotalCloseSRBs_ID 2 + // Count of CLOSE SRBs received + ULONG TotalCloseSRBs; +#define GmDemoDriverSrbActivity_TotalCloseSRBs_SIZE sizeof (ULONG) +#define GmDemoDriverSrbActivity_TotalCloseSRBs_ID 2 - // Count of IOCTL SRBs received - ULONG TotalIoCtlSrbs; - #define GmDemoDriverSrbActivity_TotalIoCtlSrbs_SIZE sizeof(ULONG) - #define GmDemoDriverSrbActivity_TotalIoCtlSrbs_ID 3 + // Count of IOCTL SRBs received + ULONG TotalIoCtlSrbs; +#define GmDemoDriverSrbActivity_TotalIoCtlSrbs_SIZE sizeof (ULONG) +#define GmDemoDriverSrbActivity_TotalIoCtlSrbs_ID 3 } GmDemoDriverSrbActivity, *PGmDemoDriverSrbActivity; -#define GmDemoDriverSrbActivity_SIZE (FIELD_OFFSET(GmDemoDriverSrbActivity, TotalIoCtlSrbs) + GmDemoDriverSrbActivity_TotalIoCtlSrbs_SIZE) +#define GmDemoDriverSrbActivity_SIZE \ + (FIELD_OFFSET(GmDemoDriverSrbActivity, TotalIoCtlSrbs) + \ + GmDemoDriverSrbActivity_TotalIoCtlSrbs_SIZE) // GmDrvDrvMethod - GmDrvDrvMethod // WMI method -#define GmDrvDrvMethodGuid \ - { 0x33168f64,0x67a8,0x408e, { 0xb2,0x62,0x12,0x40,0xaa,0xc0,0x34,0x47 } } +#define GmDrvDrvMethodGuid \ + { 0x33168f64, 0x67a8, 0x408e, \ + { 0xb2, 0x62, 0x12, 0x40, 0xaa, 0xc0, 0x34, 0x47 } } #if ! (defined(MIDL_PASS)) DEFINE_GUID(GmDrvDrvMethod_GUID, \ - 0x33168f64,0x67a8,0x408e,0xb2,0x62,0x12,0x40,0xaa,0xc0,0x34,0x47); + 0x33168f64, 0x67a8, 0x408e, 0xb2, 0x62, 0x12, 0x40, \ + 0xaa, 0xc0, 0x34, 0x47); #endif // // Method id definitions for GmDrvDrvMethod -#define GmDrvDemoMethod1 1 +#define GmDrvDemoMethod1 1 typedef struct _GmDrvDemoMethod1_IN { - // - ULONG inDatum; - #define GmDrvDemoMethod1_IN_inDatum_SIZE sizeof(ULONG) - #define GmDrvDemoMethod1_IN_inDatum_ID 1 + // + ULONG inDatum; +#define GmDrvDemoMethod1_IN_inDatum_SIZE sizeof (ULONG) +#define GmDrvDemoMethod1_IN_inDatum_ID 1 } GmDrvDemoMethod1_IN, *PGmDrvDemoMethod1_IN; -#define GmDrvDemoMethod1_IN_SIZE (FIELD_OFFSET(GmDrvDemoMethod1_IN, inDatum) + GmDrvDemoMethod1_IN_inDatum_SIZE) +#define GmDrvDemoMethod1_IN_SIZE \ + (FIELD_OFFSET(GmDrvDemoMethod1_IN, inDatum) + \ + GmDrvDemoMethod1_IN_inDatum_SIZE) typedef struct _GmDrvDemoMethod1_OUT { - // - ULONG outDatum; - #define GmDrvDemoMethod1_OUT_outDatum_SIZE sizeof(ULONG) - #define GmDrvDemoMethod1_OUT_outDatum_ID 2 + // + ULONG outDatum; +#define GmDrvDemoMethod1_OUT_outDatum_SIZE sizeof (ULONG) +#define GmDrvDemoMethod1_OUT_outDatum_ID 2 } GmDrvDemoMethod1_OUT, *PGmDrvDemoMethod1_OUT; -#define GmDrvDemoMethod1_OUT_SIZE (FIELD_OFFSET(GmDrvDemoMethod1_OUT, outDatum) + GmDrvDemoMethod1_OUT_outDatum_SIZE) +#define GmDrvDemoMethod1_OUT_SIZE \ + (FIELD_OFFSET(GmDrvDemoMethod1_OUT, outDatum) + \ + GmDrvDemoMethod1_OUT_outDatum_SIZE) -#define GmDrvDemoMethod2 2 +#define GmDrvDemoMethod2 2 typedef struct _GmDrvDemoMethod2_IN { - // - ULONG inDatum1; - #define GmDrvDemoMethod2_IN_inDatum1_SIZE sizeof(ULONG) - #define GmDrvDemoMethod2_IN_inDatum1_ID 1 + // + ULONG inDatum1; +#define GmDrvDemoMethod2_IN_inDatum1_SIZE sizeof (ULONG) +#define GmDrvDemoMethod2_IN_inDatum1_ID 1 - // - ULONG inDatum2; - #define GmDrvDemoMethod2_IN_inDatum2_SIZE sizeof(ULONG) - #define GmDrvDemoMethod2_IN_inDatum2_ID 2 + // + ULONG inDatum2; +#define GmDrvDemoMethod2_IN_inDatum2_SIZE sizeof (ULONG) +#define GmDrvDemoMethod2_IN_inDatum2_ID 2 } GmDrvDemoMethod2_IN, *PGmDrvDemoMethod2_IN; -#define GmDrvDemoMethod2_IN_SIZE (FIELD_OFFSET(GmDrvDemoMethod2_IN, inDatum2) + GmDrvDemoMethod2_IN_inDatum2_SIZE) +#define GmDrvDemoMethod2_IN_SIZE \ + (FIELD_OFFSET(GmDrvDemoMethod2_IN, inDatum2) + \ + GmDrvDemoMethod2_IN_inDatum2_SIZE) typedef struct _GmDrvDemoMethod2_OUT { - // - ULONG outDatum1; - #define GmDrvDemoMethod2_OUT_outDatum1_SIZE sizeof(ULONG) - #define GmDrvDemoMethod2_OUT_outDatum1_ID 3 + // + ULONG outDatum1; +#define GmDrvDemoMethod2_OUT_outDatum1_SIZE sizeof (ULONG) +#define GmDrvDemoMethod2_OUT_outDatum1_ID 3 } GmDrvDemoMethod2_OUT, *PGmDrvDemoMethod2_OUT; -#define GmDrvDemoMethod2_OUT_SIZE (FIELD_OFFSET(GmDrvDemoMethod2_OUT, outDatum1) + GmDrvDemoMethod2_OUT_outDatum1_SIZE) +#define GmDrvDemoMethod2_OUT_SIZE \ + (FIELD_OFFSET(GmDrvDemoMethod2_OUT, outDatum1) + \ + GmDrvDemoMethod2_OUT_outDatum1_SIZE) -#define GmDrvDemoMethod3 3 +#define GmDrvDemoMethod3 3 typedef struct _GmDrvDemoMethod3_IN { - // - ULONG inDatum1; - #define GmDrvDemoMethod3_IN_inDatum1_SIZE sizeof(ULONG) - #define GmDrvDemoMethod3_IN_inDatum1_ID 1 + // + ULONG inDatum1; +#define GmDrvDemoMethod3_IN_inDatum1_SIZE sizeof (ULONG) +#define GmDrvDemoMethod3_IN_inDatum1_ID 1 - // - ULONG inDatum2; - #define GmDrvDemoMethod3_IN_inDatum2_SIZE sizeof(ULONG) - #define GmDrvDemoMethod3_IN_inDatum2_ID 2 + // + ULONG inDatum2; +#define GmDrvDemoMethod3_IN_inDatum2_SIZE sizeof (ULONG) +#define GmDrvDemoMethod3_IN_inDatum2_ID 2 } GmDrvDemoMethod3_IN, *PGmDrvDemoMethod3_IN; -#define GmDrvDemoMethod3_IN_SIZE (FIELD_OFFSET(GmDrvDemoMethod3_IN, inDatum2) + GmDrvDemoMethod3_IN_inDatum2_SIZE) +#define GmDrvDemoMethod3_IN_SIZE \ + (FIELD_OFFSET(GmDrvDemoMethod3_IN, inDatum2) + \ + GmDrvDemoMethod3_IN_inDatum2_SIZE) typedef struct _GmDrvDemoMethod3_OUT { - // - ULONG outDatum1; - #define GmDrvDemoMethod3_OUT_outDatum1_SIZE sizeof(ULONG) - #define GmDrvDemoMethod3_OUT_outDatum1_ID 3 + // + ULONG outDatum1; +#define GmDrvDemoMethod3_OUT_outDatum1_SIZE sizeof (ULONG) +#define GmDrvDemoMethod3_OUT_outDatum1_ID 3 - // - ULONG outDatum2; - #define GmDrvDemoMethod3_OUT_outDatum2_SIZE sizeof(ULONG) - #define GmDrvDemoMethod3_OUT_outDatum2_ID 4 + // + ULONG outDatum2; +#define GmDrvDemoMethod3_OUT_outDatum2_SIZE sizeof (ULONG) +#define GmDrvDemoMethod3_OUT_outDatum2_ID 4 } GmDrvDemoMethod3_OUT, *PGmDrvDemoMethod3_OUT; -#define GmDrvDemoMethod3_OUT_SIZE (FIELD_OFFSET(GmDrvDemoMethod3_OUT, outDatum2) + GmDrvDemoMethod3_OUT_outDatum2_SIZE) +#define GmDrvDemoMethod3_OUT_SIZE \ + (FIELD_OFFSET(GmDrvDemoMethod3_OUT, outDatum2) + \ + GmDrvDemoMethod3_OUT_outDatum2_SIZE) #endif diff --git a/include/os/windows/zfs/sys/zconf.h b/include/os/windows/zfs/sys/zconf.h index 6b9637f469b..27bf8175251 100644 --- a/include/os/windows/zfs/sys/zconf.h +++ b/include/os/windows/zfs/sys/zconf.h @@ -90,8 +90,8 @@ extern "C" { #define inflateBack z_inflateBack #define inflateBackEnd z_inflateBackEnd #define compress zz_compress -//#define compress2 zz_compress2 -//#define uncompress zz_uncompress +// #define compress2 zz_compress2 +// #define uncompress zz_uncompress #define adler32 z_adler32 #define crc32 z_crc32 #define get_crc_table z_get_crc_table diff --git a/include/os/windows/zfs/sys/zfs_context_os.h b/include/os/windows/zfs/sys/zfs_context_os.h index 15a15c55917..54fed391e63 100644 --- a/include/os/windows/zfs/sys/zfs_context_os.h +++ b/include/os/windows/zfs/sys/zfs_context_os.h @@ -69,7 +69,7 @@ extern PDRIVER_OBJECT WIN_DriverObject; * Ok this is pretty gross - until we can get rid of it from lua - * it works as long as it doesn't parse strings */ -#define sscanf sscanf_s +#define sscanf sscanf_s #define DIRENT_RECLEN(namelen) (((namelen) + 7) & ~7) diff --git a/include/os/windows/zfs/sys/zfs_ctldir.h b/include/os/windows/zfs/sys/zfs_ctldir.h index 5d8441bd1d3..f24b00b873d 100644 --- a/include/os/windows/zfs/sys/zfs_ctldir.h +++ b/include/os/windows/zfs/sys/zfs_ctldir.h @@ -51,63 +51,63 @@ struct path; extern int zfs_expire_snapshot; - // Fix me Windows. - we don't want these, remove them - // once we Windowsify this file. - struct vnop_readdir_args { - struct vnode *a_vp; - struct uio *a_uio; - int a_flags; - int *a_eofflag; - int *a_numdirent; - }; - - struct vnop_getattr_args { - struct vnode *a_vp; - struct vnode_vattr *a_vap; - }; - - struct vnop_open_args { - struct vnode *a_vp; - int a_mode; - }; - - struct vnop_close_args { - struct vnode *a_vp; - int a_fflag; - }; - - struct vnop_access_args { - struct vnodeop_desc *a_desc; - struct vnode a_vp; - int a_action; - }; - - struct vnop_lookup_args { - struct vnode *a_dvp; - struct vnode **a_vpp; - struct componentname *a_cnp; - }; - - struct vnop_mkdir_args { - struct vnode *a_dvp; - struct vnode **a_vpp; - struct componentname *a_cnp; - struct vnode_vattr *a_vap; - }; - - struct vnop_rmdir_args { - struct vnode *a_dvp; - struct vnode *a_vp; - struct componentname *a_cnp; - }; - - struct vnop_reclaim_args { - struct vnode *a_vp; - }; - - struct vnop_inactive_args { - struct vnode *a_vp; - }; +// Fix me Windows. - we don't want these, remove them +// once we Windowsify this file. +struct vnop_readdir_args { + struct vnode *a_vp; + struct uio *a_uio; + int a_flags; + int *a_eofflag; + int *a_numdirent; +}; + +struct vnop_getattr_args { + struct vnode *a_vp; + struct vnode_vattr *a_vap; +}; + +struct vnop_open_args { + struct vnode *a_vp; + int a_mode; +}; + +struct vnop_close_args { + struct vnode *a_vp; + int a_fflag; +}; + +struct vnop_access_args { + struct vnodeop_desc *a_desc; + struct vnode a_vp; + int a_action; +}; + +struct vnop_lookup_args { + struct vnode *a_dvp; + struct vnode **a_vpp; + struct componentname *a_cnp; +}; + +struct vnop_mkdir_args { + struct vnode *a_dvp; + struct vnode **a_vpp; + struct componentname *a_cnp; + struct vnode_vattr *a_vap; +}; + +struct vnop_rmdir_args { + struct vnode *a_dvp; + struct vnode *a_vp; + struct componentname *a_cnp; +}; + +struct vnop_reclaim_args { + struct vnode *a_vp; +}; + +struct vnop_inactive_args { + struct vnode *a_vp; +}; /* zfsctl generic functions */ diff --git a/include/os/windows/zfs/sys/zfs_ioctl_compat.h b/include/os/windows/zfs/sys/zfs_ioctl_compat.h index ca156ee3ad6..dee50aa7f6c 100644 --- a/include/os/windows/zfs/sys/zfs_ioctl_compat.h +++ b/include/os/windows/zfs/sys/zfs_ioctl_compat.h @@ -40,8 +40,8 @@ extern "C" { #endif -#define ZFSIOCTL_TYPE 40000 -#define ZFSIOCTL_BASE 0x800 +#define ZFSIOCTL_TYPE 40000 +#define ZFSIOCTL_BASE 0x800 #define DEVICE_FUNCTION_FROM_CTL_CODE(X) (((X)>>2) & 0x1fff) diff --git a/include/os/windows/zfs/sys/zfs_mount.h b/include/os/windows/zfs/sys/zfs_mount.h index c9176a0d521..7c2d749c086 100644 --- a/include/os/windows/zfs/sys/zfs_mount.h +++ b/include/os/windows/zfs/sys/zfs_mount.h @@ -1,8 +1,29 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ + #ifndef _SYS_ZFS_MOUNT_H_ -#define _SYS_ZFS_MOUNT_H_ +#define _SYS_ZFS_MOUNT_H_ struct zfs_mount_args { - const char *fspec; /* block special device to mount */ + const char *fspec; /* block special device to mount */ int mflag; char *optptr; int optlen; diff --git a/include/os/windows/zfs/sys/zfs_vfsops_os.h b/include/os/windows/zfs/sys/zfs_vfsops_os.h index e3394cbbba0..b20909b7238 100644 --- a/include/os/windows/zfs/sys/zfs_vfsops_os.h +++ b/include/os/windows/zfs/sys/zfs_vfsops_os.h @@ -139,12 +139,12 @@ struct zfsvfs { #define ZFS_OBJ_MTX_SZ 64 struct hardlinks_struct { - avl_node_t hl_node; - avl_node_t hl_node_linkid; - uint64_t hl_parent; // parentid of entry - uint64_t hl_fileid; // the fileid (z_id) for vget - uint32_t hl_linkid; // the linkid, persistent over renames - char hl_name[PATH_MAX]; // cached name for vget + avl_node_t hl_node; + avl_node_t hl_node_linkid; + uint64_t hl_parent; // parentid of entry + uint64_t hl_fileid; // the fileid (z_id) for vget + uint32_t hl_linkid; // the linkid, persistent over renames + char hl_name[PATH_MAX]; // cached name for vget }; typedef struct hardlinks_struct hardlinks_t; diff --git a/include/os/windows/zfs/sys/zfs_vnops.h b/include/os/windows/zfs/sys/zfs_vnops.h index 3a45480d75c..396eea6455a 100644 --- a/include/os/windows/zfs/sys/zfs_vnops.h +++ b/include/os/windows/zfs/sys/zfs_vnops.h @@ -101,7 +101,7 @@ typedef struct attrinfo { void **ai_attrbufpp; void **ai_varbufpp; void *ai_varbufend; - //vfs_context_t ai_context; + // vfs_context_t ai_context; } attrinfo_t; /* @@ -170,7 +170,8 @@ extern int zfs_lookup(znode_t *dzp, char *nm, znode_t **zpp, int flags, cred_t *cr, int *direntflags, struct componentname *realpnp); extern int zfs_ioctl(vnode_t *vp, ulong_t com, intptr_t data, int flag, cred_t *cred, int *rvalp, caller_context_t *ct); -extern int zfs_readdir(vnode_t *vp, uio_t *uio, cred_t *cr, zfs_dirlist_t *zccb, int flags, int dirlisttype, int *a_numdirent); +extern int zfs_readdir(vnode_t *vp, uio_t *uio, cred_t *cr, + zfs_dirlist_t *zccb, int flags, int dirlisttype, int *a_numdirent); extern int zfs_fsync(znode_t *zp, int syncflag, cred_t *cr); extern int zfs_getattr(vnode_t *vp, vattr_t *vap, int flags, @@ -196,9 +197,8 @@ extern int zfs_ioflags(int ap_ioflag); extern int zfs_getattr_znode_unlocked(struct vnode *vp, vattr_t *vap); extern int ace_trivial_common(void *acep, int aclcnt, uint64_t (*walk)(void *, uint64_t, int aclcnt, - uint16_t *, uint16_t *, uint32_t *)); -//extern void acl_trivial_access_masks(mode_t mode, boolean_t isdir, -// trivial_acl_t *masks); + uint16_t *, uint16_t *, uint32_t *)); + extern int zpl_obtain_xattr(struct znode *, const char *name, mode_t mode, cred_t *cr, struct vnode **vpp, int flag); diff --git a/include/os/windows/zfs/sys/zfs_windows.h b/include/os/windows/zfs/sys/zfs_windows.h index e202b8dfd35..9dc383c795e 100644 --- a/include/os/windows/zfs/sys/zfs_windows.h +++ b/include/os/windows/zfs/sys/zfs_windows.h @@ -1,29 +1,29 @@ /* -* CDDL HEADER START -* -* The contents of this file are subject to the terms of the -* Common Development and Distribution License (the "License"). -* You may not use this file except in compliance with the License. -* -* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE -* or http://www.opensolaris.org/os/licensing. -* See the License for the specific language governing permissions -* and limitations under the License. -* -* When distributing Covered Code, include this CDDL HEADER in each -* file and include the License file at usr/src/OPENSOLARIS.LICENSE. -* If applicable, add the following below this CDDL HEADER, with the -* fields enclosed by brackets "[]" replaced with your own identifying -* information: Portions Copyright [yyyy] [name of copyright owner] -* -* CDDL HEADER END -*/ + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ /* -* Copyright (c) 2017 Jorgen Lundman -*/ + * Copyright (c) 2017 Jorgen Lundman + */ #ifndef SYS_WINDOWS_H_INCLUDED -#define SYS_WINDOWS_H_INCLUDED +#define SYS_WINDOWS_H_INCLUDED #include @@ -31,23 +31,23 @@ extern PDEVICE_OBJECT ioctlDeviceObject; extern PDEVICE_OBJECT fsDiskDeviceObject; -#define ZFS_SERIAL (ULONG)'wZFS' -#define VOLUME_LABEL L"ZFS" +#define ZFS_SERIAL (ULONG)'wZFS' +#define VOLUME_LABEL L"ZFS" DECLARE_GLOBAL_CONST_UNICODE_STRING(ZFSVolumeName, VOLUME_LABEL); // We have to remember "query directory" related items, like index and // search pattern. This is attached in IRP_MJ_CREATE to fscontext2 -#define ZFS_DIRLIST_MAGIC 0x6582feac +#define ZFS_DIRLIST_MAGIC 0x6582feac struct zfs_dirlist { - uint32_t magic; // Identifier - uint32_t dir_eof; // Directory listing completed? + uint32_t magic; // Identifier + uint32_t dir_eof; // Directory listing completed? uint64_t uio_offset; // Directory list offset - uint64_t ea_index; // EA list offset + uint64_t ea_index; // EA list offset uint32_t deleteonclose; // Marked for deletion - uint32_t ContainsWildCards; // searchname has wildcards - UNICODE_STRING searchname; // Search pattern + uint32_t ContainsWildCards; // searchname has wildcards + UNICODE_STRING searchname; // Search pattern }; typedef struct zfs_dirlist zfs_dirlist_t; @@ -56,25 +56,28 @@ extern uint64_t zfs_module_busy; extern CACHE_MANAGER_CALLBACKS CacheManagerCallbacks; -extern NTSTATUS dev_ioctl(PDEVICE_OBJECT DeviceObject, ULONG ControlCode, PVOID InputBuffer, ULONG InputBufferSize, - PVOID OutputBuffer, ULONG OutputBufferSize, BOOLEAN Override, IO_STATUS_BLOCK* iosb); +extern NTSTATUS dev_ioctl(PDEVICE_OBJECT DeviceObject, ULONG ControlCode, + PVOID InputBuffer, ULONG InputBufferSize, PVOID OutputBuffer, + ULONG OutputBufferSize, BOOLEAN Override, IO_STATUS_BLOCK* iosb); extern int zfs_windows_mount(zfs_cmd_t *zc); extern int zfs_windows_unmount(zfs_cmd_t *zc); extern NTSTATUS zfsdev_ioctl(PDEVICE_OBJECT DeviceObject, PIRP Irp, int flag); extern void zfs_windows_vnops_callback(PDEVICE_OBJECT deviceObject); -extern void zfs_send_notify(zfsvfs_t *zfsvfs, char *name, int, ULONG FilterMatch, ULONG Action); -extern void zfs_send_notify_stream(zfsvfs_t *, char *, int, ULONG, ULONG, char *stream); +extern void zfs_send_notify(zfsvfs_t *zfsvfs, char *name, int, + ULONG FilterMatch, ULONG Action); +extern void zfs_send_notify_stream(zfsvfs_t *, char *, int, ULONG, + ULONG, char *stream); extern void zfs_set_security(struct vnode *vp, struct vnode *dvp); extern uint64_t zfs_sid2uid(SID *sid); BOOLEAN vattr_apply_lx_ea(vattr_t *vap, PFILE_FULL_EA_INFORMATION ea); -NTSTATUS vnode_apply_eas(struct vnode *vp, PFILE_FULL_EA_INFORMATION eas, ULONG eaLength, PULONG pEaErrorOffset); +NTSTATUS vnode_apply_eas(struct vnode *vp, PFILE_FULL_EA_INFORMATION eas, + ULONG eaLength, PULONG pEaErrorOffset); /* Main function to handle all VFS "vnops" */ - extern _Function_class_(DRIVER_DISPATCH) NTSTATUS - dispatcher(_In_ PDEVICE_OBJECT DeviceObject, - _Inout_ PIRP Irp); +extern _Function_class_(DRIVER_DISPATCH) NTSTATUS + dispatcher(_In_ PDEVICE_OBJECT DeviceObject, _Inout_ PIRP Irp); extern NTSTATUS zfsdev_open(dev_t dev, PIRP Irp); extern NTSTATUS zfsdev_release(dev_t dev, PIRP Irp); @@ -82,9 +85,11 @@ extern NTSTATUS zfsdev_release(dev_t dev, PIRP Irp); extern int zfs_vnop_recycle(znode_t *zp, int force); extern uint64_t zfs_blksz(znode_t *zp); -extern int zfs_vnop_mount(PDEVICE_OBJECT DiskDevice, PIRP Irp, PIO_STACK_LOCATION IrpSp); +extern int zfs_vnop_mount(PDEVICE_OBJECT DiskDevice, PIRP Irp, + PIO_STACK_LOCATION IrpSp); -extern int zfs_build_path(znode_t *start_zp, znode_t *start_parent, char **fullpath, uint32_t *returnsize, uint32_t *start_zp_offset); +extern int zfs_build_path(znode_t *start_zp, znode_t *start_parent, + char **fullpath, uint32_t *returnsize, uint32_t *start_zp_offset); extern int xattr_protected(char *name); extern int xattr_stream(char *name); @@ -99,68 +104,85 @@ extern int AsciiStringToUnicodeString(char *in, PUNICODE_STRING out); extern void FreeUnicodeString(PUNICODE_STRING s); extern int zfs_vfs_uuid_gen(const char *osname, uuid_t uuid); extern int zfs_vfs_uuid_unparse(uuid_t uuid, char *dst); -extern int zfs_vnop_ioctl_fullfsync(struct vnode *, vfs_context_t *, zfsvfs_t *); +extern int zfs_vnop_ioctl_fullfsync(struct vnode *, vfs_context_t *, + zfsvfs_t *); extern int zfs_setwinflags(znode_t *zp, uint32_t winflags); extern uint32_t zfs_getwinflags(znode_t *zp); extern NTSTATUS zfs_setunlink(FILE_OBJECT *fo, vnode_t *dvp); extern int zfs_find_dvp_vp(zfsvfs_t *, char *, int finalpartmaynotexist, - int finalpartmustnotexist, char **lastname, struct vnode **dvpp, - struct vnode **vpp, int flags); + int finalpartmustnotexist, char **lastname, struct vnode **dvpp, + struct vnode **vpp, int flags); /* IRP_MJ_SET_INFORMATION helpers */ -extern NTSTATUS file_disposition_information(PDEVICE_OBJECT, PIRP, PIO_STACK_LOCATION); -extern NTSTATUS file_disposition_information_ex(PDEVICE_OBJECT, PIRP, PIO_STACK_LOCATION); -extern NTSTATUS file_endoffile_information(PDEVICE_OBJECT, PIRP, PIO_STACK_LOCATION); -extern NTSTATUS file_link_information(PDEVICE_OBJECT, PIRP, PIO_STACK_LOCATION); -extern NTSTATUS file_rename_information(PDEVICE_OBJECT, PIRP, PIO_STACK_LOCATION); +extern NTSTATUS file_disposition_information(PDEVICE_OBJECT, PIRP, + PIO_STACK_LOCATION); +extern NTSTATUS file_disposition_information_ex(PDEVICE_OBJECT, PIRP, + PIO_STACK_LOCATION); +extern NTSTATUS file_endoffile_information(PDEVICE_OBJECT, PIRP, + PIO_STACK_LOCATION); +extern NTSTATUS file_link_information(PDEVICE_OBJECT, PIRP, + PIO_STACK_LOCATION); +extern NTSTATUS file_rename_information(PDEVICE_OBJECT, PIRP, + PIO_STACK_LOCATION); /* IRP_MJ_GET_INFORMATION helpers */ extern NTSTATUS file_basic_information(PDEVICE_OBJECT, PIRP, PIO_STACK_LOCATION, FILE_BASIC_INFORMATION *); -extern NTSTATUS file_standard_information(PDEVICE_OBJECT, PIRP, PIO_STACK_LOCATION, - FILE_STANDARD_INFORMATION *); -extern NTSTATUS file_position_information(PDEVICE_OBJECT, PIRP, PIO_STACK_LOCATION, - FILE_POSITION_INFORMATION *); +extern NTSTATUS file_standard_information(PDEVICE_OBJECT, PIRP, + PIO_STACK_LOCATION, FILE_STANDARD_INFORMATION *); +extern NTSTATUS file_position_information(PDEVICE_OBJECT, PIRP, + PIO_STACK_LOCATION, FILE_POSITION_INFORMATION *); extern NTSTATUS file_ea_information(PDEVICE_OBJECT, PIRP, PIO_STACK_LOCATION, FILE_EA_INFORMATION *); -extern NTSTATUS file_network_open_information(PDEVICE_OBJECT, PIRP, PIO_STACK_LOCATION, - FILE_NETWORK_OPEN_INFORMATION *); -extern NTSTATUS file_standard_link_information(PDEVICE_OBJECT, PIRP, PIO_STACK_LOCATION, - FILE_STANDARD_LINK_INFORMATION *); +extern NTSTATUS file_network_open_information(PDEVICE_OBJECT, PIRP, + PIO_STACK_LOCATION, FILE_NETWORK_OPEN_INFORMATION *); +extern NTSTATUS file_standard_link_information(PDEVICE_OBJECT, PIRP, + PIO_STACK_LOCATION, FILE_STANDARD_LINK_INFORMATION *); extern NTSTATUS file_id_information(PDEVICE_OBJECT, PIRP, PIO_STACK_LOCATION, FILE_ID_INFORMATION *); -extern NTSTATUS file_case_sensitive_information(PDEVICE_OBJECT, PIRP, PIO_STACK_LOCATION, - FILE_CASE_SENSITIVE_INFORMATION *); +extern NTSTATUS file_case_sensitive_information(PDEVICE_OBJECT, PIRP, + PIO_STACK_LOCATION, FILE_CASE_SENSITIVE_INFORMATION *); extern NTSTATUS file_stat_information(PDEVICE_OBJECT, PIRP, PIO_STACK_LOCATION, FILE_STAT_INFORMATION *); -extern NTSTATUS file_stat_lx_information(PDEVICE_OBJECT, PIRP, PIO_STACK_LOCATION, - FILE_STAT_LX_INFORMATION *); +extern NTSTATUS file_stat_lx_information(PDEVICE_OBJECT, PIRP, + PIO_STACK_LOCATION, FILE_STAT_LX_INFORMATION *); extern NTSTATUS file_name_information(PDEVICE_OBJECT, PIRP, PIO_STACK_LOCATION, FILE_NAME_INFORMATION *, PULONG usedspace, int normalize); -extern NTSTATUS file_remote_protocol_information(PDEVICE_OBJECT, PIRP, PIO_STACK_LOCATION, - FILE_REMOTE_PROTOCOL_INFORMATION *); -extern NTSTATUS file_stream_information(PDEVICE_OBJECT, PIRP, PIO_STACK_LOCATION, - FILE_STREAM_INFORMATION *, PULONG usedspace); -extern NTSTATUS file_attribute_tag_information(PDEVICE_OBJECT, PIRP, PIO_STACK_LOCATION, - FILE_ATTRIBUTE_TAG_INFORMATION *tag); -extern NTSTATUS file_internal_information(PDEVICE_OBJECT, PIRP, PIO_STACK_LOCATION, - FILE_INTERNAL_INFORMATION *infernal); +extern NTSTATUS file_remote_protocol_information(PDEVICE_OBJECT, PIRP, + PIO_STACK_LOCATION, FILE_REMOTE_PROTOCOL_INFORMATION *); +extern NTSTATUS file_stream_information(PDEVICE_OBJECT, PIRP, + PIO_STACK_LOCATION, FILE_STREAM_INFORMATION *, PULONG usedspace); +extern NTSTATUS file_attribute_tag_information(PDEVICE_OBJECT, PIRP, + PIO_STACK_LOCATION, FILE_ATTRIBUTE_TAG_INFORMATION *tag); +extern NTSTATUS file_internal_information(PDEVICE_OBJECT, PIRP, + PIO_STACK_LOCATION, FILE_INTERNAL_INFORMATION *infernal); /* IRP_MJ_DEVICE_CONTROL helpers */ extern NTSTATUS QueryCapabilities(PDEVICE_OBJECT, PIRP, PIO_STACK_LOCATION); -extern NTSTATUS ioctl_query_device_name(PDEVICE_OBJECT, PIRP, PIO_STACK_LOCATION); -extern NTSTATUS ioctl_disk_get_drive_geometry(PDEVICE_OBJECT, PIRP, PIO_STACK_LOCATION); -extern NTSTATUS ioctl_disk_get_drive_geometry_ex(PDEVICE_OBJECT, PIRP, PIO_STACK_LOCATION); -extern NTSTATUS ioctl_disk_get_partition_info(PDEVICE_OBJECT, PIRP, PIO_STACK_LOCATION); -extern NTSTATUS ioctl_disk_get_partition_info_ex(PDEVICE_OBJECT, PIRP, PIO_STACK_LOCATION); -extern NTSTATUS ioctl_disk_get_length_info(PDEVICE_OBJECT, PIRP, PIO_STACK_LOCATION); -extern NTSTATUS ioctl_volume_is_io_capable(PDEVICE_OBJECT, PIRP, PIO_STACK_LOCATION); -extern NTSTATUS ioctl_storage_get_hotplug_info(PDEVICE_OBJECT, PIRP, PIO_STACK_LOCATION); -extern NTSTATUS ioctl_storage_query_property(PDEVICE_OBJECT, PIRP, PIO_STACK_LOCATION); +extern NTSTATUS ioctl_query_device_name(PDEVICE_OBJECT, PIRP, + PIO_STACK_LOCATION); +extern NTSTATUS ioctl_disk_get_drive_geometry(PDEVICE_OBJECT, PIRP, + PIO_STACK_LOCATION); +extern NTSTATUS ioctl_disk_get_drive_geometry_ex(PDEVICE_OBJECT, PIRP, + PIO_STACK_LOCATION); +extern NTSTATUS ioctl_disk_get_partition_info(PDEVICE_OBJECT, PIRP, + PIO_STACK_LOCATION); +extern NTSTATUS ioctl_disk_get_partition_info_ex(PDEVICE_OBJECT, PIRP, + PIO_STACK_LOCATION); +extern NTSTATUS ioctl_disk_get_length_info(PDEVICE_OBJECT, PIRP, + PIO_STACK_LOCATION); +extern NTSTATUS ioctl_volume_is_io_capable(PDEVICE_OBJECT, PIRP, + PIO_STACK_LOCATION); +extern NTSTATUS ioctl_storage_get_hotplug_info(PDEVICE_OBJECT, PIRP, + PIO_STACK_LOCATION); +extern NTSTATUS ioctl_storage_query_property(PDEVICE_OBJECT, PIRP, + PIO_STACK_LOCATION); extern NTSTATUS ioctl_query_unique_id(PDEVICE_OBJECT, PIRP, PIO_STACK_LOCATION); -extern NTSTATUS ioctl_mountdev_query_suggested_link_name(PDEVICE_OBJECT, PIRP, PIO_STACK_LOCATION); -extern NTSTATUS ioctl_mountdev_query_stable_guid(PDEVICE_OBJECT, PIRP, PIO_STACK_LOCATION); -extern NTSTATUS ioctl_query_stable_guid(PDEVICE_OBJECT, PIRP, PIO_STACK_LOCATION); - +extern NTSTATUS ioctl_mountdev_query_suggested_link_name(PDEVICE_OBJECT, PIRP, + PIO_STACK_LOCATION); +extern NTSTATUS ioctl_mountdev_query_stable_guid(PDEVICE_OBJECT, PIRP, + PIO_STACK_LOCATION); +extern NTSTATUS ioctl_query_stable_guid(PDEVICE_OBJECT, PIRP, + PIO_STACK_LOCATION); #endif diff --git a/include/os/windows/zfs/sys/zlib.h b/include/os/windows/zfs/sys/zlib.h index 9b971a0f572..5c44a53ec85 100644 --- a/include/os/windows/zfs/sys/zlib.h +++ b/include/os/windows/zfs/sys/zlib.h @@ -1,35 +1,36 @@ -/* zlib.h -- interface of the 'zlib' general purpose compression library - version 1.2.3, July 18th, 2005 - - Copyright (C) 1995-2005 Jean-loup Gailly and Mark Adler - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jean-loup Gailly Mark Adler - jloup@gzip.org madler@alumni.caltech.edu - - - The data format used by the zlib library is described by RFCs (Request for - Comments) 1950 to 1952 in the files http://www.ietf.org/rfc/rfc1950.txt - (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format). -*/ +/* + * zlib.h -- interface of the 'zlib' general purpose compression library + * version 1.2.3, July 18th, 2005 + * + * Copyright (C) 1995-2005 Jean-loup Gailly and Mark Adler + * + * This software is provided 'as-is', without any express or implied + * warranty. In no event will the authors be held liable for any damages + * arising from the use of this software. + * + * Permission is granted to anyone to use this software for any purpose, + * including commercial applications, and to alter it and redistribute it + * freely, subject to the following restrictions: + * + * 1. The origin of this software must not be misrepresented; you must not + * claim that you wrote the original software. If you use this software + * in a product, an acknowledgment in the product documentation would be + * appreciated but is not required. + * 2. Altered source versions must be plainly marked as such, and must not be + * misrepresented as being the original software. + * 3. This notice may not be removed or altered from any source distribution. + * + * Jean-loup Gailly Mark Adler + * jloup@gzip.org madler@alumni.caltech.edu + * + * + * The data format used by the zlib library is described by RFCs (Request for + * Comments) 1950 to 1952 in the files http://www.ietf.org/rfc/rfc1950.txt + * (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format). + */ #ifndef _ZLIB_H -#define _ZLIB_H +#define _ZLIB_H #pragma ident "%Z%%M% %I% %E% SMI" @@ -39,42 +40,42 @@ extern "C" { #endif -#define ZLIB_VERSION "1.2.3" -#define ZLIB_VERNUM 0x1230 +#define ZLIB_VERSION "1.2.3" +#define ZLIB_VERNUM 0x1230 /* - The 'zlib' compression library provides in-memory compression and - decompression functions, including integrity checks of the uncompressed - data. This version of the library supports only one compression method - (deflation) but other algorithms will be added later and will have the same - stream interface. - - Compression can be done in a single step if the buffers are large - enough (for example if an input file is mmap'ed), or can be done by - repeated calls of the compression function. In the latter case, the - application must provide more input and/or consume the output - (providing more output space) before each call. - - The compressed data format used by default by the in-memory functions is - the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped - around a deflate stream, which is itself documented in RFC 1951. - - The library also supports reading and writing files in gzip (.gz) format - with an interface similar to that of stdio using the functions that start - with "gz". The gzip format is different from the zlib format. gzip is a - gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. - - This library can optionally read and write gzip streams in memory as well. - - The zlib format was designed to be compact and fast for use in memory - and on communications channels. The gzip format was designed for single- - file compression on file systems, has a larger header than zlib to maintain - directory information, and uses a different, slower check method than zlib. - - The library does not install any signal handler. The decoder checks - the consistency of the compressed data, so the library should never - crash even in case of corrupted input. -*/ + * The 'zlib' compression library provides in-memory compression and + * decompression functions, including integrity checks of the uncompressed + * data. This version of the library supports only one compression method + * (deflation) but other algorithms will be added later and will have the same + * stream interface. + * + * Compression can be done in a single step if the buffers are large + * enough (for example if an input file is mmap'ed), or can be done by + * repeated calls of the compression function. In the latter case, the + * application must provide more input and/or consume the output + * (providing more output space) before each call. + * + * The compressed data format used by default by the in-memory functions is + * the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped + * around a deflate stream, which is itself documented in RFC 1951. + * + * The library also supports reading and writing files in gzip (.gz) format + * with an interface similar to that of stdio using the functions that start + * with "gz". The gzip format is different from the zlib format. gzip is a + * gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. + * + * This library can optionally read and write gzip streams in memory as well. + * + * The zlib format was designed to be compact and fast for use in memory + * and on communications channels. The gzip format was designed for single- + * file compression on file systems, has a larger header than zlib to maintain + * directory information, and uses a different, slower check method than zlib. + * + * The library does not install any signal handler. The decoder checks + * the consistency of the compressed data, so the library should never + * crash even in case of corrupted input. + */ typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size)); typedef void (*free_func) OF((voidpf opaque, voidpf address)); @@ -82,1275 +83,1271 @@ typedef void (*free_func) OF((voidpf opaque, voidpf address)); struct internal_state; typedef struct z_stream_s { - Bytef *next_in; /* next input byte */ - uInt avail_in; /* number of bytes available at next_in */ - uLong total_in; /* total nb of input bytes read so far */ + Bytef *next_in; /* next input byte */ + uInt avail_in; /* number of bytes available at next_in */ + uLong total_in; /* total nb of input bytes read so far */ - Bytef *next_out; /* next output byte should be put there */ - uInt avail_out; /* remaining free space at next_out */ - uLong total_out; /* total nb of bytes output so far */ + Bytef *next_out; /* next output byte should be put there */ + uInt avail_out; /* remaining free space at next_out */ + uLong total_out; /* total nb of bytes output so far */ - char *msg; /* last error message, NULL if no error */ - struct internal_state FAR *state; /* not visible by applications */ + char *msg; /* last error message, NULL if no error */ + struct internal_state FAR *state; /* not visible by applications */ - alloc_func zalloc; /* used to allocate the internal state */ - free_func zfree; /* used to free the internal state */ - voidpf opaque; /* private data object passed to zalloc and zfree */ + alloc_func zalloc; /* used to allocate the internal state */ + free_func zfree; /* used to free the internal state */ + voidpf opaque; /* private data object passed to zalloc and zfree */ - int data_type; /* best guess about the data type: binary or text */ - uLong adler; /* adler32 value of the uncompressed data */ - uLong reserved; /* reserved for future use */ + int data_type; /* best guess about the data type: binary or text */ + uLong adler; /* adler32 value of the uncompressed data */ + uLong reserved; /* reserved for future use */ } z_stream; typedef z_stream FAR *z_streamp; /* - gzip header information passed to and from zlib routines. See RFC 1952 - for more details on the meanings of these fields. -*/ + * gzip header information passed to and from zlib routines. See RFC 1952 + * for more details on the meanings of these fields. + */ typedef struct gz_header_s { - int text; /* true if compressed data believed to be text */ - uLong time; /* modification time */ - int xflags; /* extra flags (not used when writing a gzip file) */ - int os; /* operating system */ - Bytef *extra; /* pointer to extra field or Z_NULL if none */ - uInt extra_len; /* extra field length (valid if extra != Z_NULL) */ - uInt extra_max; /* space at extra (only when reading header) */ - Bytef *name; /* pointer to zero-terminated file name or Z_NULL */ - uInt name_max; /* space at name (only when reading header) */ - Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */ - uInt comm_max; /* space at comment (only when reading header) */ - int hcrc; /* true if there was or will be a header crc */ - int done; /* true when done reading gzip header (not used - when writing a gzip file) */ + int text; /* true if compressed data believed to be text */ + uLong time; /* modification time */ + int xflags; /* extra flags (not used when writing a gzip file) */ + int os; /* operating system */ + Bytef *extra; /* pointer to extra field or Z_NULL if none */ + uInt extra_len; /* extra field length (valid if extra != Z_NULL) */ + uInt extra_max; /* space at extra (only when reading header) */ + Bytef *name; /* pointer to zero-terminated file name or Z_NULL */ + uInt name_max; /* space at name (only when reading header) */ + Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */ + uInt comm_max; /* space at comment (only when reading header) */ + int hcrc; /* true if there was or will be a header crc */ + int done; /* true when done reading gzip header (not used */ + /* when writing a gzip file) */ } gz_header; typedef gz_header FAR *gz_headerp; /* - The application must update next_in and avail_in when avail_in has - dropped to zero. It must update next_out and avail_out when avail_out - has dropped to zero. The application must initialize zalloc, zfree and - opaque before calling the init function. All other fields are set by the - compression library and must not be updated by the application. - - The opaque value provided by the application will be passed as the first - parameter for calls of zalloc and zfree. This can be useful for custom - memory management. The compression library attaches no meaning to the - opaque value. - - zalloc must return Z_NULL if there is not enough memory for the object. - If zlib is used in a multi-threaded application, zalloc and zfree must be - thread safe. - - On 16-bit systems, the functions zalloc and zfree must be able to allocate - exactly 65536 bytes, but will not be required to allocate more than this - if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, - pointers returned by zalloc for objects of exactly 65536 bytes *must* - have their offset normalized to zero. The default allocation function - provided by this library ensures this (see zutil.c). To reduce memory - requirements and avoid any allocation of 64K objects, at the expense of - compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h). - - The fields total_in and total_out can be used for statistics or - progress reports. After compression, total_in holds the total size of - the uncompressed data and may be saved for use in the decompressor - (particularly if the decompressor wants to decompress everything in - a single step). -*/ - - /* constants */ - -#define Z_NO_FLUSH 0 -#define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */ -#define Z_SYNC_FLUSH 2 -#define Z_FULL_FLUSH 3 -#define Z_FINISH 4 -#define Z_BLOCK 5 + * The application must update next_in and avail_in when avail_in has + * dropped to zero. It must update next_out and avail_out when avail_out + * has dropped to zero. The application must initialize zalloc, zfree and + * opaque before calling the init function. All other fields are set by the + * compression library and must not be updated by the application. + * + * The opaque value provided by the application will be passed as the first + * parameter for calls of zalloc and zfree. This can be useful for custom + * memory management. The compression library attaches no meaning to the + * opaque value. + * + * zalloc must return Z_NULL if there is not enough memory for the object. + * If zlib is used in a multi-threaded application, zalloc and zfree must be + * thread safe. + * + * On 16-bit systems, the functions zalloc and zfree must be able to allocate + * exactly 65536 bytes, but will not be required to allocate more than this + * if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, + * pointers returned by zalloc for objects of exactly 65536 bytes *must* + * have their offset normalized to zero. The default allocation function + * provided by this library ensures this (see zutil.c). To reduce memory + * requirements and avoid any allocation of 64K objects, at the expense of + * compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h). + * + * The fields total_in and total_out can be used for statistics or + * progress reports. After compression, total_in holds the total size of + * the uncompressed data and may be saved for use in the decompressor + * (particularly if the decompressor wants to decompress everything in + * a single step). + */ + + /* constants */ + +#define Z_NO_FLUSH 0 +#define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */ +#define Z_SYNC_FLUSH 2 +#define Z_FULL_FLUSH 3 +#define Z_FINISH 4 +#define Z_BLOCK 5 /* Allowed flush values; see deflate() and inflate() below for details */ -#define Z_OK 0 -#define Z_STREAM_END 1 -#define Z_NEED_DICT 2 -#define Z_ERRNO (-1) -#define Z_STREAM_ERROR (-2) -#define Z_DATA_ERROR (-3) -#define Z_MEM_ERROR (-4) -#define Z_BUF_ERROR (-5) -#define Z_VERSION_ERROR (-6) -/* Return codes for the compression/decompression functions. Negative +#define Z_OK 0 +#define Z_STREAM_END 1 +#define Z_NEED_DICT 2 +#define Z_ERRNO (-1) +#define Z_STREAM_ERROR (-2) +#define Z_DATA_ERROR (-3) +#define Z_MEM_ERROR (-4) +#define Z_BUF_ERROR (-5) +#define Z_VERSION_ERROR (-6) +/* + * Return codes for the compression/decompression functions. Negative * values are errors, positive values are used for special but normal events. */ -#define Z_NO_COMPRESSION 0 -#define Z_BEST_SPEED 1 -#define Z_BEST_COMPRESSION 9 -#define Z_DEFAULT_COMPRESSION (-1) +#define Z_NO_COMPRESSION 0 +#define Z_BEST_SPEED 1 +#define Z_BEST_COMPRESSION 9 +#define Z_DEFAULT_COMPRESSION (-1) /* compression levels */ -#define Z_FILTERED 1 -#define Z_HUFFMAN_ONLY 2 -#define Z_RLE 3 -#define Z_FIXED 4 -#define Z_DEFAULT_STRATEGY 0 +#define Z_FILTERED 1 +#define Z_HUFFMAN_ONLY 2 +#define Z_RLE 3 +#define Z_FIXED 4 +#define Z_DEFAULT_STRATEGY 0 /* compression strategy; see deflateInit2() below for details */ -#define Z_BINARY 0 -#define Z_TEXT 1 -#define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ -#define Z_UNKNOWN 2 +#define Z_BINARY 0 +#define Z_TEXT 1 +#define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ +#define Z_UNKNOWN 2 /* Possible values of the data_type field (though see inflate()) */ -#define Z_DEFLATED 8 +#define Z_DEFLATED 8 /* The deflate compression method (the only one supported in this version) */ -#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ +#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ -#define zlib_version zlibVersion() +#define zlib_version zlibVersion() /* for compatibility with versions < 1.0.2 */ - /* basic functions */ +/* basic functions */ -ZEXTERN const char * ZEXPORT zlibVersion OF((void)); -/* The application can compare zlibVersion and ZLIB_VERSION for consistency. - If the first character differs, the library code actually used is - not compatible with the zlib.h header file used by the application. - This check is automatically made by deflateInit and inflateInit. +ZEXTERN const char *ZEXPORT zlibVersion OF((void)); +/* + * The application can compare zlibVersion and ZLIB_VERSION for consistency. + * If the first character differs, the library code actually used is + * not compatible with the zlib.h header file used by the application. + * This check is automatically made by deflateInit and inflateInit. */ /* -ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); - - Initializes the internal stream state for compression. The fields - zalloc, zfree and opaque must be initialized before by the caller. - If zalloc and zfree are set to Z_NULL, deflateInit updates them to - use default allocation functions. - - The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: - 1 gives best speed, 9 gives best compression, 0 gives no compression at - all (the input data is simply copied a block at a time). - Z_DEFAULT_COMPRESSION requests a default compromise between speed and - compression (currently equivalent to level 6). - - deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_STREAM_ERROR if level is not a valid compression level, - Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible - with the version assumed by the caller (ZLIB_VERSION). - msg is set to null if there is no error message. deflateInit does not - perform any compression: this will be done by deflate(). -*/ - + * ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); + * + * Initializes the internal stream state for compression. The fields + * zalloc, zfree and opaque must be initialized before by the caller. + * If zalloc and zfree are set to Z_NULL, deflateInit updates them to + * use default allocation functions. + * + * The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: + * 1 gives best speed, 9 gives best compression, 0 gives no compression at + * all (the input data is simply copied a block at a time). + * Z_DEFAULT_COMPRESSION requests a default compromise between speed and + * compression (currently equivalent to level 6). + * + * deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not + * enough memory, Z_STREAM_ERROR if level is not a valid compression level, + * Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible + * with the version assumed by the caller (ZLIB_VERSION). + * msg is set to null if there is no error message. deflateInit does not + * perform any compression: this will be done by deflate(). + */ ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); /* - deflate compresses as much data as possible, and stops when the input - buffer becomes empty or the output buffer becomes full. It may introduce some - output latency (reading input without producing any output) except when - forced to flush. - - The detailed semantics are as follows. deflate performs one or both of the - following actions: - - - Compress more input starting at next_in and update next_in and avail_in - accordingly. If not all input can be processed (because there is not - enough room in the output buffer), next_in and avail_in are updated and - processing will resume at this point for the next call of deflate(). - - - Provide more output starting at next_out and update next_out and avail_out - accordingly. This action is forced if the parameter flush is non zero. - Forcing flush frequently degrades the compression ratio, so this parameter - should be set only when necessary (in interactive applications). - Some output may be provided even if flush is not set. - - Before the call of deflate(), the application should ensure that at least - one of the actions is possible, by providing more input and/or consuming - more output, and updating avail_in or avail_out accordingly; avail_out - should never be zero before the call. The application can consume the - compressed output when it wants, for example when the output buffer is full - (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK - and with zero avail_out, it must be called again after making room in the - output buffer because there might be more output pending. - - Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to - decide how much data to accumualte before producing output, in order to - maximize compression. - - If the parameter flush is set to Z_SYNC_FLUSH, all pending output is - flushed to the output buffer and the output is aligned on a byte boundary, so - that the decompressor can get all input data available so far. (In particular - avail_in is zero after the call if enough output space has been provided - before the call.) Flushing may degrade compression for some compression - algorithms and so it should be used only when necessary. - - If flush is set to Z_FULL_FLUSH, all output is flushed as with - Z_SYNC_FLUSH, and the compression state is reset so that decompression can - restart from this point if previous compressed data has been damaged or if - random access is desired. Using Z_FULL_FLUSH too often can seriously degrade - compression. - - If deflate returns with avail_out == 0, this function must be called again - with the same value of the flush parameter and more output space (updated - avail_out), until the flush is complete (deflate returns with non-zero - avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that - avail_out is greater than six to avoid repeated flush markers due to - avail_out == 0 on return. - - If the parameter flush is set to Z_FINISH, pending input is processed, - pending output is flushed and deflate returns with Z_STREAM_END if there - was enough output space; if deflate returns with Z_OK, this function must be - called again with Z_FINISH and more output space (updated avail_out) but no - more input data, until it returns with Z_STREAM_END or an error. After - deflate has returned Z_STREAM_END, the only possible operations on the - stream are deflateReset or deflateEnd. - - Z_FINISH can be used immediately after deflateInit if all the compression - is to be done in a single step. In this case, avail_out must be at least - the value returned by deflateBound (see below). If deflate does not return - Z_STREAM_END, then it must be called again as described above. - - deflate() sets strm->adler to the adler32 checksum of all input read - so far (that is, total_in bytes). - - deflate() may update strm->data_type if it can make a good guess about - the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered - binary. This field is only for information purposes and does not affect - the compression algorithm in any manner. - - deflate() returns Z_OK if some progress has been made (more input - processed or more output produced), Z_STREAM_END if all input has been - consumed and all output has been produced (only when flush is set to - Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example - if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible - (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not - fatal, and deflate() can be called again with more input and more output - space to continue compressing. -*/ - + * deflate compresses as much data as possible, and stops when the input + * buffer becomes empty or the output buffer becomes full. It may introduce some + * output latency (reading input without producing any output) except when + * forced to flush. + * + * The detailed semantics are as follows. deflate performs one or both of the + * following actions: + * + * - Compress more input starting at next_in and update next_in and avail_in + * accordingly. If not all input can be processed (because there is not + * enough room in the output buffer), next_in and avail_in are updated and + * processing will resume at this point for the next call of deflate(). + * + * - Provide more output starting at next_out and update next_out and avail_out + * accordingly. This action is forced if the parameter flush is non zero. + * Forcing flush frequently degrades the compression ratio, so this parameter + * should be set only when necessary (in interactive applications). + * Some output may be provided even if flush is not set. + * + * Before the call of deflate(), the application should ensure that at least + * one of the actions is possible, by providing more input and/or consuming + * more output, and updating avail_in or avail_out accordingly; avail_out + * should never be zero before the call. The application can consume the + * compressed output when it wants, for example when the output buffer is full + * (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK + * and with zero avail_out, it must be called again after making room in the + * output buffer because there might be more output pending. + * + * Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to + * decide how much data to accumualte before producing output, in order to + * maximize compression. + * + * If the parameter flush is set to Z_SYNC_FLUSH, all pending output is + * flushed to the output buffer and the output is aligned on a byte boundary, so + * that the decompressor can get all input data available so far. (In particular + * avail_in is zero after the call if enough output space has been provided + * before the call.) Flushing may degrade compression for some compression + * algorithms and so it should be used only when necessary. + * + * If flush is set to Z_FULL_FLUSH, all output is flushed as with + * Z_SYNC_FLUSH, and the compression state is reset so that decompression can + * restart from this point if previous compressed data has been damaged or if + * random access is desired. Using Z_FULL_FLUSH too often can seriously degrade + * compression. + * + * If deflate returns with avail_out == 0, this function must be called again + * with the same value of the flush parameter and more output space (updated + * avail_out), until the flush is complete (deflate returns with non-zero + * avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that + * avail_out is greater than six to avoid repeated flush markers due to + * avail_out == 0 on return. + * + * If the parameter flush is set to Z_FINISH, pending input is processed, + * pending output is flushed and deflate returns with Z_STREAM_END if there + * was enough output space; if deflate returns with Z_OK, this function must be + * called again with Z_FINISH and more output space (updated avail_out) but no + * more input data, until it returns with Z_STREAM_END or an error. After + * deflate has returned Z_STREAM_END, the only possible operations on the + * stream are deflateReset or deflateEnd. + * + * Z_FINISH can be used immediately after deflateInit if all the compression + * is to be done in a single step. In this case, avail_out must be at least + * the value returned by deflateBound (see below). If deflate does not return + * Z_STREAM_END, then it must be called again as described above. + * + * deflate() sets strm->adler to the adler32 checksum of all input read + * so far (that is, total_in bytes). + * + * deflate() may update strm->data_type if it can make a good guess about + * the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered + * binary. This field is only for information purposes and does not affect + * the compression algorithm in any manner. + * + * deflate() returns Z_OK if some progress has been made (more input + * processed or more output produced), Z_STREAM_END if all input has been + * consumed and all output has been produced (only when flush is set to + * Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example + * if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible + * (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not + * fatal, and deflate() can be called again with more input and more output + * space to continue compressing. + */ ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); /* - All dynamically allocated data structures for this stream are freed. - This function discards any unprocessed input and does not flush any - pending output. - - deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the - stream state was inconsistent, Z_DATA_ERROR if the stream was freed - prematurely (some input or output was discarded). In the error case, - msg may be set but then points to a static string (which must not be - deallocated). -*/ + * All dynamically allocated data structures for this stream are freed. + * This function discards any unprocessed input and does not flush any + * pending output. + * + * deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the + * stream state was inconsistent, Z_DATA_ERROR if the stream was freed + * prematurely (some input or output was discarded). In the error case, + * msg may be set but then points to a static string (which must not be + * deallocated). + */ /* -ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); - - Initializes the internal stream state for decompression. The fields - next_in, avail_in, zalloc, zfree and opaque must be initialized before by - the caller. If next_in is not Z_NULL and avail_in is large enough (the exact - value depends on the compression method), inflateInit determines the - compression method from the zlib header and allocates all data structures - accordingly; otherwise the allocation will be deferred to the first call of - inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to - use default allocation functions. - - inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_VERSION_ERROR if the zlib library version is incompatible with the - version assumed by the caller. msg is set to null if there is no error - message. inflateInit does not perform any decompression apart from reading - the zlib header if present: this will be done by inflate(). (So next_in and - avail_in may be modified, but next_out and avail_out are unchanged.) -*/ + * ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); + * + * Initializes the internal stream state for decompression. The fields + * next_in, avail_in, zalloc, zfree and opaque must be initialized before by + * the caller. If next_in is not Z_NULL and avail_in is large enough (the exact + * value depends on the compression method), inflateInit determines the + * compression method from the zlib header and allocates all data structures + * accordingly; otherwise the allocation will be deferred to the first call of + * inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to + * use default allocation functions. + * + * inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough + * memory, Z_VERSION_ERROR if the zlib library version is incompatible with the + * version assumed by the caller. msg is set to null if there is no error + * message. inflateInit does not perform any decompression apart from reading + * the zlib header if present: this will be done by inflate(). (So next_in and + * avail_in may be modified, but next_out and avail_out are unchanged.) + */ ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); /* - inflate decompresses as much data as possible, and stops when the input - buffer becomes empty or the output buffer becomes full. It may introduce - some output latency (reading input without producing any output) except when - forced to flush. - - The detailed semantics are as follows. inflate performs one or both of the - following actions: - - - Decompress more input starting at next_in and update next_in and avail_in - accordingly. If not all input can be processed (because there is not - enough room in the output buffer), next_in is updated and processing - will resume at this point for the next call of inflate(). - - - Provide more output starting at next_out and update next_out and avail_out - accordingly. inflate() provides as much output as possible, until there - is no more input data or no more space in the output buffer (see below - about the flush parameter). - - Before the call of inflate(), the application should ensure that at least - one of the actions is possible, by providing more input and/or consuming - more output, and updating the next_* and avail_* values accordingly. - The application can consume the uncompressed output when it wants, for - example when the output buffer is full (avail_out == 0), or after each - call of inflate(). If inflate returns Z_OK and with zero avail_out, it - must be called again after making room in the output buffer because there - might be more output pending. - - The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, - Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much - output as possible to the output buffer. Z_BLOCK requests that inflate() stop - if and when it gets to the next deflate block boundary. When decoding the - zlib or gzip format, this will cause inflate() to return immediately after - the header and before the first block. When doing a raw inflate, inflate() - will go ahead and process the first block, and will return when it gets to - the end of that block, or when it runs out of data. - - The Z_BLOCK option assists in appending to or combining deflate streams. - Also to assist in this, on return inflate() will set strm->data_type to the - number of unused bits in the last byte taken from strm->next_in, plus 64 - if inflate() is currently decoding the last block in the deflate stream, - plus 128 if inflate() returned immediately after decoding an end-of-block - code or decoding the complete header up to just before the first byte of the - deflate stream. The end-of-block will not be indicated until all of the - uncompressed data from that block has been written to strm->next_out. The - number of unused bits may in general be greater than seven, except when - bit 7 of data_type is set, in which case the number of unused bits will be - less than eight. - - inflate() should normally be called until it returns Z_STREAM_END or an - error. However if all decompression is to be performed in a single step - (a single call of inflate), the parameter flush should be set to - Z_FINISH. In this case all pending input is processed and all pending - output is flushed; avail_out must be large enough to hold all the - uncompressed data. (The size of the uncompressed data may have been saved - by the compressor for this purpose.) The next operation on this stream must - be inflateEnd to deallocate the decompression state. The use of Z_FINISH - is never required, but can be used to inform inflate that a faster approach - may be used for the single inflate() call. - - In this implementation, inflate() always flushes as much output as - possible to the output buffer, and always uses the faster approach on the - first call. So the only effect of the flush parameter in this implementation - is on the return value of inflate(), as noted below, or when it returns early - because Z_BLOCK is used. - - If a preset dictionary is needed after this call (see inflateSetDictionary - below), inflate sets strm->adler to the adler32 checksum of the dictionary - chosen by the compressor and returns Z_NEED_DICT; otherwise it sets - strm->adler to the adler32 checksum of all output produced so far (that is, - total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described - below. At the end of the stream, inflate() checks that its computed adler32 - checksum is equal to that saved by the compressor and returns Z_STREAM_END - only if the checksum is correct. - - inflate() will decompress and check either zlib-wrapped or gzip-wrapped - deflate data. The header type is detected automatically. Any information - contained in the gzip header is not retained, so applications that need that - information should instead use raw inflate, see inflateInit2() below, or - inflateBack() and perform their own processing of the gzip header and - trailer. - - inflate() returns Z_OK if some progress has been made (more input processed - or more output produced), Z_STREAM_END if the end of the compressed data has - been reached and all uncompressed output has been produced, Z_NEED_DICT if a - preset dictionary is needed at this point, Z_DATA_ERROR if the input data was - corrupted (input stream not conforming to the zlib format or incorrect check - value), Z_STREAM_ERROR if the stream structure was inconsistent (for example - if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory, - Z_BUF_ERROR if no progress is possible or if there was not enough room in the - output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and - inflate() can be called again with more input and more output space to - continue decompressing. If Z_DATA_ERROR is returned, the application may then - call inflateSync() to look for a good compression block if a partial recovery - of the data is desired. -*/ + * inflate decompresses as much data as possible, and stops when the input + * buffer becomes empty or the output buffer becomes full. It may introduce + * some output latency (reading input without producing any output) except when + * forced to flush. + * + * The detailed semantics are as follows. inflate performs one or both of the + * following actions: + * + * - Decompress more input starting at next_in and update next_in and avail_in + * accordingly. If not all input can be processed (because there is not + * enough room in the output buffer), next_in is updated and processing + * will resume at this point for the next call of inflate(). + * + * - Provide more output starting at next_out and update next_out and avail_out + * accordingly. inflate() provides as much output as possible, until there + * is no more input data or no more space in the output buffer (see below + * about the flush parameter). + * + * Before the call of inflate(), the application should ensure that at least + * one of the actions is possible, by providing more input and/or consuming + * more output, and updating the next_* and avail_* values accordingly. + * The application can consume the uncompressed output when it wants, for + * example when the output buffer is full (avail_out == 0), or after each + * call of inflate(). If inflate returns Z_OK and with zero avail_out, it + * must be called again after making room in the output buffer because there + * might be more output pending. + * + * The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, + * Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much + * output as possible to the output buffer. Z_BLOCK requests that inflate() stop + * if and when it gets to the next deflate block boundary. When decoding the + * zlib or gzip format, this will cause inflate() to return immediately after + * the header and before the first block. When doing a raw inflate, inflate() + * will go ahead and process the first block, and will return when it gets to + * the end of that block, or when it runs out of data. + * + * The Z_BLOCK option assists in appending to or combining deflate streams. + * Also to assist in this, on return inflate() will set strm->data_type to the + * number of unused bits in the last byte taken from strm->next_in, plus 64 + * if inflate() is currently decoding the last block in the deflate stream, + * plus 128 if inflate() returned immediately after decoding an end-of-block + * code or decoding the complete header up to just before the first byte of the + * deflate stream. The end-of-block will not be indicated until all of the + * uncompressed data from that block has been written to strm->next_out. The + * number of unused bits may in general be greater than seven, except when + * bit 7 of data_type is set, in which case the number of unused bits will be + * less than eight. + * + * inflate() should normally be called until it returns Z_STREAM_END or an + * error. However if all decompression is to be performed in a single step + * (a single call of inflate), the parameter flush should be set to + * Z_FINISH. In this case all pending input is processed and all pending + * output is flushed; avail_out must be large enough to hold all the + * uncompressed data. (The size of the uncompressed data may have been saved + * by the compressor for this purpose.) The next operation on this stream must + * be inflateEnd to deallocate the decompression state. The use of Z_FINISH + * is never required, but can be used to inform inflate that a faster approach + * may be used for the single inflate() call. + * + * In this implementation, inflate() always flushes as much output as + * possible to the output buffer, and always uses the faster approach on the + * first call. So the only effect of the flush parameter in this implementation + * is on the return value of inflate(), as noted below, or when it returns early + * because Z_BLOCK is used. + * + * If a preset dictionary is needed after this call (see inflateSetDictionary + * below), inflate sets strm->adler to the adler32 checksum of the dictionary + * chosen by the compressor and returns Z_NEED_DICT; otherwise it sets + * strm->adler to the adler32 checksum of all output produced so far (that is, + * total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described + * below. At the end of the stream, inflate() checks that its computed adler32 + * checksum is equal to that saved by the compressor and returns Z_STREAM_END + * only if the checksum is correct. + * + * inflate() will decompress and check either zlib-wrapped or gzip-wrapped + * deflate data. The header type is detected automatically. Any information + * contained in the gzip header is not retained, so applications that need that + * information should instead use raw inflate, see inflateInit2() below, or + * inflateBack() and perform their own processing of the gzip header and + * trailer. + * + * inflate() returns Z_OK if some progress has been made (more input processed + * or more output produced), Z_STREAM_END if the end of the compressed data has + * been reached and all uncompressed output has been produced, Z_NEED_DICT if a + * preset dictionary is needed at this point, Z_DATA_ERROR if the input data was + * corrupted (input stream not conforming to the zlib format or incorrect check + * value), Z_STREAM_ERROR if the stream structure was inconsistent (for example + * if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory, + * Z_BUF_ERROR if no progress is possible or if there was not enough room in the + * output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and + * inflate() can be called again with more input and more output space to + * continue decompressing. If Z_DATA_ERROR is returned, the application may then + * call inflateSync() to look for a good compression block if a partial recovery + * of the data is desired. + */ ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); /* - All dynamically allocated data structures for this stream are freed. - This function discards any unprocessed input and does not flush any - pending output. - - inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state - was inconsistent. In the error case, msg may be set but then points to a - static string (which must not be deallocated). -*/ - - /* Advanced functions */ - -/* - The following functions are needed only in some special applications. -*/ - -/* -ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, - int level, - int method, - int windowBits, - int memLevel, - int strategy)); - - This is another version of deflateInit with more compression options. The - fields next_in, zalloc, zfree and opaque must be initialized before by - the caller. - - The method parameter is the compression method. It must be Z_DEFLATED in - this version of the library. - - The windowBits parameter is the base two logarithm of the window size - (the size of the history buffer). It should be in the range 8..15 for this - version of the library. Larger values of this parameter result in better - compression at the expense of memory usage. The default value is 15 if - deflateInit is used instead. - - windowBits can also be -8..-15 for raw deflate. In this case, -windowBits - determines the window size. deflate() will then generate raw deflate data - with no zlib header or trailer, and will not compute an adler32 check value. - - windowBits can also be greater than 15 for optional gzip encoding. Add - 16 to windowBits to write a simple gzip header and trailer around the - compressed data instead of a zlib wrapper. The gzip header will have no - file name, no extra data, no comment, no modification time (set to zero), - no header crc, and the operating system will be set to 255 (unknown). If a - gzip stream is being written, strm->adler is a crc32 instead of an adler32. - - The memLevel parameter specifies how much memory should be allocated - for the internal compression state. memLevel=1 uses minimum memory but - is slow and reduces compression ratio; memLevel=9 uses maximum memory - for optimal speed. The default value is 8. See zconf.h for total memory - usage as a function of windowBits and memLevel. - - The strategy parameter is used to tune the compression algorithm. Use the - value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a - filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no - string match), or Z_RLE to limit match distances to one (run-length - encoding). Filtered data consists mostly of small values with a somewhat - random distribution. In this case, the compression algorithm is tuned to - compress them better. The effect of Z_FILTERED is to force more Huffman - coding and less string matching; it is somewhat intermediate between - Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as - Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy - parameter only affects the compression ratio but not the correctness of the - compressed output even if it is not set appropriately. Z_FIXED prevents the - use of dynamic Huffman codes, allowing for a simpler decoder for special - applications. - - deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid - method). msg is set to null if there is no error message. deflateInit2 does - not perform any compression: this will be done by deflate(). -*/ + * All dynamically allocated data structures for this stream are freed. + * This function discards any unprocessed input and does not flush any + * pending output. + * + * inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state + * was inconsistent. In the error case, msg may be set but then points to a + * static string (which must not be deallocated). + */ -ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, - const Bytef *dictionary, - uInt dictLength)); -/* - Initializes the compression dictionary from the given byte sequence - without producing any compressed output. This function must be called - immediately after deflateInit, deflateInit2 or deflateReset, before any - call of deflate. The compressor and decompressor must use exactly the same - dictionary (see inflateSetDictionary). - - The dictionary should consist of strings (byte sequences) that are likely - to be encountered later in the data to be compressed, with the most commonly - used strings preferably put towards the end of the dictionary. Using a - dictionary is most useful when the data to be compressed is short and can be - predicted with good accuracy; the data can then be compressed better than - with the default empty dictionary. - - Depending on the size of the compression data structures selected by - deflateInit or deflateInit2, a part of the dictionary may in effect be - discarded, for example if the dictionary is larger than the window size in - deflate or deflate2. Thus the strings most likely to be useful should be - put at the end of the dictionary, not at the front. In addition, the - current implementation of deflate will use at most the window size minus - 262 bytes of the provided dictionary. - - Upon return of this function, strm->adler is set to the adler32 value - of the dictionary; the decompressor may later use this value to determine - which dictionary has been used by the compressor. (The adler32 value - applies to the whole dictionary even if only a subset of the dictionary is - actually used by the compressor.) If a raw deflate was requested, then the - adler32 value is not computed and strm->adler is not set. - - deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a - parameter is invalid (such as NULL dictionary) or the stream state is - inconsistent (for example if deflate has already been called for this stream - or if the compression method is bsort). deflateSetDictionary does not - perform any compression: this will be done by deflate(). -*/ +/* Advanced functions */ -ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, - z_streamp source)); /* - Sets the destination stream as a complete copy of the source stream. + * The following functions are needed only in some special applications. + */ - This function can be useful when several compression strategies will be - tried, for example when there are several ways of pre-processing the input - data with a filter. The streams that will be discarded should then be freed - by calling deflateEnd. Note that deflateCopy duplicates the internal - compression state which can be quite large, so this strategy is slow and - can consume lots of memory. +/* + * ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, + * int level, + * int method, + * int windowBits, + * int memLevel, + * int strategy)); + * + * This is another version of deflateInit with more compression options. The + * fields next_in, zalloc, zfree and opaque must be initialized before by + * the caller. + * + * The method parameter is the compression method. It must be Z_DEFLATED in + * this version of the library. + * + * The windowBits parameter is the base two logarithm of the window size + * (the size of the history buffer). It should be in the range 8..15 for this + * version of the library. Larger values of this parameter result in better + * compression at the expense of memory usage. The default value is 15 if + * deflateInit is used instead. + * + * windowBits can also be -8..-15 for raw deflate. In this case, -windowBits + * determines the window size. deflate() will then generate raw deflate data + * with no zlib header or trailer, and will not compute an adler32 check value. + * + * windowBits can also be greater than 15 for optional gzip encoding. Add + * 16 to windowBits to write a simple gzip header and trailer around the + * compressed data instead of a zlib wrapper. The gzip header will have no + * file name, no extra data, no comment, no modification time (set to zero), + * no header crc, and the operating system will be set to 255 (unknown). If a + * gzip stream is being written, strm->adler is a crc32 instead of an adler32. + * + * The memLevel parameter specifies how much memory should be allocated + * for the internal compression state. memLevel=1 uses minimum memory but + * is slow and reduces compression ratio; memLevel=9 uses maximum memory + * for optimal speed. The default value is 8. See zconf.h for total memory + * usage as a function of windowBits and memLevel. + * + * The strategy parameter is used to tune the compression algorithm. Use the + * value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a + * filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no + * string match), or Z_RLE to limit match distances to one (run-length + * encoding). Filtered data consists mostly of small values with a somewhat + * random distribution. In this case, the compression algorithm is tuned to + * compress them better. The effect of Z_FILTERED is to force more Huffman + * coding and less string matching; it is somewhat intermediate between + * Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as + * Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy + * parameter only affects the compression ratio but not the correctness of the + * compressed output even if it is not set appropriately. Z_FIXED prevents the + * use of dynamic Huffman codes, allowing for a simpler decoder for special + * applications. + * + * deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + * memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid + * method). msg is set to null if there is no error message. deflateInit2 does + * not perform any compression: this will be done by deflate(). + */ - deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_STREAM_ERROR if the source stream state was inconsistent - (such as zalloc being NULL). msg is left unchanged in both source and - destination. -*/ +ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, + const Bytef *dictionary, uInt dictLength)); +/* + * Initializes the compression dictionary from the given byte sequence + * without producing any compressed output. This function must be called + * immediately after deflateInit, deflateInit2 or deflateReset, before any + * call of deflate. The compressor and decompressor must use exactly the same + * dictionary (see inflateSetDictionary). + * + * The dictionary should consist of strings (byte sequences) that are likely + * to be encountered later in the data to be compressed, with the most commonly + * used strings preferably put towards the end of the dictionary. Using a + * dictionary is most useful when the data to be compressed is short and can be + * predicted with good accuracy; the data can then be compressed better than + * with the default empty dictionary. + * + * Depending on the size of the compression data structures selected by + * deflateInit or deflateInit2, a part of the dictionary may in effect be + * discarded, for example if the dictionary is larger than the window size in + * deflate or deflate2. Thus the strings most likely to be useful should be + * put at the end of the dictionary, not at the front. In addition, the + * current implementation of deflate will use at most the window size minus + * 262 bytes of the provided dictionary. + * + * Upon return of this function, strm->adler is set to the adler32 value + * of the dictionary; the decompressor may later use this value to determine + * which dictionary has been used by the compressor. (The adler32 value + * applies to the whole dictionary even if only a subset of the dictionary is + * actually used by the compressor.) If a raw deflate was requested, then the + * adler32 value is not computed and strm->adler is not set. + * + * deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a + * parameter is invalid (such as NULL dictionary) or the stream state is + * inconsistent (for example if deflate has already been called for this stream + * or if the compression method is bsort). deflateSetDictionary does not + * perform any compression: this will be done by deflate(). + */ -ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); +ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, + z_streamp source)); /* - This function is equivalent to deflateEnd followed by deflateInit, - but does not free and reallocate all the internal compression state. - The stream will keep the same compression level and any other attributes - that may have been set by deflateInit2. + * Sets the destination stream as a complete copy of the source stream. + * + * This function can be useful when several compression strategies will be + * tried, for example when there are several ways of pre-processing the input + * data with a filter. The streams that will be discarded should then be freed + * by calling deflateEnd. Note that deflateCopy duplicates the internal + * compression state which can be quite large, so this strategy is slow and + * can consume lots of memory. + * + * deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + * enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + * (such as zalloc being NULL). msg is left unchanged in both source and + * destination. + */ - deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent (such as zalloc or state being NULL). -*/ +ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); +/* + * This function is equivalent to deflateEnd followed by deflateInit, + * but does not free and reallocate all the internal compression state. + * The stream will keep the same compression level and any other attributes + * that may have been set by deflateInit2. + * + * deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + * stream state was inconsistent (such as zalloc or state being NULL). + */ ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, - int level, - int strategy)); -/* - Dynamically update the compression level and compression strategy. The - interpretation of level and strategy is as in deflateInit2. This can be - used to switch between compression and straight copy of the input data, or - to switch to a different kind of input data requiring a different - strategy. If the compression level is changed, the input available so far - is compressed with the old level (and may be flushed); the new level will - take effect only at the next call of deflate(). - - Before the call of deflateParams, the stream state must be set as for - a call of deflate(), since the currently available input may have to - be compressed and flushed. In particular, strm->avail_out must be non-zero. - - deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source - stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR - if strm->avail_out was zero. -*/ + int level, int strategy)); +/* + * Dynamically update the compression level and compression strategy. The + * interpretation of level and strategy is as in deflateInit2. This can be + * used to switch between compression and straight copy of the input data, or + * to switch to a different kind of input data requiring a different + * strategy. If the compression level is changed, the input available so far + * is compressed with the old level (and may be flushed); the new level will + * take effect only at the next call of deflate(). + * + * Before the call of deflateParams, the stream state must be set as for + * a call of deflate(), since the currently available input may have to + * be compressed and flushed. In particular, strm->avail_out must be non-zero. + * + * deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source + * stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR + * if strm->avail_out was zero. + */ ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm, - int good_length, - int max_lazy, - int nice_length, - int max_chain)); + int good_length, int max_lazy, int nice_length, int max_chain)); /* - Fine tune deflate's internal compression parameters. This should only be - used by someone who understands the algorithm used by zlib's deflate for - searching for the best matching string, and even then only by the most - fanatic optimizer trying to squeeze out the last compressed bit for their - specific input data. Read the deflate.c source code for the meaning of the - max_lazy, good_length, nice_length, and max_chain parameters. - - deflateTune() can be called after deflateInit() or deflateInit2(), and - returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. + * Fine tune deflate's internal compression parameters. This should only be + * used by someone who understands the algorithm used by zlib's deflate for + * searching for the best matching string, and even then only by the most + * fanatic optimizer trying to squeeze out the last compressed bit for their + * specific input data. Read the deflate.c source code for the meaning of the + * max_lazy, good_length, nice_length, and max_chain parameters. + * + * deflateTune() can be called after deflateInit() or deflateInit2(), and + * returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. */ ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, - uLong sourceLen)); + uLong sourceLen)); /* - deflateBound() returns an upper bound on the compressed size after - deflation of sourceLen bytes. It must be called after deflateInit() - or deflateInit2(). This would be used to allocate an output buffer - for deflation in a single pass, and so would be called before deflate(). -*/ + * deflateBound() returns an upper bound on the compressed size after + * deflation of sourceLen bytes. It must be called after deflateInit() + * or deflateInit2(). This would be used to allocate an output buffer + * for deflation in a single pass, and so would be called before deflate(). + */ ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, - int bits, - int value)); + int bits, int value)); /* - deflatePrime() inserts bits in the deflate output stream. The intent - is that this function is used to start off the deflate output with the - bits leftover from a previous deflate stream when appending to it. As such, - this function can only be used for raw deflate, and must be used before the - first deflate() call after a deflateInit2() or deflateReset(). bits must be - less than or equal to 16, and that many of the least significant bits of - value will be inserted in the output. - - deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ + * deflatePrime() inserts bits in the deflate output stream. The intent + * is that this function is used to start off the deflate output with the + * bits leftover from a previous deflate stream when appending to it. As such, + * this function can only be used for raw deflate, and must be used before the + * first deflate() call after a deflateInit2() or deflateReset(). bits must be + * less than or equal to 16, and that many of the least significant bits of + * value will be inserted in the output. + * + * deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source + * stream state was inconsistent. + */ ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, - gz_headerp head)); -/* - deflateSetHeader() provides gzip header information for when a gzip - stream is requested by deflateInit2(). deflateSetHeader() may be called - after deflateInit2() or deflateReset() and before the first call of - deflate(). The text, time, os, extra field, name, and comment information - in the provided gz_header structure are written to the gzip header (xflag is - ignored -- the extra flags are set according to the compression level). The - caller must assure that, if not Z_NULL, name and comment are terminated with - a zero byte, and that if extra is not Z_NULL, that extra_len bytes are - available there. If hcrc is true, a gzip header crc is included. Note that - the current versions of the command-line version of gzip (up through version - 1.3.x) do not support header crc's, and will report that it is a "multi-part - gzip file" and give up. - - If deflateSetHeader is not used, the default gzip header has text false, - the time set to zero, and os set to 255, with no extra, name, or comment - fields. The gzip header is returned to the default state by deflateReset(). - - deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -/* -ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, - int windowBits)); - - This is another version of inflateInit with an extra parameter. The - fields next_in, avail_in, zalloc, zfree and opaque must be initialized - before by the caller. - - The windowBits parameter is the base two logarithm of the maximum window - size (the size of the history buffer). It should be in the range 8..15 for - this version of the library. The default value is 15 if inflateInit is used - instead. windowBits must be greater than or equal to the windowBits value - provided to deflateInit2() while compressing, or it must be equal to 15 if - deflateInit2() was not used. If a compressed stream with a larger window - size is given as input, inflate() will return with the error code - Z_DATA_ERROR instead of trying to allocate a larger window. - - windowBits can also be -8..-15 for raw inflate. In this case, -windowBits - determines the window size. inflate() will then process raw deflate data, - not looking for a zlib or gzip header, not generating a check value, and not - looking for any check values for comparison at the end of the stream. This - is for use with other formats that use the deflate compressed data format - such as zip. Those formats provide their own check values. If a custom - format is developed using the raw deflate format for compressed data, it is - recommended that a check value such as an adler32 or a crc32 be applied to - the uncompressed data as is done in the zlib, gzip, and zip formats. For - most applications, the zlib format should be used as is. Note that comments - above on the use in deflateInit2() applies to the magnitude of windowBits. - - windowBits can also be greater than 15 for optional gzip decoding. Add - 32 to windowBits to enable zlib and gzip decoding with automatic header - detection, or add 16 to decode only the gzip format (the zlib format will - return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is - a crc32 instead of an adler32. - - inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg - is set to null if there is no error message. inflateInit2 does not perform - any decompression apart from reading the zlib header if present: this will - be done by inflate(). (So next_in and avail_in may be modified, but next_out - and avail_out are unchanged.) -*/ + gz_headerp head)); +/* + * deflateSetHeader() provides gzip header information for when a gzip + * stream is requested by deflateInit2(). deflateSetHeader() may be called + * after deflateInit2() or deflateReset() and before the first call of + * deflate(). The text, time, os, extra field, name, and comment information + * in the provided gz_header structure are written to the gzip header (xflag is + * ignored -- the extra flags are set according to the compression level). The + * caller must assure that, if not Z_NULL, name and comment are terminated with + * a zero byte, and that if extra is not Z_NULL, that extra_len bytes are + * available there. If hcrc is true, a gzip header crc is included. Note that + * the current versions of the command-line version of gzip (up through version + * 1.3.x) do not support header crc's, and will report that it is a "multi-part + * gzip file" and give up. + * + * If deflateSetHeader is not used, the default gzip header has text false, + * the time set to zero, and os set to 255, with no extra, name, or comment + * fields. The gzip header is returned to the default state by deflateReset(). + * + * deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + * stream state was inconsistent. + */ + +/* + * ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, + * int windowBits)); + * + * This is another version of inflateInit with an extra parameter. The + * fields next_in, avail_in, zalloc, zfree and opaque must be initialized + * before by the caller. + * + * The windowBits parameter is the base two logarithm of the maximum window + * size (the size of the history buffer). It should be in the range 8..15 for + * this version of the library. The default value is 15 if inflateInit is used + * instead. windowBits must be greater than or equal to the windowBits value + * provided to deflateInit2() while compressing, or it must be equal to 15 if + * deflateInit2() was not used. If a compressed stream with a larger window + * size is given as input, inflate() will return with the error code + * Z_DATA_ERROR instead of trying to allocate a larger window. + * + * windowBits can also be -8..-15 for raw inflate. In this case, -windowBits + * determines the window size. inflate() will then process raw deflate data, + * not looking for a zlib or gzip header, not generating a check value, and not + * looking for any check values for comparison at the end of the stream. This + * is for use with other formats that use the deflate compressed data format + * such as zip. Those formats provide their own check values. If a custom + * format is developed using the raw deflate format for compressed data, it is + * recommended that a check value such as an adler32 or a crc32 be applied to + * the uncompressed data as is done in the zlib, gzip, and zip formats. For + * most applications, the zlib format should be used as is. Note that comments + * above on the use in deflateInit2() applies to the magnitude of windowBits. + * + * windowBits can also be greater than 15 for optional gzip decoding. Add + * 32 to windowBits to enable zlib and gzip decoding with automatic header + * detection, or add 16 to decode only the gzip format (the zlib format will + * return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is + * a crc32 instead of an adler32. + * + * inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + * memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg + * is set to null if there is no error message. inflateInit2 does not perform + * any decompression apart from reading the zlib header if present: this will + * be done by inflate(). (So next_in and avail_in may be modified, but next_out + * and avail_out are unchanged.) + */ ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, - const Bytef *dictionary, - uInt dictLength)); -/* - Initializes the decompression dictionary from the given uncompressed byte - sequence. This function must be called immediately after a call of inflate, - if that call returned Z_NEED_DICT. The dictionary chosen by the compressor - can be determined from the adler32 value returned by that call of inflate. - The compressor and decompressor must use exactly the same dictionary (see - deflateSetDictionary). For raw inflate, this function can be called - immediately after inflateInit2() or inflateReset() and before any call of - inflate() to set the dictionary. The application must insure that the - dictionary that was used for compression is provided. - - inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a - parameter is invalid (such as NULL dictionary) or the stream state is - inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the - expected one (incorrect adler32 value). inflateSetDictionary does not - perform any decompression: this will be done by subsequent calls of - inflate(). -*/ + const Bytef *dictionary, uInt dictLength)); +/* + * Initializes the decompression dictionary from the given uncompressed byte + * sequence. This function must be called immediately after a call of inflate, + * if that call returned Z_NEED_DICT. The dictionary chosen by the compressor + * can be determined from the adler32 value returned by that call of inflate. + * The compressor and decompressor must use exactly the same dictionary (see + * deflateSetDictionary). For raw inflate, this function can be called + * immediately after inflateInit2() or inflateReset() and before any call of + * inflate() to set the dictionary. The application must insure that the + * dictionary that was used for compression is provided. + * + * inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a + * parameter is invalid (such as NULL dictionary) or the stream state is + * inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the + * expected one (incorrect adler32 value). inflateSetDictionary does not + * perform any decompression: this will be done by subsequent calls of + * inflate(). + */ ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); /* - Skips invalid compressed data until a full flush point (see above the - description of deflate with Z_FULL_FLUSH) can be found, or until all - available input is skipped. No output is provided. - - inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR - if no more input was provided, Z_DATA_ERROR if no flush point has been found, - or Z_STREAM_ERROR if the stream structure was inconsistent. In the success - case, the application may save the current current value of total_in which - indicates where valid compressed data was found. In the error case, the - application may repeatedly call inflateSync, providing more input each time, - until success or end of the input data. -*/ + * Skips invalid compressed data until a full flush point (see above the + * description of deflate with Z_FULL_FLUSH) can be found, or until all + * available input is skipped. No output is provided. + * + * inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR + * if no more input was provided, Z_DATA_ERROR if no flush point has been found, + * or Z_STREAM_ERROR if the stream structure was inconsistent. In the success + * case, the application may save the current current value of total_in which + * indicates where valid compressed data was found. In the error case, the + * application may repeatedly call inflateSync, providing more input each time, + * until success or end of the input data. + */ ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, - z_streamp source)); + z_streamp source)); /* - Sets the destination stream as a complete copy of the source stream. - - This function can be useful when randomly accessing a large stream. The - first pass through the stream can periodically record the inflate state, - allowing restarting inflate at those points when randomly accessing the - stream. - - inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_STREAM_ERROR if the source stream state was inconsistent - (such as zalloc being NULL). msg is left unchanged in both source and - destination. -*/ + * Sets the destination stream as a complete copy of the source stream. + * + * This function can be useful when randomly accessing a large stream. The + * first pass through the stream can periodically record the inflate state, + * allowing restarting inflate at those points when randomly accessing the + * stream. + * + * inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + * enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + * (such as zalloc being NULL). msg is left unchanged in both source and + * destination. + */ ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); /* - This function is equivalent to inflateEnd followed by inflateInit, - but does not free and reallocate all the internal decompression state. - The stream will keep attributes that may have been set by inflateInit2. - - inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent (such as zalloc or state being NULL). -*/ + * This function is equivalent to inflateEnd followed by inflateInit, + * but does not free and reallocate all the internal decompression state. + * The stream will keep attributes that may have been set by inflateInit2. + * + * inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + * stream state was inconsistent (such as zalloc or state being NULL). + */ ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm, - int bits, - int value)); + int bits, int value)); /* - This function inserts bits in the inflate input stream. The intent is - that this function is used to start inflating at a bit position in the - middle of a byte. The provided bits will be used before any bytes are used - from next_in. This function should only be used with raw inflate, and - should be used before the first inflate() call after inflateInit2() or - inflateReset(). bits must be less than or equal to 16, and that many of the - least significant bits of value will be inserted in the input. - - inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ + * This function inserts bits in the inflate input stream. The intent is + * that this function is used to start inflating at a bit position in the + * middle of a byte. The provided bits will be used before any bytes are used + * from next_in. This function should only be used with raw inflate, and + * should be used before the first inflate() call after inflateInit2() or + * inflateReset(). bits must be less than or equal to 16, and that many of the + * least significant bits of value will be inserted in the input. + * + * inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source + * stream state was inconsistent. + */ ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm, - gz_headerp head)); -/* - inflateGetHeader() requests that gzip header information be stored in the - provided gz_header structure. inflateGetHeader() may be called after - inflateInit2() or inflateReset(), and before the first call of inflate(). - As inflate() processes the gzip stream, head->done is zero until the header - is completed, at which time head->done is set to one. If a zlib stream is - being decoded, then head->done is set to -1 to indicate that there will be - no gzip header information forthcoming. Note that Z_BLOCK can be used to - force inflate() to return immediately after header processing is complete - and before any actual data is decompressed. - - The text, time, xflags, and os fields are filled in with the gzip header - contents. hcrc is set to true if there is a header CRC. (The header CRC - was valid if done is set to one.) If extra is not Z_NULL, then extra_max - contains the maximum number of bytes to write to extra. Once done is true, - extra_len contains the actual extra field length, and extra contains the - extra field, or that field truncated if extra_max is less than extra_len. - If name is not Z_NULL, then up to name_max characters are written there, - terminated with a zero unless the length is greater than name_max. If - comment is not Z_NULL, then up to comm_max characters are written there, - terminated with a zero unless the length is greater than comm_max. When - any of extra, name, or comment are not Z_NULL and the respective field is - not present in the header, then that field is set to Z_NULL to signal its - absence. This allows the use of deflateSetHeader() with the returned - structure to duplicate the header. However if those fields are set to - allocated memory, then the application will need to save those pointers - elsewhere so that they can be eventually freed. - - If inflateGetHeader is not used, then the header information is simply - discarded. The header is always checked for validity, including the header - CRC if present. inflateReset() will reset the process to discard the header - information. The application would need to call inflateGetHeader() again to - retrieve the header from the next gzip stream. - - inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -/* -ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, - unsigned char FAR *window)); - - Initialize the internal stream state for decompression using inflateBack() - calls. The fields zalloc, zfree and opaque in strm must be initialized - before the call. If zalloc and zfree are Z_NULL, then the default library- - derived memory allocation routines are used. windowBits is the base two - logarithm of the window size, in the range 8..15. window is a caller - supplied buffer of that size. Except for special applications where it is - assured that deflate was used with small window sizes, windowBits must be 15 - and a 32K byte window must be supplied to be able to decompress general - deflate streams. - - See inflateBack() for the usage of these routines. - - inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of - the paramaters are invalid, Z_MEM_ERROR if the internal state could not - be allocated, or Z_VERSION_ERROR if the version of the library does not - match the version of the header file. -*/ + gz_headerp head)); +/* + * inflateGetHeader() requests that gzip header information be stored in the + * provided gz_header structure. inflateGetHeader() may be called after + * inflateInit2() or inflateReset(), and before the first call of inflate(). + * As inflate() processes the gzip stream, head->done is zero until the header + * is completed, at which time head->done is set to one. If a zlib stream is + * being decoded, then head->done is set to -1 to indicate that there will be + * no gzip header information forthcoming. Note that Z_BLOCK can be used to + * force inflate() to return immediately after header processing is complete + * and before any actual data is decompressed. + * + * The text, time, xflags, and os fields are filled in with the gzip header + * contents. hcrc is set to true if there is a header CRC. (The header CRC + * was valid if done is set to one.) If extra is not Z_NULL, then extra_max + * contains the maximum number of bytes to write to extra. Once done is true, + * extra_len contains the actual extra field length, and extra contains the + * extra field, or that field truncated if extra_max is less than extra_len. + * If name is not Z_NULL, then up to name_max characters are written there, + * terminated with a zero unless the length is greater than name_max. If + * comment is not Z_NULL, then up to comm_max characters are written there, + * terminated with a zero unless the length is greater than comm_max. When + * any of extra, name, or comment are not Z_NULL and the respective field is + * not present in the header, then that field is set to Z_NULL to signal its + * absence. This allows the use of deflateSetHeader() with the returned + * structure to duplicate the header. However if those fields are set to + * allocated memory, then the application will need to save those pointers + * elsewhere so that they can be eventually freed. + * + * If inflateGetHeader is not used, then the header information is simply + * discarded. The header is always checked for validity, including the header + * CRC if present. inflateReset() will reset the process to discard the header + * information. The application would need to call inflateGetHeader() again to + * retrieve the header from the next gzip stream. + * + * inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + * stream state was inconsistent. + */ + +/* + * ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, + * unsigned char FAR *window)); + * + * Initialize the internal stream state for decompression using inflateBack() + * calls. The fields zalloc, zfree and opaque in strm must be initialized + * before the call. If zalloc and zfree are Z_NULL, then the default library- + * derived memory allocation routines are used. windowBits is the base two + * logarithm of the window size, in the range 8..15. window is a caller + * supplied buffer of that size. Except for special applications where it is + * assured that deflate was used with small window sizes, windowBits must be 15 + * and a 32K byte window must be supplied to be able to decompress general + * deflate streams. + * + * See inflateBack() for the usage of these routines. + * + * inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of + * the paramaters are invalid, Z_MEM_ERROR if the internal state could not + * be allocated, or Z_VERSION_ERROR if the version of the library does not + * match the version of the header file. + */ typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *)); typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned)); ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm, - in_func in, void FAR *in_desc, - out_func out, void FAR *out_desc)); -/* - inflateBack() does a raw inflate with a single call using a call-back - interface for input and output. This is more efficient than inflate() for - file i/o applications in that it avoids copying between the output and the - sliding window by simply making the window itself the output buffer. This - function trusts the application to not change the output buffer passed by - the output function, at least until inflateBack() returns. - - inflateBackInit() must be called first to allocate the internal state - and to initialize the state with the user-provided window buffer. - inflateBack() may then be used multiple times to inflate a complete, raw - deflate stream with each call. inflateBackEnd() is then called to free - the allocated state. - - A raw deflate stream is one with no zlib or gzip header or trailer. - This routine would normally be used in a utility that reads zip or gzip - files and writes out uncompressed files. The utility would decode the - header and process the trailer on its own, hence this routine expects - only the raw deflate stream to decompress. This is different from the - normal behavior of inflate(), which expects either a zlib or gzip header and - trailer around the deflate stream. - - inflateBack() uses two subroutines supplied by the caller that are then - called by inflateBack() for input and output. inflateBack() calls those - routines until it reads a complete deflate stream and writes out all of the - uncompressed data, or until it encounters an error. The function's - parameters and return types are defined above in the in_func and out_func - typedefs. inflateBack() will call in(in_desc, &buf) which should return the - number of bytes of provided input, and a pointer to that input in buf. If - there is no input available, in() must return zero--buf is ignored in that - case--and inflateBack() will return a buffer error. inflateBack() will call - out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out() - should return zero on success, or non-zero on failure. If out() returns - non-zero, inflateBack() will return with an error. Neither in() nor out() - are permitted to change the contents of the window provided to - inflateBackInit(), which is also the buffer that out() uses to write from. - The length written by out() will be at most the window size. Any non-zero - amount of input may be provided by in(). - - For convenience, inflateBack() can be provided input on the first call by - setting strm->next_in and strm->avail_in. If that input is exhausted, then - in() will be called. Therefore strm->next_in must be initialized before - calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called - immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in - must also be initialized, and then if strm->avail_in is not zero, input will - initially be taken from strm->next_in[0 .. strm->avail_in - 1]. - - The in_desc and out_desc parameters of inflateBack() is passed as the - first parameter of in() and out() respectively when they are called. These - descriptors can be optionally used to pass any information that the caller- - supplied in() and out() functions need to do their job. - - On return, inflateBack() will set strm->next_in and strm->avail_in to - pass back any unused input that was provided by the last in() call. The - return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR - if in() or out() returned an error, Z_DATA_ERROR if there was a format - error in the deflate stream (in which case strm->msg is set to indicate the - nature of the error), or Z_STREAM_ERROR if the stream was not properly - initialized. In the case of Z_BUF_ERROR, an input or output error can be - distinguished using strm->next_in which will be Z_NULL only if in() returned - an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to - out() returning non-zero. (in() will always be called before out(), so - strm->next_in is assured to be defined if out() returns non-zero.) Note - that inflateBack() cannot return Z_OK. -*/ + in_func in, void FAR *in_desc, + out_func out, void FAR *out_desc)); +/* + * inflateBack() does a raw inflate with a single call using a call-back + * interface for input and output. This is more efficient than inflate() for + * file i/o applications in that it avoids copying between the output and the + * sliding window by simply making the window itself the output buffer. This + * function trusts the application to not change the output buffer passed by + * the output function, at least until inflateBack() returns. + * + * inflateBackInit() must be called first to allocate the internal state + * and to initialize the state with the user-provided window buffer. + * inflateBack() may then be used multiple times to inflate a complete, raw + * deflate stream with each call. inflateBackEnd() is then called to free + * the allocated state. + * + * A raw deflate stream is one with no zlib or gzip header or trailer. + * This routine would normally be used in a utility that reads zip or gzip + * files and writes out uncompressed files. The utility would decode the + * header and process the trailer on its own, hence this routine expects + * only the raw deflate stream to decompress. This is different from the + * normal behavior of inflate(), which expects either a zlib or gzip header and + * trailer around the deflate stream. + * + * inflateBack() uses two subroutines supplied by the caller that are then + * called by inflateBack() for input and output. inflateBack() calls those + * routines until it reads a complete deflate stream and writes out all of the + * uncompressed data, or until it encounters an error. The function's + * parameters and return types are defined above in the in_func and out_func + * typedefs. inflateBack() will call in(in_desc, &buf) which should return the + * number of bytes of provided input, and a pointer to that input in buf. If + * there is no input available, in() must return zero--buf is ignored in that + * case--and inflateBack() will return a buffer error. inflateBack() will call + * out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out() + * should return zero on success, or non-zero on failure. If out() returns + * non-zero, inflateBack() will return with an error. Neither in() nor out() + * are permitted to change the contents of the window provided to + * inflateBackInit(), which is also the buffer that out() uses to write from. + * The length written by out() will be at most the window size. Any non-zero + * amount of input may be provided by in(). + * + * For convenience, inflateBack() can be provided input on the first call by + * setting strm->next_in and strm->avail_in. If that input is exhausted, then + * in() will be called. Therefore strm->next_in must be initialized before + * calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called + * immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in + * must also be initialized, and then if strm->avail_in is not zero, input will + * initially be taken from strm->next_in[0 .. strm->avail_in - 1]. + * + * The in_desc and out_desc parameters of inflateBack() is passed as the + * first parameter of in() and out() respectively when they are called. These + * descriptors can be optionally used to pass any information that the caller- + * supplied in() and out() functions need to do their job. + * + * On return, inflateBack() will set strm->next_in and strm->avail_in to + * pass back any unused input that was provided by the last in() call. The + * return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR + * if in() or out() returned an error, Z_DATA_ERROR if there was a format + * error in the deflate stream (in which case strm->msg is set to indicate the + * nature of the error), or Z_STREAM_ERROR if the stream was not properly + * initialized. In the case of Z_BUF_ERROR, an input or output error can be + * distinguished using strm->next_in which will be Z_NULL only if in() returned + * an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to + * out() returning non-zero. (in() will always be called before out(), so + * strm->next_in is assured to be defined if out() returns non-zero.) Note + * that inflateBack() cannot return Z_OK. + */ ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm)); /* - All memory allocated by inflateBackInit() is freed. - - inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream - state was inconsistent. -*/ + * All memory allocated by inflateBackInit() is freed. + * + * inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream + * state was inconsistent. + */ ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); -/* Return flags indicating compile-time options. - - Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: - 1.0: size of uInt - 3.2: size of uLong - 5.4: size of voidpf (pointer) - 7.6: size of z_off_t - - Compiler, assembler, and debug options: - 8: DEBUG - 9: ASMV or ASMINF -- use ASM code - 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention - 11: 0 (reserved) - - One-time table building (smaller code, but not thread-safe if true): - 12: BUILDFIXED -- build static block decoding tables when needed - 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed - 14,15: 0 (reserved) - - Library content (indicates missing functionality): - 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking - deflate code when not needed) - 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect - and decode gzip streams (to avoid linking crc code) - 18-19: 0 (reserved) - - Operation variations (changes in library functionality): - 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate - 21: FASTEST -- deflate algorithm with only one, lowest compression level - 22,23: 0 (reserved) - - The sprintf variant used by gzprintf (zero is best): - 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format - 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure! - 26: 0 = returns value, 1 = void -- 1 means inferred string length returned - - Remainder: - 27-31: 0 (reserved) +/* + * Return flags indicating compile-time options. + * + * Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: + * 1.0: size of uInt + * 3.2: size of uLong + * 5.4: size of voidpf (pointer) + * 7.6: size of z_off_t + * + * Compiler, assembler, and debug options: + * 8: DEBUG + * 9: ASMV or ASMINF -- use ASM code + * 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention + * 11: 0 (reserved) + * + * One-time table building (smaller code, but not thread-safe if true): + * 12: BUILDFIXED -- build static block decoding tables when needed + * 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed + * 14,15: 0 (reserved) + * + * Library content (indicates missing functionality): + * 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking + * deflate code when not needed) + * 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect + * and decode gzip streams (to avoid linking crc code) + * 18-19: 0 (reserved) + * + * Operation variations (changes in library functionality): + * 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate + * 21: FASTEST -- deflate algorithm with only one, lowest compression level + * 22,23: 0 (reserved) + * + * The sprintf variant used by gzprintf (zero is best): + * 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format + * 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure! + * 26: 0 = returns value, 1 = void -- 1 means inferred string length returned + * + * Remainder: + * 27-31: 0 (reserved) */ - /* utility functions */ +/* utility functions */ /* - The following utility functions are implemented on top of the - basic stream-oriented functions. To simplify the interface, some - default options are assumed (compression level and memory usage, - standard memory allocation functions). The source code of these - utility functions can easily be modified if you need special options. -*/ + * The following utility functions are implemented on top of the + * basic stream-oriented functions. To simplify the interface, some + * default options are assumed (compression level and memory usage, + * standard memory allocation functions). The source code of these + * utility functions can easily be modified if you need special options. + */ ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen)); -/* - Compresses the source buffer into the destination buffer. sourceLen is - the byte length of the source buffer. Upon entry, destLen is the total - size of the destination buffer, which must be at least the value returned - by compressBound(sourceLen). Upon exit, destLen is the actual size of the - compressed buffer. - This function can be used to compress a whole file at once if the - input file is mmap'ed. - compress returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_BUF_ERROR if there was not enough room in the output - buffer. -*/ + const Bytef *source, uLong sourceLen)); +/* + * Compresses the source buffer into the destination buffer. sourceLen is + * the byte length of the source buffer. Upon entry, destLen is the total + * size of the destination buffer, which must be at least the value returned + * by compressBound(sourceLen). Upon exit, destLen is the actual size of the + * compressed buffer. + * This function can be used to compress a whole file at once if the + * input file is mmap'ed. + * compress returns Z_OK if success, Z_MEM_ERROR if there was not + * enough memory, Z_BUF_ERROR if there was not enough room in the output + * buffer. + */ ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen, - int level)); + const Bytef *source, uLong sourceLen, + int level)); /* - Compresses the source buffer into the destination buffer. The level - parameter has the same meaning as in deflateInit. sourceLen is the byte - length of the source buffer. Upon entry, destLen is the total size of the - destination buffer, which must be at least the value returned by - compressBound(sourceLen). Upon exit, destLen is the actual size of the - compressed buffer. - - compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_BUF_ERROR if there was not enough room in the output buffer, - Z_STREAM_ERROR if the level parameter is invalid. -*/ + * Compresses the source buffer into the destination buffer. The level + * parameter has the same meaning as in deflateInit. sourceLen is the byte + * length of the source buffer. Upon entry, destLen is the total size of the + * destination buffer, which must be at least the value returned by + * compressBound(sourceLen). Upon exit, destLen is the actual size of the + * compressed buffer. + * + * compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + * memory, Z_BUF_ERROR if there was not enough room in the output buffer, + * Z_STREAM_ERROR if the level parameter is invalid. + */ ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen)); /* - compressBound() returns an upper bound on the compressed size after - compress() or compress2() on sourceLen bytes. It would be used before - a compress() or compress2() call to allocate the destination buffer. -*/ + * compressBound() returns an upper bound on the compressed size after + * compress() or compress2() on sourceLen bytes. It would be used before + * a compress() or compress2() call to allocate the destination buffer. + */ ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen)); + const Bytef *source, uLong sourceLen)); /* - Decompresses the source buffer into the destination buffer. sourceLen is - the byte length of the source buffer. Upon entry, destLen is the total - size of the destination buffer, which must be large enough to hold the - entire uncompressed data. (The size of the uncompressed data must have - been saved previously by the compressor and transmitted to the decompressor - by some mechanism outside the scope of this compression library.) - Upon exit, destLen is the actual size of the compressed buffer. - This function can be used to decompress a whole file at once if the - input file is mmap'ed. - - uncompress returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_BUF_ERROR if there was not enough room in the output - buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. -*/ - + * Decompresses the source buffer into the destination buffer. sourceLen is + * the byte length of the source buffer. Upon entry, destLen is the total + * size of the destination buffer, which must be large enough to hold the + * entire uncompressed data. (The size of the uncompressed data must have + * been saved previously by the compressor and transmitted to the decompressor + * by some mechanism outside the scope of this compression library.) + * Upon exit, destLen is the actual size of the compressed buffer. + * This function can be used to decompress a whole file at once if the + * input file is mmap'ed. + * + * uncompress returns Z_OK if success, Z_MEM_ERROR if there was not + * enough memory, Z_BUF_ERROR if there was not enough room in the output + * buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. + */ typedef voidp gzFile; ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); /* - Opens a gzip (.gz) file for reading or writing. The mode parameter - is as in fopen ("rb" or "wb") but can also include a compression level - ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for - Huffman only compression as in "wb1h", or 'R' for run-length encoding - as in "wb1R". (See the description of deflateInit2 for more information - about the strategy parameter.) - - gzopen can be used to read a file which is not in gzip format; in this - case gzread will directly read from the file without decompression. - - gzopen returns NULL if the file could not be opened or if there was - insufficient memory to allocate the (de)compression state; errno - can be checked to distinguish the two cases (if errno is zero, the - zlib error is Z_MEM_ERROR). */ + * Opens a gzip (.gz) file for reading or writing. The mode parameter + * is as in fopen ("rb" or "wb") but can also include a compression level + * ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for + * Huffman only compression as in "wb1h", or 'R' for run-length encoding + * as in "wb1R". (See the description of deflateInit2 for more information + * about the strategy parameter.) + * + * gzopen can be used to read a file which is not in gzip format; in this + * case gzread will directly read from the file without decompression. + * + * gzopen returns NULL if the file could not be opened or if there was + * insufficient memory to allocate the (de)compression state; errno + * can be checked to distinguish the two cases (if errno is zero, the + * zlib error is Z_MEM_ERROR). + */ ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); /* - gzdopen() associates a gzFile with the file descriptor fd. File - descriptors are obtained from calls like open, dup, creat, pipe or - fileno (in the file has been previously opened with fopen). - The mode parameter is as in gzopen. - The next call of gzclose on the returned gzFile will also close the - file descriptor fd, just like fclose(fdopen(fd), mode) closes the file - descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode). - gzdopen returns NULL if there was insufficient memory to allocate - the (de)compression state. -*/ + * gzdopen() associates a gzFile with the file descriptor fd. File + * descriptors are obtained from calls like open, dup, creat, pipe or + * fileno (in the file has been previously opened with fopen). + * The mode parameter is as in gzopen. + * The next call of gzclose on the returned gzFile will also close the + * file descriptor fd, just like fclose(fdopen(fd), mode) closes the file + * descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode). + * gzdopen returns NULL if there was insufficient memory to allocate + * the (de)compression state. + * + */ ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); /* - Dynamically update the compression level or strategy. See the description - of deflateInit2 for the meaning of these parameters. - gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not - opened for writing. -*/ + * Dynamically update the compression level or strategy. See the description + * of deflateInit2 for the meaning of these parameters. + * gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not + * opened for writing. + */ ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); /* - Reads the given number of uncompressed bytes from the compressed file. - If the input file was not in gzip format, gzread copies the given number - of bytes into the buffer. - gzread returns the number of uncompressed bytes actually read (0 for - end of file, -1 for error). */ + * Reads the given number of uncompressed bytes from the compressed file. + * If the input file was not in gzip format, gzread copies the given number + * of bytes into the buffer. + * gzread returns the number of uncompressed bytes actually read (0 for + * end of file, -1 for error). + */ ZEXTERN int ZEXPORT gzwrite OF((gzFile file, - voidpc buf, unsigned len)); + voidpc buf, unsigned len)); /* - Writes the given number of uncompressed bytes into the compressed file. - gzwrite returns the number of uncompressed bytes actually written - (0 in case of error). -*/ + * Writes the given number of uncompressed bytes into the compressed file. + * gzwrite returns the number of uncompressed bytes actually written + * (0 in case of error). + */ ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...)); /* - Converts, formats, and writes the args to the compressed file under - control of the format string, as in fprintf. gzprintf returns the number of - uncompressed bytes actually written (0 in case of error). The number of - uncompressed bytes written is limited to 4095. The caller should assure that - this limit is not exceeded. If it is exceeded, then gzprintf() will return - return an error (0) with nothing written. In this case, there may also be a - buffer overflow with unpredictable consequences, which is possible only if - zlib was compiled with the insecure functions sprintf() or vsprintf() - because the secure snprintf() or vsnprintf() functions were not available. -*/ + * Converts, formats, and writes the args to the compressed file under + * control of the format string, as in fprintf. gzprintf returns the number of + * uncompressed bytes actually written (0 in case of error). The number of + * uncompressed bytes written is limited to 4095. The caller should assure that + * this limit is not exceeded. If it is exceeded, then gzprintf() will return + * return an error (0) with nothing written. In this case, there may also be a + * buffer overflow with unpredictable consequences, which is possible only if + * zlib was compiled with the insecure functions sprintf() or vsprintf() + * because the secure snprintf() or vsnprintf() functions were not available. + */ ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); /* - Writes the given null-terminated string to the compressed file, excluding - the terminating null character. - gzputs returns the number of characters written, or -1 in case of error. -*/ + * Writes the given null-terminated string to the compressed file, excluding + * the terminating null character. + * gzputs returns the number of characters written, or -1 in case of error. + */ -ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); +ZEXTERN char *ZEXPORT gzgets OF((gzFile file, char *buf, int len)); /* - Reads bytes from the compressed file until len-1 characters are read, or - a newline character is read and transferred to buf, or an end-of-file - condition is encountered. The string is then terminated with a null - character. - gzgets returns buf, or Z_NULL in case of error. -*/ + * Reads bytes from the compressed file until len-1 characters are read, or + * a newline character is read and transferred to buf, or an end-of-file + * condition is encountered. The string is then terminated with a null + * character. + * gzgets returns buf, or Z_NULL in case of error. + */ -ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); +ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); /* - Writes c, converted to an unsigned char, into the compressed file. - gzputc returns the value that was written, or -1 in case of error. -*/ + * Writes c, converted to an unsigned char, into the compressed file. + * gzputc returns the value that was written, or -1 in case of error. + */ -ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); +ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); /* - Reads one byte from the compressed file. gzgetc returns this byte - or -1 in case of end of file or error. -*/ + * Reads one byte from the compressed file. gzgetc returns this byte + * or -1 in case of end of file or error. + */ ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); /* - Push one character back onto the stream to be read again later. - Only one character of push-back is allowed. gzungetc() returns the - character pushed, or -1 on failure. gzungetc() will fail if a - character has been pushed but not read yet, or if c is -1. The pushed - character will be discarded if the stream is repositioned with gzseek() - or gzrewind(). -*/ + * Push one character back onto the stream to be read again later. + * Only one character of push-back is allowed. gzungetc() returns the + * character pushed, or -1 on failure. gzungetc() will fail if a + * character has been pushed but not read yet, or if c is -1. The pushed + * character will be discarded if the stream is repositioned with gzseek() + * or gzrewind(). + */ ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); /* - Flushes all pending output into the compressed file. The parameter - flush is as in the deflate() function. The return value is the zlib - error number (see function gzerror below). gzflush returns Z_OK if - the flush parameter is Z_FINISH and all output could be flushed. - gzflush should be called only when strictly necessary because it can - degrade compression. -*/ + * Flushes all pending output into the compressed file. The parameter + * flush is as in the deflate() function. The return value is the zlib + * error number (see function gzerror below). gzflush returns Z_OK if + * the flush parameter is Z_FINISH and all output could be flushed. + * gzflush should be called only when strictly necessary because it can + * degrade compression. + */ ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, - z_off_t offset, int whence)); -/* - Sets the starting position for the next gzread or gzwrite on the - given compressed file. The offset represents a number of bytes in the - uncompressed data stream. The whence parameter is defined as in lseek(2); - the value SEEK_END is not supported. - If the file is opened for reading, this function is emulated but can be - extremely slow. If the file is opened for writing, only forward seeks are - supported; gzseek then compresses a sequence of zeroes up to the new - starting position. - - gzseek returns the resulting offset location as measured in bytes from - the beginning of the uncompressed stream, or -1 in case of error, in - particular if the file is opened for writing and the new starting position - would be before the current position. -*/ + z_off_t offset, int whence)); +/* + * Sets the starting position for the next gzread or gzwrite on the + * given compressed file. The offset represents a number of bytes in the + * uncompressed data stream. The whence parameter is defined as in lseek(2); + * the value SEEK_END is not supported. + * If the file is opened for reading, this function is emulated but can be + * extremely slow. If the file is opened for writing, only forward seeks are + * supported; gzseek then compresses a sequence of zeroes up to the new + * starting position. + * + * gzseek returns the resulting offset location as measured in bytes from + * the beginning of the uncompressed stream, or -1 in case of error, in + * particular if the file is opened for writing and the new starting position + * would be before the current position. + */ ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); /* - Rewinds the given file. This function is supported only for reading. - - gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET) -*/ + * Rewinds the given file. This function is supported only for reading. + * + * gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET) + */ ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); /* - Returns the starting position for the next gzread or gzwrite on the - given compressed file. This position represents a number of bytes in the - uncompressed data stream. - - gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) -*/ + * Returns the starting position for the next gzread or gzwrite on the + * given compressed file. This position represents a number of bytes in the + * uncompressed data stream. + * + * gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) + */ ZEXTERN int ZEXPORT gzeof OF((gzFile file)); /* - Returns 1 when EOF has previously been detected reading the given - input stream, otherwise zero. -*/ + * Returns 1 when EOF has previously been detected reading the given + * input stream, otherwise zero. + */ ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); /* - Returns 1 if file is being read directly without decompression, otherwise - zero. -*/ + * Returns 1 if file is being read directly without decompression, otherwise + * zero. + */ ZEXTERN int ZEXPORT gzclose OF((gzFile file)); /* - Flushes all pending output if necessary, closes the compressed file - and deallocates all the (de)compression state. The return value is the zlib - error number (see function gzerror below). -*/ + * Flushes all pending output if necessary, closes the compressed file + * and deallocates all the (de)compression state. The return value is the zlib + * error number (see function gzerror below). + */ -ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); +ZEXTERN const char *ZEXPORT gzerror OF((gzFile file, int *errnum)); /* - Returns the error message for the last error which occurred on the - given compressed file. errnum is set to zlib error number. If an - error occurred in the file system and not in the compression library, - errnum is set to Z_ERRNO and the application may consult errno - to get the exact error code. -*/ + * Returns the error message for the last error which occurred on the + * given compressed file. errnum is set to zlib error number. If an + * error occurred in the file system and not in the compression library, + * errnum is set to Z_ERRNO and the application may consult errno + * to get the exact error code. + */ ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); /* - Clears the error and end-of-file flags for file. This is analogous to the - clearerr() function in stdio. This is useful for continuing to read a gzip - file that is being written concurrently. -*/ + * Clears the error and end-of-file flags for file. This is analogous to the + * clearerr() function in stdio. This is useful for continuing to read a gzip + * file that is being written concurrently. + */ - /* checksum functions */ +/* checksum functions */ /* - These functions are not related to compression but are exported - anyway because they might be useful in applications using the - compression library. -*/ + * These functions are not related to compression but are exported + * anyway because they might be useful in applications using the + * compression library. + */ ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); /* - Update a running Adler-32 checksum with the bytes buf[0..len-1] and - return the updated checksum. If buf is NULL, this function returns - the required initial value for the checksum. - An Adler-32 checksum is almost as reliable as a CRC32 but can be computed - much faster. Usage example: - - uLong adler = adler32(0L, Z_NULL, 0); - - while (read_buffer(buffer, length) != EOF) { - adler = adler32(adler, buffer, length); - } - if (adler != original_adler) error(); -*/ + * Update a running Adler-32 checksum with the bytes buf[0..len-1] and + * return the updated checksum. If buf is NULL, this function returns + * the required initial value for the checksum. + * An Adler-32 checksum is almost as reliable as a CRC32 but can be computed + * much faster. Usage example: + * + * uLong adler = adler32(0L, Z_NULL, 0); + * + * while (read_buffer(buffer, length) != EOF) { + * adler = adler32(adler, buffer, length); + * } + * if (adler != original_adler) error(); + */ ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, - z_off_t len2)); + z_off_t len2)); /* - Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 - and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for - each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of - seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. -*/ + * Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 + * and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for + * each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of + * seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. + */ ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); /* - Update a running CRC-32 with the bytes buf[0..len-1] and return the - updated CRC-32. If buf is NULL, this function returns the required initial - value for the for the crc. Pre- and post-conditioning (one's complement) is - performed within this function so it shouldn't be done by the application. - Usage example: - - uLong crc = crc32(0L, Z_NULL, 0); - - while (read_buffer(buffer, length) != EOF) { - crc = crc32(crc, buffer, length); - } - if (crc != original_crc) error(); -*/ + * Update a running CRC-32 with the bytes buf[0..len-1] and return the + * updated CRC-32. If buf is NULL, this function returns the required initial + * value for the for the crc. Pre- and post-conditioning (one's complement) is + * performed within this function so it shouldn't be done by the application. + * Usage example: + * + * uLong crc = crc32(0L, Z_NULL, 0); + * + * while (read_buffer(buffer, length) != EOF) { + * crc = crc32(crc, buffer, length); + * } + * if (crc != original_crc) error(); + */ ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2)); /* - Combine two CRC-32 check values into one. For two sequences of bytes, - seq1 and seq2 with lengths len1 and len2, CRC-32 check values were - calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 - check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and - len2. -*/ + * Combine two CRC-32 check values into one. For two sequences of bytes, + * seq1 and seq2 with lengths len1 and len2, CRC-32 check values were + * calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 + * check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and + * len2. + */ - /* various hacks, don't look :) */ +/* various hacks, don't look :) */ -/* deflateInit and inflateInit are macros to allow checking the zlib version +/* + * deflateInit and inflateInit are macros to allow checking the zlib version * and the compiler's view of z_stream: */ ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level, - const char *version, int stream_size)); + const char *version, int stream_size)); ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm, - const char *version, int stream_size)); + const char *version, int stream_size)); ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method, - int windowBits, int memLevel, - int strategy, const char *version, - int stream_size)); + int windowBits, int memLevel, + int strategy, const char *version, + int stream_size)); ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits, - const char *version, int stream_size)); + const char *version, int stream_size)); ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, - unsigned char FAR *window, - const char *version, - int stream_size)); -#define deflateInit(strm, level) \ - deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream)) -#define inflateInit(strm) \ - inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream)) -#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ - deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ - (strategy), ZLIB_VERSION, sizeof(z_stream)) -#define inflateInit2(strm, windowBits) \ - inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream)) -#define inflateBackInit(strm, windowBits, window) \ - inflateBackInit_((strm), (windowBits), (window), \ - ZLIB_VERSION, sizeof(z_stream)) + unsigned char FAR *window, + const char *version, + int stream_size)); +#define deflateInit(strm, level) \ + deflateInit_((strm), (level), ZLIB_VERSION, sizeof (z_stream)) +#define inflateInit(strm) \ + inflateInit_((strm), ZLIB_VERSION, sizeof (z_stream)) +#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ + deflateInit2_((strm), (level), (method), (windowBits), (memLevel), \ + (strategy), ZLIB_VERSION, sizeof (z_stream)) +#define inflateInit2(strm, windowBits) \ + inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof (z_stream)) +#define inflateBackInit(strm, windowBits, window) \ + inflateBackInit_((strm), (windowBits), (window), \ + ZLIB_VERSION, sizeof (z_stream)) #if !defined(_ZUTIL_H) && !defined(NO_DUMMY_DECL) - struct internal_state {int dummy;}; /* hack for buggy compilers */ + struct internal_state {int dummy; }; /* hack for buggy compilers */ #endif -ZEXTERN const char * ZEXPORT zError OF((int)); -ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z)); -ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void)); +ZEXTERN const char *ZEXPORT zError OF((int)); +ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z)); +ZEXTERN const uLongf *ZEXPORT get_crc_table OF((void)); #ifdef __cplusplus } diff --git a/include/os/windows/zfs/sys/zvol_os.h b/include/os/windows/zfs/sys/zvol_os.h index aefb951e92b..b0425349f10 100644 --- a/include/os/windows/zfs/sys/zvol_os.h +++ b/include/os/windows/zfs/sys/zvol_os.h @@ -39,7 +39,8 @@ struct zvol_state_os { uint64_t zso_openflags; /* Remember flags used at open */ uint8_t zso_target_id; uint8_t zso_lun_id; - void *zso_target_context; // for I/O drainage (see assign_targetid, clear_targetid) + // for I/O drainage (see assign_targetid, clear_targetid) + void *zso_target_context; }; extern int zvol_os_ioctl(dev_t, unsigned long, caddr_t, diff --git a/include/os/windows/zfs/zfs_config.h b/include/os/windows/zfs/zfs_config.h index c69b409defa..659e8605ece 100644 --- a/include/os/windows/zfs/zfs_config.h +++ b/include/os/windows/zfs/zfs_config.h @@ -3,84 +3,84 @@ /* Define to 1 to enabled dmu tx validation */ /* #undef DEBUG_DMU_TX */ -#define SYSCONFDIR "/etc/zfs/scripts/" // Windwosify me +#define SYSCONFDIR "/etc/zfs/scripts/" // Windwosify me #define TEXT_DOMAIN "zfs-windows-user" /* Path where the Filesystems bundle is installed. */ -#define FILESYSTEMS_PREFIX "/Library/Filesystems" +#define FILESYSTEMS_PREFIX "/Library/Filesystems" /* Define to 1 if you have the header file. */ -#define HAVE_DLFCN_H 1 +#define HAVE_DLFCN_H 1 /* Define to 1 if you have the header file. */ -#define HAVE_INTTYPES_H 1 +#define HAVE_INTTYPES_H 1 /* Define if you have libblkid */ /* #undef HAVE_LIBBLKID */ /* Define if you have libuuid */ -#define HAVE_LIBUUID 1 +#define HAVE_LIBUUID 1 -#define HAVE_XDR_BYTESREC 1 +#define HAVE_XDR_BYTESREC 1 /* Define to 1 if you have the header file. */ -#define HAVE_MEMORY_H 1 +#define HAVE_MEMORY_H 1 /* Define to 1 if you have the `mlockall' function. */ -#define HAVE_MLOCKALL 1 +#define HAVE_MLOCKALL 1 /* Define to 1 if you have the header file. */ -#define HAVE_STDINT_H 1 +#define HAVE_STDINT_H 1 /* Define to 1 if you have the header file. */ -#define HAVE_STDLIB_H 1 +#define HAVE_STDLIB_H 1 /* Define to 1 if you have the header file. */ -#define HAVE_STRINGS_H 1 +#define HAVE_STRINGS_H 1 /* Define to 1 if you have the header file. */ -#define HAVE_STRING_H 1 +#define HAVE_STRING_H 1 /* Define to 1 if you have the header file. */ -#define HAVE_SYS_STAT_H 1 +#define HAVE_SYS_STAT_H 1 /* Define to 1 if you have the header file. */ -#define HAVE_SYS_TYPES_H 1 +#define HAVE_SYS_TYPES_H 1 /* Define to 1 if you have the header file. */ -#define HAVE_UNISTD_H 1 +#define HAVE_UNISTD_H 1 #define HAVE_SETMNTENT /* Define if you have zlib */ -#define HAVE_ZLIB 1 +#define HAVE_ZLIB 1 #define HAVE_LOFF_T 1 #define HAVE_USLEEP 1 /* Path where the kernel module is installed. */ -#define KERNEL_MODPREFIX "/Library/Extensions" +#define KERNEL_MODPREFIX "/Library/Extensions" /* Define to the sub-directory where libtool stores uninstalled libraries. */ -#define LT_OBJDIR ".libs/" +#define LT_OBJDIR ".libs/" /* Define to a directory where mount(2) will look for mount_zfs. */ -#define MOUNTEXECDIR "${exec_prefix}/sbin" +#define MOUNTEXECDIR "${exec_prefix}/sbin" /* Define ZFS_BOOT to enable kext load at boot */ -#define ZFS_BOOT 1 +#define ZFS_BOOT 1 /* zfs debugging enabled */ /* Define the project author. */ -#define ZFS_META_AUTHOR "OpenZFS on Windows" +#define ZFS_META_AUTHOR "OpenZFS on Windows" /* Define the project release date. */ /* #undef ZFS_META_DATA */ /* Define the project license. */ -#define ZFS_META_LICENSE "CDDL" +#define ZFS_META_LICENSE "CDDL" /* Define the libtool library 'age' version information. */ /* #undef ZFS_META_LT_AGE */ @@ -92,13 +92,13 @@ /* #undef ZFS_META_LT_REVISION */ /* Define the project name. */ -#define ZFS_META_NAME "zfs" +#define ZFS_META_NAME "zfs" /* Define the project release. */ -#define ZFS_META_RELEASE "2" +#define ZFS_META_RELEASE "2" /* Define the project version. */ -#define ZFS_META_VERSION "2.0.0" +#define ZFS_META_VERSION "2.0.0" /* Define the project alias string. */ -#define ZFS_META_ALIAS "zfs-" ZFS_META_VERSION "-" ZFS_META_RELEASE +#define ZFS_META_ALIAS "zfs-" ZFS_META_VERSION "-" ZFS_META_RELEASE diff --git a/include/sys/abd_impl.h b/include/sys/abd_impl.h index e96f1edfc8c..dde0403083b 100644 --- a/include/sys/abd_impl.h +++ b/include/sys/abd_impl.h @@ -95,6 +95,9 @@ void abd_iter_unmap(struct abd_iter *); #if defined(__FreeBSD__) #define abd_enter_critical(flags) critical_enter() #define abd_exit_critical(flags) critical_exit() +#elif defined(_WIN32) +#define abd_enter_critical(flags) +#define abd_exit_critical(flags) #else #define abd_enter_critical(flags) local_irq_save(flags) #define abd_exit_critical(flags) local_irq_restore(flags) diff --git a/include/sys/fs/zfs.h b/include/sys/fs/zfs.h index f52ec4607bd..f650c9ecbea 100644 --- a/include/sys/fs/zfs.h +++ b/include/sys/fs/zfs.h @@ -187,7 +187,7 @@ typedef enum { ZFS_PROP_IVSET_GUID, /* not exposed to the user */ ZFS_PROP_REDACTED, ZFS_PROP_REDACT_SNAPS, - ZFS_PROP_MIMIC, /* Windows: mimic=ntfs */ + ZFS_PROP_MIMIC, /* Windows: mimic=ntfs */ ZFS_PROP_DRIVELETTER, ZFS_NUM_PROPS } zfs_prop_t; diff --git a/lib/libefi/rdwr_efi_windows.c b/lib/libefi/rdwr_efi_windows.c index a2a3d747f35..fe379c28e92 100644 --- a/lib/libefi/rdwr_efi_windows.c +++ b/lib/libefi/rdwr_efi_windows.c @@ -142,19 +142,19 @@ static int read_disk_info(int fd, diskaddr_t *capacity, uint_t *lbsize) { DISK_GEOMETRY_EX geometry_ex; - DWORD len; + DWORD len; LARGE_INTEGER large; if (DeviceIoControl(ITOH(fd), IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, NULL, 0, - &geometry_ex, sizeof(geometry_ex), &len, NULL)) { + &geometry_ex, sizeof (geometry_ex), &len, NULL)) { *lbsize = (uint_t)geometry_ex.Geometry.BytesPerSector; *capacity = (diskaddr_t)geometry_ex.DiskSize.QuadPart; *capacity /= *lbsize; // Capacity is in # blocks - return 0; + return (0); } - return 0; + return (0); } static int @@ -286,7 +286,7 @@ efi_get_info(int fd, struct dk_cinfo *dki_info) } strlcpy(dki_info->dki_dname, &pathbuf[5], - sizeof(dki_info->dki_dname)); + sizeof (dki_info->dki_dname)); } /* @@ -329,21 +329,20 @@ efi_get_info(int fd, struct dk_cinfo *dki_info) DWORD retcount = 0; int err; err = DeviceIoControl(ITOH(fd), - IOCTL_DISK_GET_PARTITION_INFO, - (LPVOID)NULL, - (DWORD)0, - (LPVOID)&partInfo, - sizeof(partInfo), - &retcount, - (LPOVERLAPPED)NULL); + IOCTL_DISK_GET_PARTITION_INFO, + (LPVOID)NULL, + (DWORD)0, + (LPVOID)&partInfo, + sizeof (partInfo), + &retcount, + (LPOVERLAPPED)NULL); if (err) { dki_info->dki_partition = 0; dki_info->dki_ctype = DKC_DIRECT; strlcpy(dki_info->dki_dname, "getnamehere", - sizeof(dki_info->dki_dname)); - } - else { + sizeof (dki_info->dki_dname)); + } else { err = GetLastError(); } @@ -399,7 +398,7 @@ efi_alloc_and_init(int fd, uint32_t nparts, struct dk_gpt **vtoc) return (-1); if (lbsize == 0) - return (-1); + return (-1); nblocks = NBLOCKS(nparts, lbsize); if ((nblocks * lbsize) < EFI_MIN_ARRAY_SIZE + lbsize) { @@ -588,7 +587,7 @@ efi_ioctl(int fd, int cmd, dk_efi_t *dk_ioc) return (error); /* Ensure any local disk cache is also flushed */ -#if defined (__linux__) +#if defined(__linux__) if (ioctl(fd, BLKFLSBUF, 0) == -1) return (error); #endif @@ -666,8 +665,8 @@ check_label(int fd, dk_efi_t *dk_ioc) if (headerSize < EFI_MIN_LABEL_SIZE || headerSize > EFI_LABEL_SIZE) { if (efi_debug) (void) fprintf(stderr, - "Invalid EFI HeaderSize %llu. Assuming %d.\n", - headerSize, EFI_MIN_LABEL_SIZE); + "Invalid EFI HeaderSize %llu. Assuming %d.\n", + headerSize, EFI_MIN_LABEL_SIZE); } if ((headerSize > dk_ioc->dki_length) || @@ -1601,124 +1600,3 @@ efi_auto_sense(int fd, struct dk_gpt **vtoc) (*vtoc)->efi_parts[8].p_tag = V_RESERVED; return (0); } - -#ifdef __APPLE__ -#include -#include - -static const CFStringRef CoreStorageLogicalVolumeMediaPathSubstring = - CFSTR("/CoreStoragePhysical/"); -static const CFStringRef VirtualInterfaceDeviceProtocolSubstring = - CFSTR(kIOPropertyPhysicalInterconnectTypeVirtual); - -typedef struct { - DASessionRef session; - DADiskRef disk; -} DADiskSession; - -Boolean -CFDictionaryValueIfPresentMatchesSubstring(CFDictionaryRef dict, - CFStringRef key, CFStringRef substr) -{ - Boolean ret = false; - CFStringRef existing; - if (dict && - CFDictionaryGetValueIfPresent(dict, key, - (const void **)&existing)) { - CFRange range = CFStringFind(existing, substr, - kCFCompareCaseInsensitive); - if (range.location != kCFNotFound) - ret = true; - } - return (ret); -} - -int -setupDADiskSession(DADiskSession *ds, const char *bsdName) -{ - int err = 0; - - ds->session = DASessionCreate(NULL); - if (ds->session == NULL) { - err = EINVAL; - } - - if (err == 0) { - ds->disk = DADiskCreateFromBSDName(NULL, ds->session, bsdName); - if (ds->disk == NULL) - err = EINVAL; - } - return (err); -} - -void -teardownDADiskSession(DADiskSession *ds) -{ - if (ds->session != NULL) - CFRelease(ds->session); - if (ds->disk != NULL) - CFRelease(ds->disk); -} - - -int -isDeviceMatchForKeyAndSubstr(char *device, CFStringRef key, CFStringRef substr, - Boolean *isMatch) -{ - int error; - DADiskSession ds = { 0 }; - - if (!isMatch) - return (-1); - - if ((error = setupDADiskSession(&ds, device)) == 0) { - CFDictionaryRef descDict = NULL; - if((descDict = DADiskCopyDescription(ds.disk)) != NULL) { - *isMatch = - CFDictionaryValueIfPresentMatchesSubstring(descDict, - key, substr); - } else { - error = -1; - (void) fprintf(stderr, - "no DADiskCopyDescription for device %s\n", - device); - *isMatch = false; - } - } - - teardownDADiskSession(&ds); - return (error); -} - -/* - * Caller is responsible for supplying a /dev/disk* block device path - * or the BSD name (disk*). - */ -int -osx_device_isvirtual(char *device) -{ - Boolean isCoreStorageLV = false; - Boolean isVirtualInterface = false; - - if (efi_debug) - (void) fprintf(stderr, "Checking if '%s' is virtual\n", device); - - isDeviceMatchForKeyAndSubstr(device, - kDADiskDescriptionMediaPathKey, - CoreStorageLogicalVolumeMediaPathSubstring, - &isCoreStorageLV); - - isDeviceMatchForKeyAndSubstr(device, - kDADiskDescriptionDeviceProtocolKey, - VirtualInterfaceDeviceProtocolSubstring, - &isVirtualInterface); - - if (efi_debug) - (void) fprintf(stderr, - "Is CoreStorage LV %d : is virtual interface %d\n", - isCoreStorageLV, - isVirtualInterface); - - return (isCoreStorageLV || isVirtualInterface); -} -#endif diff --git a/lib/libshare/os/windows/nfs.c b/lib/libshare/os/windows/nfs.c index 0598cbcb350..d710a688fc1 100644 --- a/lib/libshare/os/windows/nfs.c +++ b/lib/libshare/os/windows/nfs.c @@ -52,10 +52,10 @@ static sa_fstype_t *nfs_fstype; static int nfs_lock_fd = -1; -#define LOCK_EX 1 -#define LOCK_SH 2 -#define LOCK_UN 3 -#define LOCK_NB 4 +#define LOCK_EX 1 +#define LOCK_SH 2 +#define LOCK_UN 3 +#define LOCK_NB 4 /* * The nfs_exports_[lock|unlock] is used to guard against conconcurrent diff --git a/lib/libspl/include/os/windows/dirent.h b/lib/libspl/include/os/windows/dirent.h index 91cf87567c1..aab9d30d695 100644 --- a/lib/libspl/include/os/windows/dirent.h +++ b/lib/libspl/include/os/windows/dirent.h @@ -1,27 +1,28 @@ /* -MIT License -Copyright (c) 2019 win32ports -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ + * MIT License + * Copyright (c) 2019 win32ports + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE + * OR OTHER DEALINGS IN THE SOFTWARE. + */ #pragma once #ifndef __DIRENT_H_9DE6B42C_8D0C_4D31_A8EF_8E4C30E6C46A__ -#define __DIRENT_H_9DE6B42C_8D0C_4D31_A8EF_8E4C30E6C46A__ +#define __DIRENT_H_9DE6B42C_8D0C_4D31_A8EF_8E4C30E6C46A__ #ifndef _WIN32 @@ -37,76 +38,76 @@ extern "C" { #include #if defined(_MSC_VER) -# define S_IRUSR S_IREAD /* read, user */ -# define S_IWUSR S_IWRITE /* write, user */ -# define S_IXUSR 0 /* execute, user */ -# define S_IRGRP 0 /* read, group */ -# define S_IWGRP 0 /* write, group */ -# define S_IXGRP 0 /* execute, group */ -# define S_IROTH 0 /* read, others */ -# define S_IWOTH 0 /* write, others */ -# define S_IXOTH 0 /* execute, others */ +#define S_IRUSR S_IREAD /* read, user */ +#define S_IWUSR S_IWRITE /* write, user */ +#define S_IXUSR 0 /* execute, user */ +#define S_IRGRP 0 /* read, group */ +#define S_IWGRP 0 /* write, group */ +#define S_IXGRP 0 /* execute, group */ +#define S_IROTH 0 /* read, others */ +#define S_IWOTH 0 /* write, others */ +#define S_IXOTH 0 /* execute, others */ #endif #ifndef NAME_MAX -#define NAME_MAX 260 +#define NAME_MAX 260 #endif /* NAME_MAX */ #ifndef DT_UNKNOWN -#define DT_UNKNOWN 0 +#define DT_UNKNOWN 0 #endif /* DT_UNKNOWN */ #ifndef DT_FIFO -#define DT_FIFO 1 +#define DT_FIFO 1 #endif /* DT_FIFO */ #ifndef DT_CHR -#define DT_CHR 2 +#define DT_CHR 2 #endif /* DT_CHR */ #ifndef DT_DIR -#define DT_DIR 4 +#define DT_DIR 4 #endif /* DT_DIR */ #ifndef DT_BLK -#define DT_BLK 6 +#define DT_BLK 6 #endif /* DT_BLK */ #ifndef DT_REG -#define DT_REG 8 +#define DT_REG 8 #endif /* DT_REF */ #ifndef DT_LNK -#define DT_LNK 10 +#define DT_LNK 10 #endif /* DT_LNK */ #ifndef DT_SOCK -#define DT_SOCK 12 +#define DT_SOCK 12 #endif /* DT_SOCK */ #ifndef DT_WHT -#define DT_WHT 14 +#define DT_WHT 14 #endif /* DT_WHT */ #ifndef _DIRENT_HAVE_D_NAMLEN -#define _DIRENT_HAVE_D_NAMLEN 1 +#define _DIRENT_HAVE_D_NAMLEN 1 #endif /* _DIRENT_HAVE_D_NAMLEN */ #ifndef _DIRENT_HAVE_D_RECLEN -#define _DIRENT_HAVE_D_RECLEN 1 +#define _DIRENT_HAVE_D_RECLEN 1 #endif /* _DIRENT_HAVE_D_RECLEN */ #ifndef _DIRENT_HAVE_D_OFF -#define _DIRENT_HAVE_D_OFF 1 +#define _DIRENT_HAVE_D_OFF 1 #endif /* _DIRENT_HAVE_D_OFF */ -#ifndef _DIRENT_HAVE_D_TYPE -#define _DIRENT_HAVE_D_TYPE 1 +#ifndef _DIRENT_HAVE_D_TYPE +#define _DIRENT_HAVE_D_TYPE 1 #endif /* _DIRENT_HAVE_D_TYPE */ #ifndef NTFS_MAX_PATH -#define NTFS_MAX_PATH 32768 +#define NTFS_MAX_PATH 32768 #endif /* NTFS_MAX_PATH */ typedef void* DIR; @@ -129,7 +130,7 @@ struct dirent struct __dir { - struct dirent* entries; + struct dirent *entries; int fd; long int count; long int index; @@ -140,21 +141,23 @@ struct __dir #pragma GCC diagnostic ignored "-Wunused-function" #endif -static int closedir(DIR* dirp) +static int +closedir(DIR* dirp) { - struct __dir* data = NULL; + struct __dir *data = NULL; if (!dirp) { errno = EBADF; - return -1; + return (-1); } - data = (struct __dir*) dirp; + data = (struct __dir *)dirp; CloseHandle((HANDLE)data->fd); free(data->entries); free(data); - return 0; + return (0); } -static void __seterrno(int value) +static void +__seterrno(int value) { #ifdef _MSC_VER _set_errno(value); @@ -163,139 +166,151 @@ static void __seterrno(int value) #endif /* _MSC_VER */ } -static int __islink(const wchar_t * name, char * buffer) +static int +__islink(const wchar_t *name, char *buffer) { DWORD io_result = 0; DWORD bytes_returned = 0; HANDLE hFile = CreateFileW(name, 0, 0, NULL, OPEN_EXISTING, - FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, 0); + FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, 0); if (hFile == INVALID_HANDLE_VALUE) - return 0; + return (0); io_result = DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT, NULL, 0, - buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE, &bytes_returned, NULL); + buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE, &bytes_returned, NULL); CloseHandle(hFile); if (io_result == 0) - return 0; + return (0); - return ((REPARSE_GUID_DATA_BUFFER*)buffer)->ReparseTag == IO_REPARSE_TAG_SYMLINK; + return (((REPARSE_GUID_DATA_BUFFER*)buffer)->ReparseTag == + IO_REPARSE_TAG_SYMLINK); } -static __ino_t __inode(const wchar_t* name) +static __ino_t +__inode(const wchar_t *name) { __ino_t value = { 0 }; BOOL result; FILE_ID_INFO fileid; BY_HANDLE_FILE_INFORMATION info; - HANDLE hFile = CreateFileW(name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0); + HANDLE hFile = CreateFileW(name, GENERIC_READ, FILE_SHARE_READ, + NULL, OPEN_EXISTING, 0, 0); if (hFile == INVALID_HANDLE_VALUE) - return value; + return (value); - result = GetFileInformationByHandleEx(hFile, FileIdInfo, &fileid, sizeof(fileid)); - if (result) - { + result = GetFileInformationByHandleEx(hFile, FileIdInfo, + &fileid, sizeof (fileid)); + if (result) { value.serial = fileid.VolumeSerialNumber; memcpy(value.fileid, fileid.FileId.Identifier, 16); - } - else - { + } else { result = GetFileInformationByHandle(hFile, &info); - if(result) - { + if (result) { value.serial = info.dwVolumeSerialNumber; memcpy(value.fileid + 8, &info.nFileIndexHigh, 4); memcpy(value.fileid + 12, &info.nFileIndexLow, 4); } } CloseHandle(hFile); - return value; + return (value); } -static DIR* __internal_opendir(wchar_t* wname, int size) +static DIR * +__internal_opendir(wchar_t *wname, int size) { - struct __dir* data = NULL; + struct __dir *data = NULL; struct dirent *tmp_entries = NULL; static char default_char = '?'; // static wchar_t* prefix = L"\\\\?\\"; - static wchar_t* suffix = L"\\*.*"; + static wchar_t *suffix = L"\\*.*"; int extra_prefix = 4; /* use prefix "\\?\" to handle long file names */ static int extra_suffix = 4; /* use suffix "\*.*" to find everything */ WIN32_FIND_DATAW w32fd = { 0 }; HANDLE hFindFile = INVALID_HANDLE_VALUE; static int grow_factor = 2; - char* buffer = NULL; + char *buffer = NULL; - memcpy(wname + extra_prefix + size - 1, suffix, sizeof(wchar_t) * extra_prefix); + memcpy(wname + extra_prefix + size - 1, suffix, + sizeof (wchar_t) * extra_prefix); wname[size + extra_prefix + extra_suffix - 1] = 0; - if (memcmp(wname + extra_prefix, L"\\\\?\\", sizeof(wchar_t) * extra_prefix) == 0) - { + if (memcmp(wname + extra_prefix, L"\\\\?\\", + sizeof (wchar_t) * extra_prefix) == 0) { wname += extra_prefix; extra_prefix = 0; } - + hFindFile = FindFirstFileW(wname, &w32fd); - if (INVALID_HANDLE_VALUE == hFindFile) - { + if (INVALID_HANDLE_VALUE == hFindFile) { __seterrno(ENOENT); - return NULL; + return (NULL); } - data = (struct __dir*) malloc(sizeof(struct __dir)); + data = (struct __dir *)malloc(sizeof (struct __dir)); if (!data) goto out_of_memory; wname[extra_prefix + size - 1] = 0; - data->fd = (int)CreateFileW(wname, 0, 0, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0); + data->fd = (int)CreateFileW(wname, 0, 0, NULL, OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS, 0); wname[extra_prefix + size - 1] = L'\\'; data->count = 16; data->index = 0; - data->entries = (struct dirent*) malloc(sizeof(struct dirent) * data->count); + data->entries = (struct dirent *)malloc( + sizeof (struct dirent) * data->count); if (!data->entries) goto out_of_memory; buffer = (char *)malloc(MAXIMUM_REPARSE_DATA_BUFFER_SIZE); if (!buffer) goto out_of_memory; - do - { - WideCharToMultiByte(CP_UTF8, 0, w32fd.cFileName, -1, data->entries[data->index].d_name, NAME_MAX, &default_char, NULL); + do { + WideCharToMultiByte(CP_UTF8, 0, w32fd.cFileName, -1, + data->entries[data->index].d_name, NAME_MAX, + &default_char, NULL); - memcpy(wname + extra_prefix + size, w32fd.cFileName, sizeof(wchar_t) * NAME_MAX); + memcpy(wname + extra_prefix + size, w32fd.cFileName, + sizeof (wchar_t) * NAME_MAX); - if (((w32fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) == FILE_ATTRIBUTE_REPARSE_POINT) && __islink(wname, buffer)) + if (((w32fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) == + FILE_ATTRIBUTE_REPARSE_POINT) && __islink(wname, buffer)) data->entries[data->index].d_type = DT_LNK; - else if ((w32fd.dwFileAttributes & FILE_ATTRIBUTE_DEVICE) == FILE_ATTRIBUTE_DEVICE) + else if ((w32fd.dwFileAttributes & FILE_ATTRIBUTE_DEVICE) == + FILE_ATTRIBUTE_DEVICE) data->entries[data->index].d_type = DT_CHR; - else if ((w32fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY) + else if ((w32fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == + FILE_ATTRIBUTE_DIRECTORY) data->entries[data->index].d_type = DT_DIR; else data->entries[data->index].d_type = DT_REG; data->entries[data->index].d_ino = __inode(wname); - data->entries[data->index].d_reclen = sizeof(struct dirent); - data->entries[data->index].d_namelen = (unsigned char)wcslen(w32fd.cFileName); + data->entries[data->index].d_reclen = sizeof (struct dirent); + data->entries[data->index].d_namelen = + (unsigned char)wcslen(w32fd.cFileName); data->entries[data->index].d_off = 0; if (++data->index == data->count) { - tmp_entries = (struct dirent*) realloc(data->entries, sizeof(struct dirent) * data->count * grow_factor); + tmp_entries = (struct dirent *)realloc(data->entries, + sizeof (struct dirent) * data->count * grow_factor); if (!tmp_entries) goto out_of_memory; data->entries = tmp_entries; data->count *= grow_factor; } } - while (FindNextFileW(hFindFile, &w32fd) != 0); + while (FindNextFileW(hFindFile, &w32fd) != 0) + ; free(buffer); FindClose(hFindFile); data->count = data->index; data->index = 0; - return (DIR*)data; + return ((DIR*)data); + out_of_memory: - if (data) - { + if (data) { if (INVALID_HANDLE_VALUE != (HANDLE)data->fd) CloseHandle((HANDLE)data->fd); free(data->entries); @@ -305,225 +320,232 @@ static DIR* __internal_opendir(wchar_t* wname, int size) if (INVALID_HANDLE_VALUE != hFindFile) FindClose(hFindFile); __seterrno(ENOMEM); - return NULL; + return (NULL); } -static wchar_t* __get_buffer() +static wchar_t * +__get_buffer(void) { - wchar_t* name = (wchar_t *)malloc(sizeof(wchar_t) * (NTFS_MAX_PATH + NAME_MAX + 8)); + wchar_t *name = (wchar_t *)malloc( + sizeof (wchar_t) * (NTFS_MAX_PATH + NAME_MAX + 8)); if (name) - memcpy(name, L"\\\\?\\", sizeof(wchar_t) * 4); - return name; + memcpy(name, L"\\\\?\\", sizeof (wchar_t) * 4); + return (name); } -static DIR* opendir(const char* name) +static DIR * +opendir(const char *name) { - DIR* dirp = NULL; - wchar_t* wname = __get_buffer(); + DIR *dirp = NULL; + wchar_t *wname = __get_buffer(); int size = 0; - if (!wname) - { + if (!wname) { errno = ENOMEM; - return NULL; + return (NULL); } - size = MultiByteToWideChar(CP_UTF8, 0, name, -1, wname + 4, NTFS_MAX_PATH); - if (0 == size) - { + size = MultiByteToWideChar(CP_UTF8, 0, name, -1, wname + 4, + NTFS_MAX_PATH); + if (0 == size) { free(wname); - return NULL; + return (NULL); } dirp = __internal_opendir(wname, size); free(wname); - return dirp; + return (dirp); } -static DIR* _wopendir(const wchar_t* name) +static DIR * +_wopendir(const wchar_t *name) { - DIR* dirp = NULL; - wchar_t* wname = __get_buffer(); + DIR *dirp = NULL; + wchar_t *wname = __get_buffer(); int size = 0; - if (!wname) - { + if (!wname) { errno = ENOMEM; - return NULL; + return (NULL); } size = (int)wcslen(name); - if (size > NTFS_MAX_PATH) - { + if (size > NTFS_MAX_PATH) { free(wname); - return NULL; + return (NULL); } - memcpy(wname + 4, name, sizeof(wchar_t) * (size + 1)); + memcpy(wname + 4, name, sizeof (wchar_t) * (size + 1)); dirp = __internal_opendir(wname, size + 1); free(wname); - return dirp; + return (dirp); } -static DIR* fdopendir(int fd) +static DIR * +fdopendir(int fd) { - DIR* dirp = NULL; - wchar_t* wname = __get_buffer(); + DIR *dirp = NULL; + wchar_t *wname = __get_buffer(); int size = 0; - if (!wname) - { + if (!wname) { errno = ENOMEM; - return NULL; + return (NULL); } - size = GetFinalPathNameByHandleW((HANDLE)fd, wname, NTFS_MAX_PATH, FILE_NAME_NORMALIZED); - if (0 == size) - { + size = GetFinalPathNameByHandleW((HANDLE)fd, wname, + NTFS_MAX_PATH, FILE_NAME_NORMALIZED); + if (0 == size) { free(wname); errno = ENOTDIR; - return NULL; + return (NULL); } dirp = __internal_opendir(wname, size + 1); free(wname); - return dirp; + return (dirp); } -static struct dirent* readdir(DIR* dirp) +static struct dirent * +readdir(DIR *dirp) { - struct __dir* data = (struct __dir*) dirp; + struct __dir *data = (struct __dir *)dirp; if (!data) { errno = EBADF; - return NULL; + return (NULL); } - if (data->index < data->count) - { - return &data->entries[data->index++]; + if (data->index < data->count) { + return (&data->entries[data->index++]); } - return NULL; + return (NULL); } -static int readdir_r(DIR* dirp, struct dirent* entry, struct dirent**result) +static int +readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result) { - struct __dir* data = (struct __dir*) dirp; + struct __dir *data = (struct __dir *)dirp; if (!data) { - return EBADF; + return (EBADF); } - if (data->index < data->count) - { + if (data->index < data->count) { if (entry) - memcpy(entry, &data->entries[data->index++], sizeof(struct dirent)); + memcpy(entry, &data->entries[data->index++], + sizeof (struct dirent)); if (result) *result = entry; - } - else if (result) + } else if (result) *result = NULL; - return 0; + return (0); } -static void seekdir(DIR* dirp, long int offset) +static void +seekdir(DIR *dirp, long int offset) { - if (dirp) - { - struct __dir* data = (struct __dir*) dirp; + if (dirp) { + struct __dir *data = (struct __dir *)dirp; data->index = (offset < data->count) ? offset : data->index; } } -static void rewinddir(DIR* dirp) +static void +rewinddir(DIR *dirp) { seekdir(dirp, 0); } -static long int telldir(DIR* dirp) +static long int +telldir(DIR *dirp) { if (!dirp) { errno = EBADF; - return -1; + return (-1); } - return ((struct __dir*)dirp)->count; + return (((struct __dir *)dirp)->count); } -static int dirfd(DIR * dirp) +static int +dirfd(DIR *dirp) { if (!dirp) { errno = EINVAL; - return -1; + return (-1); } - return ((struct __dir*)dirp)->fd; + return (((struct __dir *)dirp)->fd); } -static int scandir(const char* dirp, struct dirent*** namelist, - int (*filter)(const struct dirent*), - int (*compar)(const struct dirent**, const struct dirent**)) +static int +scandir(const char *dirp, struct dirent ***namelist, + int (*filter)(const struct dirent *), + int (*compar)(const struct dirent **, const struct dirent **)) { - struct dirent ** entries = NULL, ** tmp_entries = NULL; + struct dirent **entries = NULL, **tmp_entries = NULL; long int i = 0, index = 0, count = 16; - DIR * d = opendir(dirp); - struct __dir* data = (struct __dir*) d; + DIR *d = opendir(dirp); + struct __dir *data = (struct __dir *)d; if (!data) { closedir(d); __seterrno(ENOENT); - return -1; + return (-1); } - entries = (struct dirent**) malloc(sizeof(struct dirent*) * count); - if (!entries) - { + entries = (struct dirent **) malloc(sizeof (struct dirent *) * count); + if (!entries) { closedir(d); __seterrno(ENOMEM); - return -1; + return (-1); } - for (i = 0; i < data->count; ++i) - { - if (!filter || filter(&data->entries[i])) - { - entries[index] = (struct dirent*) malloc(sizeof(struct dirent)); - if (!entries[index]) - { + for (i = 0; i < data->count; ++i) { + if (!filter || filter(&data->entries[i])) { + entries[index] = (struct dirent *) + malloc(sizeof (struct dirent)); + if (!entries[index]) { closedir(d); for (i = 0; i < index; ++i) free(entries[index]); free(entries); __seterrno(ENOMEM); - return -1; + return (-1); } - memcpy(entries[index], &data->entries[i], sizeof(struct dirent)); - if (++index == count) - { - tmp_entries = (struct dirent**)realloc(entries, sizeof(struct dirent*) * count * 2); - if (!tmp_entries) - { + memcpy(entries[index], &data->entries[i], + sizeof (struct dirent)); + if (++index == count) { + tmp_entries = (struct dirent **)realloc(entries, + sizeof (struct dirent *) * count * 2); + if (!tmp_entries) { closedir(d); for (i = 0; i < index; ++i) free(entries[index - 1]); free(entries); __seterrno(ENOMEM); - return -1; + return (-1); } entries = tmp_entries; count *= 2; } } } - // qsort(entries, index, sizeof(struct dirent*), compar); + // qsort(entries, index, sizeof (struct dirent*), compar); entries[index] = NULL; if (namelist) *namelist = entries; closedir(d); - return 0; + return (0); } -static int alphasort(const void* a, const void* b) +static int +alphasort(const void *a, const void *b) { - struct dirent** dira = (struct dirent**)a, **dirb = (struct dirent**)b; + struct dirent **dira = (struct dirent **)a, + **dirb = (struct dirent **)b; if (!dira || !dirb) - return 0; - return strcoll((*dira)->d_name, (*dirb)->d_name); + return (0); + return (strcoll((*dira)->d_name, (*dirb)->d_name)); } -static int __strverscmp(const char* s1, const char* s2) +static int +__strverscmp(const char *s1, const char *s2) { - return alphasort(s1, s2); + return (alphasort(s1, s2)); } -static int versionsort(const void* a, const void* b) +static int +versionsort(const void *a, const void *b) { - struct dirent** dira = (struct dirent**)a, ** dirb = (struct dirent**)b; + struct dirent **dira = (struct dirent **)a, + **dirb = (struct dirent **)b; if (!dira || !dirb) - return 0; - return __strverscmp((*dira)->d_name, (*dirb)->d_name); + return (0); + return (__strverscmp((*dira)->d_name, (*dirb)->d_name)); } #if __clang__ diff --git a/lib/libspl/include/os/windows/fcntl.h b/lib/libspl/include/os/windows/fcntl.h index 07ad5bd8222..40d0d7fd4df 100644 --- a/lib/libspl/include/os/windows/fcntl.h +++ b/lib/libspl/include/os/windows/fcntl.h @@ -25,22 +25,22 @@ #include_next -#define O_LARGEFILE 0 -#define O_RSYNC 0 -#define O_DIRECT 0 -#define O_SYNC 0 -#define O_DSYNC 0 -#define O_CLOEXEC 0 -#define O_NDELAY 0 -#define O_NOCTTY 0 +#define O_LARGEFILE 0 +#define O_RSYNC 0 +#define O_DIRECT 0 +#define O_SYNC 0 +#define O_DSYNC 0 +#define O_CLOEXEC 0 +#define O_NDELAY 0 +#define O_NOCTTY 0 #define F_SETFD 2 #define FD_CLOEXEC 1 /* * Special value used to indicate openat should use the current - * working directory. + * working directory. */ -#define AT_FDCWD -100 +#define AT_FDCWD -100 #endif /* _LIBSPL_SYS_FCNTL_H */ diff --git a/lib/libspl/include/os/windows/getopt.h b/lib/libspl/include/os/windows/getopt.h index 83ff7259410..0c2d8c9bcb7 100644 --- a/lib/libspl/include/os/windows/getopt.h +++ b/lib/libspl/include/os/windows/getopt.h @@ -1,21 +1,45 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License, Version 1.0 only + * (the "License"). You may not use this file except in compliance + * with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ + #ifndef LIBSPL_GETOPT_H_INCLUDED -#define LIBSPL_GETOPT_H_INCLUDED +#define LIBSPL_GETOPT_H_INCLUDED -#define no_argument 0 -#define required_argument 1 -#define optional_argument 2 +#define no_argument 0 +#define required_argument 1 +#define optional_argument 2 struct option { - const char* name; - int has_arg; - int* flag; - int val; + const char *name; + int has_arg; + int *flag; + int val; }; -extern int getopt(int, char* const*, const char*); -extern int getopt_long(int, char* const*, const char*, const struct option*, int*); -extern int getopt_long_only(int, char* const*, const char*, const struct option*, int*); -extern int getsubopt(char** optionsp, char* tokens[], char** valuep); +extern int getopt(int, char * const *, const char *); +extern int getopt_long(int, char * const *, const char *, + const struct option *, int *); +extern int getopt_long_only(int, char * const *, const char *, + const struct option *, int *); +extern int getsubopt(char **optionsp, char *tokens[], char **valuep); -#endif // LIBSPL_GETOPT_H_INCLUDED \ No newline at end of file +#endif // LIBSPL_GETOPT_H_INCLUDED diff --git a/lib/libspl/include/os/windows/grp.h b/lib/libspl/include/os/windows/grp.h index 86894f78660..0a9ebe6cda9 100644 --- a/lib/libspl/include/os/windows/grp.h +++ b/lib/libspl/include/os/windows/grp.h @@ -1,27 +1,27 @@ /* -* CDDL HEADER START -* -* The contents of this file are subject to the terms of the -* Common Development and Distribution License (the "License"). -* You may not use this file except in compliance with the License. -* -* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE -* or http://www.opensolaris.org/os/licensing. -* See the License for the specific language governing permissions -* and limitations under the License. -* -* When distributing Covered Code, include this CDDL HEADER in each -* file and include the License file at usr/src/OPENSOLARIS.LICENSE. -* If applicable, add the following below this CDDL HEADER, with the -* fields enclosed by brackets "[]" replaced with your own identifying -* information: Portions Copyright [yyyy] [name of copyright owner] -* -* CDDL HEADER END -*/ + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ /* -* Copyright (c) 2017 Jorgen Lundman -*/ + * Copyright (c) 2017 Jorgen Lundman + */ #ifndef _SPL_GRP_H #define _SPL_GRP_H diff --git a/lib/libspl/include/os/windows/libintl.h b/lib/libspl/include/os/windows/libintl.h index cda703f4d15..c9b6e15696c 100644 --- a/lib/libspl/include/os/windows/libintl.h +++ b/lib/libspl/include/os/windows/libintl.h @@ -1,12 +1,34 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License, Version 1.0 only + * (the "License"). You may not use this file except in compliance + * with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ + #ifndef LIBSPL_LIBINTL_H -#define LIBSPL_LIBINTL_H +#define LIBSPL_LIBINTL_H #ifdef HAVE_GETTEXT #else #define gettext(str) (str) #define dgettext(domain, str) (str) -#define textdomain(domain) (domain) +#define textdomain(domain) (domain) #endif diff --git a/lib/libspl/include/os/windows/mntent.h b/lib/libspl/include/os/windows/mntent.h index dc1c0bdafd5..a4135d5aa5c 100644 --- a/lib/libspl/include/os/windows/mntent.h +++ b/lib/libspl/include/os/windows/mntent.h @@ -133,24 +133,24 @@ extern "C" { #define MNTOPT_RESTRICT "restrict" /* restricted autofs mount */ #define MNTOPT_BROWSE "browse" /* browsable autofs mount */ #define MNTOPT_NOBROWSE "nobrowse" /* non-browsable autofs mount */ -#define MNTOPT_OWNERS "owners" /* VFS will not ignore ownership information on filesystem objects */ -#define MNTOPT_NOOWNERS "noowners" /* VFS will ignore ownership information on filesystem objects */ +#define MNTOPT_OWNERS "owners" /* not ignore ownership */ +#define MNTOPT_NOOWNERS "noowners" /* ignore ownership */ -#define MNT_RDONLY 0x00000001 /* read only filesystem */ -#define MNT_NOEXEC 0x00000004 /* can't exec from filesystem */ -#define MNT_NOSUID 0x00000008 /* don't honor setuid bits on fs */ -#define MNT_NODEV 0x00000010 /* don't interpret special files */ -#define MNT_UNION 0x00000020 /* union with underlying filesystem */ -#define MNT_ASYNC 0x00000040 /* file system written asynchronously */ +#define MNT_RDONLY 0x00000001 /* read only filesystem */ +#define MNT_NOEXEC 0x00000004 /* can't exec from filesystem */ +#define MNT_NOSUID 0x00000008 /* don't honor setuid bits on fs */ +#define MNT_NODEV 0x00000010 /* don't interpret special files */ +#define MNT_UNION 0x00000020 /* union with underlying filesystem */ +#define MNT_ASYNC 0x00000040 /* file system written asynchronously */ -#define MNT_NOATIME 0x10000000 /* disable update of file access time */ +#define MNT_NOATIME 0x10000000 /* disable update of file access time */ -#define MNT_UPDATE 0x00010000 /* not a real mount, just an update */ -#define MNT_RELOAD 0x00040000 /* reload filesystem data */ -#define MNT_FORCE 0x00080000 /* force unmount or readonly change */ +#define MNT_UPDATE 0x00010000 /* not a real mount, just an update */ +#define MNT_RELOAD 0x00040000 /* reload filesystem data */ +#define MNT_FORCE 0x00080000 /* force unmount or readonly change */ -#define MNT_WAIT 1 /* synchronized I/O file integrity completion */ -#define MNT_NOWAIT 2 /* start all I/O, but do not wait for it */ +#define MNT_WAIT 1 /* synchronized I/O file integrity completion */ +#define MNT_NOWAIT 2 /* start all I/O, but do not wait for it */ #ifdef __cplusplus } diff --git a/lib/libspl/include/os/windows/pwd.h b/lib/libspl/include/os/windows/pwd.h index 743d3f44797..93c2b3cf3cf 100644 --- a/lib/libspl/include/os/windows/pwd.h +++ b/lib/libspl/include/os/windows/pwd.h @@ -1,27 +1,27 @@ /* -* CDDL HEADER START -* -* The contents of this file are subject to the terms of the -* Common Development and Distribution License (the "License"). -* You may not use this file except in compliance with the License. -* -* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE -* or http://www.opensolaris.org/os/licensing. -* See the License for the specific language governing permissions -* and limitations under the License. -* -* When distributing Covered Code, include this CDDL HEADER in each -* file and include the License file at usr/src/OPENSOLARIS.LICENSE. -* If applicable, add the following below this CDDL HEADER, with the -* fields enclosed by brackets "[]" replaced with your own identifying -* information: Portions Copyright [yyyy] [name of copyright owner] -* -* CDDL HEADER END -*/ + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ /* -* Copyright (c) 2017 Jorgen Lundman -*/ + * Copyright (c) 2017 Jorgen Lundman + */ #ifndef _SPL_PWD_H #define _SPL_PWD_H diff --git a/lib/libspl/include/os/windows/regex.h b/lib/libspl/include/os/windows/regex.h index d0db526a2eb..2bf66d0d86f 100644 --- a/lib/libspl/include/os/windows/regex.h +++ b/lib/libspl/include/os/windows/regex.h @@ -1,28 +1,27 @@ - /* -* CDDL HEADER START -* -* The contents of this file are subject to the terms of the -* Common Development and Distribution License, Version 1.0 only -* (the "License"). You may not use this file except in compliance -* with the License. -* -* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE -* or http://www.opensolaris.org/os/licensing. -* See the License for the specific language governing permissions -* and limitations under the License. -* -* When distributing Covered Code, include this CDDL HEADER in each -* file and include the License file at usr/src/OPENSOLARIS.LICENSE. -* If applicable, add the following below this CDDL HEADER, with the -* fields enclosed by brackets "[]" replaced with your own identifying -* information: Portions Copyright [yyyy] [name of copyright owner] -* -* CDDL HEADER END -*/ + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License, Version 1.0 only + * (the "License"). You may not use this file except in compliance + * with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ /* -* Copyright(c) 2017 Jorgen Lundman -*/ + * Copyright(c) 2017 Jorgen Lundman + */ #ifndef _LIBSPL_SYS_REGEX_H @@ -32,8 +31,10 @@ typedef ssize_t regoff_t; typedef struct { - regoff_t rm_so; /* Byte offset from string's start to substring's start. */ - regoff_t rm_eo; /* Byte offset from string's start to substring's end. */ + /* Byte offset from string's start to substring's start. */ + regoff_t rm_so; + /* Byte offset from string's start to substring's end. */ + regoff_t rm_eo; } regmatch_t; struct regex { diff --git a/lib/libspl/include/os/windows/rpc/types.h b/lib/libspl/include/os/windows/rpc/types.h index 6a418beea03..9a6fc83e063 100644 --- a/lib/libspl/include/os/windows/rpc/types.h +++ b/lib/libspl/include/os/windows/rpc/types.h @@ -26,7 +26,6 @@ #ifndef LIBSPL_RPC_TYPES_H #define LIBSPL_RPC_TYPES_H -//#include_next #include #include diff --git a/lib/libspl/include/os/windows/rpc/xdr.h b/lib/libspl/include/os/windows/rpc/xdr.h index 1577424e734..9ad2770df95 100644 --- a/lib/libspl/include/os/windows/rpc/xdr.h +++ b/lib/libspl/include/os/windows/rpc/xdr.h @@ -27,8 +27,6 @@ #ifndef _rpc_windows_xdr_h #define _rpc_windows_xdr_h -//#pragma ident "%Z%%M% %I% %E% SMI" - /* * xdr.h, External Data Representation Serialization Routines. */ @@ -39,7 +37,7 @@ #include - /* +/* * XDR provides a conventional way for converting between C data * types and an external bit-string representation. Library supplied * routines provide for the conversion on built-in C data types. These @@ -75,12 +73,12 @@ * request. */ enum xdr_op { - XDR_ENCODE=0, - XDR_DECODE=1, - XDR_FREE=2 + XDR_ENCODE = 0, + XDR_DECODE = 1, + XDR_FREE = 2 }; -#define XDR_GET_BYTES_AVAIL 1 +#define XDR_GET_BYTES_AVAIL 1 /* * This is the number of bytes per unit of external data. @@ -120,9 +118,9 @@ typedef struct { bool_t (*x_putlong)(); /* put a long to " */ bool_t (*x_getbytes)(); /* get some bytes from " */ bool_t (*x_putbytes)(); /* put some bytes to " */ - u_int (*x_getpostn)(); /* returns bytes off from beginning */ + uint_t (*x_getpostn)(); /* returns bytes off from beginning */ bool_t (*x_setpostn)(); /* lets you reposition the stream */ - long * (*x_inline)(); /* buf quick ptr to buffered data */ + long *(*x_inline)(); /* buf quick ptr to buffered data */ void (*x_destroy)(); /* free privates of this xdr_stream */ bool_t(*x_control)(struct XDR *, int, void *); bool_t(*x_getint32)(struct XDR *, int32_t *); @@ -184,15 +182,15 @@ typedef struct { (*(xdrs)->x_ops->x_destroy)(xdrs) #define xdr_destroy(xdrs) XDR_DESTROY(xdrs) -#define XDR_GETINT32(xdrs, int32p) \ - (*(xdrs)->x_ops->x_getint32)(xdrs, int32p) -#define xdr_getint32(xdrs, int32p) \ - (*(xdrs)->x_ops->x_getint32)(xdrs, int32p) +#define XDR_GETINT32(xdrs, int32p) \ + (*(xdrs)->x_ops->x_getint32)(xdrs, int32p) +#define xdr_getint32(xdrs, int32p) \ + (*(xdrs)->x_ops->x_getint32)(xdrs, int32p) -#define XDR_PUTINT32(xdrs, int32p) \ - (*(xdrs)->x_ops->x_putint32)(xdrs, int32p) -#define xdr_putint32(xdrs, int32p) \ - (*(xdrs)->x_ops->x_putint32)(xdrs, int32p) +#define XDR_PUTINT32(xdrs, int32p) \ + (*(xdrs)->x_ops->x_putint32)(xdrs, int32p) +#define xdr_putint32(xdrs, int32p) \ + (*(xdrs)->x_ops->x_putint32)(xdrs, int32p) /* * Support struct for discriminated unions. @@ -225,14 +223,14 @@ struct xdr_discrim { * N.B. and frozen for all time: each data type here uses 4 bytes * of external representation. */ -#define IXDR_GET_LONG(buf) ((long)ntohl((u_long)*(buf)++)) -#define IXDR_PUT_LONG(buf, v) (*(buf)++ = (long)htonl((u_long)v)) +#define IXDR_GET_LONG(buf) ((long)ntohl((ulong_t)*(buf)++)) +#define IXDR_PUT_LONG(buf, v) (*(buf)++ = (long)htonl((ulong_t)v)) #define IXDR_GET_BOOL(buf) ((bool_t)IXDR_GET_LONG(buf)) #define IXDR_GET_ENUM(buf, t) ((t)IXDR_GET_LONG(buf)) -#define IXDR_GET_U_LONG(buf) ((u_long)IXDR_GET_LONG(buf)) +#define IXDR_GET_U_LONG(buf) ((ulong_t)IXDR_GET_LONG(buf)) #define IXDR_GET_SHORT(buf) ((short)IXDR_GET_LONG(buf)) -#define IXDR_GET_U_SHORT(buf) ((u_short)IXDR_GET_LONG(buf)) +#define IXDR_GET_U_SHORT(buf) ((ushort_t)IXDR_GET_LONG(buf)) #define IXDR_PUT_BOOL(buf, v) IXDR_PUT_LONG((buf), ((long)(v))) #define IXDR_PUT_ENUM(buf, v) IXDR_PUT_LONG((buf), ((long)(v))) @@ -266,9 +264,9 @@ extern bool_t xdr_double(); extern bool_t xdr_reference(); extern bool_t xdr_pointer(); extern bool_t xdr_wrapstring(); -extern bool_t xdr_longlong_t(XDR* xdrs, longlong_t* hp); -extern bool_t xdr_u_longlong_t(XDR* xdrs, u_longlong_t* hp); -extern bool_t xdr_control(XDR* xdrs, int request, void* info); +extern bool_t xdr_longlong_t(XDR *xdrs, longlong_t *hp); +extern bool_t xdr_u_longlong_t(XDR *xdrs, u_longlong_t *hp); +extern bool_t xdr_control(XDR *xdrs, int request, void *info); /* * Common opaque bytes objects used by many rpc protocols; @@ -276,7 +274,7 @@ extern bool_t xdr_control(XDR* xdrs, int request, void* info); */ #define MAX_NETOBJ_SZ 1024 struct netobj { - u_int n_len; + uint_t n_len; char *n_bytes; }; typedef struct netobj netobj; @@ -294,9 +292,9 @@ extern int xdrrec_readbytes(); /* like a read on a pipe */ extern bool_t xdrrec_skiprecord(); /* move to beginning of next record */ extern bool_t xdrrec_eof(); /* true if no more input */ -#define XDR_PEEK 2 -#define XDR_SKIPBYTES 3 -#define XDR_RDMAGET 4 -#define XDR_RDMASET 5 +#define XDR_PEEK 2 +#define XDR_SKIPBYTES 3 +#define XDR_RDMAGET 4 +#define XDR_RDMASET 5 #endif /* !_rpc_xdr_h */ diff --git a/lib/libspl/include/os/windows/sched.h b/lib/libspl/include/os/windows/sched.h index e90c23d4445..63d29b89b6f 100644 --- a/lib/libspl/include/os/windows/sched.h +++ b/lib/libspl/include/os/windows/sched.h @@ -20,21 +20,21 @@ */ #ifndef _SPL_SCHED_H -#define _SPL_SCHED_H +#define _SPL_SCHED_H -struct sched_param { - int32_t sched_priority; - int32_t sched_curpriority; - union { - int32_t reserved[8]; - struct { - int32_t __ss_low_priority; - int32_t __ss_max_repl; - struct timespec __ss_repl_period; - struct timespec __ss_init_budget; - } __ss; - } __ss_un; +struct sched_param { + int32_t sched_priority; + int32_t sched_curpriority; + union { + int32_t reserved[8]; + struct { + int32_t __ss_low_priority; + int32_t __ss_max_repl; + struct timespec __ss_repl_period; + struct timespec __ss_init_budget; + } __ss; + } __ss_un; }; #endif diff --git a/lib/libspl/include/os/windows/signal.h b/lib/libspl/include/os/windows/signal.h index 97aba486d79..652fe8d5185 100644 --- a/lib/libspl/include/os/windows/signal.h +++ b/lib/libspl/include/os/windows/signal.h @@ -20,7 +20,7 @@ */ #ifndef _SPL_SIGNAL_H -#define _SPL_SIGNAL_H +#define _SPL_SIGNAL_H // #include // #include @@ -36,8 +36,8 @@ struct proc; -//extern int -//thread_issignal(struct proc *, thread_t, sigset_t); +// extern int +// thread_issignal(struct proc *, thread_t, sigset_t); #define SA_SIGINFO 0x00000008 typedef struct __siginfo { @@ -64,7 +64,8 @@ struct sigaction { int sa_flags; }; -/* The "why" argument indicates the allowable side-effects of the call: +/* + * The "why" argument indicates the allowable side-effects of the call: * * FORREAL: Extract the next pending signal from p_sig into p_cursig; * stop the process if a stop has been requested or if a traced signal @@ -73,19 +74,20 @@ struct sigaction { * JUSTLOOKING: Don't stop the process, just indicate whether or not * a signal might be pending (FORREAL is needed to tell for sure). */ -#define threadmask (sigmask(SIGILL)|sigmask(SIGTRAP)|\ - sigmask(SIGIOT)|sigmask(SIGEMT)|\ - sigmask(SIGFPE)|sigmask(SIGBUS)|\ - sigmask(SIGSEGV)|sigmask(SIGSYS)|\ - sigmask(SIGPIPE)|sigmask(SIGKILL)|\ - sigmask(SIGTERM)|sigmask(SIGINT)) +#define threadmask \ + (sigmask(SIGILL)|sigmask(SIGTRAP)| \ + sigmask(SIGIOT)|sigmask(SIGEMT)| \ + sigmask(SIGFPE)|sigmask(SIGBUS)| \ + sigmask(SIGSEGV)|sigmask(SIGSYS)| \ + sigmask(SIGPIPE)|sigmask(SIGKILL)| \ + sigmask(SIGTERM)|sigmask(SIGINT)) static inline int issig(int why) { - return 0; + return (0); } -#define signal_pending(p) issig(0) +#define signal_pending(p) issig(0) #endif /* SPL_SIGNAL_H */ diff --git a/lib/libspl/include/os/windows/sys/byteorder.h b/lib/libspl/include/os/windows/sys/byteorder.h index dff53aea8df..322061160af 100644 --- a/lib/libspl/include/os/windows/sys/byteorder.h +++ b/lib/libspl/include/os/windows/sys/byteorder.h @@ -40,8 +40,6 @@ #ifndef _SYS_BYTEORDER_H #define _SYS_BYTEORDER_H - - #include #include #include @@ -122,25 +120,29 @@ typedef uint32_t in_addr_t; #ifdef _BIG_ENDIAN static __inline__ uint64_t -htonll(uint64_t n) { +htonll(uint64_t n) +{ return (n); } static __inline__ uint64_t -ntohll(uint64_t n) { +ntohll(uint64_t n) +{ return (n); } #else #if 0 static __inline__ uint64_t -htonll(uint64_t n) { - return _OSSwapInt64(n); +htonll(uint64_t n) +{ + return (_OSSwapInt64(n)); } static __inline__ uint64_t -ntohll(uint64_t n) { - return _OSSwapInt64(n); +ntohll(uint64_t n) +{ + return (_OSSwapInt64(n)); } #endif diff --git a/lib/libspl/include/os/windows/sys/errno.h b/lib/libspl/include/os/windows/sys/errno.h index 05165458250..2ca882dd4ec 100644 --- a/lib/libspl/include/os/windows/sys/errno.h +++ b/lib/libspl/include/os/windows/sys/errno.h @@ -1,9 +1,30 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License, Version 1.0 only + * (the "License"). You may not use this file except in compliance + * with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ #ifndef _LIBSPL_SYS_ERRNO_H #define _LIBSPL_SYS_ERRNO_H #include #define ECKSUM EBADE -#define ERESTART 85 /* Interrupted system call should be restarted */ +#define ERESTART 85 /* Interrupted system call should be restarted */ #endif diff --git a/lib/libspl/include/os/windows/sys/file.h b/lib/libspl/include/os/windows/sys/file.h index 5131ec0e4a0..25bb4366035 100644 --- a/lib/libspl/include/os/windows/sys/file.h +++ b/lib/libspl/include/os/windows/sys/file.h @@ -27,26 +27,22 @@ #ifndef _LIBSPL_SYS_FILE_H #define _LIBSPL_SYS_FILE_H -//#include_next - -//#include - -#define FREAD 1 -#define FWRITE 2 -#define FAPPEND 8 - -#define FCREAT O_CREAT -#define FTRUNC O_TRUNC -#define FOFFMAX 0 -#define FSYNC O_SYNC -#define FDSYNC O_DSYNC -#define FRSYNC O_RSYNC -#define FEXCL O_EXCL - -#define O_DIRECT 0 - -#define FNODSYNC 0x10000 /* fsync pseudo flag */ -#define FNOFOLLOW 0x20000 /* don't follow symlinks */ -#define FIGNORECASE 0x80000 /* request case-insensitive lookups */ +#define FREAD 1 +#define FWRITE 2 +#define FAPPEND 8 + +#define FCREAT O_CREAT +#define FTRUNC O_TRUNC +#define FOFFMAX 0 +#define FSYNC O_SYNC +#define FDSYNC O_DSYNC +#define FRSYNC O_RSYNC +#define FEXCL O_EXCL + +#define O_DIRECT 0 + +#define FNODSYNC 0x10000 /* fsync pseudo flag */ +#define FNOFOLLOW 0x20000 /* don't follow symlinks */ +#define FIGNORECASE 0x80000 /* request case-insensitive lookups */ #endif diff --git a/lib/libspl/include/os/windows/sys/ioctl.h b/lib/libspl/include/os/windows/sys/ioctl.h index 1ccb342bebe..340895f7602 100644 --- a/lib/libspl/include/os/windows/sys/ioctl.h +++ b/lib/libspl/include/os/windows/sys/ioctl.h @@ -26,4 +26,3 @@ #include #endif /* _LIBSPL_SYS_STAT_H */ - diff --git a/lib/libspl/include/os/windows/sys/mnttab.h b/lib/libspl/include/os/windows/sys/mnttab.h index 1323db902b5..39f0f4d2af3 100644 --- a/lib/libspl/include/os/windows/sys/mnttab.h +++ b/lib/libspl/include/os/windows/sys/mnttab.h @@ -65,12 +65,12 @@ struct mnttab { uint_t mnt_minor; uint32_t mnt_fssubtype; }; -#define extmnttab mnttab +#define extmnttab mnttab extern DIR *fdopendir(int fd); extern int openat64(int, const char *, int, ...); -//From FreeBSD +// From FreeBSD extern int getmntany(FILE *fd, struct mnttab *mgetp, struct mnttab *mrefp); extern int getmntent(FILE *fp, struct mnttab *mp); extern char *hasmntopt(struct mnttab *mnt, char *opt); @@ -79,7 +79,7 @@ FILE *setmntent(const char *filename, const char *type); extern void statfs2mnttab(struct statfs *sfs, struct mnttab *mp); #ifndef AT_SYMLINK_NOFOLLOW -#define AT_SYMLINK_NOFOLLOW 0x100 +#define AT_SYMLINK_NOFOLLOW 0x100 #endif extern int fstatat64(int, const char *, struct _stat64 *, int); diff --git a/lib/libspl/include/os/windows/sys/mount.h b/lib/libspl/include/os/windows/sys/mount.h index 6fab311150d..b6968856d84 100644 --- a/lib/libspl/include/os/windows/sys/mount.h +++ b/lib/libspl/include/os/windows/sys/mount.h @@ -29,7 +29,6 @@ #include #include #include -//#include_next /* * Some old glibc headers don't define BLKGETSIZE64 @@ -104,18 +103,18 @@ #define MFSTYPENAMELEN 16 struct statfs { - uint32_t f_bsize; /* fundamental file system block size */ - uint64_t f_blocks; /* total data blocks in file system */ - uint64_t f_bfree; /* free blocks in fs */ - uint64_t f_bavail; /* free blocks avail to non-superuser */ - uint64_t f_files; /* total file nodes in file system */ - uint64_t f_ffree; /* free file nodes in fs */ - uint32_t f_type; /* type of filesystem */ - uint32_t f_flags; /* copy of mount exported flags */ - uint32_t f_fssubtype; /* fs sub-type (flavor) */ - char f_fstypename[MFSTYPENAMELEN]; /* fs type name */ - char f_mntonname[MAXPATHLEN]; /* directory on which mounted */ - char f_mntfromname[MAXPATHLEN]; /* mounted filesystem */ + uint32_t f_bsize; /* fundamental file system block size */ + uint64_t f_blocks; /* total data blocks in file system */ + uint64_t f_bfree; /* free blocks in fs */ + uint64_t f_bavail; /* free blocks avail to non-superuser */ + uint64_t f_files; /* total file nodes in file system */ + uint64_t f_ffree; /* free file nodes in fs */ + uint32_t f_type; /* type of filesystem */ + uint32_t f_flags; /* copy of mount exported flags */ + uint32_t f_fssubtype; /* fs sub-type (flavor) */ + char f_fstypename[MFSTYPENAMELEN]; /* fs type name */ + char f_mntonname[MAXPATHLEN]; /* dir on which mounted */ + char f_mntfromname[MAXPATHLEN]; /* mounted filesystem */ }; int statfs(const char *path, struct statfs *buf); diff --git a/lib/libspl/include/os/windows/sys/param.h b/lib/libspl/include/os/windows/sys/param.h index 21e97d7d5a9..477cd61768b 100644 --- a/lib/libspl/include/os/windows/sys/param.h +++ b/lib/libspl/include/os/windows/sys/param.h @@ -27,7 +27,6 @@ #ifndef _LIBSPL_WINDOWS_SYS_PARAM_H #define _LIBSPL_WINDOWS_SYS_PARAM_H -//#include_next #include #include @@ -44,9 +43,9 @@ * Note that the blocked devices are assumed to have DEV_BSIZE * "sectors" and that fragments must be some multiple of this size. */ -//#define MAXBSIZE 8192 -#define DEV_BSIZE 512 -#define DEV_BSHIFT 9 /* log2(DEV_BSIZE) */ +// #define MAXBSIZE 8192 +#define DEV_BSIZE 512 +#define DEV_BSHIFT 9 /* log2(DEV_BSIZE) */ #define MAXNAMELEN 256 #define MAXOFFSET_T _I64_MAX @@ -62,6 +61,6 @@ #define PAGESIZE (8192) // SYSTEM_INFO.dwPageSize; #endif /* PAGESIZE */ -#define NBBY 8 +#define NBBY 8 #endif diff --git a/lib/libspl/include/os/windows/sys/resource.h b/lib/libspl/include/os/windows/sys/resource.h index e69de29bb2d..6a15078ff23 100644 --- a/lib/libspl/include/os/windows/sys/resource.h +++ b/lib/libspl/include/os/windows/sys/resource.h @@ -0,0 +1,26 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License, Version 1.0 only + * (the "License"). You may not use this file except in compliance + * with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ + +#ifndef _LIBSPL_RESOURCE_H +#define _LIBSPL_RESOURCE_H + +#endif diff --git a/lib/libspl/include/os/windows/sys/socket.h b/lib/libspl/include/os/windows/sys/socket.h index e00b18c316a..4b50b6f3ac0 100644 --- a/lib/libspl/include/os/windows/sys/socket.h +++ b/lib/libspl/include/os/windows/sys/socket.h @@ -1,27 +1,27 @@ /* -* CDDL HEADER START -* -* The contents of this file are subject to the terms of the -* Common Development and Distribution License, Version 1.0 only -* (the "License"). You may not use this file except in compliance -* with the License. -* -* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE -* or http://www.opensolaris.org/os/licensing. -* See the License for the specific language governing permissions -* and limitations under the License. -* -* When distributing Covered Code, include this CDDL HEADER in each -* file and include the License file at usr/src/OPENSOLARIS.LICENSE. -* If applicable, add the following below this CDDL HEADER, with the -* fields enclosed by brackets "[]" replaced with your own identifying -* information: Portions Copyright [yyyy] [name of copyright owner] -* -* CDDL HEADER END -*/ + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * C ommon Development and Distribution License, Version 1.0 only + * (t he "License"). You may not use this file except in compliance + * wit h the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ /* -* Copyright(c) 2017 Jorgen Lundman -*/ + * Copyright(c) 2017 Jorgen Lundman + */ #ifndef _LIBSPL_SYS_SOCKET_H #define _LIBSPL_SYS_SOCKET_H diff --git a/lib/libspl/include/os/windows/sys/stat.h b/lib/libspl/include/os/windows/sys/stat.h index 73fa1614ec8..f48026b2083 100644 --- a/lib/libspl/include/os/windows/sys/stat.h +++ b/lib/libspl/include/os/windows/sys/stat.h @@ -1,6 +1,3 @@ - - - /* * CDDL HEADER START * @@ -38,51 +35,51 @@ #undef S_IFDIR #undef S_IFREG -#define S_IFMT 0170000 /* [XSI] type of file mask */ -#define S_IFIFO 0010000 /* [XSI] named pipe (fifo) */ -#define S_IFCHR 0020000 /* [XSI] character special */ -#define S_IFDIR 0040000 /* [XSI] directory */ -#define S_IFBLK 0060000 /* [XSI] block special */ -#define S_IFREG 0100000 /* [XSI] regular */ -#define S_IFLNK 0120000 /* [XSI] symbolic link */ -#define S_IFSOCK 0140000 /* [XSI] socket */ -#if !defined(_POSIX_C_SOURCE) -#define S_IFWHT 0160000 /* OBSOLETE: whiteout */ +#define S_IFMT 0170000 /* [XSI] type of file mask */ +#define S_IFIFO 0010000 /* [XSI] named pipe (fifo) */ +#define S_IFCHR 0020000 /* [XSI] character special */ +#define S_IFDIR 0040000 /* [XSI] directory */ +#define S_IFBLK 0060000 /* [XSI] block special */ +#define S_IFREG 0100000 /* [XSI] regular */ +#define S_IFLNK 0120000 /* [XSI] symbolic link */ +#define S_IFSOCK 0140000 /* [XSI] socket */ +#if !defined(_POSIX_C_SOURCE) +#define S_IFWHT 0160000 /* OBSOLETE: whiteout */ #endif /* File mode */ /* Read, write, execute/search by owner */ -#define S_IRWXU 0000700 /* [XSI] RWX mask for owner */ -#define S_IRUSR 0000400 /* [XSI] R for owner */ -#define S_IWUSR 0000200 /* [XSI] W for owner */ -#define S_IXUSR 0000100 /* [XSI] X for owner */ +#define S_IRWXU 0000700 /* [XSI] RWX mask for owner */ +#define S_IRUSR 0000400 /* [XSI] R for owner */ +#define S_IWUSR 0000200 /* [XSI] W for owner */ +#define S_IXUSR 0000100 /* [XSI] X for owner */ /* Read, write, execute/search by group */ -#define S_IRWXG 0000070 /* [XSI] RWX mask for group */ -#define S_IRGRP 0000040 /* [XSI] R for group */ -#define S_IWGRP 0000020 /* [XSI] W for group */ -#define S_IXGRP 0000010 /* [XSI] X for group */ +#define S_IRWXG 0000070 /* [XSI] RWX mask for group */ +#define S_IRGRP 0000040 /* [XSI] R for group */ +#define S_IWGRP 0000020 /* [XSI] W for group */ +#define S_IXGRP 0000010 /* [XSI] X for group */ /* Read, write, execute/search by others */ -#define S_IRWXO 0000007 /* [XSI] RWX mask for other */ -#define S_IROTH 0000004 /* [XSI] R for other */ -#define S_IWOTH 0000002 /* [XSI] W for other */ -#define S_IXOTH 0000001 /* [XSI] X for other */ +#define S_IRWXO 0000007 /* [XSI] RWX mask for other */ +#define S_IROTH 0000004 /* [XSI] R for other */ +#define S_IWOTH 0000002 /* [XSI] W for other */ +#define S_IXOTH 0000001 /* [XSI] X for other */ -#define S_ISUID 0004000 /* [XSI] set user id on execution */ -#define S_ISGID 0002000 /* [XSI] set group id on execution */ -#define S_ISVTX 0001000 /* [XSI] directory restrcted delete */ +#define S_ISUID 0004000 /* [XSI] set user id on execution */ +#define S_ISGID 0002000 /* [XSI] set group id on execution */ +#define S_ISVTX 0001000 /* [XSI] directory restrcted delete */ -#if !defined(_POSIX_C_SOURCE) -#define S_ISTXT S_ISVTX /* sticky bit: not supported */ -#define S_IREAD S_IRUSR /* backward compatability */ -#define S_IWRITE S_IWUSR /* backward compatability */ -#define S_IEXEC S_IXUSR /* backward compatability */ +#if !defined(_POSIX_C_SOURCE) +#define S_ISTXT S_ISVTX /* sticky bit: not supported */ +#define S_IREAD S_IRUSR /* backward compatability */ +#define S_IWRITE S_IWUSR /* backward compatability */ +#define S_IEXEC S_IXUSR /* backward compatability */ #endif /* -* File type macros. Note that block devices, sockets and links cannot be -* distinguished on Windows and the macros S_ISBLK, S_ISSOCK and S_ISLNK are -* only defined for compatibility. These macros should always return false -* on Windows. -*/ + * File type macros. Note that block devices, sockets and links cannot be + * distinguished on Windows and the macros S_ISBLK, S_ISSOCK and S_ISLNK are + * only defined for compatibility. These macros should always return false + * on Windows. + */ #define S_ISFIFO(mode) (((mode) & S_IFMT) == S_IFIFO) #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR) #define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG) diff --git a/lib/libspl/include/os/windows/sys/sysmacros.h b/lib/libspl/include/os/windows/sys/sysmacros.h index 5dc99c8908f..ebb3eb1c315 100644 --- a/lib/libspl/include/os/windows/sys/sysmacros.h +++ b/lib/libspl/include/os/windows/sys/sysmacros.h @@ -27,7 +27,7 @@ #ifndef _LIBSPL_SYS_SYSMACROS_H #define _LIBSPL_SYS_SYSMACROS_H -//#include_next +// #include_next /* common macros */ #ifndef MIN @@ -43,17 +43,18 @@ #define ARRAY_SIZE(a) (sizeof (a) / sizeof (a[0])) #endif #ifndef DIV_ROUND_UP -#define DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d)) +#define DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d)) #endif #define makedevice(maj, min) makedev(maj, min) #define _sysconf(a) sysconf(a) -//#define __NORETURN __attribute__((noreturn)) +// #define __NORETURN __attribute__((noreturn)) /* - * Compatibility macros/typedefs needed for Solaris -> Linux port + * Compatibility macros/typedefs needed for Solaris -> Windows port */ -#pragma warning( disable: 4146 ) // unary minus operator applied to unsigned type +// unary minus operator applied to unsigned type +#pragma warning(disable: 4146) #define P2ALIGN(x, align) ((x) & -(align)) #define P2CROSS(x, y, align) (((x) ^ (y)) > (align) - 1) #define P2ROUNDUP(x, align) (-(-(x) & -(align))) @@ -67,7 +68,7 @@ (-(type)(x) & ((type)(align) - 1)) #define ISP2(x) (((x) & ((x) - 1)) == 0) #define IS_P2ALIGNED(v, a) ((((uintptr_t)(v)) & ((uintptr_t)(a) - 1)) == 0) -#pragma warning( default: 4146 ) +#pragma warning(default: 4146) /* * Typed version of the P2* macros. These macros should be used to ensure @@ -104,9 +105,9 @@ #endif #ifndef RLIM64_INFINITY -#define RLIM64_INFINITY (~0ULL) +#define RLIM64_INFINITY (~0ULL) #endif -#define _LITTLE_ENDIAN +#define _LITTLE_ENDIAN #endif /* _LIBSPL_SYS_SYSMACROS_H */ diff --git a/lib/libspl/include/os/windows/sys/time.h b/lib/libspl/include/os/windows/sys/time.h index f1e400ccc9c..b212e32b5f7 100644 --- a/lib/libspl/include/os/windows/sys/time.h +++ b/lib/libspl/include/os/windows/sys/time.h @@ -77,27 +77,27 @@ typedef struct timespec inode_timespec_t; #if 0 #ifndef _WINSOCK2API_ struct timeval { - long tv_sec; /* seconds */ - long tv_usec; /* and microseconds */ + long tv_sec; /* seconds */ + long tv_usec; /* and microseconds */ }; #endif #endif typedef enum clock_type { - __CLOCK_REALTIME0 = 0, /* obsolete; same as CLOCK_REALTIME */ - CLOCK_VIRTUAL = 1, /* thread's user-level CPU clock */ - CLOCK_THREAD_CPUTIME_ID = 2, /* thread's user+system CPU clock */ - CLOCK_REALTIME = 3, /* wall clock */ - CLOCK_MONOTONIC = 4, /* high resolution monotonic clock */ - CLOCK_PROCESS_CPUTIME_ID = 5, /* process's user+system CPU clock */ - CLOCK_HIGHRES = CLOCK_MONOTONIC, /* alternate name */ - CLOCK_PROF = CLOCK_THREAD_CPUTIME_ID, /* alternate name */ + __CLOCK_REALTIME0 = 0, /* obsolete; same as CLOCK_REALTIME */ + CLOCK_VIRTUAL = 1, /* thread's user-level CPU clock */ + CLOCK_THREAD_CPUTIME_ID = 2, /* thread's user+system CPU clock */ + CLOCK_REALTIME = 3, /* wall clock */ + CLOCK_MONOTONIC = 4, /* high resolution monotonic clock */ + CLOCK_PROCESS_CPUTIME_ID = 5, /* process's user+system CPU clock */ + CLOCK_HIGHRES = CLOCK_MONOTONIC, /* alternate name */ + CLOCK_PROF = CLOCK_THREAD_CPUTIME_ID, /* alternate name */ } clock_type_t; extern void gethrestime(timestruc_t *); const char *win_ctime_r(char *buffer, size_t bufsize, time_t cur_time); -#define ctime_r(CLOCK, STR) win_ctime_r((STR), sizeof((STR)), (CLOCK)) +#define ctime_r(CLOCK, STR) win_ctime_r((STR), sizeof ((STR)), (CLOCK)) struct tm *localtime_r(const time_t *clock, struct tm *result); diff --git a/lib/libspl/include/os/windows/sys/timer.h b/lib/libspl/include/os/windows/sys/timer.h index 069e8af57ed..65bdd7b2569 100644 --- a/lib/libspl/include/os/windows/sys/timer.h +++ b/lib/libspl/include/os/windows/sys/timer.h @@ -1,7 +1,26 @@ -#ifndef _LIBSPL_TIMER_H -#define _LIBSPL_TIMER_H - - +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License, Version 1.0 only + * (the "License"). You may not use this file except in compliance + * with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ +#ifndef _LIBSPL_TIMER_H +#define _LIBSPL_TIMER_H #endif /* _LIBSPL_TIMER_H */ diff --git a/lib/libspl/include/os/windows/sys/types.h b/lib/libspl/include/os/windows/sys/types.h index 91cc16559c1..48e68bb0972 100644 --- a/lib/libspl/include/os/windows/sys/types.h +++ b/lib/libspl/include/os/windows/sys/types.h @@ -50,7 +50,6 @@ typedef unsigned long long u_longlong_t; typedef signed char int8_t; typedef unsigned char uint8_t; typedef unsigned char uchar_t; -typedef unsigned int u_int; typedef longlong_t offset_t; typedef u_longlong_t u_offset_t; @@ -96,15 +95,15 @@ typedef uint32_t dev_t; typedef int64_t ssize_t; -#define F_OK 0 -#define W_OK 2 -#define R_OK 4 +#define F_OK 0 +#define W_OK 2 +#define R_OK 4 /* MAXPATHLEN need to match between kernel and userland. MAX_PATH is only 260 */ -//#define MAXPATHLEN MAX_PATH -#define MAXPATHLEN 1024 -#define PATH_MAX MAX_PATH +// #define MAXPATHLEN MAX_PATH +#define MAXPATHLEN 1024 +#define PATH_MAX MAX_PATH typedef struct timespec timestruc_t; /* definition per SVr4 */ typedef struct timespec timespec_t; @@ -138,20 +137,20 @@ typedef union { #define ENOTBLK 15 /* Block device required */ #define EDQUOT 49 /* Disc quota exceeded */ #define EBADE 50 /* invalid exchange */ -#define ESHUTDOWN 58 /* Can't send after socket shutdown */ -#define ESTALE 70 /* Stale NFS file handle */ +#define ESHUTDOWN 58 /* Can't send after socket shutdown */ +#define ESTALE 70 /* Stale NFS file handle */ -#define ENOTACTIVE 142 -#define ECHRNG 143 -#define EREMOTEIO 144 +#define ENOTACTIVE 142 +#define ECHRNG 143 +#define EREMOTEIO 144 -#define O_SHLOCK 0 +#define O_SHLOCK 0 // #ifdef _MSC_VER #ifndef __clang__ -#define INT_MAX 2147483647 +#define INT_MAX 2147483647 #define DBL_DIG 15 #define DBL_MAX 1.7976931348623157081452E+308 @@ -162,49 +161,49 @@ typedef union { #define FLT_MIN 1.1754943508222875079688E-38F #endif -#define STDIN_FILENO HTOI(GetStdHandle(STD_INPUT_HANDLE)) -#define STDOUT_FILENO HTOI(GetStdHandle(STD_OUTPUT_HANDLE)) -#define STDERR_FILENO HTOI(GetStdHandle(STD_ERROR_HANDLE)) -#define O_EXLOCK 0 +#define STDIN_FILENO HTOI(GetStdHandle(STD_INPUT_HANDLE)) +#define STDOUT_FILENO HTOI(GetStdHandle(STD_OUTPUT_HANDLE)) +#define STDERR_FILENO HTOI(GetStdHandle(STD_ERROR_HANDLE)) +#define O_EXLOCK 0 -#define bzero(b,len) (memset((b), '\0', (len))) -#define bcopy(b1,b2,len) (memmove((b2), (b1), (len))) -#define bcmp(b1, b2, len) (memcmp((b2), (b1), (len))) +#define bzero(b, len) (memset((b), '\0', (len))) +#define bcopy(b1, b2, len) (memmove((b2), (b1), (len))) +#define bcmp(b1, b2, len) (memcmp((b2), (b1), (len))) -#define alloca _alloca -#define posix_memalign_free _aligned_free +#define alloca _alloca +#define posix_memalign_free _aligned_free int posix_memalign(void **memptr, size_t alignment, size_t size); #ifndef MIN -#define MIN(a, b) (((a) < (b)) ? (a) : (b)) +#define MIN(a, b) (((a) < (b)) ? (a) : (b)) #endif -#define sleep(x) Sleep(x * 1000) +#define sleep(x) Sleep(x * 1000) -#define lstat _stat64 -#define unlink _unlink -#define strdup _strdup +#define lstat _stat64 +#define unlink _unlink +#define strdup _strdup -#define MFSTYPENAMELEN 16 -#define MNAMELEN MAXPATHLEN +#define MFSTYPENAMELEN 16 +#define MNAMELEN MAXPATHLEN -#define roundup(x, y) ((((x) + ((y) - 1)) / (y)) * (y)) -#define howmany(x, y) ((((x) % (y)) == 0) ? ((x) / (y)) : (((x) / (y)) + 1)) +#define roundup(x, y) ((((x) + ((y) - 1)) / (y)) * (y)) +#define howmany(x, y) ((((x) % (y)) == 0) ? ((x) / (y)) : (((x) / (y)) + 1)) -#define RLIMIT_NOFILE 8 /* number of open files */ +#define RLIMIT_NOFILE 8 /* number of open files */ typedef uint64_t rlim_t; struct rlimit { - rlim_t rlim_cur; /* current (soft) limit */ - rlim_t rlim_max; /* hard limit */ + rlim_t rlim_cur; /* current (soft) limit */ + rlim_t rlim_max; /* hard limit */ }; -#define _Atomic +#define _Atomic #ifndef SIGTSTP -#define SIGTSTP 0 +#define SIGTSTP 0 #endif -#define strcasecmp _stricmp +#define strcasecmp _stricmp int nanosleep(const struct timespec *rqtp, struct timespec *rmtp); @@ -222,7 +221,7 @@ int nanosleep(const struct timespec *rqtp, struct timespec *rmtp); /* Windows defines off_t as "long" and functions take it as parameter. */ #include typedef uint64_t zoff_t; -#define off_t zoff_t +#define off_t zoff_t /* Now replace POSIX calls with our versions. */ diff --git a/lib/libspl/include/os/windows/sys/types32.h b/lib/libspl/include/os/windows/sys/types32.h index 2ca619c89ac..5a4da61636d 100644 --- a/lib/libspl/include/os/windows/sys/types32.h +++ b/lib/libspl/include/os/windows/sys/types32.h @@ -33,9 +33,8 @@ #ifdef __cplusplus extern "C" { #endif - -#define WIN32_LEAN_AND_MEAN -//#include + +#define WIN32_LEAN_AND_MEAN #include #include diff --git a/lib/libspl/include/os/windows/sys/uio.h b/lib/libspl/include/os/windows/sys/uio.h index e2e59385fec..c1438be5333 100644 --- a/lib/libspl/include/os/windows/sys/uio.h +++ b/lib/libspl/include/os/windows/sys/uio.h @@ -41,8 +41,8 @@ #define _LIBSPL_WINDOWS_SYS_UIO_H struct iovec { - void *iov_base; /* Base address. */ - uint32_t iov_len; /* Length. */ + void *iov_base; /* Base address. */ + uint32_t iov_len; /* Length. */ }; typedef struct iovec iovec_t; diff --git a/lib/libspl/include/os/windows/sys/utsname.h b/lib/libspl/include/os/windows/sys/utsname.h index 5c03f1cc3d2..6075b7ef937 100644 --- a/lib/libspl/include/os/windows/sys/utsname.h +++ b/lib/libspl/include/os/windows/sys/utsname.h @@ -27,7 +27,7 @@ #ifndef _LIBSPL_UTSNAME_H #define _LIBSPL_UTSNAME_H -#define _SYS_NMLN 257 +#define _SYS_NMLN 257 struct utsname { char sysname[_SYS_NMLN]; char nodename[_SYS_NMLN]; diff --git a/lib/libspl/include/os/windows/sys/vfs.h b/lib/libspl/include/os/windows/sys/vfs.h index f79409bf60f..a0447a5a1c0 100644 --- a/lib/libspl/include/os/windows/sys/vfs.h +++ b/lib/libspl/include/os/windows/sys/vfs.h @@ -1,9 +1,26 @@ -#ifndef LIBSPL_VFS_H_INCLUDED -#define LIBSPL_VFS_H_INCLUDED - - - - +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License, Version 1.0 only + * (the "License"). You may not use this file except in compliance + * with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ +#ifndef LIBSPL_VFS_H_INCLUDED +#define LIBSPL_VFS_H_INCLUDED #endif diff --git a/lib/libspl/include/os/windows/sys/wait.h b/lib/libspl/include/os/windows/sys/wait.h index e69de29bb2d..2ca58e62584 100644 --- a/lib/libspl/include/os/windows/sys/wait.h +++ b/lib/libspl/include/os/windows/sys/wait.h @@ -0,0 +1,26 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License, Version 1.0 only + * (the "License"). You may not use this file except in compliance + * with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ + +#ifndef _LIBSPL_WAIT_H +#define _LIBSPL_WAIT_H + +#endif diff --git a/lib/libspl/include/os/windows/sys/zfs_mount.h b/lib/libspl/include/os/windows/sys/zfs_mount.h index c9176a0d521..fb044404856 100644 --- a/lib/libspl/include/os/windows/sys/zfs_mount.h +++ b/lib/libspl/include/os/windows/sys/zfs_mount.h @@ -1,10 +1,32 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License, Version 1.0 only + * (the "License"). You may not use this file except in compliance + * with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ + #ifndef _SYS_ZFS_MOUNT_H_ -#define _SYS_ZFS_MOUNT_H_ +#define _SYS_ZFS_MOUNT_H_ struct zfs_mount_args { - const char *fspec; /* block special device to mount */ + const char *fspec; /* block special device to mount */ int mflag; - char *optptr; + char *optptr; int optlen; int struct_size; }; diff --git a/lib/libspl/include/os/windows/termios.h b/lib/libspl/include/os/windows/termios.h index 281ebdc3a67..d75eb6cfa42 100644 --- a/lib/libspl/include/os/windows/termios.h +++ b/lib/libspl/include/os/windows/termios.h @@ -1,34 +1,34 @@ /* -* CDDL HEADER START -* -* This file and its contents are supplied under the terms of the -* Common Development and Distribution License ("CDDL"), version 1.0. -* You may only use this file in accordance with the terms of version -* 1.0 of the CDDL. -* -* A full copy of the text of the CDDL should have accompanied this -* source. A copy of the CDDL is also available via the Internet at -* http://www.illumos.org/license/CDDL. -* -* CDDL HEADER END -*/ + * CDDL HEADER START + * + * This file and its contents are supplied under the terms of the + * Common Development and Distribution License ("CDDL"), version 1.0. + * You may only use this file in accordance with the terms of version + * 1.0 of the CDDL. + * + * A full copy of the text of the CDDL should have accompanied this + * source. A copy of the CDDL is also available via the Internet at + * http://www.illumos.org/license/CDDL. + * + * CDDL HEADER END + */ /* -* Copyright (c) 2017, Jorgen Lundman. All rights reserved. -*/ + * Copyright (c) 2017, Jorgen Lundman. All rights reserved. + */ #ifndef _TERMIOS_H #define _TERMIOS_H -#define ECHOE 0x00000002 /* visually erase chars */ -#define ECHOK 0x00000004 /* echo NL after line kill */ -#define ECHO 0x00000008 /* enable echoing */ -#define ECHONL 0x00000010 /* echo NL even if ECHO is off */ +#define ECHOE 0x00000002 /* visually erase chars */ +#define ECHOK 0x00000004 /* echo NL after line kill */ +#define ECHO 0x00000008 /* enable echoing */ +#define ECHONL 0x00000010 /* echo NL even if ECHO is off */ -#define TCSAFLUSH 2 /* drain output, flush input */ +#define TCSAFLUSH 2 /* drain output, flush input */ -#define TIOCGWINSZ (104) -#define TIOCSWINSZ (103) +#define TIOCGWINSZ (104) +#define TIOCSWINSZ (103) struct termios { diff --git a/lib/libspl/include/os/windows/unistd.h b/lib/libspl/include/os/windows/unistd.h index 4888be8c196..3e124b90322 100644 --- a/lib/libspl/include/os/windows/unistd.h +++ b/lib/libspl/include/os/windows/unistd.h @@ -54,20 +54,20 @@ extern char *optarg; #define X_OK 1 -size_t strlcpy(register char* s, register const char* t, register size_t n); +size_t strlcpy(register char *s, register const char *t, register size_t n); -size_t strlcat(register char* s, register const char* t, register size_t n); +size_t strlcat(register char *s, register const char *t, register size_t n); -ssize_t getline(char** linep, size_t *linecapp, FILE* stream); +ssize_t getline(char **linep, size_t *linecapp, FILE *stream); -//int pread_win(HANDLE h, void *buf, size_t nbyte, off_t offset); +// int pread_win(HANDLE h, void *buf, size_t nbyte, off_t offset); int pipe(int fildes[2]); -char* realpath(const char* file_name, char* resolved_name); +char *realpath(const char *file_name, char *resolved_name); int usleep(__int64 usec); -int vasprintf(char** strp, const char* fmt, va_list ap); -int asprintf(char** strp, const char* fmt, ...); +int vasprintf(char **strp, const char *fmt, va_list ap); +int asprintf(char **strp, const char *fmt, ...); int strncasecmp(const char *s1, const char *s2, size_t n); -int readlink(const char *path, char* buf, size_t bufsize); +int readlink(const char *path, char *buf, size_t bufsize); const char *getexecname(void); uint64_t geteuid(void); diff --git a/lib/libspl/include/os/windows/uuid/uuid.h b/lib/libspl/include/os/windows/uuid/uuid.h index 874d65a196d..7d0b6add494 100644 --- a/lib/libspl/include/os/windows/uuid/uuid.h +++ b/lib/libspl/include/os/windows/uuid/uuid.h @@ -33,7 +33,7 @@ */ #ifndef _UUID_UUID_H -#define _UUID_UUID_H +#define _UUID_UUID_H #include #ifndef _WIN32 @@ -44,22 +44,26 @@ typedef unsigned char uuid_t[16]; /* UUID Variant definitions */ -#define UUID_VARIANT_NCS 0 -#define UUID_VARIANT_DCE 1 -#define UUID_VARIANT_MICROSOFT 2 -#define UUID_VARIANT_OTHER 3 +#define UUID_VARIANT_NCS 0 +#define UUID_VARIANT_DCE 1 +#define UUID_VARIANT_MICROSOFT 2 +#define UUID_VARIANT_OTHER 3 /* UUID Type definitions */ -#define UUID_TYPE_DCE_TIME 1 -#define UUID_TYPE_DCE_RANDOM 4 +#define UUID_TYPE_DCE_TIME 1 +#define UUID_TYPE_DCE_RANDOM 4 /* Allow UUID constants to be defined */ #ifdef __GNUC__ -#define UUID_DEFINE(name,u0,u1,u2,u3,u4,u5,u6,u7,u8,u9,u10,u11,u12,u13,u14,u15) \ - static const uuid_t name __attribute__ ((unused)) = {u0,u1,u2,u3,u4,u5,u6,u7,u8,u9,u10,u11,u12,u13,u14,u15} +#define UUID_DEFINE(name, u0, u1, u2, u3, u4, u5, u6, u7, u8, u9, u10, \ + u11, u12, u13, u14, u15) \ + static const uuid_t name __attribute__((unused)) = {u0, u1, u2, u3, \ + u4, u5, u6, u7, u8, u9, u10, u11, u12, u13, u14, u15} #else -#define UUID_DEFINE(name,u0,u1,u2,u3,u4,u5,u6,u7,u8,u9,u10,u11,u12,u13,u14,u15) \ - static const uuid_t name = {u0,u1,u2,u3,u4,u5,u6,u7,u8,u9,u10,u11,u12,u13,u14,u15} +#define UUID_DEFINE(name, u0, u1, u2, u3, u4, u5, u6, u7, u8, u9, u10, \ + u11, u12, u13, u14, u15) \ + static const uuid_t name = {u0, u1, u2, u3, u4, u5, u6, u7, u8, u9, \ + u10, u11, u12, u13, u14, u15} #endif #ifdef __cplusplus diff --git a/lib/libspl/include/os/windows/wosix.h b/lib/libspl/include/os/windows/wosix.h index 641ba8329eb..db522887f60 100644 --- a/lib/libspl/include/os/windows/wosix.h +++ b/lib/libspl/include/os/windows/wosix.h @@ -19,14 +19,15 @@ * * CDDL HEADER END */ - /* - * Copyright(c) 2019 Jorgen Lundman - */ +/* + * Copyright(c) 2019 Jorgen Lundman + */ #ifndef WOSIX_HEADER -#define WOSIX_HEADER +#define WOSIX_HEADER -/* Replace all the normal POSIX calls; open, read, write, close, lseek, fstat +/* + * Replace all the normal POSIX calls; open, read, write, close, lseek, fstat * As we have to use HANDLEs to open devices, we add a shim-layer to handle * int fd and the change in underlying API calls. * First, include the header that defines them in Windows. @@ -36,10 +37,10 @@ #include #include -#define HTOI(H) ((int)(unsigned __int64)(H)) -#define ITOH(I) ((HANDLE)(unsigned __int64)(I)) +#define HTOI(H) ((int)(unsigned __int64)(H)) +#define ITOH(I) ((HANDLE)(unsigned __int64)(I)) -/* keep the struct type before we #define */ +/* keep the struct type before we #define */ struct wosix_stat { union { struct stat; @@ -68,88 +69,89 @@ extern int wosix_isatty(int fd); extern int wosix_mkdir(const char *path, mode_t mode); extern int wosix_pwrite(int fd, const void *buf, size_t nbyte, off_t offset); extern int wosix_pread(int fd, void *buf, size_t nbyte, off_t offset); -extern int wosix_stat(char* path, struct _stat64* st); +extern int wosix_stat(char *path, struct _stat64 *st); extern int wosix_fstat(int fd, struct _stat64 *st); extern int wosix_fstat_blk(int fd, struct _stat64 *st); extern uint64_t wosix_lseek(int fd, uint64_t offset, int seek); extern int wosix_fdatasync(int fd); extern int wosix_ftruncate(int fd, off_t length); -extern int wosix_socketpair(int domain, int type, int protocol, int socket_vector[2]); +extern int wosix_socketpair(int domain, int type, int protocol, + int socket_vector[2]); extern int wosix_dup2(int fildes, int fildes2); extern int wosix_pipe(int fildes[2]); -#define wosix_fileno(X) (_get_osfhandle(_fileno((X)))) +#define wosix_fileno(X) (_get_osfhandle(_fileno((X)))) extern FILE *wosix_fdopen(int fildes, const char *mode); extern FILE *wosix_freopen(const char *path, const char *mode, FILE *stream); - /* +/* * Thin wrapper for the POSIX IO calls, to translate to HANDLEs * * Currently it "hopes" that HANDLE value will fit in type "int". * This could be improved in future. */ #undef open -#define open wosix_open +#define open wosix_open #undef openat -#define openat wosix_openat +#define openat wosix_openat #undef open64 -#define open64 wosix_open +#define open64 wosix_open #undef close -#define close wosix_close +#define close wosix_close #undef ioctl -#define ioctl wosix_ioctl +#define ioctl wosix_ioctl #undef lseek -#define lseek wosix_lseek +#define lseek wosix_lseek #undef fsync -#define fsync wosix_fsync +#define fsync wosix_fsync #undef read -#define read wosix_read +#define read wosix_read #undef write -#define write wosix_write +#define write wosix_write #undef fileno -#define fileno wosix_fileno +#define fileno wosix_fileno #undef isatty -#define isatty wosix_isatty +#define isatty wosix_isatty #undef mkdir -#define mkdir wosix_mkdir +#define mkdir wosix_mkdir #undef pread -#define pread wosix_pread -#define pread64 wosix_pread +#define pread wosix_pread +#define pread64 wosix_pread #undef pwrite -#define pwrite wosix_pwrite -#define pwrite64 wosix_pwrite +#define pwrite wosix_pwrite +#define pwrite64 wosix_pwrite #undef fstat -#define fstat wosix_fstat +#define fstat wosix_fstat #undef lstat -#define lstat wosix_lstat +#define lstat wosix_lstat #undef lstat64 -#define lstat64 wosix_lstat +#define lstat64 wosix_lstat #undef _fstat64 -#define _fstat64 wosix_fstat +#define _fstat64 wosix_fstat #undef fstat64 -#define fstat64 wosix_fstat +#define fstat64 wosix_fstat #undef fstat_blk -#define fstat_blk wosix_fstat_blk +#define fstat_blk wosix_fstat_blk #undef fstat64_blk -#define fstat64_blk wosix_fstat_blk +#define fstat64_blk wosix_fstat_blk #undef stat -#define stat wosix_stat +#define stat wosix_stat #undef stat -#define stat64 wosix_stat +#define stat64 wosix_stat #undef fdatasync -#define fdatasync wosix_fdatasync +#define fdatasync wosix_fdatasync #undef ftruncate -#define ftruncate wosix_ftruncate +#define ftruncate wosix_ftruncate #undef socketpair -#define socketpair wosix_socketpair +#define socketpair wosix_socketpair #undef fdopen -#define fdopen wosix_fdopen +#define fdopen wosix_fdopen #undef freopen -#define freopen wosix_freopen - // Alas, edonr.c has a member named "pipe". +#define freopen wosix_freopen +// Alas, edonr.c has a member named "pipe". #ifndef _SYS_EDONR_H_ #undef pipe -#define pipe wosix_pipe +#define pipe wosix_pipe #endif #endif /* WOSIX_HEADER */ diff --git a/lib/libspl/include/sys/debug.h b/lib/libspl/include/sys/debug.h index 56312fa2a54..a4bde124d45 100644 --- a/lib/libspl/include/sys/debug.h +++ b/lib/libspl/include/sys/debug.h @@ -32,11 +32,11 @@ #ifdef _MSC_VER #ifndef __printflike -#define __printflike(x, y) +#define __printflike(x, y) #endif #ifndef __maybe_unused -#define __maybe_unused +#define __maybe_unused #endif #else diff --git a/lib/libspl/include/sys/feature_tests.h b/lib/libspl/include/sys/feature_tests.h index d908ead1651..f80b90dc8eb 100644 --- a/lib/libspl/include/sys/feature_tests.h +++ b/lib/libspl/include/sys/feature_tests.h @@ -29,7 +29,7 @@ #define ____cacheline_aligned #ifdef _MSC_VER -#define __NORETURN +#define __NORETURN #else #define __NORETURN __attribute__((__noreturn__)) #endif diff --git a/lib/libspl/os/windows/getmntany.c b/lib/libspl/os/windows/getmntany.c index 7de92cc0d19..4224d4ffd90 100644 --- a/lib/libspl/os/windows/getmntany.c +++ b/lib/libspl/os/windows/getmntany.c @@ -44,8 +44,8 @@ #include #endif -#define DIFF(xx) ((mrefp->xx != NULL) && \ - (mgetp->xx == NULL || strcmp(mrefp->xx, mgetp->xx) != 0)) +#define DIFF(xx) ((mrefp->xx != NULL) && \ + (mgetp->xx == NULL || strcmp(mrefp->xx, mgetp->xx) != 0)) static struct statfs *gsfs = NULL; static int allfs = 0; @@ -55,22 +55,12 @@ static int allfs = 0; * option due to VFS rejecting with EACCESS. */ -//#include -//typedef struct attrlist attrlist_t; - -//struct attrBufS { -// u_int32_t length; -// vol_capabilities_set_t caps; -//} __attribute__((aligned(4), packed)); - - - static int chdir_block_begin(int newroot_fd) { int cwdfd, error; - cwdfd = open(".", O_RDONLY /*| O_DIRECTORY*/); + cwdfd = open(".", O_RDONLY /* | O_DIRECTORY */); if (cwdfd == -1) return (-1); @@ -124,10 +114,10 @@ fstatat64(int dirfd, const char *path, struct _stat64 *statbuf, int flag) if ((cwdfd = chdir_block_begin(dirfd)) == -1) return (-1); - //if (flag == AT_SYMLINK_NOFOLLOW) + // if (flag == AT_SYMLINK_NOFOLLOW) // error = lstat(path, statbuf); - //else - error = _stat64(path, statbuf); + // else + error = _stat64(path, statbuf); chdir_block_end(cwdfd); return (error); @@ -191,7 +181,7 @@ statfs2mnttab(struct statfs *sfs, struct mnttab *mp) mntopts[0] = '\0'; flags = sfs->f_flags; -#define OPTADD(opt) optadd(mntopts, sizeof(mntopts), (opt)) +#define OPTADD(opt) optadd(mntopts, sizeof (mntopts), (opt)) if (flags & MNT_RDONLY) OPTADD(MNTOPT_RO); else @@ -206,17 +196,17 @@ statfs2mnttab(struct statfs *sfs, struct mnttab *mp) #if 0 { struct attrBufS attrBuf; - attrlist_t attrList; + attrlist_t attrList; - memset(&attrList, 0, sizeof(attrList)); + memset(&attrList, 0, sizeof (attrList)); attrList.bitmapcount = ATTR_BIT_MAP_COUNT; attrList.volattr = ATTR_VOL_INFO|ATTR_VOL_CAPABILITIES; if (getattrlist(sfs->f_mntonname, &attrList, &attrBuf, - sizeof(attrBuf), 0) == 0) { + sizeof (attrBuf), 0) == 0) { if (attrBuf.caps[VOL_CAPABILITIES_INTERFACES] & - VOL_CAP_INT_EXTENDED_ATTR) { + VOL_CAP_INT_EXTENDED_ATTR) { OPTADD(MNTOPT_XATTR); } else { OPTADD(MNTOPT_NOXATTR); @@ -250,7 +240,8 @@ statfs2mnttab(struct statfs *sfs, struct mnttab *mp) mp->mnt_fssubtype = sfs->f_fssubtype; } -void DisplayVolumePaths(char *VolumeName, char *out, int len) +void +DisplayVolumePaths(char *VolumeName, char *out, int len) { DWORD CharCount = MAX_PATH + 1; char *Names = NULL; @@ -260,16 +251,16 @@ void DisplayVolumePaths(char *VolumeName, char *out, int len) for (;;) { // // Allocate a buffer to hold the paths. - Names = (char *) malloc(CharCount); + Names = (char *)malloc(CharCount); - if (!Names) return; + if (!Names) + return; // // Obtain all of the paths // for this volume. Success = GetVolumePathNamesForVolumeName( - VolumeName, Names, CharCount, &CharCount - ); + VolumeName, Names, CharCount, &CharCount); if (Success) break; @@ -286,35 +277,34 @@ void DisplayVolumePaths(char *VolumeName, char *out, int len) // // Display the various paths. for (NameIdx = Names; - NameIdx[0] != '\0'; - NameIdx += strlen(NameIdx) + 1) { - //printf(" %s", NameIdx); + NameIdx[0] != '\0'; + NameIdx += strlen(NameIdx) + 1) { + // printf(" %s", NameIdx); snprintf(out, len, "%s%s ", out, NameIdx); } - //printf("\n"); + // printf("\n"); } if (Names != NULL) { free(Names); Names = NULL; } - - return; } typedef struct _MOUNTDEV_NAME { USHORT NameLength; WCHAR Name[1]; } MOUNTDEV_NAME, *PMOUNTDEV_NAME; -#define IOCTL_MOUNTDEV_QUERY_DEVICE_NAME 0x004d0008 +#define IOCTL_MOUNTDEV_QUERY_DEVICE_NAME 0x004d0008 typedef struct _MOUNTDEV_UNIQUE_ID { USHORT UniqueIdLength; UCHAR UniqueId[1]; } MOUNTDEV_UNIQUE_ID; typedef MOUNTDEV_UNIQUE_ID *PMOUNTDEV_UNIQUE_ID; -#define IOCTL_MOUNTDEV_QUERY_UNIQUE_ID 0x4d0000 +#define IOCTL_MOUNTDEV_QUERY_UNIQUE_ID 0x4d0000 -int getfsstat(struct statfs *buf, int bufsize, int flags) +int +getfsstat(struct statfs *buf, int bufsize, int flags) { char name[256]; HANDLE vh; @@ -322,21 +312,23 @@ int getfsstat(struct statfs *buf, int bufsize, int flags) MOUNTDEV_UNIQUE_ID *UID = NULL; // If buf is NULL, return number of entries - vh = FindFirstVolume(name, sizeof(name)); - if (vh == INVALID_HANDLE_VALUE) return -1; + vh = FindFirstVolume(name, sizeof (name)); + if (vh == INVALID_HANDLE_VALUE) + return (-1); do { char *s = name; // Still room in out buffer? - if (buf && (bufsize < sizeof(struct statfs))) break; + if (buf && (bufsize < sizeof (struct statfs))) + break; // We must skip the "\\?\" start if (s[0] == '\\' && - s[1] == '\\' && - s[2] == '?' && - s[3] == '\\') + s[1] == '\\' && + s[2] == '?' && + s[3] == '\\') s = &s[4]; // We must eat the final "\\" int trail = strlen(name) - 1; @@ -346,26 +338,26 @@ int getfsstat(struct statfs *buf, int bufsize, int flags) // Query DOS char DeviceName[256], driveletter[256] = ""; int CharCount; - CharCount = QueryDosDevice(s, DeviceName, sizeof(DeviceName)); + CharCount = QueryDosDevice(s, DeviceName, sizeof (DeviceName)); // Restore trailing "\\" if (name[trail] == 0) name[trail] = '\\'; - //printf("%s: volume '%s' device '%s'\n", __func__, name, DeviceName); - DisplayVolumePaths(name, driveletter, sizeof(driveletter)); + DisplayVolumePaths(name, driveletter, sizeof (driveletter)); // Open DeviceName, and query it for dataset name HANDLE h; - name[2] = '.'; // "\\?\" -> "\\.\" + name[2] = '.'; // "\\?\" -> "\\.\" - // We open the devices returned; like "'\\.\Volume{0b1bb601-af0b-32e8-a1d2-54c167af6277}'" and + // We open the devices returned; like + // "'\\.\Volume{0b1bb601-af0b-32e8-a1d2-54c167af6277}'" and // query its Unique ID, where we return the dataset name. "BOOM" - h = CreateFile(name, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); -// printf("Open '%s': %d : getlast %d\n", name, h, GetLastError()); - // fflush(stdout); + h = CreateFile(name, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, + NULL, OPEN_EXISTING, 0, NULL); + if (h != INVALID_HANDLE_VALUE) { char *dataset; char cheat[1024]; @@ -373,11 +365,14 @@ int getfsstat(struct statfs *buf, int bufsize, int flags) DWORD Size; BOOL gotname = FALSE; - gotname = DeviceIoControl(h, IOCTL_MOUNTDEV_QUERY_UNIQUE_ID, NULL, 0, UID, sizeof(cheat) - 1, &Size, NULL); - //printf("deviocon %d: namelen %d\n", status, UID->UniqueIdLength); + gotname = DeviceIoControl(h, + IOCTL_MOUNTDEV_QUERY_UNIQUE_ID, + NULL, 0, UID, sizeof (cheat) - 1, &Size, NULL); + // printf("deviocon %d: namelen %d\n", status, + // UID->UniqueIdLength); if (gotname) { - UID->UniqueId[UID->UniqueIdLength] = 0; // Kernel doesn't null terminate - //printf("'%s' ==> '%s'\n", name, UID->UniqueId); + // Kernel doesn't null terminate + UID->UniqueId[UID->UniqueIdLength] = 0; } else UID = NULL; CloseHandle(h); @@ -385,38 +380,39 @@ int getfsstat(struct statfs *buf, int bufsize, int flags) // We found a mount here, add it. if (buf) { - memset(buf, 0, sizeof(*buf)); + memset(buf, 0, sizeof (*buf)); if (UID) { // Look up mountpoint - strlcpy(buf->f_mntfromname, UID->UniqueId, sizeof(buf->f_mntfromname)); - strlcpy(buf->f_fstypename, MNTTYPE_ZFS, sizeof(buf->f_fstypename)); + strlcpy(buf->f_mntfromname, UID->UniqueId, + sizeof (buf->f_mntfromname)); + strlcpy(buf->f_fstypename, MNTTYPE_ZFS, + sizeof (buf->f_fstypename)); + // FIXME, should be mountpoint! if (strlen(driveletter) > 2) - strlcpy(buf->f_mntonname, driveletter, sizeof(buf->f_mntonname)); // FIXME, should be mountpoint! + strlcpy(buf->f_mntonname, driveletter, + sizeof (buf->f_mntonname)); else - strlcpy(buf->f_mntonname, UID->UniqueId, sizeof(buf->f_mntonname)); // FIXME, should be mountpoint! + strlcpy(buf->f_mntonname, UID->UniqueId, + sizeof (buf->f_mntonname)); } else { - strlcpy(buf->f_mntfromname, DeviceName, sizeof(buf->f_mntfromname)); - strlcpy(buf->f_fstypename, "UKN", sizeof(buf->f_fstypename)); - strlcpy(buf->f_mntonname, name, sizeof(buf->f_mntonname)); + strlcpy(buf->f_mntfromname, DeviceName, + sizeof (buf->f_mntfromname)); + strlcpy(buf->f_fstypename, "UKN", + sizeof (buf->f_fstypename)); + strlcpy(buf->f_mntonname, name, + sizeof (buf->f_mntonname)); } UID = NULL; - /* - printf(" entry '%s' '%s' '%s'\n", - buf->f_mntfromname, - buf->f_mntonname, - name); - */ buf++; // Go to next struct. - bufsize -= sizeof(*buf); + bufsize -= sizeof (*buf); } count++; - } while (FindNextVolume(vh, name, sizeof(name)) != 0); + } while (FindNextVolume(vh, name, sizeof (name)) != 0); FindVolumeClose(vh); - //printf("%s: returning %d structures\n", __func__, count); - return count; + return (count); } @@ -434,14 +430,14 @@ statfs_init(void) allfs = getfsstat(NULL, 0, MNT_NOWAIT); if (allfs == -1) goto fail; - gsfs = malloc(sizeof(gsfs[0]) * allfs * 2); + gsfs = malloc(sizeof (gsfs[0]) * allfs * 2); if (gsfs == NULL) goto fail; - allfs = getfsstat(gsfs, (long)(sizeof(gsfs[0]) * allfs * 2), - MNT_NOWAIT); + allfs = getfsstat(gsfs, (long)(sizeof (gsfs[0]) * allfs * 2), + MNT_NOWAIT); if (allfs == -1) goto fail; - sfs = realloc(gsfs, allfs * sizeof(gsfs[0])); + sfs = realloc(gsfs, allfs * sizeof (gsfs[0])); if (sfs != NULL) gsfs = sfs; return (0); @@ -501,7 +497,7 @@ getmntent(FILE *fp, struct mnttab *mp) // start from the beginning, and return EOF. if (index >= allfs) { index = -1; - return -1; + return (-1); } statfs2mnttab(&gsfs[index], mp); @@ -526,7 +522,7 @@ getextmntent(const char *path, struct extmnttab *entry, struct stat64 *statbuf) if (statfs(path, &sfs) != 0) { (void) fprintf(stderr, "%s: %s\n", path, - strerror(errno)); + strerror(errno)); return (-1); } statfs2mnttab(&sfs, (struct mnttab *)entry); @@ -546,5 +542,5 @@ setmntent(const char *filename, const char *type) void endmntent(FILE *fd) { - fclose(fd); + fclose(fd); } diff --git a/lib/libspl/os/windows/getopt.c b/lib/libspl/os/windows/getopt.c index ce4c42d8c16..6c2d689a522 100644 --- a/lib/libspl/os/windows/getopt.c +++ b/lib/libspl/os/windows/getopt.c @@ -49,15 +49,15 @@ __RCSID("$NetBSD: getopt.c,v 1.10 1997/07/21 14:08:51 jtc Exp $"); #include #ifdef __weak_alias -__weak_alias(getopt,_getopt); +__weak_alias(getopt, _getopt); #endif int opterr = 1, /* if error message should be printed */ - optind = 1, /* index into parent argv vector */ - optopt, /* character checked for validity */ - optreset; /* reset getopt */ -char *optarg; /* argument associated with option */ + optind = 1, /* index into parent argv vector */ + optopt, /* character checked for validity */ + optreset; /* reset getopt */ +char *optarg; /* argument associated with option */ #define BADCH (int)'?' #define BADARG (int)':' @@ -68,15 +68,15 @@ char *optarg; /* argument associated with option */ * Parse argc/argv argument vector. */ int -getopt(nargc, nargv, ostr) - int nargc; - char * const *nargv; - const char *ostr; +getopt( + int nargc, + char *const *nargv, + const char *ostr) { static char *place = EMSG; /* option letter processing */ - char *oli; /* option letter list index */ + char *oli; /* option letter list index */ - if (optreset || !*place) { /* update scanning pointer */ + if (optreset || !*place) { /* update scanning pointer */ optreset = 0; if (optind >= nargc || *(place = nargv[optind]) != '-') { place = EMSG; @@ -99,16 +99,15 @@ getopt(nargc, nargv, ostr) if (!*place) ++optind; if (opterr && *ostr != ':') - (void)fprintf(stderr, - ": illegal option -- %c\n", optopt); + (void) fprintf(stderr, + ": illegal option -- %c\n", optopt); return (BADCH); } if (*++oli != ':') { /* don't need argument */ optarg = NULL; if (!*place) ++optind; - } - else { /* need an argument */ + } else { /* need an argument */ if (*place) /* no white space */ optarg = place; else if (nargc <= ++optind) { /* no arg */ @@ -116,12 +115,11 @@ getopt(nargc, nargv, ostr) if (*ostr == ':') return (BADARG); if (opterr) - (void)fprintf(stderr, - ": option requires an argument -- %c\n", - optopt); + (void) fprintf(stderr, + ": option requires an argument -- %c\n", + optopt); return (BADCH); - } - else /* white space */ + } else /* white space */ optarg = nargv[optind]; place = EMSG; ++optind; @@ -130,10 +128,10 @@ getopt(nargc, nargv, ostr) } int -getsubopt(optionsp, tokens, valuep) -char **optionsp; -char *tokens[]; -char **valuep; +getsubopt( + char **optionsp, + char *tokens[], + char **valuep) { register char *s = *optionsp, *p; register int i, optlen; @@ -141,29 +139,27 @@ char **valuep; *valuep = NULL; if (*s == '\0') return (-1); - p = strchr(s, ','); /* find next option */ + p = strchr(s, ','); /* find next option */ if (p == NULL) { p = s + strlen(s); + } else { + *p++ = '\0'; /* mark end and point to next */ } - else { - *p++ = '\0'; /* mark end and point to next */ - } - *optionsp = p; /* point to next option */ - p = strchr(s, '='); /* find value */ + *optionsp = p; /* point to next option */ + p = strchr(s, '='); /* find value */ if (p == NULL) { optlen = strlen(s); *valuep = NULL; - } - else { + } else { optlen = p - s; *valuep = ++p; } for (i = 0; tokens[i] != NULL; i++) { if ((optlen == strlen(tokens[i])) && - (strncmp(s, tokens[i], optlen) == 0)) + (strncmp(s, tokens[i], optlen) == 0)) return (i); } /* no match, point value at option and return error */ *valuep = s; return (-1); -} \ No newline at end of file +} diff --git a/lib/libspl/os/windows/getoptl.c b/lib/libspl/os/windows/getoptl.c index e05371ef6b0..4966ec335f7 100644 --- a/lib/libspl/os/windows/getoptl.c +++ b/lib/libspl/os/windows/getoptl.c @@ -13,35 +13,38 @@ static struct getopt_private_state { } pvt; static inline const char *option_matches(const char *arg_str, - const char *opt_name) + const char *opt_name) { while (*arg_str != '\0' && *arg_str != '=') { if (*arg_str++ != *opt_name++) - return NULL; + return (NULL); } if (*opt_name) - return NULL; + return (NULL); - return arg_str; + return (arg_str); } -int getopt_long(int argc, char *const *argv, const char *optstring, - const struct option *longopts, int *longindex) +int +getopt_long(int argc, char *const *argv, const char *optstring, + const struct option *longopts, int *longindex) { const char *carg; const char *osptr; int opt; - /* getopt() relies on a number of different global state - variables, which can make this really confusing if there is - more than one use of getopt() in the same program. This - attempts to detect that situation by detecting if the - "optstring" or "argv" argument have changed since last time - we were called; if so, reinitialize the query state. */ + /* + * getopt() relies on a number of different global state + * variables, which can make this really confusing if there is + * more than one use of getopt() in the same program. This + * attempts to detect that situation by detecting if the + * "optstring" or "argv" argument have changed since last time + * we were called; if so, reinitialize the query state. + */ if (optstring != pvt.last_optstring || argv != pvt.last_argv || - optind < 1 || optind > argc) { + optind < 1 || optind > argc) { /* optind doesn't match the current query */ pvt.last_optstring = optstring; pvt.last_argv = argv; @@ -54,7 +57,7 @@ int getopt_long(int argc, char *const *argv, const char *optstring, /* First, eliminate all non-option cases */ if (!carg || carg[0] != '-' || !carg[1]) - return -1; + return (-1); if (carg[1] == '-') { const struct option *lo; @@ -65,7 +68,7 @@ int getopt_long(int argc, char *const *argv, const char *optstring, /* Either it's a long option, or it's -- */ if (!carg[2]) { /* It's -- */ - return -1; + return (-1); } for (lo = longopts; lo->name; lo++) { @@ -73,7 +76,7 @@ int getopt_long(int argc, char *const *argv, const char *optstring, break; } if (!opt_end) - return '?'; + return ('?'); if (longindex) *longindex = lo - longopts; @@ -82,18 +85,18 @@ int getopt_long(int argc, char *const *argv, const char *optstring, if (lo->has_arg) optarg = (char *)opt_end + 1; else - return '?'; + return ('?'); } else if (lo->has_arg == 1) { if (!(optarg = argv[optind])) - return '?'; + return ('?'); optind++; } if (lo->flag) { *lo->flag = lo->val; - return 0; + return (0); } else { - return lo->val; + return (lo->val); } } @@ -107,13 +110,17 @@ int getopt_long(int argc, char *const *argv, const char *optstring, if (opt != ':' && (osptr = strchr(optstring, opt))) { if (osptr[1] == ':') { if (*pvt.optptr) { - /* Argument-taking option with attached - argument */ + /* + * Argument-taking option with attached + * argument + */ optarg = (char *)pvt.optptr; optind++; } else { - /* Argument-taking option with non-attached - argument */ + /* + * Argument-taking option with non-attached + * argument + */ if (argv[optind + 1]) { optarg = (char *)argv[optind + 1]; optind += 2; @@ -121,23 +128,25 @@ int getopt_long(int argc, char *const *argv, const char *optstring, /* Missing argument */ optind++; return (optstring[0] == ':') - ? ':' : '?'; + ? ':' : '?'; } } - return opt; + return (opt); } else { - /* Non-argument-taking option */ - /* pvt.optptr will remember the exact position to - resume at */ + /* + * Non-argument-taking option + * pvt.optptr will remember the exact position to + * resume at + */ if (!*pvt.optptr) optind++; - return opt; + return (opt); } } else { /* Unknown option */ optopt = opt; if (!*pvt.optptr) optind++; - return '?'; + return ('?'); } } diff --git a/lib/libspl/os/windows/page.c b/lib/libspl/os/windows/page.c index 4ae07f3939f..0c3256f227a 100644 --- a/lib/libspl/os/windows/page.c +++ b/lib/libspl/os/windows/page.c @@ -20,7 +20,7 @@ * CDDL HEADER END */ -#define _WINDOWS_MEAN_AND_LEAN +#define _WINDOWS_MEAN_AND_LEAN #include size_t pagesize = 0; diff --git a/lib/libspl/os/windows/posix.c b/lib/libspl/os/windows/posix.c index a558a9f0a19..5cdc9293c85 100644 --- a/lib/libspl/os/windows/posix.c +++ b/lib/libspl/os/windows/posix.c @@ -1,29 +1,29 @@ /* -* CDDL HEADER START -* -* The contents of this file are subject to the terms of the -* Common Development and Distribution License, Version 1.0 only -* (the "License"). You may not use this file except in compliance -* with the License. -* -* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE -* or http://www.opensolaris.org/os/licensing. -* See the License for the specific language governing permissions -* and limitations under the License. -* -* When distributing Covered Code, include this CDDL HEADER in each -* file and include the License file at usr/src/OPENSOLARIS.LICENSE. -* If applicable, add the following below this CDDL HEADER, with the -* fields enclosed by brackets "[]" replaced with your own identifying -* information: Portions Copyright [yyyy] [name of copyright owner] -* -* CDDL HEADER END -*/ + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License, Version 1.0 only + * (the "License"). You may not use this file except in compliance + * with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ /* -* Copyright (c) 2017 Jorgen Lundman #include #include @@ -43,7 +43,8 @@ #pragma comment(lib, "ws2_32.lib") -void clock_gettime(clock_type_t t, struct timespec *ts) +void +clock_gettime(clock_type_t t, struct timespec *ts) { LARGE_INTEGER time; LARGE_INTEGER frequency; @@ -62,7 +63,7 @@ void clock_gettime(clock_type_t t, struct timespec *ts) GetSystemTimeAsFileTime(&ft); time.LowPart = ft.dwLowDateTime; time.HighPart = ft.dwHighDateTime; - time.QuadPart -= 116444736000000000; + time.QuadPart -= 116444736000000000; ts->tv_sec = (long)(time.QuadPart / 10000000UL); ts->tv_nsec = 100*(long)(time.QuadPart % 10000000UL); break; @@ -96,45 +97,50 @@ gethrtime(void) return ((((uint64_t)ts.tv_sec) * NANOSEC) + ts.tv_nsec); } -int posix_memalign(void **memptr, size_t alignment, size_t size) +int +posix_memalign(void **memptr, size_t alignment, size_t size) { void *ptr; ptr = _aligned_malloc(size, alignment); if (ptr == NULL) - return ENOMEM; + return (ENOMEM); *memptr = ptr; - return 0; + return (0); } -const char *getexecname(void) +const char * +getexecname(void) { __declspec(thread) static char execname[32767 + 1]; - GetModuleFileNameA(NULL, execname, sizeof(execname)); - return execname; + GetModuleFileNameA(NULL, execname, sizeof (execname)); + return (execname); } -struct passwd *getpwnam(const char *login) +struct passwd * +getpwnam(const char *login) { - return NULL; + return (NULL); } -struct passwd *getgrnam(const char *group) +struct passwd * +getgrnam(const char *group) { - return NULL; + return (NULL); } -struct tm *localtime_r(const time_t *clock, struct tm *result) +struct tm * +localtime_r(const time_t *clock, struct tm *result) { if (localtime_s(result, clock) == 0) - return result; + return (result); // To avoid the ASSERT and abort(), make tm be something valid - memset(result, 0, sizeof(*result)); + memset(result, 0, sizeof (*result)); result->tm_mday = 1; - return NULL; + return (NULL); } char * -strsep(char **stringp, const char *delim) +strsep(char **stringp, const char *delim) { char *s; const char *spanp; @@ -143,7 +149,7 @@ strsep(char **stringp, const char *delim) if ((s = *stringp) == NULL) return (NULL); - for (tok = s;;) { + for (tok = s; /* empty */; ) { c = *s++; spanp = delim; do { @@ -160,7 +166,8 @@ strsep(char **stringp, const char *delim) /* NOTREACHED */ } -char *realpath(const char *file_name, char *resolved_name) +char * +realpath(const char *file_name, char *resolved_name) { DWORD ret; // If resolved_name is NULL, we allocate space. Otherwise we assume @@ -168,15 +175,16 @@ char *realpath(const char *file_name, char *resolved_name) if (resolved_name == NULL) resolved_name = malloc(PATH_MAX); if (resolved_name == NULL) - return NULL; + return (NULL); ret = GetFullPathName(file_name, PATH_MAX, resolved_name, NULL); if (ret == 0) - return NULL; + return (NULL); - return resolved_name; + return (resolved_name); } -int statfs(const char *path, struct statfs *buf) +int +statfs(const char *path, struct statfs *buf) { ULARGE_INTEGER lpFreeBytesAvailable; ULARGE_INTEGER lpTotalNumberOfBytes; @@ -185,10 +193,10 @@ int statfs(const char *path, struct statfs *buf) #if 1 if (GetDiskFreeSpaceEx(path, - &lpFreeBytesAvailable, - &lpTotalNumberOfBytes, - &lpTotalNumberOfFreeBytes)) - return -1; + &lpFreeBytesAvailable, + &lpTotalNumberOfBytes, + &lpTotalNumberOfFreeBytes)) + return (-1); #endif DISK_GEOMETRY_EX geometry_ex; @@ -198,8 +206,8 @@ int statfs(const char *path, struct statfs *buf) int fd = open(path, O_RDONLY | O_BINARY); handle = (HANDLE) _get_osfhandle(fd); if (!DeviceIoControl(handle, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, NULL, 0, - &geometry_ex, sizeof(geometry_ex), &len, NULL)) - return -1; + &geometry_ex, sizeof (geometry_ex), &len, NULL)) + return (-1); close(fd); lbsize = (uint_t)geometry_ex.Geometry.BytesPerSector; @@ -212,7 +220,7 @@ int statfs(const char *path, struct statfs *buf) strcpy(buf->f_mntonname, "fixme_to"); strcpy(buf->f_mntfromname, "fixme_from"); - return 0; + return (0); } @@ -229,7 +237,7 @@ mkstemp(char *tmpl) int fd = -1; int save_errno = errno; -#define ATTEMPTS_MIN (62 * 62 * 62) +#define ATTEMPTS_MIN (62 * 62 * 62) #if ATTEMPTS_MIN < TMP_MAX unsigned int attempts = TMP_MAX; @@ -238,34 +246,32 @@ mkstemp(char *tmpl) #endif len = strlen(tmpl); - if (len < 6 || strcmp(&tmpl[len - 6], "XXXXXX")) - { + if (len < 6 || strcmp(&tmpl[len - 6], "XXXXXX")) { errno = EINVAL; - return -1; + return (-1); } XXXXXX = &tmpl[len - 6]; { - SYSTEMTIME stNow; + SYSTEMTIME stNow; FILETIME ftNow; // get system time GetSystemTime(&stNow); stNow.wMilliseconds = 500; - if (!SystemTimeToFileTime(&stNow, &ftNow)) - { + if (!SystemTimeToFileTime(&stNow, &ftNow)) { errno = -1; - return -1; + return (-1); } - random_time_bits = (((unsigned long long)ftNow.dwHighDateTime << 32) - | (unsigned long long)ftNow.dwLowDateTime); + random_time_bits = + (((unsigned long long)ftNow.dwHighDateTime << 32) | + (unsigned long long)ftNow.dwLowDateTime); } value += random_time_bits ^ (unsigned long long)GetCurrentThreadId(); - for (count = 0; count < attempts; value += 7777, ++count) - { + for (count = 0; count < attempts; value += 7777, ++count) { unsigned long long v = value; /* Fill in the random bits. */ @@ -281,38 +287,39 @@ mkstemp(char *tmpl) v /= 62; XXXXXX[5] = letters[v % 62]; - fd = open(tmpl, O_RDWR | O_CREAT | O_EXCL, _S_IREAD | _S_IWRITE); - if (fd >= 0) - { + fd = open(tmpl, + O_RDWR | O_CREAT | O_EXCL, _S_IREAD | _S_IWRITE); + if (fd >= 0) { errno = save_errno; - return fd; - } - else if (errno != EEXIST) - return -1; + return (fd); + } else if (errno != EEXIST) + return (-1); } /* We got out of the loop because we ran out of combinations to try. */ errno = EEXIST; - return -1; + return (-1); } -int readlink(const char *path, char *buf, size_t bufsize) +int +readlink(const char *path, char *buf, size_t bufsize) { - return -1; + return (-1); } -int usleep(__int64 usec) +int +usleep(__int64 usec) { HANDLE timer; LARGE_INTEGER ft; - ft.QuadPart = -(10 * usec); // Convert to 100 nanosecond interval, negative value indicates relative time + ft.QuadPart = -(10 * usec); timer = CreateWaitableTimer(NULL, TRUE, NULL); SetWaitableTimer(timer, &ft, 0, NULL, NULL, 0); WaitForSingleObject(timer, INFINITE); CloseHandle(timer); - return 0; + return (0); } int @@ -327,42 +334,42 @@ nanosleep(const struct timespec *rqtp, struct timespec *rmtp) li.QuadPart = -((SEC2NSEC(rqtp->tv_sec) + rqtp->tv_nsec) / 100ULL); if (!(timer = CreateWaitableTimer(NULL, TRUE, NULL))) - return FALSE; + return (FALSE); /* Set timer properties */ if (!SetWaitableTimer(timer, &li, 0, NULL, NULL, FALSE)) { CloseHandle(timer); - return FALSE; + return (FALSE); } /* Start & wait for timer */ WaitForSingleObject(timer, INFINITE); /* Clean resources */ CloseHandle(timer); /* Slept without problems */ - return 0; + return (0); } -int strncasecmp(const char *s1, const char *s2, size_t n) +int +strncasecmp(const char *s1, const char *s2, size_t n) { if (n == 0) - return 0; + return (0); - while (n-- != 0 && tolower(*s1) == tolower(*s2)) - { + while (n-- != 0 && tolower(*s1) == tolower(*s2)) { if (n == 0 || *s1 == '\0' || *s2 == '\0') break; s1++; s2++; } - return tolower(*(unsigned char *)s1) - tolower(*(unsigned char *)s2); + return (tolower(*(unsigned char *)s1) - tolower(*(unsigned char *)s2)); } -#define DIRNAME 0 -#define BASENAME 1 +#define DIRNAME 0 +#define BASENAME 1 -#define M_FSDELIM(c) ((c)=='/'||(c)=='\\') -#define M_DRDELIM(c) (0) +#define M_FSDELIM(c) ((c) == '/' || (c) == '\\') +#define M_DRDELIM(c) (0) static char curdir[] = "."; static char * @@ -371,10 +378,9 @@ basedir(char *arg, int type) register char *cp, *path; if (arg == (char *)0 || *arg == '\0' || - (*arg == '.' && (arg[1] == '\0' || - (type == DIRNAME && arg[1] == '.' && arg[2] == '\0')))) - - return curdir; /* arg NULL, empty, ".", or ".." in DIRNAME */ + (*arg == '.' && (arg[1] == '\0' || + (type == DIRNAME && arg[1] == '.' && arg[2] == '\0')))) + return (curdir); /* arg NULL, empty, ".", or ".." in DIRNAME */ if (M_DRDELIM(arg[1])) /* drive-specified pathnames */ path = arg + 2; @@ -382,7 +388,7 @@ basedir(char *arg, int type) path = arg; if (path[1] == '\0'&&M_FSDELIM(*path)) /* "/", or drive analog */ - return arg; + return (arg); cp = strchr(path, '\0'); cp--; @@ -390,41 +396,40 @@ basedir(char *arg, int type) while (cp != path && M_FSDELIM(*cp)) *(cp--) = '\0'; - for (;cp>path && !M_FSDELIM(*cp); cp--) + for (; cp > path && !M_FSDELIM(*cp); cp--) ; if (!M_FSDELIM(*cp)) if (type == DIRNAME && path != arg) { *path = '\0'; - return arg; /* curdir on the specified drive */ - } - else - return (type == DIRNAME) ? curdir : path; + return (arg); /* curdir on the specified drive */ + } else + return ((type == DIRNAME) ? curdir : path); else if (cp == path && type == DIRNAME) { cp[1] = '\0'; - return arg; /* root directory involved */ - } - else if (cp == path && cp[1] == '\0') - return(arg); + return (arg); /* root directory involved */ + } else if (cp == path && cp[1] == '\0') + return (arg); else if (type == BASENAME) - return ++cp; + return (++cp); *cp = '\0'; - return arg; + return (arg); } char * dirname(char *arg) { - return(basedir(arg, DIRNAME)); + return (basedir(arg, DIRNAME)); } char * basename(char *arg) { - return(basedir(arg, BASENAME)); + return (basedir(arg, BASENAME)); } -char* getIoctlAsString(int cmdNo) +char * +getIoctlAsString(int cmdNo) { switch (cmdNo) { case 0x800: return "ZFS_IOC_FIRST"; @@ -522,7 +527,8 @@ char* getIoctlAsString(int cmdNo) } -int vasprintf(char **strp, const char *fmt, va_list ap) +int +vasprintf(char **strp, const char *fmt, va_list ap) { int r = -1, size; @@ -541,24 +547,27 @@ int vasprintf(char **strp, const char *fmt, va_list ap) *strp = 0; } - return(r); + return (r); } -int asprintf(char **strp, const char *fmt, ...) +int +asprintf(char **strp, const char *fmt, ...) { int r; va_list ap; va_start(ap, fmt); r = vasprintf(strp, fmt, ap); va_end(ap); - return(r); + return (r); } -int gettimeofday(struct timeval *tp, struct timezone *tzp) +int +gettimeofday(struct timeval *tp, struct timezone *tzp) { - // Note: some broken versions only have 8 trailing zero's, the correct epoch has 9 trailing zero's + // Note: some broken versions only have 8 trailing zero's, + // the correct epoch has 9 trailing zero's static const uint64_t EPOCH = ((uint64_t)116444736000000000ULL); SYSTEMTIME system_time; @@ -572,19 +581,22 @@ int gettimeofday(struct timeval *tp, struct timezone *tzp) tp->tv_sec = (long)((time - EPOCH) / 10000000L); tp->tv_usec = (long)(system_time.wMilliseconds * 1000); - return 0; + return (0); } -void flockfile(FILE *file) +void +flockfile(FILE *file) { } -void funlockfile(FILE *file) +void +funlockfile(FILE *file) { } -unsigned long gethostid(void) +unsigned long +gethostid(void) { LSTATUS Status; unsigned long hostid = 0UL; @@ -592,13 +604,15 @@ unsigned long gethostid(void) DWORD type; DWORD len; - Status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SYSTEM\\ControlSet001\\Services\\ZFSin", - 0, KEY_READ, &key); + Status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, + "SYSTEM\\ControlSet001\\Services\\ZFSin", + 0, KEY_READ, &key); if (Status != ERROR_SUCCESS) - return 0UL; + return (0UL); - len = sizeof(hostid); - Status = RegQueryValueEx(key, "hostid", NULL, &type, (LPBYTE)&hostid, &len); + len = sizeof (hostid); + Status = RegQueryValueEx(key, "hostid", NULL, &type, + (LPBYTE)&hostid, &len); if (Status != ERROR_SUCCESS) hostid = 0; @@ -609,51 +623,55 @@ unsigned long gethostid(void) return (hostid & 0xffffffff); } -uid_t geteuid(void) +uid_t +geteuid(void) { - return 0; // woah, root? + return (0); // woah, root? } -struct passwd *getpwuid(uid_t uid) +struct passwd * +getpwuid(uid_t uid) { - return NULL; + return (NULL); } -const char *win_ctime_r(char *buffer, size_t bufsize, time_t cur_time) +const char * +win_ctime_r(char *buffer, size_t bufsize, time_t cur_time) { errno_t e = ctime_s(buffer, bufsize, &cur_time); - return buffer; + return (buffer); } -uint64_t GetFileDriveSize(HANDLE h) +uint64_t +GetFileDriveSize(HANDLE h) { LARGE_INTEGER large; if (GetFileSizeEx(h, &large)) - return large.QuadPart; + return (large.QuadPart); PARTITION_INFORMATION_EX partInfo; DWORD retcount = 0; if (DeviceIoControl(h, - IOCTL_DISK_GET_PARTITION_INFO_EX, - (LPVOID)NULL, - (DWORD)0, - (LPVOID)&partInfo, - sizeof(partInfo), - &retcount, - (LPOVERLAPPED)NULL)) { - return partInfo.PartitionLength.QuadPart; + IOCTL_DISK_GET_PARTITION_INFO_EX, + (LPVOID)NULL, + (DWORD)0, + (LPVOID)&partInfo, + sizeof (partInfo), + &retcount, + (LPOVERLAPPED)NULL)) { + return (partInfo.PartitionLength.QuadPart); } DISK_GEOMETRY_EX geometry_ex; DWORD len; if (DeviceIoControl(h, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, NULL, 0, - &geometry_ex, sizeof(geometry_ex), &len, NULL)) - return geometry_ex.DiskSize.QuadPart; + &geometry_ex, sizeof (geometry_ex), &len, NULL)) + return (geometry_ex.DiskSize.QuadPart); - return 0; + return (0); } @@ -678,59 +696,54 @@ closelog(void) int pipe(int fildes[2]) { - return wosix_socketpair(AF_UNIX, SOCK_STREAM, 0, fildes); + return (wosix_socketpair(AF_UNIX, SOCK_STREAM, 0, fildes)); } struct group * - getgrgid(gid_t gid) +getgrgid(gid_t gid) { - return NULL; + return (NULL); } int unmount(const char *dir, int flags) { - return -1; + return (-1); } extern size_t -strlcpy(register char* s, register const char* t, register size_t n) +strlcpy(register char *s, register const char *t, register size_t n) { - const char* o = t; + const char *o = t; if (n) - do - { - if (!--n) - { + do { + if (!--n) { *s = 0; break; } } while (*s++ = *t++); if (!n) - while (*t++); - return t - o - 1; + while (*t++) + ; + return (t - o - 1); } extern size_t -strlcat(register char* s, register const char* t, register size_t n) +strlcat(register char *s, register const char *t, register size_t n) { register size_t m; - const char* o = t; + const char *o = t; - if (m = n) - { - while (n && *s) - { + if (m = n) { + while (n && *s) { n--; s++; } m -= n; if (n) - do - { - if (!--n) - { + do { + if (!--n) { *s = 0; break; } @@ -739,37 +752,43 @@ strlcat(register char* s, register const char* t, register size_t n) *s = 0; } if (!n) - while (*t++); - return (t - o) + m - 1; + while (*t++) + ; + return ((t - o) + m - 1); } -char *strndup(const char *src, size_t size) +char * +strndup(const char *src, size_t size) { char *r = _strdup(src); if (r) { r[size] = 0; } - return r; + return (r); } -int setrlimit(int resource, const struct rlimit *rlp) +int +setrlimit(int resource, const struct rlimit *rlp) { - return 0; + return (0); } -int tcgetattr(int fildes, struct termios *termios_p) +int +tcgetattr(int fildes, struct termios *termios_p) { - return 0; + return (0); } -int tcsetattr(int fildes, int optional_actions, - const struct termios *termios_p) +int +tcsetattr(int fildes, int optional_actions, + const struct termios *termios_p) { - return 0; + return (0); } -void console_echo(boolean_t willecho) +void +console_echo(boolean_t willecho) { HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE); int constype = isatty(hStdin); @@ -795,9 +814,10 @@ void console_echo(boolean_t willecho) } // Not really getline, just used for password input in libzfs_crypto.c -#define MAX_GETLINE 128 -ssize_t getline(char **linep, size_t* linecapp, - FILE *stream) +#define MAX_GETLINE 128 +ssize_t +getline(char **linep, size_t *linecapp, + FILE *stream) { static char getpassbuf[MAX_GETLINE + 1]; size_t i = 0; @@ -805,20 +825,15 @@ ssize_t getline(char **linep, size_t* linecapp, console_echo(FALSE); int c; - for (;;) - { + for (;;) { c = getc(stream); - if ((c == '\r') || (c == '\n')) - { + if ((c == '\r') || (c == '\n')) { getpassbuf[i] = '\0'; break; - } - else if (i < MAX_GETLINE) - { + } else if (i < MAX_GETLINE) { getpassbuf[i++] = c; } - if (i >= MAX_GETLINE) - { + if (i >= MAX_GETLINE) { getpassbuf[i] = '\0'; break; } @@ -829,21 +844,23 @@ ssize_t getline(char **linep, size_t* linecapp, console_echo(TRUE); - return i; + return (i); } /* Windows POSIX wrappers */ -int wosix_fsync(int fd) +int +wosix_fsync(int fd) { if (!FlushFileBuffers(ITOH(fd))) - return EIO; - return 0; + return (EIO); + return (0); } -int wosix_open(const char *path, int oflag, ...) +int +wosix_open(const char *path, int oflag, ...) { HANDLE h; DWORD mode = GENERIC_READ; // RDONLY=0, WRONLY=1, RDWR=2; @@ -861,7 +878,8 @@ int wosix_open(const char *path, int oflag, ...) how = TRUNCATE_EXISTING; break; case (O_CREAT | O_EXCL): - case (O_CREAT | O_EXCL | O_TRUNC): // Only creating new implies starting from 0 + case (O_CREAT | O_EXCL | O_TRUNC): + // Only creating new implies starting from 0 how = CREATE_NEW; break; case (O_CREAT | O_TRUNC): @@ -882,7 +900,8 @@ int wosix_open(const char *path, int oflag, ...) // "#offset#length#name" style, and try again. We let it fail first // just in case someone names their file with a starting '#'. - h = CreateFile(path, mode, share, NULL, how, FILE_ATTRIBUTE_NORMAL, NULL); + h = CreateFile(path, mode, share, NULL, how, FILE_ATTRIBUTE_NORMAL, + NULL); if (h == INVALID_HANDLE_VALUE && path[0] == '#') { char *end = NULL; @@ -893,21 +912,22 @@ int wosix_open(const char *path, int oflag, ...) len = strtoull(end, &end, 10); while (end && *end == '#') end++; - h = CreateFile(end, mode, share, NULL, how, FILE_ATTRIBUTE_NORMAL, NULL); + h = CreateFile(end, mode, share, NULL, how, + FILE_ATTRIBUTE_NORMAL, NULL); if (h != INVALID_HANDLE_VALUE) { // Upper layer probably handles this, but let's help LARGE_INTEGER place; place.QuadPart = offset; SetFilePointerEx(h, place, NULL, FILE_BEGIN); } - } // Also handle "/dev/" if (strncmp("/dev/", path, 5) == 0) { char tmp[PATH_MAX]; - snprintf(tmp, sizeof(tmp), "\\\\?\\%s", &path[5]); - h = CreateFile(tmp, mode, share, NULL, how, FILE_ATTRIBUTE_NORMAL, NULL); + snprintf(tmp, sizeof (tmp), "\\\\?\\%s", &path[5]); + h = CreateFile(tmp, mode, share, NULL, how, + FILE_ATTRIBUTE_NORMAL, NULL); } // If we failed, translate error to posix @@ -925,7 +945,7 @@ int wosix_open(const char *path, int oflag, ...) errno = EEXIST; break; } - return -1; + return (-1); } return (HTOI(h)); } @@ -933,63 +953,72 @@ int wosix_open(const char *path, int oflag, ...) // Figure out when to call WSAStartup(); static int posix_init_winsock = 0; -int wosix_close(int fd) +int +wosix_close(int fd) { HANDLE h = ITOH(fd); // Use CloseHandle() for everything except sockets. if ((GetFileType(h) == FILE_TYPE_REMOTE) && - !GetNamedPipeInfo(h, NULL, NULL, NULL, NULL)) { + !GetNamedPipeInfo(h, NULL, NULL, NULL, NULL)) { int err; err = closesocket((SOCKET)h); - return err; + return (err); } if (CloseHandle(h)) - return 0; - return -1; + return (0); + return (-1); } -int wosix_ioctl(int fd, unsigned long request, zfs_iocparm_t *wrap) +int +wosix_ioctl(int fd, unsigned long request, zfs_iocparm_t *wrap) { int error; ULONG bytesReturned; error = DeviceIoControl(ITOH(fd), - (DWORD)request, - wrap, - (DWORD)sizeof(zfs_iocparm_t), - wrap, - (DWORD)sizeof(zfs_iocparm_t), - &bytesReturned, - NULL - ); + (DWORD)request, + wrap, + (DWORD)sizeof (zfs_iocparm_t), + wrap, + (DWORD)sizeof (zfs_iocparm_t), + &bytesReturned, + NULL); if (error == 0) error = GetLastError(); else error = 0; - + #ifdef DEBUG - fprintf(stderr, " (ioctl 0x%x (%s) status %d bytes %ld)\n", (request & 0x2ffc) >> 2, getIoctlAsString((request & 0x2ffc) >> 2), error, bytesReturned); fflush(stderr); + fprintf(stderr, + " (ioctl 0x%x (%s) status %d bytes %ld)\n", + (request & 0x2ffc) >> 2, + getIoctlAsString((request & 0x2ffc) >> 2), error, + bytesReturned); + fflush(stderr); #endif #if 0 for (int x = 0; x < 16; x++) fprintf(stderr, "%02x ", ((unsigned char *)zc)[x]); fprintf(stderr, "\n"); fflush(stderr); - fprintf(stderr, "returned ioctl on 0x%x (raw 0x%x) struct size %d in %p:%d out %p:%d\n", - (request & 0x2ffc) >> 2, request, - sizeof(zfs_cmd_t), - zc->zc_nvlist_src, zc->zc_nvlist_src_size, - zc->zc_nvlist_dst, zc->zc_nvlist_dst_size - ); fflush(stderr); + fprintf(stderr, + "returned ioctl on 0x%x (raw 0x%x) struct size %d in " + "%p:%d out %p:%d\n", + (request & 0x2ffc) >> 2, request, + sizeof (zfs_cmd_t), + zc->zc_nvlist_src, zc->zc_nvlist_src_size, + zc->zc_nvlist_dst, zc->zc_nvlist_dst_size); + fflush(stderr); #endif errno = error; - return error; + return (error); } -uint64_t wosix_lseek(int fd, uint64_t offset, int seek) +uint64_t +wosix_lseek(int fd, uint64_t offset, int seek) { LARGE_INTEGER LOFF, LNEW; int type = FILE_BEGIN; @@ -1007,43 +1036,45 @@ uint64_t wosix_lseek(int fd, uint64_t offset, int seek) break; } if (!SetFilePointerEx(ITOH(fd), LOFF, &LNEW, type)) - return -1; - return LNEW.QuadPart; + return (-1); + return (LNEW.QuadPart); } -int wosix_read(int fd, void *data, uint32_t len) +int +wosix_read(int fd, void *data, uint32_t len) { DWORD red; OVERLAPPED ow = {0}; if (GetFileType(ITOH(fd)) == FILE_TYPE_PIPE) { if (!ReadFile(ITOH(fd), data, len, &red, &ow)) - return -1; + return (-1); } else { if (!ReadFile(ITOH(fd), data, len, &red, NULL)) - return -1; + return (-1); } - return red; + return (red); } -int wosix_write(int fd, const void *data, uint32_t len) +int +wosix_write(int fd, const void *data, uint32_t len) { DWORD wrote; OVERLAPPED ow = { 0 }; if (GetFileType(ITOH(fd)) == FILE_TYPE_PIPE) { if (!WriteFile(ITOH(fd), data, len, &wrote, &ow)) - return -1; + return (-1); } else { if (!WriteFile(ITOH(fd), data, len, &wrote, NULL)) - return -1; + return (-1); } - return wrote; + return (wrote); } -#define is_wprefix(s, prefix) \ - (wcsncmp((s), (prefix), sizeof(prefix) / sizeof(WCHAR) - 1) == 0) +#define is_wprefix(s, prefix) \ + (wcsncmp((s), (prefix), sizeof (prefix) / sizeof (WCHAR) - 1) == 0) // Parts by: // * Copyright(c) 2015 - 2017 K.Takata @@ -1053,7 +1084,8 @@ int wosix_write(int fd, const void *data, uint32_t len) // Extend isatty() slightly to return 1 for DOS Console, or // 2 for cygwin/mingw - as we will have to do different things // for NOECHO etc. -int wosix_isatty(int fd) +int +wosix_isatty(int fd) { DWORD mode; HANDLE h = ITOH(fd); @@ -1063,29 +1095,33 @@ int wosix_isatty(int fd) // If not, check for cygwin ... // check for mingw ... // check for powershell ... - if (GetConsoleMode(h, &mode)) return 1; + if (GetConsoleMode(h, &mode)) + return (1); // Not CMDbox, check mingw if (GetFileType(h) == FILE_TYPE_PIPE) { - int size = sizeof(FILE_NAME_INFO) + sizeof(WCHAR) * (MAX_PATH - 1); + int size = sizeof (FILE_NAME_INFO) + + sizeof (WCHAR) * (MAX_PATH - 1); FILE_NAME_INFO* nameinfo; WCHAR* p = NULL; - nameinfo = malloc(size + sizeof(WCHAR)); + nameinfo = malloc(size + sizeof (WCHAR)); if (nameinfo != NULL) { - if (GetFileInformationByHandleEx(h, FileNameInfo, nameinfo, size)) { - nameinfo->FileName[nameinfo->FileNameLength / sizeof(WCHAR)] = L'\0'; + if (GetFileInformationByHandleEx(h, FileNameInfo, + nameinfo, size)) { + nameinfo->FileName[nameinfo->FileNameLength / + sizeof (WCHAR)] = L'\0'; p = nameinfo->FileName; - if (is_wprefix(p, L"\\cygwin-")) { /* Cygwin */ + if (is_wprefix(p, L"\\cygwin-")) { p += 8; - } else if (is_wprefix(p, L"\\msys-")) { /* MSYS and MSYS2 */ + } else if (is_wprefix(p, L"\\msys-")) { p += 6; } else { p = NULL; } if (p != NULL) { - while (*p && isxdigit(*p)) /* Skip 16-digit hexadecimal. */ + while (*p && isxdigit(*p)) ++p; if (is_wprefix(p, L"-pty")) { p += 4; @@ -1094,12 +1130,13 @@ int wosix_isatty(int fd) } } if (p != NULL) { - while (*p && isdigit(*p)) /* Skip pty number. */ + while (*p && isdigit(*p)) ++p; if (is_wprefix(p, L"-from-master")) { - //p += 12; - } else if (is_wprefix(p, L"-to-master")) { - //p += 10; + // p += 12; + } else if (is_wprefix(p, + L"-to-master")) { + // p += 10; } else { p = NULL; } @@ -1107,41 +1144,44 @@ int wosix_isatty(int fd) } free(nameinfo); if (p != NULL) - return 2; + return (2); } } // Give up, it's not a TTY - return 0; + return (0); } // A bit different, just to wrap away the second argument // Presumably _mkdir() sets errno, as EEXIST is tested. -int wosix_mkdir(const char *path, mode_t mode) +int +wosix_mkdir(const char *path, mode_t mode) { - return _mkdir(path); + return (_mkdir(path)); } -int wosix_stat(char *path, struct _stat64 *st) +int +wosix_stat(char *path, struct _stat64 *st) { int fd; int ret; fd = open(path, O_RDONLY); if (fd == -1) - return -1; + return (-1); ret = wosix_fstat(fd, st); - close(fd); - return (ret); + close(fd); + return (ret); } -int wosix_lstat(char *path, struct _stat64 *st) +int +wosix_lstat(char *path, struct _stat64 *st) { int fd; int ret; fd = open(path, O_RDONLY); if (fd == -1) - return -1; + return (-1); ret = wosix_fstat(fd, st); // Fix me? Symlinks close(fd); return (ret); @@ -1150,41 +1190,47 @@ int wosix_lstat(char *path, struct _stat64 *st) // Only fill in what we actually use in ZFS // Mostly used to test for existance, st_mode, st_size // also FIFO and BLK (fixme) -// Remember to convert between POSIX (S_IFDIR) and WINDOWS (_S_IFDIR) when required. +// Remember to convert between POSIX (S_IFDIR) and WINDOWS +// (_S_IFDIR) when required. // Not that we call Windows _stat() in here. -int wosix_fstat(int fd, struct _stat64 *st) +int +wosix_fstat(int fd, struct _stat64 *st) { HANDLE h = ITOH(fd); BY_HANDLE_FILE_INFORMATION info; if (!GetFileInformationByHandle(h, &info)) - return wosix_fstat_blk(fd, st); + return (wosix_fstat_blk(fd, st)); st->st_dev = 0; st->st_ino = 0; st->st_mode = (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? - S_IFDIR : S_IFREG; - st->st_nlink = (info.nNumberOfLinks > SHRT_MAX ? SHRT_MAX : info.nNumberOfLinks); + S_IFDIR : S_IFREG; + st->st_nlink = + (info.nNumberOfLinks > SHRT_MAX ? SHRT_MAX : info.nNumberOfLinks); st->st_uid = 0; st->st_gid = 0; st->st_rdev = 0; - st->st_size = ((long long)info.nFileSizeHigh << 32ULL) | (long long)info.nFileSizeLow; + st->st_size = + ((long long)info.nFileSizeHigh << 32ULL) | + (long long)info.nFileSizeLow; st->st_atime = 0; st->st_mtime = 0; st->st_ctime = 0; - return 0; + return (0); } -int wosix_fstat_blk(int fd, struct _stat64 *st) +int +wosix_fstat_blk(int fd, struct _stat64 *st) { DISK_GEOMETRY_EX geometry_ex; HANDLE handle = ITOH(fd); DWORD len; if (!DeviceIoControl(handle, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, NULL, 0, - &geometry_ex, sizeof(geometry_ex), &len, NULL)) - return -1; // errno? + &geometry_ex, sizeof (geometry_ex), &len, NULL)) + return (-1); // errno? st->st_size = (diskaddr_t)geometry_ex.DiskSize.QuadPart; st->st_mode = S_IFBLK; @@ -1193,13 +1239,15 @@ int wosix_fstat_blk(int fd, struct _stat64 *st) } // os specific files can call this directly. -int pread_win(HANDLE h, void *buf, size_t nbyte, off_t offset) +int +pread_win(HANDLE h, void *buf, size_t nbyte, off_t offset) { uint64_t off; DWORD red; LARGE_INTEGER large; LARGE_INTEGER lnew; - // This code does all seeks based on "current" so we can pre-seek to offset start + // This code does all seeks based on "current" so we can + // pre-seek to offset start // Find current position large.QuadPart = 0; @@ -1224,12 +1272,14 @@ int pread_win(HANDLE h, void *buf, size_t nbyte, off_t offset) return (red); } -int wosix_pread(int fd, void *buf, size_t nbyte, off_t offset) +int +wosix_pread(int fd, void *buf, size_t nbyte, off_t offset) { - return pread_win(ITOH(fd), buf, nbyte, offset); + return (pread_win(ITOH(fd), buf, nbyte, offset)); } -int wosix_pwrite(int fd, const void *buf, size_t nbyte, off_t offset) +int +wosix_pwrite(int fd, const void *buf, size_t nbyte, off_t offset) { HANDLE h = ITOH(fd); uint64_t off; @@ -1237,7 +1287,8 @@ int wosix_pwrite(int fd, const void *buf, size_t nbyte, off_t offset) LARGE_INTEGER large; LARGE_INTEGER lnew; - // This code does all seeks based on "current" so we can pre-seek to offset start + // This code does all seeks based on "current" so we can + // pre-seek to offset start // Find current position large.QuadPart = 0; @@ -1254,36 +1305,39 @@ int wosix_pwrite(int fd, const void *buf, size_t nbyte, off_t offset) // Restore position SetFilePointerEx(h, lnew, NULL, FILE_BEGIN); - return wrote; + return (wrote); } -int wosix_fdatasync(int fd) +int +wosix_fdatasync(int fd) { - //if (fcntl(fd, F_FULLFSYNC) == -1) + // if (fcntl(fd, F_FULLFSYNC) == -1) // return -1; - return 0; + return (0); } -int wosix_ftruncate(int fd, off_t length) +int +wosix_ftruncate(int fd, off_t length) { HANDLE h = ITOH(fd); LARGE_INTEGER lnew; lnew.QuadPart = length; if (SetFilePointerEx(h, lnew, NULL, FILE_BEGIN) && - SetEndOfFile(h)) - return 0; // Success + SetEndOfFile(h)) + return (0); // Success // errno? - return -1; + return (-1); } -FILE *wosix_fdopen(int fd, const char *mode) +FILE * +wosix_fdopen(int fd, const char *mode) { // Convert HANDLE to int int temp = _open_osfhandle((intptr_t)ITOH(fd), _O_APPEND | _O_RDONLY); if (temp == -1) { - return NULL; + return (NULL); } // Convert int to FILE* @@ -1291,7 +1345,7 @@ FILE *wosix_fdopen(int fd, const char *mode) if (f == NULL) { _close(temp); - return NULL; + return (NULL); } // Why is this print required? @@ -1301,7 +1355,8 @@ FILE *wosix_fdopen(int fd, const char *mode) return (f); } -int wosix_socketpair(int domain, int type, int protocol, int sv[2]) +int +wosix_socketpair(int domain, int type, int protocol, int sv[2]) { int temp, s1, s2, result; struct sockaddr_in saddr; @@ -1318,26 +1373,28 @@ int wosix_socketpair(int domain, int type, int protocol, int sv[2]) err = WSAStartup(MAKEWORD(2, 2), &wsaData); if (err != 0) { errno = err; - return -1; + return (-1); } } - nameLen = sizeof(saddr); + nameLen = sizeof (saddr); /* ignore address family for now; just stay with AF_INET */ temp = socket(AF_INET, SOCK_STREAM, 0); if (temp == INVALID_SOCKET) { int err = WSAGetLastError(); errno = err; - return -1; + return (-1); } setsockopt(temp, SOL_SOCKET, SO_REUSEADDR, (void *)&option_arg, - sizeof(option_arg)); + sizeof (option_arg)); - /* We *SHOULD* choose the correct sockaddr structure based - on the address family requested... */ - memset(&saddr, 0, sizeof(saddr)); + /* + * We *SHOULD* choose the correct sockaddr structure based + * on the address family requested... + */ + memset(&saddr, 0, sizeof (saddr)); saddr.sin_family = AF_INET; saddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); @@ -1347,36 +1404,36 @@ int wosix_socketpair(int domain, int type, int protocol, int sv[2]) if (result == SOCKET_ERROR) { errno = WSAGetLastError(); closesocket(temp); - return -2; + return (-2); } // Don't care about error here, the connect will fail instead listen(temp, 1); // Fetch out the port that was given to us. - nameLen = sizeof(struct sockaddr_in); + nameLen = sizeof (struct sockaddr_in); result = getsockname(temp, (struct sockaddr *)&saddr, &nameLen); if (result == INVALID_SOCKET) { closesocket(temp); - return -4; /* error case */ + return (-4); /* error case */ } s1 = socket(AF_INET, SOCK_STREAM, 0); if (s1 == INVALID_SOCKET) { closesocket(temp); - return -5; + return (-5); } - nameLen = sizeof(struct sockaddr_in); + nameLen = sizeof (struct sockaddr_in); result = connect(s1, (struct sockaddr *)&saddr, nameLen); if (result == INVALID_SOCKET) { closesocket(temp); closesocket(s1); - return -6; /* error case */ + return (-6); /* error case */ } s2 = accept(temp, NULL, NULL); @@ -1385,19 +1442,21 @@ int wosix_socketpair(int domain, int type, int protocol, int sv[2]) if (s2 == INVALID_SOCKET) { closesocket(s1); - return -7; + return (-7); } sv[0] = s1; sv[1] = s2; - if ((sv[0] < 0) || (sv[1] < 0)) return -8; + if ((sv[0] < 0) || (sv[1] < 0)) + return (-8); - return 0; /* normal case */ + return (0); /* normal case */ } -int wosix_dup2(int fildes, int fildes2) +int +wosix_dup2(int fildes, int fildes2) { - return -1; + return (-1); } static long GetLogicalProcessors(void); @@ -1407,44 +1466,43 @@ sysconf(int name) { SYSTEM_INFO info; MEMORYSTATUSEX status; - + switch (name) { case _SC_NPROCESSORS_ONLN: - return GetLogicalProcessors(); + return (GetLogicalProcessors()); case _SC_PHYS_PAGES: case _SC_PAGE_SIZE: GetSystemInfo(&info); if (name == _SC_PAGE_SIZE) - return info.dwPageSize; - status.dwLength = sizeof(status); - GlobalMemoryStatusEx( &status ); - return (long)(status.ullTotalPhys / info.dwPageSize); + return (info.dwPageSize); + status.dwLength = sizeof (status); + GlobalMemoryStatusEx(&status); + return ((long)(status.ullTotalPhys / info.dwPageSize)); default: return (-1); } } -typedef BOOL (WINAPI *LPFN_GLPI)( - PSYSTEM_LOGICAL_PROCESSOR_INFORMATION, +typedef BOOL(WINAPI *LPFN_GLPI)(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION, PDWORD); // Helper function to count set bits in the processor mask. -static DWORD CountSetBits(ULONG_PTR bitMask) +static DWORD +CountSetBits(ULONG_PTR bitMask) { - DWORD LSHIFT = sizeof(ULONG_PTR)*8 - 1; - DWORD bitSetCount = 0; - ULONG_PTR bitTest = (ULONG_PTR)1 << LSHIFT; - DWORD i; - - for (i = 0; i <= LSHIFT; ++i) - { - bitSetCount += ((bitMask & bitTest)?1:0); - bitTest/=2; - } + DWORD LSHIFT = sizeof (ULONG_PTR)*8 - 1; + DWORD bitSetCount = 0; + ULONG_PTR bitTest = (ULONG_PTR)1 << LSHIFT; + DWORD i; + + for (i = 0; i <= LSHIFT; ++i) { + bitSetCount += ((bitMask & bitTest)?1:0); + bitTest /= 2; + } - return bitSetCount; + return (bitSetCount); } static long @@ -1466,9 +1524,9 @@ GetLogicalProcessors(void) PCACHE_DESCRIPTOR Cache; glpi = (LPFN_GLPI) GetProcAddress( - GetModuleHandle(TEXT("kernel32")), - "GetLogicalProcessorInformation"); - if (NULL == glpi) + GetModuleHandle(TEXT("kernel32")), + "GetLogicalProcessorInformation"); + if (NULL == glpi) return (-1); while (!done) { @@ -1476,13 +1534,13 @@ GetLogicalProcessors(void) if (FALSE == rc) { if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) { - if (buffer) + if (buffer) free(buffer); - buffer = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION)malloc( - returnLength); + buffer = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION) + malloc(returnLength); - if (NULL == buffer) + if (NULL == buffer) return (-1); } else { return (-1); @@ -1494,7 +1552,8 @@ GetLogicalProcessors(void) ptr = buffer; - while (byteOffset + sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION) <= returnLength) { + while (byteOffset + sizeof (SYSTEM_LOGICAL_PROCESSOR_INFORMATION) <= + returnLength) { switch (ptr->Relationship) { case RelationNumaNode: // Non-NUMA systems report a single record of this type. @@ -1504,12 +1563,15 @@ GetLogicalProcessors(void) case RelationProcessorCore: processorCoreCount++; - // A hyperthreaded core supplies more than one logical processor. - logicalProcessorCount += CountSetBits(ptr->ProcessorMask); + // A hyperthreaded core supplies more than one + // logical processor. + logicalProcessorCount += + CountSetBits(ptr->ProcessorMask); break; case RelationCache: - // Cache data is in ptr->Cache, one CACHE_DESCRIPTOR structure for each cache. + // Cache data is in ptr->Cache, one CACHE_DESCRIPTOR + // structure for each cache. Cache = &ptr->Cache; if (Cache->Level == 1) processorL1CacheCount++; @@ -1527,7 +1589,7 @@ GetLogicalProcessors(void) default: break; } - byteOffset += sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); + byteOffset += sizeof (SYSTEM_LOGICAL_PROCESSOR_INFORMATION); ptr++; } @@ -1535,22 +1597,24 @@ GetLogicalProcessors(void) return (logicalProcessorCount); } -int mprotect(void *addr, size_t len, int prot) +int +mprotect(void *addr, size_t len, int prot) { // We can probably implement something using VirtualProtect() here. return (0); } -int getuid (void) +int +getuid(void) { - return 1; + return (1); } int fcntl(int fildes, int cmd, /* arg */ ...) { - return (0); + return (0); } int @@ -1578,7 +1642,7 @@ uname(struct utsname *buf) GetSystemInfo(&info); - switch(info.wProcessorArchitecture) { + switch (info.wProcessorArchitecture) { case PROCESSOR_ARCHITECTURE_AMD64: strcpy(buf->machine, "x86_64"); break; @@ -1599,26 +1663,25 @@ uname(struct utsname *buf) char * nl_langinfo(nl_item item) { - switch (item) - { + switch (item) { /* nl_langinfo items of the LC_CTYPE category */ case _DATE_FMT: - "%y/%m/%d"; + return ("%y/%m/%d"); } - return ""; + return (""); } /* * The port of openat() is quite half-hearted. But it is currently * only used with opendir(), and not used to create "..." nor with "fd". - */ + */ int -wosix_openat(int fd, const char* path, int oflag, ...) +wosix_openat(int fd, const char *path, int oflag, ...) { - if (fd == AT_FDCWD) - return wosix_open(path, oflag); - ASSERT("openat() implementation lacking support"); - return (-1); + if (fd == AT_FDCWD) + return (wosix_open(path, oflag)); + ASSERT("openat() implementation lacking support"); + return (-1); } /* @@ -1626,7 +1689,8 @@ wosix_openat(int fd, const char* path, int oflag, ...) * used to re-open the MNTTAB, of which we have none, and the return * code is never used. */ -FILE *wosix_freopen(const char *path, const char *mode, FILE *stream) +FILE * +wosix_freopen(const char *path, const char *mode, FILE *stream) { return ((FILE *)path); // Anything not NULL } diff --git a/lib/libspl/os/windows/regex.c b/lib/libspl/os/windows/regex.c index 472ef073fde..f7665c3314c 100644 --- a/lib/libspl/os/windows/regex.c +++ b/lib/libspl/os/windows/regex.c @@ -25,21 +25,20 @@ /* Fill me in when we want regex support */ int -regexec(const regex_t* restrict preg, const char* restrict string, +regexec(const regex_t *restrict preg, const char *restrict string, size_t nmatch, regmatch_t pmatch[restrict], int eflags) { - return (0); + return (0); } int -regcomp(regex_t* restrict preg, const char* restrict pattern, +regcomp(regex_t *restrict preg, const char *restrict pattern, int cflags) { return (0); } void -regfree(regex_t* preg) +regfree(regex_t *preg) { - } diff --git a/lib/libspl/os/windows/signal.c b/lib/libspl/os/windows/signal.c index 12ee4c464d7..ac2eb1a5cb3 100644 --- a/lib/libspl/os/windows/signal.c +++ b/lib/libspl/os/windows/signal.c @@ -36,16 +36,16 @@ sigfillset(sigset_t *set) } int -sigaddset(sigset_t *set, int sig) +sigaddset(sigset_t *set, int sig) { - // *set |= (1<<(sig-1)); + // *set |= (1<<(sig-1)); return (0); } int -sigdelset(sigset_t *set, int sig) +sigdelset(sigset_t *set, int sig) { - // *set &= ~(1<<(sig-1)); + // *set &= ~(1<<(sig-1)); return (0); } @@ -60,7 +60,8 @@ int sigaction(int sig, struct sigaction *sa, struct sigaction *osa) { if (osa) - osa->sa_handler = signal(sig, (void(__cdecl*)(int))sa->sa_handler); + osa->sa_handler = signal(sig, + (void(__cdecl*)(int))sa->sa_handler); else signal(sig, (void(__cdecl*)(int))sa->sa_handler); return (0); diff --git a/lib/libspl/os/windows/uio.c b/lib/libspl/os/windows/uio.c index 739f6c5cd6c..04fe46f0a12 100644 --- a/lib/libspl/os/windows/uio.c +++ b/lib/libspl/os/windows/uio.c @@ -1,102 +1,113 @@ /* -* CDDL HEADER START -* -* The contents of this file are subject to the terms of the -* Common Development and Distribution License, Version 1.0 only -* (the "License"). You may not use this file except in compliance -* with the License. -* -* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE -* or http://www.opensolaris.org/os/licensing. -* See the License for the specific language governing permissions -* and limitations under the License. -* -* When distributing Covered Code, include this CDDL HEADER in each -* file and include the License file at usr/src/OPENSOLARIS.LICENSE. -* If applicable, add the following below this CDDL HEADER, with the -* fields enclosed by brackets "[]" replaced with your own identifying -* information: Portions Copyright [yyyy] [name of copyright owner] -* -* CDDL HEADER END -*/ + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License, Version 1.0 only + * (the "License"). You may not use this file except in compliance + * with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ /* -* Copyright (c) 2017 Jorgen Lundman struct uio *uio_create( - int a_iovcount, /* max number of iovecs */ - off_t a_offset, /* current offset */ - int a_spacetype, /* type of address space */ - int a_iodirection ) /* read or write flag */ + int a_iovcount, /* max number of iovecs */ + off_t a_offset, /* current offset */ + int a_spacetype, /* type of address space */ + int a_iodirection) /* read or write flag */ { - return NULL; + return (NULL); } -user_addr_t uio_curriovbase( struct uio *a_uio ) +user_addr_t +uio_curriovbase(struct uio *a_uio) { - return 0; + return (0); } -int uio_iovcnt( struct uio *a_uio ) +int +uio_iovcnt(struct uio *a_uio) { - return 0; + return (0); } -void uio_free( struct uio *a_uio ) +void +uio_free(struct uio *a_uio) { } -int uio_addiov(struct uio *o, user_addr_t a_baseaddr, user_size_t a_length ) +int +uio_addiov(struct uio *o, user_addr_t a_baseaddr, user_size_t a_length) { - return -1; + return (-1); } -int uio_getiov( struct uio *a_uio, - int a_index, - user_addr_t * a_baseaddr_p, - user_size_t * a_length_p ) +int +uio_getiov(struct uio *a_uio, + int a_index, + user_addr_t *a_baseaddr_p, + user_size_t *a_length_p) { - return -1; + return (-1); } -user_size_t uio_curriovlen( struct uio *a_uio ) +user_size_t +uio_curriovlen(struct uio *a_uio) { - return 0; + return (0); } -int uio_isuserspace( struct uio *a_uio ) +int +uio_isuserspace(struct uio *a_uio) { - return 0; + return (0); } -user_size_t uio_resid( struct uio *a_uio ) +user_size_t +uio_resid(struct uio *a_uio) { - return 0; + return (0); } -void uio_setrw( struct uio *a_uio, int a_value ) +void +uio_setrw(struct uio *a_uio, int a_value) { } -int uiomove(const char * cp, int n, int r, struct uio *uio) +int +uiomove(const char *cp, int n, int r, struct uio *uio) { - return 0; + return (0); } -void uio_update( struct uio *a_uio, user_size_t a_count ) +void +uio_update(struct uio *a_uio, user_size_t a_count) { - } -off_t uio_offset( struct uio *a_uio ) +off_t +uio_offset(struct uio *a_uio) { - return 0; + return (0); } -void uio_reset( struct uio *a_uio, off_t a_offset, int a_spacetype, - int a_iodirection ) +void +uio_reset(struct uio *a_uio, off_t a_offset, int a_spacetype, + int a_iodirection) { - } diff --git a/lib/libspl/os/windows/xdr.c b/lib/libspl/os/windows/xdr.c index 6097ac6e51a..a80d91cb9b8 100644 --- a/lib/libspl/os/windows/xdr.c +++ b/lib/libspl/os/windows/xdr.c @@ -33,7 +33,7 @@ * California. */ -//#pragma ident "%Z%%M% %I% %E% SMI" +// #pragma ident "%Z%%M% %I% %E% SMI" /* * Generic XDR routines implementation. @@ -42,11 +42,9 @@ * most common data items. See xdr.h for more info on the interface to * xdr. */ -//#include "mt.h" #include #include #include -//#include #include #include #include @@ -59,7 +57,7 @@ #include // warning C4133 : 'function' : incompatible types - from 'XDR *' to 'XDR *' -#pragma warning( disable: 4133 ) +#pragma warning(disable: 4133) #ifndef _WIN32 #pragma weak xdr_int64_t = xdr_hyper @@ -496,7 +494,7 @@ xdr_netobj(XDR *xdrs, struct netobj *np) */ bool_t xdr_union(XDR *xdrs, int *dscmp, char *unp, - const struct xdr_discrim *choices, const xdrproc_t dfault) + const struct xdr_discrim *choices, const xdrproc_t dfault) { int dscm; @@ -630,11 +628,11 @@ xdr_hyper(XDR *xdrs, longlong_t *hp) if (XDR_PUTINT32(xdrs, (int *)hp) == TRUE) /* LINTED pointer cast */ return (XDR_PUTINT32(xdrs, (int *)((char *)hp + - BYTES_PER_XDR_UNIT))); + BYTES_PER_XDR_UNIT))); #else /* LINTED pointer cast */ if (XDR_PUTINT32(xdrs, (int *)((char *)hp + - BYTES_PER_XDR_UNIT)) == TRUE) + BYTES_PER_XDR_UNIT)) == TRUE) return (XDR_PUTINT32(xdrs, (int32_t *)hp)); #endif return (FALSE); @@ -645,13 +643,13 @@ xdr_hyper(XDR *xdrs, longlong_t *hp) if (XDR_GETINT32(xdrs, (int *)hp) == FALSE || /* LINTED pointer cast */ (XDR_GETINT32(xdrs, (int *)((char *)hp + - BYTES_PER_XDR_UNIT)) == FALSE)) + BYTES_PER_XDR_UNIT)) == FALSE)) return (FALSE); #else /* LINTED pointer cast */ if ((XDR_GETINT32(xdrs, (int *)((char *)hp + - BYTES_PER_XDR_UNIT)) == FALSE) || - (XDR_GETINT32(xdrs, (int *)hp) == FALSE)) + BYTES_PER_XDR_UNIT)) == FALSE) || + (XDR_GETINT32(xdrs, (int *)hp) == FALSE)) return (FALSE); #endif return (TRUE); @@ -704,19 +702,19 @@ xdr_control(XDR *xdrs, int request, void *info) case XDR_PEEK: /* - * Return the next 4 byte unit in the XDR stream. - */ - if (xdrs->x_handy < sizeof(int32_t)) + * Return the next 4 byte unit in the XDR stream. + */ + if (xdrs->x_handy < sizeof (int32_t)) return (FALSE); int32p = (int32_t *)info; *int32p = (int32_t)ntohl((uint32_t) - (*((int32_t *)(xdrs->x_private)))); + (*((int32_t *)(xdrs->x_private)))); return (TRUE); case XDR_SKIPBYTES: /* - * Skip the next N bytes in the XDR stream. - */ + * Skip the next N bytes in the XDR stream. + */ int32p = (int32_t *)info; len = RNDUP((int)(*int32p)); if (xdrs->x_handy < len) diff --git a/lib/libspl/os/windows/xdr_array.c b/lib/libspl/os/windows/xdr_array.c index 1cfaac83930..46b6bff52b6 100644 --- a/lib/libspl/os/windows/xdr_array.c +++ b/lib/libspl/os/windows/xdr_array.c @@ -36,13 +36,11 @@ /* * Generic XDR routines impelmentation. * - * These are the "non-trivial" xdr primitives used to serialize and de-serialize - * arrays. See xdr.h for more info on the interface to xdr. + * These are the "non-trivial" xdr primitives used to serialize and + * de-serialize arrays. See xdr.h for more info on the interface to xdr. */ -//#include "mt.h" #include -//#include #include #include @@ -64,7 +62,7 @@ char mem_err_msg_arr[] = "xdr_array: out of memory"; */ bool_t xdr_array(XDR *xdrs, caddr_t *addrp, uint_t *sizep, const uint_t maxsize, - const uint_t elsize, const xdrproc_t elproc) + const uint_t elsize, const xdrproc_t elproc) { uint_t i; caddr_t target = *addrp; @@ -92,7 +90,7 @@ xdr_array(XDR *xdrs, caddr_t *addrp, uint_t *sizep, const uint_t maxsize, return (TRUE); *addrp = target = malloc(nodesize); if (target == NULL) { - //(void) syslog(LOG_ERR, mem_err_msg_arr); + // (void) syslog(LOG_ERR, mem_err_msg_arr); return (FALSE); } (void) memset(target, 0, nodesize); @@ -132,7 +130,7 @@ xdr_array(XDR *xdrs, caddr_t *addrp, uint_t *sizep, const uint_t maxsize, */ bool_t xdr_vector(XDR *xdrs, char *basep, const uint_t nelem, - const uint_t elemsize, const xdrproc_t xdr_elem) + const uint_t elemsize, const xdrproc_t xdr_elem) { uint_t i; char *elptr; diff --git a/lib/libspl/os/windows/xdr_float.c b/lib/libspl/os/windows/xdr_float.c index 2408961d87a..d308ae54523 100644 --- a/lib/libspl/os/windows/xdr_float.c +++ b/lib/libspl/os/windows/xdr_float.c @@ -43,19 +43,17 @@ * xdr. */ -//#include "mt.h" #include #include #include -//#include #include #include #include // incompatible types - from 'XDR *' to 'XDR *' -#pragma warning (disable: 4133) +#pragma warning(disable: 4133) -#define _IEEE_754 +#define _IEEE_754 #ifdef _IEEE_754 /* diff --git a/lib/libspl/os/windows/xdr_mem.c b/lib/libspl/os/windows/xdr_mem.c index 49b0fd7096f..086238a7a13 100644 --- a/lib/libspl/os/windows/xdr_mem.c +++ b/lib/libspl/os/windows/xdr_mem.c @@ -40,8 +40,6 @@ * then this is the package for you. */ -//#include "mt.h" -//#include "rpc_mt.h" #include #include #include @@ -52,7 +50,7 @@ static struct xdr_ops *xdrmem_ops(void); // formal parameter 1 different from declaration (XDR* != struct XDR *)? -#pragma warning (disable: 4028) +#pragma warning(disable: 4028) /* * Meaning of the private areas of the xdr struct for xdr_mem @@ -67,7 +65,7 @@ static struct xdr_ops *xdrmem_ops(void); */ void xdrmem_create(XDR *xdrs, const caddr_t addr, const uint_t size, - const enum xdr_op op) + const enum xdr_op op) { caddr_t eaddr = addr; @@ -230,7 +228,7 @@ xdrmem_control(XDR *xdrs, int request, void *info) switch (request) { case XDR_GET_BYTES_AVAIL: - xptr = (struct xdr_bytesrec *) info; + xptr = (struct xdr_bytesrec *)info; xptr->xc_is_last_record = TRUE; xptr->xc_num_avail = xdrs->x_handy; return (TRUE); diff --git a/lib/libzfs/os/windows/libzfs_mount_os.c b/lib/libzfs/os/windows/libzfs_mount_os.c index fd9227d7361..2589009fc9f 100644 --- a/lib/libzfs/os/windows/libzfs_mount_os.c +++ b/lib/libzfs/os/windows/libzfs_mount_os.c @@ -69,21 +69,25 @@ do_mount(zfs_handle_t *zhp, const char *dir, char *optptr, int mflag) // mount 'spec' "tank/joe" on path 'dir' "/home/joe". #ifdef DEBUG - fprintf(stderr, "zmount running, emulating Unix mount: '%s'\r\n", dir); fflush(stderr); + fprintf(stderr, + "zmount running, emulating Unix mount: '%s'\r\n", + dir); + fflush(stderr); #endif zfs_cmd_t zc = { "\0" }; if (zhp) { if (zhp->zpool_hdl && - !strcmp(zpool_get_name(zhp->zpool_hdl), - zfs_get_name(zhp))) + strcmp(zpool_get_name(zhp->zpool_hdl), + zfs_get_name(zhp)) == 0) ispool = 1; ret = zfs_prop_get(zhp, ZFS_PROP_DRIVELETTER, driveletter, - sizeof(driveletter), NULL, NULL, 0, B_FALSE); + sizeof (driveletter), NULL, NULL, 0, B_FALSE); hasprop = ret ? 0 : 1; - if (!ret && !strncmp("-", driveletter, sizeof(driveletter))) + if (!ret && + strncmp("-", driveletter, sizeof (driveletter)) == 0) hasprop = 0; } @@ -94,20 +98,20 @@ do_mount(zfs_handle_t *zhp, const char *dir, char *optptr, int mflag) strcpy(driveletter, "on"); hasprop = 1; } - if (!strcmp("off", driveletter)) + if (strcmp("off", driveletter) == 0) hasprop = 0; - else if (!strcmp("on", driveletter)) + else if (strcmp("on", driveletter) == 0) strcpy(driveletter, "?"); - (void)strlcpy(zc.zc_name, zhp->zfs_name, sizeof(zc.zc_name)); - (void)strlcpy(zc.zc_value, dir, sizeof(zc.zc_value)); + (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name)); + (void) strlcpy(zc.zc_value, dir, sizeof (zc.zc_value)); // If hasprop is set, use 'driveletter' and ignore mountpoint path // if !hasprop && rootds same if (hasprop) { // We just pass "\\??\\X:" to kernel. - snprintf(zc.zc_value, sizeof(zc.zc_value), "\\??\\%c:", - tolower(driveletter[0])); + snprintf(zc.zc_value, sizeof (zc.zc_value), "\\??\\%c:", + tolower(driveletter[0])); } else { // We are to mount with path. Attempt to find parent // driveletter, if any. Otherwise assume c:/ @@ -118,15 +122,18 @@ do_mount(zfs_handle_t *zhp, const char *dir, char *optptr, int mflag) char *slashp; struct mnttab entry = { 0 }; - zfs_parent_name(zhp, parent, sizeof(parent)); + zfs_parent_name(zhp, parent, sizeof (parent)); while (strlen(parent) >= 1) { - if ((libzfs_mnttab_find(zhp->zfs_hdl, parent, &entry) == 0) && - (entry.mnt_mountp[1] == ':')) { + if ((libzfs_mnttab_find(zhp->zfs_hdl, parent, + &entry) == 0) && + (entry.mnt_mountp[1] == ':')) { driveletter[0] = entry.mnt_mountp[0]; #ifdef DEBUG - fprintf(stderr, "we think '%s' parent is '%s' and its mounts are: '%s'\r\n", - zfs_get_name(zhp), parent, entry.mnt_mountp); fflush(stderr); + fprintf(stderr, + "we think '%s' parent is '%s' and its mounts are: '%s'\r\n", + zfs_get_name(zhp), parent, entry.mnt_mountp); + fflush(stderr); #endif break; } @@ -135,17 +142,21 @@ do_mount(zfs_handle_t *zhp, const char *dir, char *optptr, int mflag) *slashp = '\0'; } - // We need to skip the parent name part, in mountpoint "dir" here,ie - // if parent is "BOOM/lower" we need to skip to the 3nd slash - // in "/BOOM/lower/newfs" - // So, check if the mounted name is in the string - snprintf(parent, sizeof(parent), "/%s/", entry.mnt_special); // "BOOM" -> "/BOOM/" +/* + * We need to skip the parent name part, in mountpoint "dir" here,ie + * if parent is "BOOM/lower" we need to skip to the 3nd slash + * in "/BOOM/lower/newfs" + * So, check if the mounted name is in the string + */ + // "BOOM" -> "/BOOM/" + snprintf(parent, sizeof (parent), "/%s/", + entry.mnt_special); char *part = strstr(dir, parent); if (part) dir = &part[strlen(parent) - 1]; } - - snprintf(zc.zc_value, sizeof(zc.zc_value), "\\??\\%c:%s", - tolower(driveletter[0]), dir); + + snprintf(zc.zc_value, sizeof (zc.zc_value), "\\??\\%c:%s", + tolower(driveletter[0]), dir); } // Convert Unix slash to Win32 backslash @@ -154,253 +165,90 @@ do_mount(zfs_handle_t *zhp, const char *dir, char *optptr, int mflag) zc.zc_value[i] = '\\'; // "\\??\\c:\\BOOM\\lower" #ifdef DEBUG fprintf(stderr, "zmount(%s,'%s') hasprop %d ispool %d\n", - zhp->zfs_name, zc.zc_value, hasprop, ispool); fflush(stderr); + zhp->zfs_name, zc.zc_value, hasprop, ispool); + fflush(stderr); #endif ret = zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_MOUNT, &zc); if (ret == 0) { // Tell Explorer we have a new drive - // Whats the deal here with this header file - did not like to be included. -//#include + // Whats the deal here with this header file - + // did not like to be included. + // #include struct mnttab entry; // Locate this mount - if (libzfs_mnttab_find(zhp->zfs_hdl, zhp->zfs_name, &entry) == 0) { + if (libzfs_mnttab_find(zhp->zfs_hdl, zhp->zfs_name, + &entry) == 0) { - // If we get a driveletter, we tell Explorer. Otherwise not required. + // If we get a driveletter, we tell Explorer. + // Otherwise not required. if (entry.mnt_mountp[1] == ':') { // "E:\ " -> "E:" entry.mnt_mountp[2] = 0; - SHChangeNotify(SHCNE_DRIVEADD, SHCNF_PATH, entry.mnt_mountp, NULL); + SHChangeNotify(SHCNE_DRIVEADD, SHCNF_PATH, + entry.mnt_mountp, NULL); } } } #ifdef DEBUG fprintf(stderr, "zmount(%s,%s) returns %d\n", - zhp->zfs_name, dir, ret); + zhp->zfs_name, dir, ret); fprintf(stderr, "'%s' mounted on %s\r\n", zc.zc_name, zc.zc_value); #endif - // For BOOM, we get back + // For BOOM, we get back // "\\Device\\Volume{0b1bb601-af0b-32e8-a1d2-54c167af6277}\\" // which is the volume name, and the FS device attached to it is: // "\\\??\\\Volume{7cc383a0-beac-11e7-b56d-02150b22a130}" - // and if change that to "\\\\?\\Volume{7cc383a0-beac-11e7-b56d-02150b22a130}\\"; - // we can use GetVolumePathNamesForVolumeName() to get back "\\DosDevices\\E". + // and if change that to + // "\\\\?\\Volume{7cc383a0-beac-11e7-b56d-02150b22a130}\\"; + // we can use GetVolumePathNamesForVolumeName() + // to get back "\\DosDevices\\E". #if 0 char out[MAXPATHLEN]; DWORD outlen; - //if (QueryDosDevice( + // if (QueryDosDevice( // "G:", // out, MAXPATHLEN) > 0) - // fprintf(stderr, "'%s' mounted on %s\r\n", zc.zc_name, zc.zc_value); - //else + // fprintf(stderr, "'%s' mounted on %s\r\n", zc.zc_name, zc.zc_value); + // else // fprintf(stderr, "QueryDos getlast 0x%x\n", GetLastError()); outlen = 0; - // these give error 0x57 (invalid parameter) - //char *name = "\\\\?\\ZFS{0b1bb601-af0b-32e8-a1d2-54c167af6277}\\"; - //char *name = "\\\\?\\Device\\ZFS{0b1bb601-af0b-32e8-a1d2-54c167af6277}\\"; - //char *name = "\\\\?\\Device\\Volume{0b1bb601-af0b-32e8-a1d2-54c167af6277}\\"; - //char *name = "\\\\?\\DosDevices\\Global\\Volume{0b1bb601-af0b-32e8-a1d2-54c167af6277}\\"; - // this gives error 0x1 ERROR_INVALID_FUNCTION - //char *name = "\\\\?\\Volume{0b1bb601-af0b-32e8-a1d2-54c167af6277}\\"; - - //char *name = "\\\\?\\Volume{0b1bb601-af0b-32e8-a1d2-54c167af6277}\\"; char *name = zc.zc_value; - // Kernel returns "\\Device\\Volume{0b1bb601-af0b-32e8-a1d2-54c167af6277}\\" + // Kernel returns + // "\\Device\\Volume{0b1bb601-af0b-32e8-a1d2-54c167af6277}\\" if (strncmp(name, "\\Device\\Volume{", 15) == 0) { - strlcpy(&name[0], "\\\\?\\", sizeof(zc.zc_value)); - strlcpy(&name[4], &name[8], sizeof(zc.zc_value)); - strlcat(name, "\\", sizeof(zc.zc_value)); + strlcpy(&name[0], "\\\\?\\", sizeof (zc.zc_value)); + strlcpy(&name[4], &name[8], sizeof (zc.zc_value)); + strlcat(name, "\\", sizeof (zc.zc_value)); } fprintf(stderr, "Looking up '%s'\r\n", name); ret = GetVolumePathNamesForVolumeName(name, out, MAXPATHLEN, &outlen); if (ret != 1) - fprintf(stderr, "GetVolumePathNamesForVolumeName ret %d outlen %d GetLastError 0x%x\n", ret, outlen, GetLastError()); + fprintf(stderr, + "GetVolumePathNamesForVolumeName ret %d out %d Err 0x%x\n", + ret, outlen, GetLastError()); if (outlen > 0 && ret > 0) { char *NameIdx; fprintf(stderr, "%s: ", zc.zc_name); for (NameIdx = out; - NameIdx[0] != '\0'; - NameIdx += strlen(NameIdx) + 1) - { + NameIdx[0] != '\0'; + NameIdx += strlen(NameIdx) + 1) { fprintf(stderr, " %s", NameIdx); } fprintf(stderr, "\r\n"); } #endif -#if 0 - fprintf(stderr, "Trying mountmgr\r\n"); -#define MOUNTMGR_DOS_DEVICE_NAME L"\\\\.\\MountPointManager" - typedef struct _MOUNTMGR_MOUNT_POINT { - ULONG SymbolicLinkNameOffset; - USHORT SymbolicLinkNameLength; - ULONG UniqueIdOffset; - USHORT UniqueIdLength; - ULONG DeviceNameOffset; - USHORT DeviceNameLength; - } MOUNTMGR_MOUNT_POINT, *PMOUNTMGR_MOUNT_POINT; -#define MOUNTMGRCONTROLTYPE ((ULONG) 'm') -#define IOCTL_MOUNTMGR_QUERY_POINTS CTL_CODE(MOUNTMGRCONTROLTYPE, 2, METHOD_BUFFERED, FILE_ANY_ACCESS) - - HANDLE mgr = CreateFileW(MOUNTMGR_DOS_DEVICE_NAME, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, - NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, INVALID_HANDLE_VALUE); - if (mgr == INVALID_HANDLE_VALUE) return ret; - - MOUNTMGR_MOUNT_POINT input = { 0 }; - outlen = 0; - fprintf(stderr, "sending\r\n"); - if (DeviceIoControl(mgr, IOCTL_MOUNTMGR_QUERY_POINTS, &input, sizeof(input), - out, MAXPATHLEN, &outlen, NULL) != 0) { - fprintf(stderr, "mountmgr returned success %d\r\n", outlen); - } - fprintf(stderr, "return outlen %d: GetLastError %d\r\n", outlen, GetLastError()); - CloseHandle(mgr); -#endif - -#if 0 - typedef struct _REPARSE_DATA_BUFFER { - /** - * Reparse point tag. Must be a Microsoft reparse point tag. - */ - ULONG ReparseTag; - /** - * Size, in bytes, of the reparse data in the DataBuffer member. - */ - USHORT ReparseDataLength; - /** - * Length, in bytes, of the unparsed portion of the file name pointed - * to by the FileName member of the associated file object. - */ - USHORT Reserved; - union { - struct { - /** Offset, in bytes, of the substitute name string in the PathBuffer array. */ - USHORT SubstituteNameOffset; - /** Length, in bytes, of the substitute name string. */ - USHORT SubstituteNameLength; - /** Offset, in bytes, of the print name string in the PathBuffer array. */ - USHORT PrintNameOffset; - /** Length, in bytes, of the print name string. */ - USHORT PrintNameLength; - /** Used to indicate if the given symbolic link is an absolute or relative symbolic link. */ - ULONG Flags; - /** First character of the path string. This is followed in memory by the remainder of the string. */ - WCHAR PathBuffer[1]; - } SymbolicLinkReparseBuffer; - struct { - /** Offset, in bytes, of the substitute name string in the PathBuffer array. */ - USHORT SubstituteNameOffset; - /** Length, in bytes, of the substitute name string. */ - USHORT SubstituteNameLength; - /** Offset, in bytes, of the print name string in the PathBuffer array. */ - USHORT PrintNameOffset; - /** Length, in bytes, of the print name string. */ - USHORT PrintNameLength; - /** First character of the path string. */ - WCHAR PathBuffer[1]; - } MountPointReparseBuffer; - struct { - /** Microsoft-defined data for the reparse point. */ - UCHAR DataBuffer[1]; - } GenericReparseBuffer; - } DUMMYUNIONNAME; - } REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER; -#pragma warning(pop) -#define REPARSE_DATA_BUFFER_HEADER_SIZE \ -FIELD_OFFSET(REPARSE_DATA_BUFFER, GenericReparseBuffer) - - PREPARSE_DATA_BUFFER reparseData; - USHORT bufferLength; - USHORT targetLength; - BOOL result; - ULONG resultLength; - WCHAR targetDeviceName[MAX_PATH]; - - fprintf(stderr, "making a reparse point\r\n"); - HANDLE handle; - handle = CreateFile(L"\\DosDevices\\C:\\BOOM", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, - FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, - NULL); - if (handle == INVALID_HANDLE_VALUE) { - fprintf(stderr, "failed %u 0x%x\r\n", GetLastError(), GetLastError()); - } - else { - fprintf(stderr, "reparse point ok\r\n"); - } - - ZeroMemory(targetDeviceName, sizeof(targetDeviceName)); - wcscat_s(targetDeviceName, MAX_PATH, L"\\??\\Volume{7cc383a0-beac-11e7-b56d-02150b22a130}"); - - targetLength = (USHORT)wcslen(targetDeviceName) * sizeof(WCHAR); - bufferLength = - FIELD_OFFSET(REPARSE_DATA_BUFFER, MountPointReparseBuffer.PathBuffer) + - targetLength + sizeof(WCHAR) + sizeof(WCHAR); - - reparseData = (PREPARSE_DATA_BUFFER)malloc(bufferLength); - if (reparseData == NULL) { - CloseHandle(handle); - return FALSE; - } - - ZeroMemory(reparseData, bufferLength); - - reparseData->ReparseTag = IO_REPARSE_TAG_MOUNT_POINT; - reparseData->ReparseDataLength = - bufferLength - REPARSE_DATA_BUFFER_HEADER_SIZE; - - reparseData->MountPointReparseBuffer.SubstituteNameOffset = 0; - reparseData->MountPointReparseBuffer.SubstituteNameLength = targetLength; - reparseData->MountPointReparseBuffer.PrintNameOffset = - targetLength + sizeof(WCHAR); - reparseData->MountPointReparseBuffer.PrintNameLength = 0; - - RtlCopyMemory(reparseData->MountPointReparseBuffer.PathBuffer, - targetDeviceName, targetLength); - - result = DeviceIoControl(handle, FSCTL_SET_REPARSE_POINT, reparseData, - bufferLength, NULL, 0, &resultLength, NULL); - - CloseHandle(handle); - free(reparseData); - - if (result) { - fprintf(stderr, "CreateMountPoint -> %S success\n", - targetDeviceName); - } - else { - WCHAR errorMsg[256]; - FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), errorMsg, 256, - NULL); - fprintf(stderr, "CreateMountPoint -> %S failed: (%d) %S", - targetDeviceName, GetLastError(), errorMsg); - } - - - - - - fprintf(stderr, "trying to set the mountpoint\r\n"); - - ret = SetVolumeMountPoint( - L"C:\\BOOM\\", - L"\\\\?\\Volume{7cc383a0-beac-11e7-b56d-02150b22a130}\\" // This string must be of the form "\\?\Volume{GUID}\" - ); - - fprintf(stderr, "trying to set the mountpoint: %d %d\r\n", ret, GetLastError()); - -#endif - - return ret; + return (ret); } @@ -411,47 +259,56 @@ do_unmount_impl(zfs_handle_t *zhp, const char *mntpt, int flags) // mount 'spec' "tank/joe" on path 'dir' "/home/joe". fprintf(stderr, "zunmount(%s,%s) running\r\n", - zhp->zfs_name, mntpt); fflush(stderr); + zhp->zfs_name, mntpt); + fflush(stderr); zfs_cmd_t zc = { "\0" }; - (void)strlcpy(zc.zc_name, zhp->zfs_name, sizeof(zc.zc_name)); - (void)strlcpy(zc.zc_value, mntpt, sizeof(zc.zc_value)); + (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name)); + (void) strlcpy(zc.zc_value, mntpt, sizeof (zc.zc_value)); ret = zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_UNMOUNT, &zc); if (!ret) { - // if mountpoint is a folder, we need to turn it back from JUNCTION - // to a real folder + // if mountpoint is a folder, we need to turn it back + // from JUNCTION to a real folder char mtpt_prop[ZFS_MAXPROPLEN]; char driveletter[MAX_PATH]; verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mtpt_prop, - sizeof(mtpt_prop), NULL, NULL, 0, B_FALSE) == 0); + sizeof (mtpt_prop), NULL, NULL, 0, B_FALSE) == 0); verify(zfs_prop_get(zhp, ZFS_PROP_DRIVELETTER, driveletter, - sizeof(driveletter), NULL, NULL, 0, B_FALSE) == 0); - // if mountpoint starts with '/' we assume that it is a path to a directory - // make sure we didn't mount as driveletter - if (mtpt_prop && mtpt_prop[0] == '/' && - (strstr(driveletter, "-") != 0 || strstr(driveletter, "off") != 0) && - (mntpt && strstr(mntpt, ":\\") == 0)) { - fprintf(stderr, "recreate mountpoint %s\n", mtpt_prop); fflush(stderr); + sizeof (driveletter), NULL, NULL, 0, B_FALSE) == 0); + // if mountpoint starts with '/' we assume that it is a path + // to a directory make sure we didn't mount as driveletter + if (mtpt_prop && mtpt_prop[0] == '/' && + (strstr(driveletter, "-") != 0 || + strstr(driveletter, "off") != 0) && + (mntpt && strstr(mntpt, ":\\") == 0)) { + fprintf(stderr, "recreate mountpoint %s\n", mtpt_prop); + fflush(stderr); BOOL val = RemoveDirectoryA(mtpt_prop); if (!val) { if (GetLastError() != ERROR_FILE_NOT_FOUND) - fprintf(stderr, "RemoveDirectoryA returns false, last error %lu\n", GetLastError()); fflush(stderr); + fprintf(stderr, + "RemoveDirectoryA false, err %lu\n", + GetLastError()); + fflush(stderr); } else { val = CreateDirectoryA(mtpt_prop, NULL); - if (!val) - fprintf(stderr, "CreateDirectoryA returns false, last error %lu\n", GetLastError()); fflush(stderr); + if (!val) + fprintf(stderr, + "CreateDirectoryA false, err %lu\n", + GetLastError()); + fflush(stderr); } - + } - + } fprintf(stderr, "zunmount(%s,%s) returns %d\n", - zhp->zfs_name, mntpt, ret); + zhp->zfs_name, mntpt, ret); - return ret; + return (ret); } @@ -483,7 +340,8 @@ unmount_snapshots(zfs_handle_t *zhp, const char *mntpt, int flags) if (strncmp("/.zfs/snapshot/", &entry.mnt_mountp[len], 15) == 0) { /* Unmount it */ - do_unmount_impl(zhp, entry.mnt_mountp, MS_FORCE); + do_unmount_impl(zhp, entry.mnt_mountp, + MS_FORCE); } } } diff --git a/lib/libzfs/os/windows/libzfs_util_os.c b/lib/libzfs/os/windows/libzfs_util_os.c index a91231ef68c..eeaea6469c3 100644 --- a/lib/libzfs/os/windows/libzfs_util_os.c +++ b/lib/libzfs/os/windows/libzfs_util_os.c @@ -124,7 +124,8 @@ int zfs_version_kernel(char *version, int len) { HKEY hKey; // SYSTEM\ControlSet001\Services\ZFSin - LSTATUS status = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "SYSTEM\\ControlSet001\\Services\\ZFSin", 0, KEY_READ, &hKey); + LSTATUS status = RegOpenKeyExA(HKEY_LOCAL_MACHINE, + "SYSTEM\\ControlSet001\\Services\\ZFSin", 0, KEY_READ, &hKey); if (status != ERROR_SUCCESS) return (-1); @@ -277,8 +278,8 @@ libzfs_set_pipe_max(int infd) } int -libzfs_run_process_impl(const char* path, char* argv[], char* env[], int flags, - char** lines[], int* lines_cnt) +libzfs_run_process_impl(const char *path, char *argv[], char *env[], + int flags, char **lines[], int *lines_cnt) { return (0); } diff --git a/lib/libzpool/kernel.c b/lib/libzpool/kernel.c index 95c01344261..9360fb3b98a 100644 --- a/lib/libzpool/kernel.c +++ b/lib/libzpool/kernel.c @@ -723,17 +723,17 @@ random_fini(void) #ifdef _WIN32 static int -random_get_bytes_common(uint8_t* ptr, size_t len, int fd) +random_get_bytes_common(uint8_t *ptr, size_t len, int fd) { size_t resid = len; ssize_t bytes; - unsigned int number; + unsigned int number; while (resid != 0) { rand_s(&number); bytes = MIN(resid, sizeof (number)); memcpy(ptr, &number, bytes); - ASSERT3S(bytes, >= , 0); + ASSERT3S(bytes, >=, 0); ptr += bytes; resid -= bytes; } diff --git a/lib/libzutil/os/windows/zutil_compat.c b/lib/libzutil/os/windows/zutil_compat.c index e31431f8534..7615a896bc1 100644 --- a/lib/libzutil/os/windows/zutil_compat.c +++ b/lib/libzutil/os/windows/zutil_compat.c @@ -37,30 +37,30 @@ zcmd_ioctl_compat(int fd, int request, zfs_cmd_t *zc, const int cflag) switch (cflag) { case ZFS_CMD_COMPAT_NONE: - ncmd = CTL_CODE(ZFSIOCTL_TYPE, ZFSIOCTL_BASE + request, METHOD_NEITHER, FILE_ANY_ACCESS); + ncmd = CTL_CODE(ZFSIOCTL_TYPE, ZFSIOCTL_BASE + request, + METHOD_NEITHER, FILE_ANY_ACCESS); - zip = malloc(sizeof(zfs_iocparm_t)); + zip = malloc(sizeof (zfs_iocparm_t)); zip->zfs_cmd = (uint64_t)zc; zip->zfs_cmd_size = sizeof (zfs_cmd_t); zip->zfs_ioctl_version = ZFS_IOCVER_ZOF; zip->zfs_ioc_error = 0; - bytesReturned = sizeof(zfs_iocparm_t); + bytesReturned = sizeof (zfs_iocparm_t); // ret = ioctl(fd, ncmd, &zp); ret = DeviceIoControl(ITOH(fd), (DWORD)ncmd, zip, - (DWORD)sizeof(zfs_iocparm_t), + (DWORD)sizeof (zfs_iocparm_t), zc, - (DWORD)sizeof(zfs_cmd_t), + (DWORD)sizeof (zfs_cmd_t), &bytesReturned, - NULL - ); + NULL); if (ret == 0) - ret = GetLastError(); + ret = GetLastError(); else - ret = 0; + ret = 0; /* diff --git a/lib/libzutil/os/windows/zutil_device_path_os.c b/lib/libzutil/os/windows/zutil_device_path_os.c index e6dcec66ee7..e8252695477 100644 --- a/lib/libzutil/os/windows/zutil_device_path_os.c +++ b/lib/libzutil/os/windows/zutil_device_path_os.c @@ -81,15 +81,19 @@ zfs_append_partition(char *path, size_t max_len) if ((efi_alloc_and_read(fd, &vtoc)) == 0) { for (int i = 0; i < vtoc->efi_nparts; i++) { - if (vtoc->efi_parts[i].p_start == 0 && + if (vtoc->efi_parts[i].p_start == 0 && vtoc->efi_parts[i].p_size == 0) continue; if (tolower(vtoc->efi_parts[i].p_name[0]) == 'z' && tolower(vtoc->efi_parts[i].p_name[1]) == 'f' && tolower(vtoc->efi_parts[i].p_name[2]) == 's') { - size_t length = vtoc->efi_parts[i].p_size * vtoc->efi_lbasize; - off_t offset = vtoc->efi_parts[i].p_start * vtoc->efi_lbasize; + size_t length = + vtoc->efi_parts[i].p_size * + vtoc->efi_lbasize; + off_t offset = + vtoc->efi_parts[i].p_start * + vtoc->efi_lbasize; char *copypath = strdup(path); snprintf(path, max_len, "#%llu#%llu#%s", offset, length, copypath); @@ -100,9 +104,11 @@ zfs_append_partition(char *path, size_t max_len) } } else { - // If we can't read the partition, we are most likely creating a pool, - // and it will be slice 1, alas, we do not know the size/offset here, yet. - // which is why we call this function again after zpool_label_disk. + // If we can't read the partition, we are most likely + // creating a pool, and it will be slice 1, alas, we + // do not know the size/offset here, yet. + // which is why we call this function again after + // zpool_label_disk. } close(fd); return (len); @@ -122,7 +128,7 @@ zfs_strip_path(char *path) return (&r[1]); r = strrchr(path, '\\'); if (r != NULL) - return (&r[1]); + return (&r[1]); return (path); } @@ -198,7 +204,8 @@ zpool_label_disk_wait(const char *path, int timeout_ms) boolean_t is_mpath_whole_disk(const char *path) { - // Return TRUE here to have make_disks() call update_vdev_config_dev_strs() + // Return TRUE here to have make_disks() call + // update_vdev_config_dev_strs() return (B_TRUE); } diff --git a/lib/libzutil/os/windows/zutil_import_os.c b/lib/libzutil/os/windows/zutil_import_os.c index 119a5d1be9b..e6e79eabc3d 100644 --- a/lib/libzutil/os/windows/zutil_import_os.c +++ b/lib/libzutil/os/windows/zutil_import_os.c @@ -76,11 +76,11 @@ #include #endif -#define _WIN32_MEAN_AND_LEAN +#define _WIN32_MEAN_AND_LEAN #include #include #include -#pragma comment( lib, "setupapi.lib" ) +#pragma comment(lib, "setupapi.lib") /* * We allow /dev/ to be search in DEBUG build @@ -284,7 +284,8 @@ label_offset(uint64_t size, int l) } static int -zpool_read_label_win(HANDLE h, off_t offset, uint64_t len, nvlist_t **config, int *num_labels) +zpool_read_label_win(HANDLE h, off_t offset, uint64_t len, + nvlist_t **config, int *num_labels) { int l, count = 0; vdev_label_t *label; @@ -296,37 +297,37 @@ zpool_read_label_win(HANDLE h, off_t offset, uint64_t len, nvlist_t **config, in *config = NULL; drivesize = len; - size = P2ALIGN_TYPED(drivesize, sizeof(vdev_label_t), uint64_t); + size = P2ALIGN_TYPED(drivesize, sizeof (vdev_label_t), uint64_t); - if ((label = malloc(sizeof(vdev_label_t))) == NULL) + if ((label = malloc(sizeof (vdev_label_t))) == NULL) return (-1); for (l = 0; l < VDEV_LABELS; l++) { uint64_t state, guid, txg; - if (pread_win(h, label, sizeof(vdev_label_t), - label_offset(size, l) + offset) != sizeof(vdev_label_t)) + if (pread_win(h, label, sizeof (vdev_label_t), + label_offset(size, l) + offset) != sizeof (vdev_label_t)) continue; if (nvlist_unpack(label->vl_vdev_phys.vp_nvlist, - sizeof(label->vl_vdev_phys.vp_nvlist), config, 0) != 0) + sizeof (label->vl_vdev_phys.vp_nvlist), config, 0) != 0) continue; if (nvlist_lookup_uint64(*config, ZPOOL_CONFIG_GUID, - &guid) != 0 || guid == 0) { + &guid) != 0 || guid == 0) { nvlist_free(*config); continue; } if (nvlist_lookup_uint64(*config, ZPOOL_CONFIG_POOL_STATE, - &state) != 0 || state > POOL_STATE_L2CACHE) { + &state) != 0 || state > POOL_STATE_L2CACHE) { nvlist_free(*config); continue; } if (state != POOL_STATE_SPARE && state != POOL_STATE_L2CACHE && - (nvlist_lookup_uint64(*config, ZPOOL_CONFIG_POOL_TXG, - &txg) != 0 || txg == 0)) { + (nvlist_lookup_uint64(*config, ZPOOL_CONFIG_POOL_TXG, + &txg) != 0 || txg == 0)) { nvlist_free(*config); continue; } @@ -336,8 +337,7 @@ zpool_read_label_win(HANDLE h, off_t offset, uint64_t len, nvlist_t **config, in count++; nvlist_free(*config); - } - else { + } else { expected_config = *config; expected_guid = guid; count++; @@ -360,7 +360,7 @@ static void zfs_backslashes(char *s) { char *r; - while((r = strchr(s, '/')) != NULL) + while ((r = strchr(s, '/')) != NULL) *r = '\\'; } @@ -390,35 +390,35 @@ zpool_open_func(void *arg) len = strtoull(end, &end, 10); while (end && *end == '#') end++; fd = CreateFile(end, - GENERIC_READ, - FILE_SHARE_READ /*| FILE_SHARE_WRITE*/, - NULL, - OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL /*| FILE_FLAG_OVERLAPPED*/, - NULL); + GENERIC_READ, + FILE_SHARE_READ /* | FILE_SHARE_WRITE */, + NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL /* | FILE_FLAG_OVERLAPPED */, + NULL); if (fd == INVALID_HANDLE_VALUE) { int error = GetLastError(); return; } LARGE_INTEGER place; place.QuadPart = offset; - SetFilePointerEx(fd, place, NULL, FILE_BEGIN); // If it fails, we cant read label + // If it fails, we cant read label + SetFilePointerEx(fd, place, NULL, FILE_BEGIN); drive_len = len; - } else { // We have no openat() - so stitch paths togther. // char fullpath[MAX_PATH]; - // snprintf(fullpath, sizeof(fullpath), "%s%s", + // snprintf(fullpath, sizeof (fullpath), "%s%s", // "", rn->rn_name); zfs_backslashes(rn->rn_name); fd = CreateFile(rn->rn_name, - GENERIC_READ, - FILE_SHARE_READ /*| FILE_SHARE_WRITE*/, - NULL, - OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL /*| FILE_FLAG_OVERLAPPED*/, - NULL); + GENERIC_READ, + FILE_SHARE_READ /* | FILE_SHARE_WRITE */, + NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL /* | FILE_FLAG_OVERLAPPED */, + NULL); if (fd == INVALID_HANDLE_VALUE) { int error = GetLastError(); return; @@ -428,29 +428,25 @@ zpool_open_func(void *arg) } DWORD type = GetFileType(fd); - //fprintf(stderr, "device '%s' filetype %d 0x%x\n", rn->rn_name, type, type); - - // type = GetDriveType(rn->rn_name); - //fprintf(stderr, "device '%s' filetype %d 0x%x\n", rn->rn_name, type, type); - /* this file is too small to hold a zpool */ if (type == FILE_TYPE_DISK && - drive_len < SPA_MINDEVSIZE) { + drive_len < SPA_MINDEVSIZE) { CloseHandle(fd); return; } // else if (type != FILE_TYPE_DISK) { /* - * Try to read the disk label first so we don't have to - * open a bunch of minor nodes that can't have a zpool. - */ + * Try to read the disk label first so we don't have to + * open a bunch of minor nodes that can't have a zpool. + */ // check_slices(rn->rn_avl, HTOI(fd), rn->rn_name); // } - if ((zpool_read_label_win(fd, offset, drive_len, &config, &num_labels)) != 0) { + if ((zpool_read_label_win(fd, offset, drive_len, &config, + &num_labels)) != 0) { CloseHandle(fd); - (void)no_memory(rn->rn_hdl); + (void) no_memory(rn->rn_hdl); return; } @@ -666,7 +662,7 @@ zpool_find_import_blkidXXX(libpc_handle_t *hdl, pthread_mutex_t *lock, /* * Call Windows API to get list of physical disks, and iterate through them * finding partitions. -*/ + */ int zpool_find_import_blkid(libpc_handle_t *hdl, pthread_mutex_t *lock, avl_tree_t **slice_cache) @@ -688,7 +684,7 @@ zpool_find_import_blkid(libpc_handle_t *hdl, pthread_mutex_t *lock, PSP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData; DWORD requiredSize; DWORD deviceIndex; - + HANDLE disk = INVALID_HANDLE_VALUE; STORAGE_DEVICE_NUMBER diskNumber; DWORD bytesReturned; @@ -703,81 +699,88 @@ zpool_find_import_blkid(libpc_handle_t *hdl, pthread_mutex_t *lock, sizeof (rdsk_node_t), offsetof(rdsk_node_t, rn_node)); - + /* First, open all raw physical devices */ - + diskClassDevices = SetupDiGetClassDevs(&diskClassDeviceInterfaceGuid, - NULL, - NULL, - DIGCF_PRESENT | - DIGCF_DEVICEINTERFACE); - //CHK(INVALID_HANDLE_VALUE != diskClassDevices, + NULL, + NULL, + DIGCF_PRESENT | + DIGCF_DEVICEINTERFACE); + // CHK(INVALID_HANDLE_VALUE != diskClassDevices, // "SetupDiGetClassDevs"); - ZeroMemory(&deviceInterfaceData, sizeof(SP_DEVICE_INTERFACE_DATA)); - deviceInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA); + ZeroMemory(&deviceInterfaceData, sizeof (SP_DEVICE_INTERFACE_DATA)); + deviceInterfaceData.cbSize = sizeof (SP_DEVICE_INTERFACE_DATA); deviceIndex = 0; while (SetupDiEnumDeviceInterfaces(diskClassDevices, - NULL, - &diskClassDeviceInterfaceGuid, - deviceIndex, - &deviceInterfaceData)) { + NULL, + &diskClassDeviceInterfaceGuid, + deviceIndex, + &deviceInterfaceData)) { ++deviceIndex; SetupDiGetDeviceInterfaceDetail(diskClassDevices, - &deviceInterfaceData, - NULL, - 0, - &requiredSize, - NULL); - //CHK(ERROR_INSUFFICIENT_BUFFER == GetLastError(), + &deviceInterfaceData, + NULL, + 0, + &requiredSize, + NULL); + // CHK(ERROR_INSUFFICIENT_BUFFER == GetLastError(), // "SetupDiGetDeviceInterfaceDetail - 1"); - deviceInterfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)malloc(requiredSize); - //CHK(NULL != deviceInterfaceDetailData, + deviceInterfaceDetailData = + (PSP_DEVICE_INTERFACE_DETAIL_DATA)malloc(requiredSize); + // CHK(NULL != deviceInterfaceDetailData, // "malloc"); ZeroMemory(deviceInterfaceDetailData, requiredSize); - deviceInterfaceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA); + deviceInterfaceDetailData->cbSize = + sizeof (SP_DEVICE_INTERFACE_DETAIL_DATA); SetupDiGetDeviceInterfaceDetail(diskClassDevices, - &deviceInterfaceData, - deviceInterfaceDetailData, - requiredSize, - NULL, - NULL); + &deviceInterfaceData, + deviceInterfaceDetailData, + requiredSize, + NULL, + NULL); // Here, the device path is something like - // " \\?\ide#diskvmware_virtual_ide_hard_drive___________00000001#5&1778b74b&0&0.0.0#{53f56307-b6bf-11d0-94f2-00a0c91efb8b}" + // " \\?\ide#diskvmware_virtual_ide_hard_drive___________" + // "00000001#5&1778b74b&0&0.0.0#{53f56307-b6bf-11d0-" + // "94f2-00a0c91efb8b}" // and we create a path like // "\\?\PhysicalDrive0" // but perhaps it is better to use the full name of the device. disk = CreateFile(deviceInterfaceDetailData->DevicePath, - 0/*GENERIC_READ*/, - FILE_SHARE_READ /*| FILE_SHARE_WRITE*/, - NULL, - OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL /*| FILE_FLAG_OVERLAPPED*/, - NULL); + 0 /* GENERIC_READ */, + FILE_SHARE_READ /* | FILE_SHARE_WRITE */, + NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL /* | FILE_FLAG_OVERLAPPED */, + NULL); if (disk == INVALID_HANDLE_VALUE) continue; DeviceIoControl(disk, - IOCTL_STORAGE_GET_DEVICE_NUMBER, - NULL, - 0, - &diskNumber, - sizeof(STORAGE_DEVICE_NUMBER), - &bytesReturned, - NULL); - - fprintf(stderr, "path '%s'\n and '\\\\?\\PhysicalDrive%d'\n", deviceInterfaceDetailData->DevicePath, - diskNumber.DeviceNumber); fflush(stderr); - snprintf(rdsk, MAXPATHLEN, "\\\\.\\PHYSICALDRIVE%d", diskNumber.DeviceNumber); - - //CloseHandle(disk); + IOCTL_STORAGE_GET_DEVICE_NUMBER, + NULL, + 0, + &diskNumber, + sizeof (STORAGE_DEVICE_NUMBER), + &bytesReturned, + NULL); + + fprintf(stderr, "path '%s'\n and '\\\\?\\PhysicalDrive%d'\n", + deviceInterfaceDetailData->DevicePath, + diskNumber.DeviceNumber); + fflush(stderr); + snprintf(rdsk, MAXPATHLEN, "\\\\.\\PHYSICALDRIVE%d", + diskNumber.DeviceNumber); + + // CloseHandle(disk); #if 0 // This debug code was here to skip the boot disk, @@ -789,66 +792,84 @@ zpool_find_import_blkid(libpc_handle_t *hdl, pthread_mutex_t *lock, #endif DWORD ior; PDRIVE_LAYOUT_INFORMATION_EX partitions; - DWORD partitionsSize = sizeof(DRIVE_LAYOUT_INFORMATION_EX) + 127 * sizeof(PARTITION_INFORMATION_EX); - partitions = (PDRIVE_LAYOUT_INFORMATION_EX)malloc(partitionsSize); - if (DeviceIoControl(disk, IOCTL_DISK_GET_DRIVE_LAYOUT_EX, NULL, 0, partitions, partitionsSize, &ior, NULL)) { - fprintf(stderr, "read partitions ok %d\n", partitions->PartitionCount); fflush(stderr); + DWORD partitionsSize = sizeof (DRIVE_LAYOUT_INFORMATION_EX) + + 127 * sizeof (PARTITION_INFORMATION_EX); + partitions = + (PDRIVE_LAYOUT_INFORMATION_EX)malloc(partitionsSize); + if (DeviceIoControl(disk, IOCTL_DISK_GET_DRIVE_LAYOUT_EX, + NULL, 0, partitions, partitionsSize, &ior, NULL)) { + fprintf(stderr, "read partitions ok %d\n", + partitions->PartitionCount); + fflush(stderr); for (int i = 0; i < partitions->PartitionCount; i++) { int add = 0; - switch (partitions->PartitionEntry[i].PartitionStyle) { - case PARTITION_STYLE_MBR: - fprintf(stderr, " mbr %d: type %x off 0x%llx len 0x%llx\n", i, - partitions->PartitionEntry[i].Mbr.PartitionType, - partitions->PartitionEntry[i].StartingOffset.QuadPart, - partitions->PartitionEntry[i].PartitionLength.QuadPart); fflush(stderr); - add = 1; - break; - case PARTITION_STYLE_GPT: - fprintf(stderr, " gpt %d: type %x off 0x%llx len 0x%llx\n", i, - partitions->PartitionEntry[i].Gpt.PartitionType, - partitions->PartitionEntry[i].StartingOffset.QuadPart, - partitions->PartitionEntry[i].PartitionLength.QuadPart); fflush(stderr); - add = 1; - break; - } + switch (partitions->PartitionEntry[i].PartitionStyle) { + case PARTITION_STYLE_MBR: + fprintf(stderr, + " mbr %d: type %x off 0x%llx len 0x%llx\n", i, + partitions->PartitionEntry[i].Mbr.PartitionType, + partitions->PartitionEntry[i]. + StartingOffset.QuadPart, + partitions->PartitionEntry[i]. + PartitionLength.QuadPart); + fflush(stderr); + add = 1; + break; + case PARTITION_STYLE_GPT: + fprintf(stderr, + " gpt %d: type %x off 0x%llx len 0x%llx\n", i, + partitions->PartitionEntry[i].Gpt.PartitionType, + partitions->PartitionEntry[i]. + StartingOffset.QuadPart, + partitions->PartitionEntry[i].PartitionLength. + QuadPart); + fflush(stderr); + add = 1; + break; + } - if (add && partitions->PartitionEntry[i].PartitionLength.QuadPart > SPA_MINDEVSIZE) { - slice = zutil_alloc(hdl, sizeof(rdsk_node_t)); - - error = asprintf(&slice->rn_name, "\\\\?\\Harddisk%uPartition%u", - diskNumber.DeviceNumber, i); - if (error == -1) { - free(slice); - continue; - } - - slice->rn_vdev_guid = 0; - slice->rn_lock = lock; - slice->rn_avl = *slice_cache; - slice->rn_hdl = hdl; - slice->rn_labelpaths = B_FALSE; - slice->rn_order = IMPORT_ORDER_PREFERRED_2; - - pthread_mutex_lock(lock); - if (avl_find(*slice_cache, slice, &where)) { - free(slice->rn_name); - free(slice); - } else { - avl_insert(*slice_cache, slice, where); - } - pthread_mutex_unlock(lock); - } + if (add && + partitions->PartitionEntry[i].PartitionLength. + QuadPart > SPA_MINDEVSIZE) { + slice = zutil_alloc(hdl, sizeof (rdsk_node_t)); + error = asprintf(&slice->rn_name, + "\\\\?\\Harddisk%uPartition%u", + diskNumber.DeviceNumber, i); + if (error == -1) { + free(slice); + continue; + } + + slice->rn_vdev_guid = 0; + slice->rn_lock = lock; + slice->rn_avl = *slice_cache; + slice->rn_hdl = hdl; + slice->rn_labelpaths = B_FALSE; + slice->rn_order = IMPORT_ORDER_PREFERRED_2; + + pthread_mutex_lock(lock); + if (avl_find(*slice_cache, slice, &where)) { + free(slice->rn_name); + free(slice); + } else { + avl_insert(*slice_cache, slice, where); } - // in case we have a disk without partition, it would be possible that the + pthread_mutex_unlock(lock); + } + } + // in case we have a disk without partition, + // it would be possible that the // disk itself contains a pool, so let's check that if (partitions->PartitionCount == 0) { slice = zutil_alloc(hdl, sizeof (rdsk_node_t)); - error = asprintf(&slice->rn_name, "#%llu#%llu#%s", - 0ULL, GetFileDriveSize(disk), deviceInterfaceDetailData->DevicePath); + error = asprintf(&slice->rn_name, + "#%llu#%llu#%s", + 0ULL, GetFileDriveSize(disk), + deviceInterfaceDetailData->DevicePath); if (error == -1) { free(slice); continue; @@ -859,7 +880,8 @@ zpool_find_import_blkid(libpc_handle_t *hdl, pthread_mutex_t *lock, slice->rn_avl = *slice_cache; slice->rn_hdl = hdl; slice->rn_labelpaths = B_FALSE; - slice->rn_order = IMPORT_ORDER_SCAN_OFFSET + deviceIndex; + slice->rn_order = + IMPORT_ORDER_SCAN_OFFSET + deviceIndex; pthread_mutex_lock(lock); if (avl_find(*slice_cache, slice, &where)) { @@ -873,76 +895,95 @@ zpool_find_import_blkid(libpc_handle_t *hdl, pthread_mutex_t *lock, free(partitions); } else { - fprintf(stderr, "read partitions ng\n"); fflush(stderr); + fprintf(stderr, "read partitions ng\n"); + fflush(stderr); } CloseHandle(disk); #if 1 // efi - // Add the whole physical device, but lets also try to read EFI off it. + // Add the whole physical device, but lets also try + // to read EFI off it. disk = CreateFile(deviceInterfaceDetailData->DevicePath, - GENERIC_READ, - FILE_SHARE_READ /*| FILE_SHARE_WRITE*/, - NULL, - OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL /*| FILE_FLAG_OVERLAPPED*/, - NULL); + GENERIC_READ, + FILE_SHARE_READ /* | FILE_SHARE_WRITE */, + NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL /* | FILE_FLAG_OVERLAPPED */, + NULL); // On standard OsX created zpool, we expect: - // offset name - // 0x200 MBR partition protective GPT - // 0x400 EFI partition, s0 as ZFS - // 0x8410 "version" "name" "testpool" ZFS label + // offset name + // 0x200 MBR partition protective GPT + // 0x400 EFI partition, s0 as ZFS + // 0x8410 "version" "name" "testpool" ZFS label if (disk != INVALID_HANDLE_VALUE) { - fprintf(stderr, "asking libefi to read label\n"); fflush(stderr); + fprintf(stderr, "asking libefi to read label\n"); + fflush(stderr); int error; struct dk_gpt *vtoc; error = efi_alloc_and_read(disk, &vtoc); if (error >= 0) { - fprintf(stderr, "EFI read OK, max partitions %d\n", vtoc->efi_nparts); fflush(stderr); + fprintf(stderr, + "EFI read OK, max partitions %d\n", + vtoc->efi_nparts); + fflush(stderr); for (int i = 0; i < vtoc->efi_nparts; i++) { if (vtoc->efi_parts[i].p_start == 0 && - vtoc->efi_parts[i].p_size == 0) continue; + vtoc->efi_parts[i].p_size == 0) + continue; - fprintf(stderr, " part %d: offset %llx: len %llx: tag: %x name: '%s'\n", i, vtoc->efi_parts[i].p_start, vtoc->efi_parts[i].p_size, - vtoc->efi_parts[i].p_tag, vtoc->efi_parts[i].p_name); fflush(stderr); - if (vtoc->efi_parts[i].p_start != 0 && - vtoc->efi_parts[i].p_size != 0 /* && - (strstr(vtoc->efi_parts[i].p_name, "ZFS") != NULL || strstr(vtoc->efi_parts[i].p_name, "zfs") != NULL)*/) { - // Lets invent a naming scheme with start, and len in it. + fprintf(stderr, + " part %d: offset %llx: len %llx: " + "tag: %x name: '%s'\n", + i, vtoc->efi_parts[i].p_start, + vtoc->efi_parts[i].p_size, + vtoc->efi_parts[i].p_tag, + vtoc->efi_parts[i].p_name); + fflush(stderr); + if (vtoc->efi_parts[i].p_start != 0 && + vtoc->efi_parts[i].p_size != 0) { + // Lets invent a naming scheme with start, + // and len in it. + + slice = zutil_alloc(hdl, + sizeof (rdsk_node_t)); + + error = asprintf(&slice->rn_name, "#%llu#%llu#%s", + vtoc->efi_parts[i].p_start * vtoc->efi_lbasize, + vtoc->efi_parts[i].p_size * vtoc->efi_lbasize, + deviceInterfaceDetailData->DevicePath); + if (error == -1) { + free(slice); + continue; + } - slice = zutil_alloc(hdl, sizeof (rdsk_node_t)); + slice->rn_vdev_guid = 0; + slice->rn_lock = lock; + slice->rn_avl = *slice_cache; + slice->rn_hdl = hdl; + slice->rn_labelpaths = B_FALSE; + slice->rn_order = IMPORT_ORDER_SCAN_OFFSET + i; - error = asprintf(&slice->rn_name, "#%llu#%llu#%s", - vtoc->efi_parts[i].p_start * vtoc->efi_lbasize, vtoc->efi_parts[i].p_size * vtoc->efi_lbasize, deviceInterfaceDetailData->DevicePath); - if (error == -1) { - free(slice); - continue; - } - - slice->rn_vdev_guid = 0; - slice->rn_lock = lock; - slice->rn_avl = *slice_cache; - slice->rn_hdl = hdl; - slice->rn_labelpaths = B_FALSE; - slice->rn_order = IMPORT_ORDER_SCAN_OFFSET + i; - - pthread_mutex_lock(lock); - if (avl_find(*slice_cache, slice, &where)) { - free(slice->rn_name); - free(slice); - } else { - avl_insert(*slice_cache, slice, where); - } - pthread_mutex_unlock(lock); - - } - } + pthread_mutex_lock(lock); + if (avl_find(*slice_cache, slice, &where)) { + free(slice->rn_name); + free(slice); + } else { + avl_insert(*slice_cache, slice, where); + } + pthread_mutex_unlock(lock); + } + } } efi_free(vtoc); CloseHandle(disk); } else { // Unable to open handle - fprintf(stderr, "Unable to open disk, are we Administrator? GetLastError() is 0x%x\n", GetLastError()); fflush(stderr); + fprintf(stderr, + "Unable to open disk, are we Administrator? " + "GetLastError() is 0x%x\n", + GetLastError()); + fflush(stderr); } #endif @@ -951,7 +992,7 @@ zpool_find_import_blkid(libpc_handle_t *hdl, pthread_mutex_t *lock, #if 1 /* Now lets iterate the partitions (volumes) */ HANDLE vol; - vol = FindFirstVolume(rdsk, sizeof(rdsk)); + vol = FindFirstVolume(rdsk, sizeof (rdsk)); while (vol != INVALID_HANDLE_VALUE) { // If it ends with a \, we need to eat it. @@ -960,7 +1001,8 @@ zpool_find_import_blkid(libpc_handle_t *hdl, pthread_mutex_t *lock, if (*r == '\\' || *r == '/') *r = 0; - fprintf(stderr, "Processing volume '%s'\n", rdsk); fflush(stderr); + fprintf(stderr, "Processing volume '%s'\n", rdsk); + fflush(stderr); slice = zutil_alloc(hdl, sizeof (rdsk_node_t)); @@ -982,7 +1024,7 @@ zpool_find_import_blkid(libpc_handle_t *hdl, pthread_mutex_t *lock, pthread_mutex_unlock(lock); - if (!FindNextVolume(vol, rdsk, sizeof(rdsk))) { + if (!FindNextVolume(vol, rdsk, sizeof (rdsk))) { FindVolumeClose(vol); vol = INVALID_HANDLE_VALUE; } @@ -1017,7 +1059,7 @@ zfs_device_get_physical(struct udev_device *dev, char *bufptr, size_t buflen) return (ENODATA); } -/* Given a "#1234#1234#/path/part" - find the path part only */ +/* Given a "#1234#1234#/path/part" - find the path part only */ static void remove_partition_offset_hack(char *hacked_path, char **out_dev_path) { @@ -1050,26 +1092,30 @@ get_device_number(char *device_path, STORAGE_DEVICE_NUMBER *device_number) hDevice = CreateFile(device_path, GENERIC_READ, - FILE_SHARE_READ /*| FILE_SHARE_WRITE*/, + FILE_SHARE_READ /* | FILE_SHARE_WRITE */, NULL, OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL /*| FILE_FLAG_OVERLAPPED*/, + FILE_ATTRIBUTE_NORMAL /* | FILE_FLAG_OVERLAPPED */, NULL); if (hDevice == INVALID_HANDLE_VALUE) { - //fprintf(stderr, "invalid handle value\n"); fflush(stderr); - return GetLastError(); + // fprintf(stderr, "invalid handle value\n"); fflush(stderr); + return (GetLastError()); } - BOOL ret = DeviceIoControl(hDevice, IOCTL_STORAGE_GET_DEVICE_NUMBER, NULL, 0, (LPVOID)device_number, (DWORD)sizeof(*device_number), (LPDWORD)&returned, (LPOVERLAPPED)NULL); + BOOL ret = DeviceIoControl(hDevice, + IOCTL_STORAGE_GET_DEVICE_NUMBER, NULL, 0, + (LPVOID)device_number, (DWORD)sizeof (*device_number), + (LPDWORD)&returned, (LPOVERLAPPED)NULL); CloseHandle(hDevice); if (!ret) { - //fprintf(stderr, "DeviceIoControl returned error\n"); fflush(stderr); - return ERROR_INVALID_FUNCTION; + // fprintf(stderr, "DeviceIoControl returned error\n"); + // fflush(stderr); + return (ERROR_INVALID_FUNCTION); } - return ERROR_SUCCESS; + return (ERROR_SUCCESS); } @@ -1114,20 +1160,23 @@ update_vdev_config_dev_strs(nvlist_t *nv) devid = strdup(path); HANDLE h; - h = CreateFile(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); + h = CreateFile(path, GENERIC_READ, + FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); if (h != INVALID_HANDLE_VALUE) { - struct dk_gpt* vtoc; - if ((efi_alloc_and_read(h, &vtoc)) == 0) { + struct dk_gpt *vtoc; + if ((efi_alloc_and_read(h, &vtoc)) == 0) { // Slice 1 should be ZFS - fprintf(stderr, "this code assumes ZFS is on partition 1 - tell lundman\n"); fflush(stderr); + fprintf(stderr, + "this code assumes ZFS is on partition 1\n"); + fflush(stderr); snprintf(udevpath, MAXPATHLEN, "#%llu#%llu#%s", vtoc->efi_parts[0].p_start * (uint64_t)vtoc->efi_lbasize, vtoc->efi_parts[0].p_size * (uint64_t)vtoc->efi_lbasize, path); efi_free(vtoc); path = udevpath; - } - CloseHandle(h); + } + CloseHandle(h); } remove_partition_offset_hack(devid, &end); @@ -1138,20 +1187,25 @@ update_vdev_config_dev_strs(nvlist_t *nv) char *vdev_path; if (wholedisk) - asprintf(&vdev_path, "/dev/physicaldrive%lu", deviceNumber.DeviceNumber); + asprintf(&vdev_path, "/dev/physicaldrive%lu", + deviceNumber.DeviceNumber); else - asprintf(&vdev_path, "/dev/Harddisk%luPartition%lu", deviceNumber.DeviceNumber, + asprintf(&vdev_path, "/dev/Harddisk%luPartition%lu", + deviceNumber.DeviceNumber, deviceNumber.PartitionNumber); - fprintf(stderr, "setting path here '%s'\r\n", vdev_path); fflush(stderr); - fprintf(stderr, "setting physpath here '%s'\r\n", path); fflush(stderr); + fprintf(stderr, "setting path here '%s'\r\n", vdev_path); + fflush(stderr); + fprintf(stderr, "setting physpath here '%s'\r\n", path); + fflush(stderr); if (nvlist_add_string(nv, ZPOOL_CONFIG_PHYS_PATH, path) != 0) - return; + return; // This call frees the original path. if (nvlist_add_string(nv, ZPOOL_CONFIG_PATH, vdev_path) != 0) return; } else { - fprintf(stderr, "not setting physpath \r\n", path); fflush(stderr); + fprintf(stderr, "not setting physpath \r\n", path); + fflush(stderr); // if (nvlist_add_string(nv, ZPOOL_CONFIG_PATH, path) != 0) // return; @@ -1159,7 +1213,6 @@ update_vdev_config_dev_strs(nvlist_t *nv) free(devid); - return; } /* @@ -1168,7 +1221,7 @@ update_vdev_config_dev_strs(nvlist_t *nv) * store is not opendir()able. */ int -zfs_resolve_shortname_os(const char* name, char* path, size_t len) +zfs_resolve_shortname_os(const char *name, char *path, size_t len) { /* Ok lets let them say just "PHYSICALDRIVEx" */ if (!strncasecmp("PHYSICALDRIVE", name, 13)) { @@ -1179,9 +1232,9 @@ zfs_resolve_shortname_os(const char* name, char* path, size_t len) } if (!strncasecmp("Harddisk", name, 8)) { // Convert to "\\?\HarddiskXPartitionY" - snprintf(path, len, "\\\\?\\%s", name); - printf("Expanded path to '%s'\n", path); - return (0); + snprintf(path, len, "\\\\?\\%s", name); + printf("Expanded path to '%s'\n", path); + return (0); } return (ENOENT); } diff --git a/lib/os/windows/libkstat/gmatch.c b/lib/os/windows/libkstat/gmatch.c index 03340a95586..08a5a4fe9e1 100644 --- a/lib/os/windows/libkstat/gmatch.c +++ b/lib/os/windows/libkstat/gmatch.c @@ -31,8 +31,8 @@ #include #include #include -//#include -//#include "_range.h" +// #include +// #include "_range.h" #define multibyte (0) @@ -44,10 +44,10 @@ p += n #define WCHAR_CSMASK 0x30000000 -#define valid_range(c1, c2) \ - (((c1) & WCHAR_CSMASK) == ((c2) & WCHAR_CSMASK) && \ - ((c1) > 0xff || !iscntrl((int)c1)) && ((c2) > 0xff || \ - !iscntrl((int)c2))) +#define valid_range(c1, c2) \ + (((c1) & WCHAR_CSMASK) == ((c2) & WCHAR_CSMASK) && \ + ((c1) > 0xff || !iscntrl((int)c1)) && ((c2) > 0xff || \ + !iscntrl((int)c2))) int gmatch(const char *s, const char *p) diff --git a/lib/os/windows/libkstat/kstat.c b/lib/os/windows/libkstat/kstat.c index be464d074c3..ed3320c1e51 100644 --- a/lib/os/windows/libkstat/kstat.c +++ b/lib/os/windows/libkstat/kstat.c @@ -74,9 +74,10 @@ kstat_open(void) kstat_ctl_t *kc; HANDLE h; - h = CreateFile("\\\\.\\ZFS", GENERIC_READ | GENERIC_WRITE, // ZFSDEV - no includes - 0, NULL, OPEN_EXISTING, 0, NULL); - if (h == INVALID_HANDLE_VALUE) + // ZFSDEV - no includes + h = CreateFile("\\\\.\\ZFS", GENERIC_READ | GENERIC_WRITE, + 0, NULL, OPEN_EXISTING, 0, NULL); + if (h == INVALID_HANDLE_VALUE) return (NULL); kstat_zalloc((void **)&kc, sizeof (kstat_ctl_t), 0); @@ -106,20 +107,20 @@ kstat_close(kstat_ctl_t *kc) return (rc); } -int kstat_ioctl(HANDLE hDevice, int request, kstat_t *ksp) +int +kstat_ioctl(HANDLE hDevice, int request, kstat_t *ksp) { int error; ULONG bytesReturned; error = DeviceIoControl(hDevice, - (DWORD)request, - ksp, - (DWORD)sizeof(kstat_t), - ksp, - (DWORD)sizeof(kstat_t), - &bytesReturned, - NULL - ); + (DWORD)request, + ksp, + (DWORD)sizeof (kstat_t), + ksp, + (DWORD)sizeof (kstat_t), + &bytesReturned, + NULL); // Windows: error from DeviceIoControl() is unlikely if (error == 0) { @@ -131,7 +132,7 @@ int kstat_ioctl(HANDLE hDevice, int request, kstat_t *ksp) error = ksp->ks_returnvalue; } - return error; + return (error); } kid_t @@ -144,7 +145,8 @@ kstat_read(kstat_ctl_t *kc, kstat_t *ksp, void *data) if (ksp->ks_data == NULL) return (-1); } - while ((kcid = (kid_t)kstat_ioctl(kc->kc_kd, KSTAT_IOC_READ, ksp)) == -1) { + while ((kcid = + (kid_t)kstat_ioctl(kc->kc_kd, KSTAT_IOC_READ, ksp)) == -1) { if (errno == EAGAIN) { (void) usleep(100); /* back off a moment */ continue; /* and try again */ @@ -234,7 +236,8 @@ kstat_write(kstat_ctl_t *kc, kstat_t *ksp, void *data) } } - while ((kcid = (kid_t)kstat_ioctl(kc->kc_kd, KSTAT_IOC_WRITE, ksp)) == -1) { + while ((kcid = + (kid_t)kstat_ioctl(kc->kc_kd, KSTAT_IOC_WRITE, ksp)) == -1) { if (errno == EAGAIN) { (void) usleep(100); /* back off a moment */ continue; /* and try again */ diff --git a/lib/os/windows/libpthread/pthread.h b/lib/os/windows/libpthread/pthread.h index 0f8908c8c9a..5ceed597a46 100644 --- a/lib/os/windows/libpthread/pthread.h +++ b/lib/os/windows/libpthread/pthread.h @@ -8,8 +8,8 @@ * (C) 2010 Lockless Inc. * All rights reserved. * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: * * * * Redistributions of source code must retain the above copyright notice, @@ -17,20 +17,21 @@ * * 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. - * * Neither the name of Lockless Inc. nor the names of its contributors may be - * used to endorse or promote products derived from this software without - * specific prior written permission. + * * Neither the name of Lockless Inc. 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AN - * 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 COPYRIGHT HOLDER 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. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AN 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 COPYRIGHT HOLDER 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. */ /* @@ -44,12 +45,12 @@ */ #ifndef WIN_PTHREADS -#define WIN_PTHREADS +#define WIN_PTHREADS /* Windows has own VT_ERROR to libefi one */ #undef VT_ERROR #define VT_ERROR WIN_VT_ERROR -#define _WIN32_MEAN_AND_LEAN +#define _WIN32_MEAN_AND_LEAN #include #undef VT_ERROR @@ -61,72 +62,62 @@ #include #include -//#define ETIMEDOUT 110 -//#define ENOTSUP 134 +// #define ETIMEDOUT 110 +// #define ENOTSUP 134 -// warning C4018: '>': signed/unsigned mismatch -#pragma warning (disable: 4018) +// warning C4018: '>': signed/unsigned mismatch +#pragma warning(disable: 4018) #if __clang__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-function" #endif -#define PTHREAD_CANCEL_DISABLE 0 -#define PTHREAD_CANCEL_ENABLE 0x01 +#define PTHREAD_CANCEL_DISABLE 0 +#define PTHREAD_CANCEL_ENABLE 0x01 -#define PTHREAD_CANCEL_DEFERRED 0 -#define PTHREAD_CANCEL_ASYNCHRONOUS 0x02 +#define PTHREAD_CANCEL_DEFERRED 0 +#define PTHREAD_CANCEL_ASYNCHRONOUS 0x02 -#define PTHREAD_CREATE_JOINABLE 0 -#define PTHREAD_CREATE_DETACHED 0x04 +#define PTHREAD_CREATE_JOINABLE 0 +#define PTHREAD_CREATE_DETACHED 0x04 -#define PTHREAD_EXPLICT_SCHED 0 -#define PTHREAD_INHERIT_SCHED 0x08 +#define PTHREAD_EXPLICT_SCHED 0 +#define PTHREAD_INHERIT_SCHED 0x08 -#define PTHREAD_SCOPE_PROCESS 0 -#define PTHREAD_SCOPE_SYSTEM 0x10 +#define PTHREAD_SCOPE_PROCESS 0 +#define PTHREAD_SCOPE_SYSTEM 0x10 -#define PTHREAD_DEFAULT_ATTR (PTHREAD_CANCEL_ENABLE) +#define PTHREAD_DEFAULT_ATTR (PTHREAD_CANCEL_ENABLE) -#define PTHREAD_CANCELED ((void *) 0xDEADBEEFULL) +#define PTHREAD_CANCELED ((void *) 0xDEADBEEFULL) -#define PTHREAD_ONCE_INIT 0 -#define PTHREAD_MUTEX_INITIALIZER {(void*)-1,-1,0,0,0,0} -#define PTHREAD_RWLOCK_INITIALIZER {0} -#define PTHREAD_COND_INITIALIZER {0} -#define PTHREAD_BARRIER_INITIALIZER \ - {0,0,PTHREAD_MUTEX_INITIALIZER,PTHREAD_COND_INITIALIZER} -#define PTHREAD_SPINLOCK_INITIALIZER 0 +#define PTHREAD_ONCE_INIT 0 +#define PTHREAD_MUTEX_INITIALIZER {(void*)-1, -1, 0, 0, 0, 0} +#define PTHREAD_RWLOCK_INITIALIZER {0} +#define PTHREAD_COND_INITIALIZER {0} +#define PTHREAD_BARRIER_INITIALIZER \ + {0, 0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER} +#define PTHREAD_SPINLOCK_INITIALIZER 0 -#define PTHREAD_DESTRUCTOR_ITERATIONS 256 -#define PTHREAD_KEYS_MAX (1<<20) +#define PTHREAD_DESTRUCTOR_ITERATIONS 256 +#define PTHREAD_KEYS_MAX (1<<20) -#define PTHREAD_MUTEX_NORMAL 0 -#define PTHREAD_MUTEX_ERRORCHECK 1 -#define PTHREAD_MUTEX_RECURSIVE 2 -#define PTHREAD_MUTEX_DEFAULT 3 -#define PTHREAD_MUTEX_SHARED 4 -#define PTHREAD_MUTEX_PRIVATE 0 -#define PTHREAD_PRIO_NONE 0 -#define PTHREAD_PRIO_INHERIT 8 -#define PTHREAD_PRIO_PROTECT 16 -#define PTHREAD_PRIO_MULT 32 -#define PTHREAD_PROCESS_SHARED 0 -#define PTHREAD_PROCESS_PRIVATE 1 +#define PTHREAD_MUTEX_NORMAL 0 +#define PTHREAD_MUTEX_ERRORCHECK 1 +#define PTHREAD_MUTEX_RECURSIVE 2 +#define PTHREAD_MUTEX_DEFAULT 3 +#define PTHREAD_MUTEX_SHARED 4 +#define PTHREAD_MUTEX_PRIVATE 0 +#define PTHREAD_PRIO_NONE 0 +#define PTHREAD_PRIO_INHERIT 8 +#define PTHREAD_PRIO_PROTECT 16 +#define PTHREAD_PRIO_MULT 32 +#define PTHREAD_PROCESS_SHARED 0 +#define PTHREAD_PROCESS_PRIVATE 1 -#define PTHREAD_BARRIER_SERIAL_THREAD 1 +#define PTHREAD_BARRIER_SERIAL_THREAD 1 -#define PTHREAD_STACK_MIN 0 - - - -/* Windows doesn't have this, so declare it ourselves. */ -//struct timespec -//{ -// /* long long in windows is the same as long in unix for 64bit */ -// long long tv_sec; -// long long tv_nsec; -//}; +#define PTHREAD_STACK_MIN 0 typedef struct _pthread_cleanup _pthread_cleanup; struct _pthread_cleanup @@ -195,16 +186,19 @@ long _pthread_key_sch; void (**_pthread_key_dest)(void *); -#define pthread_cleanup_push(F, A)\ +#define pthread_cleanup_push(F, A)\ {\ - const _pthread_cleanup _pthread_cup = {(F), (A), pthread_self()->clean};\ + const _pthread_cleanup _pthread_cup = {(F), (A), \ + pthread_self()->clean}; \ _ReadWriteBarrier();\ pthread_self()->clean = (_pthread_cleanup *) &_pthread_cup;\ _ReadWriteBarrier() /* Note that if async cancelling is used, then there is a race here */ -#define pthread_cleanup_pop(E)\ - (pthread_self()->clean = _pthread_cup.next, (E?_pthread_cup.func(_pthread_cup.arg):0));} +#define pthread_cleanup_pop(E) \ + (pthread_self()->clean = _pthread_cup.next, \ + (E?_pthread_cup.func(_pthread_cup.arg):0)); \ +} static void _pthread_once_cleanup(pthread_once_t *o) { @@ -218,12 +212,9 @@ static int pthread_once(pthread_once_t *o, void (*func)(void)) _ReadWriteBarrier(); - while (state != 1) - { - if (!state) - { - if (!_InterlockedCompareExchange(o, 2, 0)) - { + while (state != 1) { + if (!state) { + if (!_InterlockedCompareExchange(o, 2, 0)) { /* Success */ pthread_cleanup_push(_pthread_once_cleanup, o); func(); @@ -232,7 +223,7 @@ static int pthread_once(pthread_once_t *o, void (*func)(void)) /* Mark as done */ *o = 1; - return 0; + return (0); } } @@ -244,7 +235,7 @@ static int pthread_once(pthread_once_t *o, void (*func)(void)) } /* Done */ - return 0; + return (0); } static int _pthread_once_raw(pthread_once_t *o, void (*func)(void)) @@ -253,19 +244,16 @@ static int _pthread_once_raw(pthread_once_t *o, void (*func)(void)) _ReadWriteBarrier(); - while (state != 1) - { - if (!state) - { - if (!_InterlockedCompareExchange(o, 2, 0)) - { + while (state != 1) { + if (!state) { + if (!_InterlockedCompareExchange(o, 2, 0)) { /* Success */ func(); /* Mark as done */ *o = 1; - return 0; + return (0); } } @@ -277,24 +265,24 @@ static int _pthread_once_raw(pthread_once_t *o, void (*func)(void)) } /* Done */ - return 0; + return (0); } static int pthread_mutex_lock(pthread_mutex_t *m) { EnterCriticalSection(m); - return 0; + return (0); } static int pthread_mutex_unlock(pthread_mutex_t *m) { LeaveCriticalSection(m); - return 0; + return (0); } static int pthread_mutex_trylock(pthread_mutex_t *m) { - return TryEnterCriticalSection(m) ? 0 : EBUSY; + return (TryEnterCriticalSection(m) ? 0 : EBUSY); } static int pthread_mutex_init(pthread_mutex_t *m, pthread_mutexattr_t *a) @@ -302,21 +290,21 @@ static int pthread_mutex_init(pthread_mutex_t *m, pthread_mutexattr_t *a) (void) a; InitializeCriticalSection(m); - return 0; + return (0); } static int pthread_mutex_destroy(pthread_mutex_t *m) { DeleteCriticalSection(m); - return 0; + return (0); } -#define pthread_mutex_getprioceiling(M, P) ENOTSUP -#define pthread_mutex_setprioceiling(M, P) ENOTSUP +#define pthread_mutex_getprioceiling(M, P) ENOTSUP +#define pthread_mutex_setprioceiling(M, P) ENOTSUP static int pthread_equal(pthread_t t1, pthread_t t2) { - return t1 == t2; + return (t1 == t2); } static void pthread_testcancel(void); @@ -326,13 +314,13 @@ static int pthread_rwlock_init(pthread_rwlock_t *l, pthread_rwlockattr_t *a) (void) a; InitializeSRWLock(l); - return 0; + return (0); } static int pthread_rwlock_destroy(pthread_rwlock_t *l) { (void) *l; - return 0; + return (0); } static int pthread_rwlock_rdlock(pthread_rwlock_t *l) @@ -340,7 +328,7 @@ static int pthread_rwlock_rdlock(pthread_rwlock_t *l) pthread_testcancel(); AcquireSRWLockShared(l); - return 0; + return (0); } static int pthread_rwlock_wrlock(pthread_rwlock_t *l) @@ -348,7 +336,7 @@ static int pthread_rwlock_wrlock(pthread_rwlock_t *l) pthread_testcancel(); AcquireSRWLockExclusive(l); - return 0; + return (0); } static void pthread_tls_init(void) @@ -359,25 +347,21 @@ static void pthread_tls_init(void) if (_pthread_tls == TLS_OUT_OF_INDEXES) abort(); } -static int pthread_rwlock_unlock(pthread_rwlock_t* l); +static int pthread_rwlock_unlock(pthread_rwlock_t *l); static void _pthread_cleanup_dest(pthread_t t) { int i, j; - for (j = 0; j < PTHREAD_DESTRUCTOR_ITERATIONS; j++) - { + for (j = 0; j < PTHREAD_DESTRUCTOR_ITERATIONS; j++) { int flag = 0; - for (i = 0; i < t->keymax; i++) - { + for (i = 0; i < t->keymax; i++) { void *val = t->keyval[i]; - if (val) - { + if (val) { pthread_rwlock_rdlock(&_pthread_key_lock); - if ((uintptr_t) _pthread_key_dest[i] > 1) - { + if ((uintptr_t)_pthread_key_dest[i] > 1) { /* Call destructor */ t->keyval[i] = NULL; _pthread_key_dest[i](val); @@ -388,7 +372,8 @@ static void _pthread_cleanup_dest(pthread_t t) } /* Nothing to do? */ - if (!flag) return; + if (!flag) + return; } } @@ -401,11 +386,10 @@ static pthread_t pthread_self(void) t = TlsGetValue(_pthread_tls); /* Main thread? */ - if (!t) - { - t = malloc(sizeof(struct _pthread_v)); + if (!t) { + t = malloc(sizeof (struct _pthread_v)); - /* If cannot initialize main thread, then the only thing we can do is abort */ + /* If cannot init main thread, then the only thing is abort */ if (!t) abort(); t->ret_arg = NULL; @@ -420,8 +404,7 @@ static pthread_t pthread_self(void) /* Save for later */ TlsSetValue(_pthread_tls, t); - if (setjmp(t->jb)) - { + if (setjmp(t->jb)) { /* Make sure we free ourselves if we are detached */ if (!t->h) free(t); @@ -430,25 +413,22 @@ static pthread_t pthread_self(void) } } - return t; + return (t); } static int pthread_rwlock_unlock(pthread_rwlock_t *l) { void *state = *(void **)l; - if (state == (void *) 1) - { + if (state == (void *) 1) { /* Known to be an exclusive lock */ ReleaseSRWLockExclusive(l); - } - else - { + } else { /* A shared unlock will work */ ReleaseSRWLockShared(l); } - return 0; + return (0); } @@ -457,30 +437,37 @@ static int pthread_rwlock_tryrdlock(pthread_rwlock_t *l) /* Get the current state of the lock */ void *state = *(void **) l; - if (!state) - { + if (!state) { /* Unlocked to locked */ - if (!_InterlockedCompareExchangePointer((void *) l, (void *)0x11, NULL)) return 0; - return EBUSY; + if (!_InterlockedCompareExchangePointer((void *) l, + (void *)0x11, NULL)) + return (0); + return (EBUSY); } /* A single writer exists */ - if (state == (void *) 1) return EBUSY; + if (state == (void *) 1) + return (EBUSY); /* Multiple writers exist? */ - if ((uintptr_t) state & 14) return EBUSY; + if ((uintptr_t)state & 14) + return (EBUSY); - if (_InterlockedCompareExchangePointer((void *) l, (void *) ((uintptr_t)state + 16), state) == state) return 0; + if (_InterlockedCompareExchangePointer((void *) l, + (void *)((uintptr_t)state + 16), state) == state) + return (0); - return EBUSY; + return (EBUSY); } static int pthread_rwlock_trywrlock(pthread_rwlock_t *l) { /* Try to grab lock if it has no users */ - if (!_InterlockedCompareExchangePointer((void *) l, (void *)1, NULL)) return 0; + if (!_InterlockedCompareExchangePointer((void *) l, (void *)1, + NULL)) + return (0); - return EBUSY; + return (EBUSY); } static unsigned long long _pthread_time_in_ms(void) @@ -489,15 +476,16 @@ static unsigned long long _pthread_time_in_ms(void) _ftime64(&tb); - return tb.time * 1000 + tb.millitm; + return (tb.time * 1000 + tb.millitm); } -static unsigned long long _pthread_time_in_ms_from_timespec(const struct timespec *ts) +static unsigned long long +_pthread_time_in_ms_from_timespec(const struct timespec *ts) { unsigned long long t = ts->tv_sec * 1000; t += ts->tv_nsec / 1000000; - return t; + return (t); } static unsigned long long _pthread_rel_time_in_ms(const struct timespec *ts) @@ -506,11 +494,13 @@ static unsigned long long _pthread_rel_time_in_ms(const struct timespec *ts) unsigned long long t2 = _pthread_time_in_ms(); /* Prevent underflow */ - if (t1 < t2) return 0; - return t1 - t2; + if (t1 < t2) + return (0); + return (t1 - t2); } -static int pthread_rwlock_timedrdlock(pthread_rwlock_t *l, const struct timespec *ts) +static int +pthread_rwlock_timedrdlock(pthread_rwlock_t *l, const struct timespec *ts) { unsigned long long ct = _pthread_time_in_ms(); unsigned long long t = _pthread_time_in_ms_from_timespec(ts); @@ -518,20 +508,22 @@ static int pthread_rwlock_timedrdlock(pthread_rwlock_t *l, const struct timespec pthread_testcancel(); /* Use a busy-loop */ - while (1) - { + while (1) { /* Try to grab lock */ - if (!pthread_rwlock_tryrdlock(l)) return 0; + if (!pthread_rwlock_tryrdlock(l)) + return (0); /* Get current time */ ct = _pthread_time_in_ms(); /* Have we waited long enough? */ - if (ct > t) return ETIMEDOUT; + if (ct > t) + return (ETIMEDOUT); } } -static int pthread_rwlock_timedwrlock(pthread_rwlock_t *l, const struct timespec *ts) +static int +pthread_rwlock_timedwrlock(pthread_rwlock_t *l, const struct timespec *ts) { unsigned long long ct = _pthread_time_in_ms(); unsigned long long t = _pthread_time_in_ms_from_timespec(ts); @@ -539,34 +531,35 @@ static int pthread_rwlock_timedwrlock(pthread_rwlock_t *l, const struct timespec pthread_testcancel(); /* Use a busy-loop */ - while (1) - { + while (1) { /* Try to grab lock */ - if (!pthread_rwlock_trywrlock(l)) return 0; + if (!pthread_rwlock_trywrlock(l)) + return (0); /* Get current time */ ct = _pthread_time_in_ms(); /* Have we waited long enough? */ - if (ct > t) return ETIMEDOUT; + if (ct > t) + return (ETIMEDOUT); } } static int pthread_get_concurrency(int *val) { *val = _pthread_concur; - return 0; + return (0); } static int pthread_set_concurrency(int val) { _pthread_concur = val; - return 0; + return (0); } -#define pthread_getschedparam(T, P, S) ENOTSUP -#define pthread_setschedparam(T, P, S) ENOTSUP -#define pthread_getcpuclockid(T, C) ENOTSUP +#define pthread_getschedparam(T, P, S) ENOTSUP +#define pthread_setschedparam(T, P, S) ENOTSUP +#define pthread_getcpuclockid(T, C) ENOTSUP static int pthread_exit(void *res) { @@ -587,8 +580,7 @@ static void _pthread_invoke_cancel(void) _InterlockedDecrement(&_pthread_cancelling); /* Call cancel queue */ - for (pcup = pthread_self()->clean; pcup; pcup = pcup->next) - { + for (pcup = pthread_self()->clean; pcup; pcup = pcup->next) { pcup->func(pcup->arg); } @@ -597,12 +589,10 @@ static void _pthread_invoke_cancel(void) static void pthread_testcancel(void) { - if (_pthread_cancelling) - { + if (_pthread_cancelling) { pthread_t t = pthread_self(); - if (t->cancelled && (t->p_state & PTHREAD_CANCEL_ENABLE)) - { + if (t->cancelled && (t->p_state & PTHREAD_CANCEL_ENABLE)) { _pthread_invoke_cancel(); } } @@ -611,22 +601,22 @@ static void pthread_testcancel(void) static int pthread_cancel(pthread_t t) { - if (t->p_state & PTHREAD_CANCEL_ASYNCHRONOUS) - { + if (t->p_state & PTHREAD_CANCEL_ASYNCHRONOUS) { /* Dangerous asynchronous cancelling */ CONTEXT ctxt; /* Already done? */ - if (t->cancelled) return ESRCH; + if (t->cancelled) + return (ESRCH); ctxt.ContextFlags = CONTEXT_CONTROL; SuspendThread(t->h); GetThreadContext(t->h, &ctxt); #ifdef _M_X64 - ctxt.Rip = (uintptr_t) _pthread_invoke_cancel; + ctxt.Rip = (uintptr_t)_pthread_invoke_cancel; #else - ctxt.Eip = (uintptr_t) _pthread_invoke_cancel; + ctxt.Eip = (uintptr_t)_pthread_invoke_cancel; #endif SetThreadContext(t->h, &ctxt); @@ -637,9 +627,7 @@ static int pthread_cancel(pthread_t t) _InterlockedIncrement(&_pthread_cancelling); ResumeThread(t->h); - } - else - { + } else { /* Safe deferred Cancelling */ t->cancelled = 1; @@ -647,21 +635,22 @@ static int pthread_cancel(pthread_t t) _InterlockedIncrement(&_pthread_cancelling); } - return 0; + return (0); } static unsigned _pthread_get_state(pthread_attr_t *attr, unsigned flag) { - return attr->p_state & flag; + return (attr->p_state & flag); } static int _pthread_set_state(pthread_attr_t *attr, unsigned flag, unsigned val) { - if (~flag & val) return EINVAL; + if (~flag & val) + return (EINVAL); attr->p_state &= ~flag; attr->p_state |= val; - return 0; + return (0); } static int pthread_attr_init(pthread_attr_t *attr) @@ -669,117 +658,120 @@ static int pthread_attr_init(pthread_attr_t *attr) attr->p_state = PTHREAD_DEFAULT_ATTR; attr->stack = NULL; attr->s_size = 0; - return 0; + return (0); } static int pthread_attr_destroy(pthread_attr_t *attr) { /* No need to do anything */ - return 0; + return (0); } static int pthread_attr_setdetachstate(pthread_attr_t *a, int flag) { - return _pthread_set_state(a, PTHREAD_CREATE_DETACHED, flag); + return (_pthread_set_state(a, PTHREAD_CREATE_DETACHED, flag)); } static int pthread_attr_getdetachstate(pthread_attr_t *a, int *flag) { *flag = _pthread_get_state(a, PTHREAD_CREATE_DETACHED); - return 0; + return (0); } static int pthread_attr_setinheritsched(pthread_attr_t *a, int flag) { - return _pthread_set_state(a, PTHREAD_INHERIT_SCHED, flag); + return (_pthread_set_state(a, PTHREAD_INHERIT_SCHED, flag)); } static int pthread_attr_getinheritsched(pthread_attr_t *a, int *flag) { *flag = _pthread_get_state(a, PTHREAD_INHERIT_SCHED); - return 0; + return (0); } static int pthread_attr_setscope(pthread_attr_t *a, int flag) { - return _pthread_set_state(a, PTHREAD_SCOPE_SYSTEM, flag); + return (_pthread_set_state(a, PTHREAD_SCOPE_SYSTEM, flag)); } static int pthread_attr_getscope(pthread_attr_t *a, int *flag) { *flag = _pthread_get_state(a, PTHREAD_SCOPE_SYSTEM); - return 0; + return (0); } static int pthread_attr_getstackaddr(pthread_attr_t *attr, void **stack) { *stack = attr->stack; - return 0; + return (0); } static int pthread_attr_setstackaddr(pthread_attr_t *attr, void *stack) { attr->stack = stack; - return 0; + return (0); } static int pthread_attr_getstacksize(pthread_attr_t *attr, size_t *size) { *size = attr->s_size; - return 0; + return (0); } static int pthread_attr_setstacksize(pthread_attr_t *attr, size_t size) { attr->s_size = size; - return 0; + return (0); } -static int pthread_attr_getstack(pthread_attr_t *attr, void **stack, size_t *size) +static int +pthread_attr_getstack(pthread_attr_t *attr, void **stack, size_t *size) { *stack = attr->stack; *size = attr->s_size; - return 0; + return (0); } static int pthread_attr_setstack(pthread_attr_t *attr, void *stack, size_t size) { attr->stack = stack; attr->s_size = size; - return 0; + return (0); } -#define pthread_attr_getguardsize(A, S) ENOTSUP -#define pthread_attr_setguardsize(A, S) ENOTSUP -#define pthread_attr_getschedparam(A, S) ENOTSUP -#define pthread_attr_setschedparam(A, S) ENOTSUP -#define pthread_attr_getschedpolicy(A, S) ENOTSUP -#define pthread_attr_setschedpolicy(A, S) ENOTSUP +#define pthread_attr_getguardsize(A, S) ENOTSUP +#define pthread_attr_setguardsize(A, S) ENOTSUP +#define pthread_attr_getschedparam(A, S) ENOTSUP +#define pthread_attr_setschedparam(A, S) ENOTSUP +#define pthread_attr_getschedpolicy(A, S) ENOTSUP +#define pthread_attr_setschedpolicy(A, S) ENOTSUP static int pthread_setcancelstate(int state, int *oldstate) { pthread_t t = pthread_self(); - if ((state & PTHREAD_CANCEL_ENABLE) != state) return EINVAL; + if ((state & PTHREAD_CANCEL_ENABLE) != state) + return (EINVAL); if (oldstate) *oldstate = t->p_state & PTHREAD_CANCEL_ENABLE; t->p_state &= ~PTHREAD_CANCEL_ENABLE; t->p_state |= state; - return 0; + return (0); } static int pthread_setcanceltype(int type, int *oldtype) { pthread_t t = pthread_self(); - if ((type & PTHREAD_CANCEL_ASYNCHRONOUS) != type) return EINVAL; + if ((type & PTHREAD_CANCEL_ASYNCHRONOUS) != type) + return (EINVAL); if (oldtype) *oldtype = t->p_state & PTHREAD_CANCEL_ASYNCHRONOUS; t->p_state &= ~PTHREAD_CANCEL_ASYNCHRONOUS; t->p_state |= type; - return 0; + return (0); } static int __stdcall pthread_create_wrapper(void *args) @@ -790,8 +782,7 @@ static int __stdcall pthread_create_wrapper(void *args) TlsSetValue(_pthread_tls, tv); - if (!setjmp(tv->jb)) - { + if (!setjmp(tv->jb)) { /* Call function and save return value */ tv->ret_arg = tv->func(tv->ret_arg); @@ -800,8 +791,7 @@ static int __stdcall pthread_create_wrapper(void *args) } /* If we exit too early, then we can race with create */ - while (tv->h == (HANDLE) -1) - { + while (tv->h == (HANDLE) -1) { YieldProcessor(); _ReadWriteBarrier(); } @@ -809,15 +799,18 @@ static int __stdcall pthread_create_wrapper(void *args) /* Make sure we free ourselves if we are detached */ if (!tv->h) free(tv); - return 0; + return (0); } -static int pthread_create(pthread_t *th, pthread_attr_t *attr, void *(* func)(void *), void *arg) +static int +pthread_create(pthread_t *th, pthread_attr_t *attr, + void *(*func)(void *), void *arg) { - struct _pthread_v *tv = malloc(sizeof(struct _pthread_v)); + struct _pthread_v *tv = malloc(sizeof (struct _pthread_v)); unsigned ssize = 0; - if (!tv) return 1; + if (!tv) + return (1); *th = tv; @@ -831,8 +824,7 @@ static int pthread_create(pthread_t *th, pthread_attr_t *attr, void *(* func)(vo tv->keyval = NULL; tv->h = (HANDLE) -1; - if (attr) - { + if (attr) { tv->p_state = attr->p_state; ssize = attr->s_size; } @@ -840,19 +832,20 @@ static int pthread_create(pthread_t *th, pthread_attr_t *attr, void *(* func)(vo /* Make sure tv->h has value of -1 */ _ReadWriteBarrier(); - tv->h = (HANDLE) _beginthreadex(NULL, ssize, (_beginthreadex_proc_type) pthread_create_wrapper, tv, 0, NULL); + tv->h = (HANDLE) _beginthreadex(NULL, ssize, + (_beginthreadex_proc_type) pthread_create_wrapper, tv, 0, NULL); /* Failed */ - if (!tv->h) return 1; + if (!tv->h) + return (1); - if (tv->p_state & PTHREAD_CREATE_DETACHED) - { + if (tv->p_state & PTHREAD_CREATE_DETACHED) { CloseHandle(tv->h); _ReadWriteBarrier(); tv->h = 0; } - return 0; + return (0); } static int pthread_join(pthread_t t, void **res) @@ -869,7 +862,7 @@ static int pthread_join(pthread_t t, void **res) free(tv); - return 0; + return (0); } static int pthread_detach(pthread_t t) @@ -885,75 +878,78 @@ static int pthread_detach(pthread_t t) _ReadWriteBarrier(); tv->h = 0; - return 0; + return (0); } static int pthread_mutexattr_init(pthread_mutexattr_t *a) { *a = 0; - return 0; + return (0); } static int pthread_mutexattr_destroy(pthread_mutexattr_t *a) { (void) a; - return 0; + return (0); } static int pthread_mutexattr_gettype(pthread_mutexattr_t *a, int *type) { *type = *a & 3; - return 0; + return (0); } static int pthread_mutexattr_settype(pthread_mutexattr_t *a, int type) { - if ((unsigned) type > 3) return EINVAL; + if ((unsigned)type > 3) + return (EINVAL); *a &= ~3; *a |= type; - return 0; + return (0); } static int pthread_mutexattr_getpshared(pthread_mutexattr_t *a, int *type) { *type = *a & 4; - return 0; + return (0); } -static int pthread_mutexattr_setpshared(pthread_mutexattr_t * a, int type) +static int pthread_mutexattr_setpshared(pthread_mutexattr_t *a, int type) { - if ((type & 4) != type) return EINVAL; + if ((type & 4) != type) + return (EINVAL); *a &= ~4; *a |= type; - return 0; + return (0); } static int pthread_mutexattr_getprotocol(pthread_mutexattr_t *a, int *type) { *type = *a & (8 + 16); - return 0; + return (0); } static int pthread_mutexattr_setprotocol(pthread_mutexattr_t *a, int type) { - if ((type & (8 + 16)) != 8 + 16) return EINVAL; + if ((type & (8 + 16)) != 8 + 16) + return (EINVAL); *a &= ~(8 + 16); *a |= type; - return 0; + return (0); } -static int pthread_mutexattr_getprioceiling(pthread_mutexattr_t *a, int * prio) +static int pthread_mutexattr_getprioceiling(pthread_mutexattr_t *a, int *prio) { *prio = *a / PTHREAD_PRIO_MULT; - return 0; + return (0); } static int pthread_mutexattr_setprioceiling(pthread_mutexattr_t *a, int prio) @@ -961,15 +957,14 @@ static int pthread_mutexattr_setprioceiling(pthread_mutexattr_t *a, int prio) *a &= (PTHREAD_PRIO_MULT - 1); *a += prio * PTHREAD_PRIO_MULT; - return 0; + return (0); } static int pthread_mutex_timedlock(pthread_mutex_t *m, struct timespec *ts) { unsigned long long t, ct; - struct _pthread_crit_t - { + struct _pthread_crit_t { void *debug; LONG count; LONG r_count; @@ -979,35 +974,36 @@ static int pthread_mutex_timedlock(pthread_mutex_t *m, struct timespec *ts) }; /* Try to lock it without waiting */ - if (!pthread_mutex_trylock(m)) return 0; + if (!pthread_mutex_trylock(m)) + return (0); ct = _pthread_time_in_ms(); t = _pthread_time_in_ms_from_timespec(ts); - while (1) - { + while (1) { /* Have we waited long enough? */ - if (ct > t) return ETIMEDOUT; + if (ct > t) + return (ETIMEDOUT); /* Wait on semaphore within critical section */ WaitForSingleObject(((struct _pthread_crit_t *)m)->sem, t - ct); /* Try to grab lock */ - if (!pthread_mutex_trylock(m)) return 0; + if (!pthread_mutex_trylock(m)) + return (0); /* Get current time */ ct = _pthread_time_in_ms(); } } -#define _PTHREAD_BARRIER_FLAG (1<<30) +#define _PTHREAD_BARRIER_FLAG (1<<30) static int pthread_barrier_destroy(pthread_barrier_t *b) { EnterCriticalSection(&b->m); - while (b->total > _PTHREAD_BARRIER_FLAG) - { + while (b->total > _PTHREAD_BARRIER_FLAG) { /* Wait until everyone exits the barrier */ SleepConditionVariableCS(&b->cv, &b->m, INFINITE); } @@ -1016,7 +1012,7 @@ static int pthread_barrier_destroy(pthread_barrier_t *b) DeleteCriticalSection(&b->m); - return 0; + return (0); } static int pthread_barrier_init(pthread_barrier_t *b, void *attr, int count) @@ -1030,15 +1026,14 @@ static int pthread_barrier_init(pthread_barrier_t *b, void *attr, int count) InitializeCriticalSection(&b->m); InitializeConditionVariable(&b->cv); - return 0; + return (0); } static int pthread_barrier_wait(pthread_barrier_t *b) { EnterCriticalSection(&b->m); - while (b->total > _PTHREAD_BARRIER_FLAG) - { + while (b->total > _PTHREAD_BARRIER_FLAG) { /* Wait until everyone exits the barrier */ SleepConditionVariableCS(&b->cv, &b->m, INFINITE); } @@ -1048,19 +1043,15 @@ static int pthread_barrier_wait(pthread_barrier_t *b) b->total++; - if (b->total == b->count) - { + if (b->total == b->count) { b->total += _PTHREAD_BARRIER_FLAG - 1; WakeAllConditionVariable(&b->cv); LeaveCriticalSection(&b->m); - return 1; - } - else - { - while (b->total < _PTHREAD_BARRIER_FLAG) - { + return (1); + } else { + while (b->total < _PTHREAD_BARRIER_FLAG) { /* Wait until enough threads enter the barrier */ SleepConditionVariableCS(&b->cv, &b->m, INFINITE); } @@ -1068,18 +1059,19 @@ static int pthread_barrier_wait(pthread_barrier_t *b) b->total--; /* Get entering threads to wake up */ - if (b->total == _PTHREAD_BARRIER_FLAG) WakeAllConditionVariable(&b->cv); + if (b->total == _PTHREAD_BARRIER_FLAG) + WakeAllConditionVariable(&b->cv); LeaveCriticalSection(&b->m); - return 0; + return (0); } } static int pthread_barrierattr_init(void **attr) { *attr = NULL; - return 0; + return (0); } static int pthread_barrierattr_destroy(void **attr) @@ -1087,20 +1079,20 @@ static int pthread_barrierattr_destroy(void **attr) /* Ignore attr */ (void) attr; - return 0; + return (0); } static int pthread_barrierattr_setpshared(void **attr, int s) { *attr = (void *)(uintptr_t)s; - return 0; + return (0); } static int pthread_barrierattr_getpshared(void **attr, int *s) { - *s = (int) (size_t) *attr; + *s = (int)(size_t)*attr; - return 0; + return (0); } static int pthread_key_create(pthread_key_t *key, void (* dest)(void *)) @@ -1109,70 +1101,60 @@ static int pthread_key_create(pthread_key_t *key, void (* dest)(void *)) long nmax; void (**d)(void *); - if (!key) return EINVAL; + if (!key) + return (EINVAL); pthread_rwlock_wrlock(&_pthread_key_lock); - for (i = _pthread_key_sch; i < _pthread_key_max; i++) - { - if (!_pthread_key_dest[i]) - { + for (i = _pthread_key_sch; i < _pthread_key_max; i++) { + if (!_pthread_key_dest[i]) { *key = i; - if (dest) - { + if (dest) { _pthread_key_dest[i] = dest; - } - else - { + } else { _pthread_key_dest[i] = (void(*)(void *))1; } pthread_rwlock_unlock(&_pthread_key_lock); - return 0; + return (0); } } - for (i = 0; i < _pthread_key_sch; i++) - { - if (!_pthread_key_dest[i]) - { + for (i = 0; i < _pthread_key_sch; i++) { + if (!_pthread_key_dest[i]) { *key = i; - if (dest) - { + if (dest) { _pthread_key_dest[i] = dest; - } - else - { + } else { _pthread_key_dest[i] = (void(*)(void *))1; } pthread_rwlock_unlock(&_pthread_key_lock); - return 0; + return (0); } } if (!_pthread_key_max) _pthread_key_max = 1; - if (_pthread_key_max == PTHREAD_KEYS_MAX) - { + if (_pthread_key_max == PTHREAD_KEYS_MAX) { pthread_rwlock_unlock(&_pthread_key_lock); - return ENOMEM; + return (ENOMEM); } nmax = _pthread_key_max * 2; if (nmax > PTHREAD_KEYS_MAX) nmax = PTHREAD_KEYS_MAX; /* No spare room anywhere */ - d = realloc(_pthread_key_dest, nmax * sizeof(*d)); - if (!d) - { + d = realloc(_pthread_key_dest, nmax * sizeof (*d)); + if (!d) { pthread_rwlock_unlock(&_pthread_key_lock); - return ENOMEM; + return (ENOMEM); } /* Clear new region */ - memset((void *) &d[_pthread_key_max], 0, (nmax-_pthread_key_max)*sizeof(void *)); + memset((void *) &d[_pthread_key_max], 0, + (nmax-_pthread_key_max)*sizeof (void *)); /* Use new region */ _pthread_key_dest = d; @@ -1180,24 +1162,23 @@ static int pthread_key_create(pthread_key_t *key, void (* dest)(void *)) *key = _pthread_key_max; _pthread_key_max = nmax; - if (dest) - { + if (dest) { _pthread_key_dest[*key] = dest; - } - else - { + } else { _pthread_key_dest[*key] = (void(*)(void *))1; } pthread_rwlock_unlock(&_pthread_key_lock); - return 0; + return (0); } static int pthread_key_delete(pthread_key_t key) { - if (key > _pthread_key_max) return EINVAL; - if (!_pthread_key_dest) return EINVAL; + if (key > _pthread_key_max) + return (EINVAL); + if (!_pthread_key_dest) + return (EINVAL); pthread_rwlock_wrlock(&_pthread_key_lock); _pthread_key_dest[key] = NULL; @@ -1207,16 +1188,17 @@ static int pthread_key_delete(pthread_key_t key) pthread_rwlock_unlock(&_pthread_key_lock); - return 0; + return (0); } static void *pthread_getspecific(pthread_key_t key) { pthread_t t = pthread_self(); - if (key >= t->keymax) return NULL; + if (key >= t->keymax) + return (NULL); - return t->keyval[key]; + return (t->keyval[key]); } @@ -1224,15 +1206,15 @@ static int pthread_setspecific(pthread_key_t key, const void *value) { pthread_t t = pthread_self(); - if (key > t->keymax) - { + if (key > t->keymax) { int keymax = (key + 1) * 2; - void **kv = realloc(t->keyval, keymax * sizeof(void *)); + void **kv = realloc(t->keyval, keymax * sizeof (void *)); - if (!kv) return ENOMEM; + if (!kv) + return (ENOMEM); /* Clear new region */ - memset(&kv[t->keymax], 0, (keymax - t->keymax)*sizeof(void*)); + memset(&kv[t->keymax], 0, (keymax - t->keymax)*sizeof (void*)); t->keyval = kv; t->keymax = keymax; @@ -1240,7 +1222,7 @@ static int pthread_setspecific(pthread_key_t key, const void *value) t->keyval[key] = (void *) value; - return 0; + return (0); } @@ -1249,23 +1231,21 @@ static int pthread_spin_init(pthread_spinlock_t *l, int pshared) (void) pshared; *l = 0; - return 0; + return (0); } static int pthread_spin_destroy(pthread_spinlock_t *l) { (void) l; - return 0; + return (0); } /* No-fair spinlock due to lack of knowledge of thread number */ static int pthread_spin_lock(pthread_spinlock_t *l) { - while (_InterlockedExchange(l, EBUSY)) - { + while (_InterlockedExchange(l, EBUSY)) { /* Don't lock the bus whilst waiting */ - while (*l) - { + while (*l) { YieldProcessor(); /* Compiler barrier. Prevent caching of *l */ @@ -1273,12 +1253,12 @@ static int pthread_spin_lock(pthread_spinlock_t *l) } } - return 0; + return (0); } static int pthread_spin_trylock(pthread_spinlock_t *l) { - return _InterlockedExchange(l, EBUSY); + return (_InterlockedExchange(l, EBUSY)); } static int pthread_spin_unlock(pthread_spinlock_t *l) @@ -1288,7 +1268,7 @@ static int pthread_spin_unlock(pthread_spinlock_t *l) *l = 0; - return 0; + return (0); } static int pthread_cond_init(pthread_cond_t *c, pthread_condattr_t *a) @@ -1296,345 +1276,372 @@ static int pthread_cond_init(pthread_cond_t *c, pthread_condattr_t *a) (void) a; InitializeConditionVariable(c); - return 0; + return (0); } static int pthread_cond_signal(pthread_cond_t *c) { WakeConditionVariable(c); - return 0; + return (0); } static int pthread_cond_broadcast(pthread_cond_t *c) { WakeAllConditionVariable(c); - return 0; + return (0); } static int pthread_cond_wait(pthread_cond_t *c, pthread_mutex_t *m) { pthread_testcancel(); SleepConditionVariableCS(c, m, INFINITE); - return 0; + return (0); } static int pthread_cond_destroy(pthread_cond_t *c) { (void) c; - return 0; + return (0); } -static int pthread_cond_timedwait(pthread_cond_t *c, pthread_mutex_t *m, struct timespec *t) +static int +pthread_cond_timedwait(pthread_cond_t *c, pthread_mutex_t *m, + struct timespec *t) { unsigned long long tm = _pthread_rel_time_in_ms(t); pthread_testcancel(); - if (!SleepConditionVariableCS(c, m, tm)) return ETIMEDOUT; + if (!SleepConditionVariableCS(c, m, tm)) + return (ETIMEDOUT); /* We can have a spurious wakeup after the timeout */ - if (!_pthread_rel_time_in_ms(t)) return ETIMEDOUT; + if (!_pthread_rel_time_in_ms(t)) + return (ETIMEDOUT); - return 0; + return (0); } static int pthread_condattr_destroy(pthread_condattr_t *a) { (void) a; - return 0; + return (0); } -#define pthread_condattr_getclock(A, C) ENOTSUP -#define pthread_condattr_setclock(A, C) ENOTSUP +#define pthread_condattr_getclock(A, C) ENOTSUP +#define pthread_condattr_setclock(A, C) ENOTSUP static int pthread_condattr_init(pthread_condattr_t *a) { *a = 0; - return 0; + return (0); } static int pthread_condattr_getpshared(pthread_condattr_t *a, int *s) { *s = *a; - return 0; + return (0); } static int pthread_condattr_setpshared(pthread_condattr_t *a, int s) { *a = s; - return 0; + return (0); } static int pthread_rwlockattr_destroy(pthread_rwlockattr_t *a) { (void) a; - return 0; + return (0); } static int pthread_rwlockattr_init(pthread_rwlockattr_t *a) { *a = 0; - return 0; + return (0); } static int pthread_rwlockattr_getpshared(pthread_rwlockattr_t *a, int *s) { *s = *a; - return 0; + return (0); } static int pthread_rwlockattr_setpshared(pthread_rwlockattr_t *a, int s) { *a = s; - return 0; + return (0); } /* No fork() in windows - so ignore this */ -#define pthread_atfork(F1,F2,F3) 0 +#define pthread_atfork(F1, F2, F3) 0 /* Windows has rudimentary signals support */ -#define pthread_kill(T, S) 0 -#define pthread_sigmask(H, S1, S2) 0 +#define pthread_kill(T, S) 0 +#define pthread_sigmask(H, S1, S2) 0 #if 0 /* Wrap cancellation points */ -#define accept(...) (pthread_testcancel(), accept(__VA_ARGS__)) -#define aio_suspend(...) (pthread_testcancel(), aio_suspend(__VA_ARGS__)) -#define clock_nanosleep(...) (pthread_testcancel(), clock_nanosleep(__VA_ARGS__)) -#define close(...) (pthread_testcancel(), close(__VA_ARGS__)) -#define connect(...) (pthread_testcancel(), connect(__VA_ARGS__)) -#define creat(...) (pthread_testcancel(), creat(__VA_ARGS__)) -#define fcntl(...) (pthread_testcancel(), fcntl(__VA_ARGS__)) -#define fdatasync(...) (pthread_testcancel(), fdatasync(__VA_ARGS__)) -#define fsync(...) (pthread_testcancel(), fsync(__VA_ARGS__)) -#define getmsg(...) (pthread_testcancel(), getmsg(__VA_ARGS__)) -#define getpmsg(...) (pthread_testcancel(), getpmsg(__VA_ARGS__)) -#define lockf(...) (pthread_testcancel(), lockf(__VA_ARGS__)) -#define mg_receive(...) (pthread_testcancel(), mg_receive(__VA_ARGS__)) -#define mg_send(...) (pthread_testcancel(), mg_send(__VA_ARGS__)) -#define mg_timedreceive(...) (pthread_testcancel(), mg_timedreceive(__VA_ARGS__)) -#define mg_timessend(...) (pthread_testcancel(), mg_timedsend(__VA_ARGS__)) -#define msgrcv(...) (pthread_testcancel(), msgrecv(__VA_ARGS__)) -#define msgsnd(...) (pthread_testcancel(), msgsnd(__VA_ARGS__)) -#define msync(...) (pthread_testcancel(), msync(__VA_ARGS__)) -#define nanosleep(...) (pthread_testcancel(), nanosleep(__VA_ARGS__)) -#define open(...) (pthread_testcancel(), open(__VA_ARGS__)) -#define pause(...) (pthread_testcancel(), pause(__VA_ARGS__)) -#define poll(...) (pthread_testcancel(), poll(__VA_ARGS__)) -#define pread(...) (pthread_testcancel(), pread(__VA_ARGS__)) -#define pselect(...) (pthread_testcancel(), pselect(__VA_ARGS__)) -#define putmsg(...) (pthread_testcancel(), putmsg(__VA_ARGS__)) -#define putpmsg(...) (pthread_testcancel(), putpmsg(__VA_ARGS__)) -#define pwrite(...) (pthread_testcancel(), pwrite(__VA_ARGS__)) -#define read(...) (pthread_testcancel(), read(__VA_ARGS__)) -#define readv(...) (pthread_testcancel(), readv(__VA_ARGS__)) -#define recv(...) (pthread_testcancel(), recv(__VA_ARGS__)) -#define recvfrom(...) (pthread_testcancel(), recvfrom(__VA_ARGS__)) -#define recvmsg(...) (pthread_testcancel(), recvmsg(__VA_ARGS__)) -#define select(...) (pthread_testcancel(), select(__VA_ARGS__)) -#define sem_timedwait(...) (pthread_testcancel(), sem_timedwait(__VA_ARGS__)) -#define sem_wait(...) (pthread_testcancel(), sem_wait(__VA_ARGS__)) -#define send(...) (pthread_testcancel(), send(__VA_ARGS__)) -#define sendmsg(...) (pthread_testcancel(), sendmsg(__VA_ARGS__)) -#define sendto(...) (pthread_testcancel(), sendto(__VA_ARGS__)) -#define sigpause(...) (pthread_testcancel(), sigpause(__VA_ARGS__)) -#define sigsuspend(...) (pthread_testcancel(), sigsuspend(__VA_ARGS__)) -#define sigwait(...) (pthread_testcancel(), sigwait(__VA_ARGS__)) -#define sigwaitinfo(...) (pthread_testcancel(), sigwaitinfo(__VA_ARGS__)) -#define sleep(...) (pthread_testcancel(), sleep(__VA_ARGS__)) -//#define Sleep(...) (pthread_testcancel(), Sleep(__VA_ARGS__)) -#define system(...) (pthread_testcancel(), system(__VA_ARGS__)) - - -#define access(...) (pthread_testcancel(), access(__VA_ARGS__)) -#define asctime(...) (pthread_testcancel(), asctime(__VA_ARGS__)) -#define asctime_r(...) (pthread_testcancel(), asctime_r(__VA_ARGS__)) -#define catclose(...) (pthread_testcancel(), catclose(__VA_ARGS__)) -#define catgets(...) (pthread_testcancel(), catgets(__VA_ARGS__)) -#define catopen(...) (pthread_testcancel(), catopen(__VA_ARGS__)) -#define closedir(...) (pthread_testcancel(), closedir(__VA_ARGS__)) -#define closelog(...) (pthread_testcancel(), closelog(__VA_ARGS__)) -#define ctermid(...) (pthread_testcancel(), ctermid(__VA_ARGS__)) -#define ctime(...) (pthread_testcancel(), ctime(__VA_ARGS__)) -#define ctime_r(...) (pthread_testcancel(), ctime_r(__VA_ARGS__)) -#define dbm_close(...) (pthread_testcancel(), dbm_close(__VA_ARGS__)) -#define dbm_delete(...) (pthread_testcancel(), dbm_delete(__VA_ARGS__)) -#define dbm_fetch(...) (pthread_testcancel(), dbm_fetch(__VA_ARGS__)) -#define dbm_nextkey(...) (pthread_testcancel(), dbm_nextkey(__VA_ARGS__)) -#define dbm_open(...) (pthread_testcancel(), dbm_open(__VA_ARGS__)) -#define dbm_store(...) (pthread_testcancel(), dbm_store(__VA_ARGS__)) -#define dlclose(...) (pthread_testcancel(), dlclose(__VA_ARGS__)) -#define dlopen(...) (pthread_testcancel(), dlopen(__VA_ARGS__)) -#define endgrent(...) (pthread_testcancel(), endgrent(__VA_ARGS__)) -#define endhostent(...) (pthread_testcancel(), endhostent(__VA_ARGS__)) -#define endnetent(...) (pthread_testcancel(), endnetent(__VA_ARGS__)) -#define endprotoent(...) (pthread_testcancel(), endprotoend(__VA_ARGS__)) -#define endpwent(...) (pthread_testcancel(), endpwent(__VA_ARGS__)) -#define endservent(...) (pthread_testcancel(), endservent(__VA_ARGS__)) -#define endutxent(...) (pthread_testcancel(), endutxent(__VA_ARGS__)) -#define fclose(...) (pthread_testcancel(), fclose(__VA_ARGS__)) -#define fflush(...) (pthread_testcancel(), fflush(__VA_ARGS__)) -#define fgetc(...) (pthread_testcancel(), fgetc(__VA_ARGS__)) -#define fgetpos(...) (pthread_testcancel(), fgetpos(__VA_ARGS__)) -#define fgets(...) (pthread_testcancel(), fgets(__VA_ARGS__)) -#define fgetwc(...) (pthread_testcancel(), fgetwc(__VA_ARGS__)) -#define fgetws(...) (pthread_testcancel(), fgetws(__VA_ARGS__)) -#define fmtmsg(...) (pthread_testcancel(), fmtmsg(__VA_ARGS__)) -#define fopen(...) (pthread_testcancel(), fopen(__VA_ARGS__)) -#define fpathconf(...) (pthread_testcancel(), fpathconf(__VA_ARGS__)) -#define fprintf(...) (pthread_testcancel(), fprintf(__VA_ARGS__)) -#define fputc(...) (pthread_testcancel(), fputc(__VA_ARGS__)) -#define fputs(...) (pthread_testcancel(), fputs(__VA_ARGS__)) -#define fputwc(...) (pthread_testcancel(), fputwc(__VA_ARGS__)) -#define fputws(...) (pthread_testcancel(), fputws(__VA_ARGS__)) -#define fread(...) (pthread_testcancel(), fread(__VA_ARGS__)) -#define freopen(...) (pthread_testcancel(), freopen(__VA_ARGS__)) -#define fscanf(...) (pthread_testcancel(), fscanf(__VA_ARGS__)) -#define fseek(...) (pthread_testcancel(), fseek(__VA_ARGS__)) -#define fseeko(...) (pthread_testcancel(), fseeko(__VA_ARGS__)) -#define fsetpos(...) (pthread_testcancel(), fsetpos(__VA_ARGS__)) -#define fstat(...) (pthread_testcancel(), fstat(__VA_ARGS__)) -#define ftell(...) (pthread_testcancel(), ftell(__VA_ARGS__)) -#define ftello(...) (pthread_testcancel(), ftello(__VA_ARGS__)) -#define ftw(...) (pthread_testcancel(), ftw(__VA_ARGS__)) -#define fwprintf(...) (pthread_testcancel(), fwprintf(__VA_ARGS__)) -#define fwrite(...) (pthread_testcancel(), fwrite(__VA_ARGS__)) -#define fwscanf(...) (pthread_testcancel(), fwscanf(__VA_ARGS__)) -#define getaddrinfo(...) (pthread_testcancel(), getaddrinfo(__VA_ARGS__)) -#define getc(...) (pthread_testcancel(), getc(__VA_ARGS__)) -#define getc_unlocked(...) (pthread_testcancel(), getc_unlocked(__VA_ARGS__)) -#define getchar(...) (pthread_testcancel(), getchar(__VA_ARGS__)) -#define getchar_unlocked(...) (pthread_testcancel(), getchar_unlocked(__VA_ARGS__)) -#define getcwd(...) (pthread_testcancel(), getcwd(__VA_ARGS__)) -#define getdate(...) (pthread_testcancel(), getdate(__VA_ARGS__)) -#define getgrent(...) (pthread_testcancel(), getgrent(__VA_ARGS__)) -#define getgrgid(...) (pthread_testcancel(), getgrgid(__VA_ARGS__)) -#define getgrgid_r(...) (pthread_testcancel(), getgrgid_r(__VA_ARGS__)) -#define gergrnam(...) (pthread_testcancel(), getgrnam(__VA_ARGS__)) -#define getgrnam_r(...) (pthread_testcancel(), getgrnam_r(__VA_ARGS__)) -#define gethostbyaddr(...) (pthread_testcancel(), gethostbyaddr(__VA_ARGS__)) -#define gethostbyname(...) (pthread_testcancel(), gethostbyname(__VA_ARGS__)) -#define gethostent(...) (pthread_testcancel(), gethostent(__VA_ARGS__)) -#define gethostid(...) (pthread_testcancel(), gethostid(__VA_ARGS__)) -#define gethostname(...) (pthread_testcancel(), gethostname(__VA_ARGS__)) -#define getlogin(...) (pthread_testcancel(), getlogin(__VA_ARGS__)) -#define getlogin_r(...) (pthread_testcancel(), getlogin_r(__VA_ARGS__)) -#define getnameinfo(...) (pthread_testcancel(), getnameinfo(__VA_ARGS__)) -#define getnetbyaddr(...) (pthread_testcancel(), getnetbyaddr(__VA_ARGS__)) -#define getnetbyname(...) (pthread_testcancel(), getnetbyname(__VA_ARGS__)) -#define getnetent(...) (pthread_testcancel(), getnetent(__VA_ARGS__)) -#define getopt(...) (pthread_testcancel(), getopt(__VA_ARGS__)) -#define getprotobyname(...) (pthread_testcancel(), getprotobyname(__VA_ARGS__)) -#define getprotobynumber(...) (pthread_testcancel(), getprotobynumber(__VA_ARGS__)) -#define getprotoent(...) (pthread_testcancel(), getprotoent(__VA_ARGS__)) -#define getpwent(...) (pthread_testcancel(), getpwent(__VA_ARGS__)) -#define getpwnam(...) (pthread_testcancel(), getpwnam(__VA_ARGS__)) -#define getpwnam_r(...) (pthread_testcancel(), getpwnam_r(__VA_ARGS__)) -#define getpwuid(...) (pthread_testcancel(), getpwuid(__VA_ARGS__)) -#define getpwuid_r(...) (pthread_testcancel(), getpwuid_r(__VA_ARGS__)) -#define gets(...) (pthread_testcancel(), gets(__VA_ARGS__)) -#define getservbyname(...) (pthread_testcancel(), getservbyname(__VA_ARGS__)) -#define getservbyport(...) (pthread_testcancel(), getservbyport(__VA_ARGS__)) -#define getservent(...) (pthread_testcancel(), getservent(__VA_ARGS__)) -#define getutxent(...) (pthread_testcancel(), getutxent(__VA_ARGS__)) -#define getutxid(...) (pthread_testcancel(), getutxid(__VA_ARGS__)) -#define getutxline(...) (pthread_testcancel(), getutxline(__VA_ARGS__)) +#define accept(...) (pthread_testcancel(), accept(__VA_ARGS__)) +#define aio_suspend(...) (pthread_testcancel(), aio_suspend(__VA_ARGS__)) +#define clock_nanosleep(...) \ + (pthread_testcancel(), clock_nanosleep(__VA_ARGS__)) +#define close(...) (pthread_testcancel(), close(__VA_ARGS__)) +#define connect(...) (pthread_testcancel(), connect(__VA_ARGS__)) +#define creat(...) (pthread_testcancel(), creat(__VA_ARGS__)) +#define fcntl(...) (pthread_testcancel(), fcntl(__VA_ARGS__)) +#define fdatasync(...) (pthread_testcancel(), fdatasync(__VA_ARGS__)) +#define fsync(...) (pthread_testcancel(), fsync(__VA_ARGS__)) +#define getmsg(...) (pthread_testcancel(), getmsg(__VA_ARGS__)) +#define getpmsg(...) (pthread_testcancel(), getpmsg(__VA_ARGS__)) +#define lockf(...) (pthread_testcancel(), lockf(__VA_ARGS__)) +#define mg_receive(...) (pthread_testcancel(), mg_receive(__VA_ARGS__)) +#define mg_send(...) (pthread_testcancel(), mg_send(__VA_ARGS__)) +#define mg_timedreceive(...) \ + (pthread_testcancel(), mg_timedreceive(__VA_ARGS__)) +#define mg_timessend(...) (pthread_testcancel(), mg_timedsend(__VA_ARGS__)) +#define msgrcv(...) (pthread_testcancel(), msgrecv(__VA_ARGS__)) +#define msgsnd(...) (pthread_testcancel(), msgsnd(__VA_ARGS__)) +#define msync(...) (pthread_testcancel(), msync(__VA_ARGS__)) +#define nanosleep(...) (pthread_testcancel(), nanosleep(__VA_ARGS__)) +#define open(...) (pthread_testcancel(), open(__VA_ARGS__)) +#define pause(...) (pthread_testcancel(), pause(__VA_ARGS__)) +#define poll(...) (pthread_testcancel(), poll(__VA_ARGS__)) +#define pread(...) (pthread_testcancel(), pread(__VA_ARGS__)) +#define pselect(...) (pthread_testcancel(), pselect(__VA_ARGS__)) +#define putmsg(...) (pthread_testcancel(), putmsg(__VA_ARGS__)) +#define putpmsg(...) (pthread_testcancel(), putpmsg(__VA_ARGS__)) +#define pwrite(...) (pthread_testcancel(), pwrite(__VA_ARGS__)) +#define read(...) (pthread_testcancel(), read(__VA_ARGS__)) +#define readv(...) (pthread_testcancel(), readv(__VA_ARGS__)) +#define recv(...) (pthread_testcancel(), recv(__VA_ARGS__)) +#define recvfrom(...) (pthread_testcancel(), recvfrom(__VA_ARGS__)) +#define recvmsg(...) (pthread_testcancel(), recvmsg(__VA_ARGS__)) +#define select(...) (pthread_testcancel(), select(__VA_ARGS__)) +#define sem_timedwait(...) (pthread_testcancel(), sem_timedwait(__VA_ARGS__)) +#define sem_wait(...) (pthread_testcancel(), sem_wait(__VA_ARGS__)) +#define send(...) (pthread_testcancel(), send(__VA_ARGS__)) +#define sendmsg(...) (pthread_testcancel(), sendmsg(__VA_ARGS__)) +#define sendto(...) (pthread_testcancel(), sendto(__VA_ARGS__)) +#define sigpause(...) (pthread_testcancel(), sigpause(__VA_ARGS__)) +#define sigsuspend(...) (pthread_testcancel(), sigsuspend(__VA_ARGS__)) +#define sigwait(...) (pthread_testcancel(), sigwait(__VA_ARGS__)) +#define sigwaitinfo(...) (pthread_testcancel(), sigwaitinfo(__VA_ARGS__)) +#define sleep(...) (pthread_testcancel(), sleep(__VA_ARGS__)) +// #define Sleep(...) (pthread_testcancel(), Sleep(__VA_ARGS__)) +#define system(...) (pthread_testcancel(), system(__VA_ARGS__)) + + +#define access(...) (pthread_testcancel(), access(__VA_ARGS__)) +#define asctime(...) (pthread_testcancel(), asctime(__VA_ARGS__)) +#define asctime_r(...) (pthread_testcancel(), asctime_r(__VA_ARGS__)) +#define catclose(...) (pthread_testcancel(), catclose(__VA_ARGS__)) +#define catgets(...) (pthread_testcancel(), catgets(__VA_ARGS__)) +#define catopen(...) (pthread_testcancel(), catopen(__VA_ARGS__)) +#define closedir(...) (pthread_testcancel(), closedir(__VA_ARGS__)) +#define closelog(...) (pthread_testcancel(), closelog(__VA_ARGS__)) +#define ctermid(...) (pthread_testcancel(), ctermid(__VA_ARGS__)) +#define ctime(...) (pthread_testcancel(), ctime(__VA_ARGS__)) +#define ctime_r(...) (pthread_testcancel(), ctime_r(__VA_ARGS__)) +#define dbm_close(...) (pthread_testcancel(), dbm_close(__VA_ARGS__)) +#define dbm_delete(...) (pthread_testcancel(), dbm_delete(__VA_ARGS__)) +#define dbm_fetch(...) (pthread_testcancel(), dbm_fetch(__VA_ARGS__)) +#define dbm_nextkey(...) (pthread_testcancel(), dbm_nextkey(__VA_ARGS__)) +#define dbm_open(...) (pthread_testcancel(), dbm_open(__VA_ARGS__)) +#define dbm_store(...) (pthread_testcancel(), dbm_store(__VA_ARGS__)) +#define dlclose(...) (pthread_testcancel(), dlclose(__VA_ARGS__)) +#define dlopen(...) (pthread_testcancel(), dlopen(__VA_ARGS__)) +#define endgrent(...) (pthread_testcancel(), endgrent(__VA_ARGS__)) +#define endhostent(...) (pthread_testcancel(), endhostent(__VA_ARGS__)) +#define endnetent(...) (pthread_testcancel(), endnetent(__VA_ARGS__)) +#define endprotoent(...) (pthread_testcancel(), endprotoend(__VA_ARGS__)) +#define endpwent(...) (pthread_testcancel(), endpwent(__VA_ARGS__)) +#define endservent(...) (pthread_testcancel(), endservent(__VA_ARGS__)) +#define endutxent(...) (pthread_testcancel(), endutxent(__VA_ARGS__)) +#define fclose(...) (pthread_testcancel(), fclose(__VA_ARGS__)) +#define fflush(...) (pthread_testcancel(), fflush(__VA_ARGS__)) +#define fgetc(...) (pthread_testcancel(), fgetc(__VA_ARGS__)) +#define fgetpos(...) (pthread_testcancel(), fgetpos(__VA_ARGS__)) +#define fgets(...) (pthread_testcancel(), fgets(__VA_ARGS__)) +#define fgetwc(...) (pthread_testcancel(), fgetwc(__VA_ARGS__)) +#define fgetws(...) (pthread_testcancel(), fgetws(__VA_ARGS__)) +#define fmtmsg(...) (pthread_testcancel(), fmtmsg(__VA_ARGS__)) +#define fopen(...) (pthread_testcancel(), fopen(__VA_ARGS__)) +#define fpathconf(...) (pthread_testcancel(), fpathconf(__VA_ARGS__)) +#define fprintf(...) (pthread_testcancel(), fprintf(__VA_ARGS__)) +#define fputc(...) (pthread_testcancel(), fputc(__VA_ARGS__)) +#define fputs(...) (pthread_testcancel(), fputs(__VA_ARGS__)) +#define fputwc(...) (pthread_testcancel(), fputwc(__VA_ARGS__)) +#define fputws(...) (pthread_testcancel(), fputws(__VA_ARGS__)) +#define fread(...) (pthread_testcancel(), fread(__VA_ARGS__)) +#define freopen(...) (pthread_testcancel(), freopen(__VA_ARGS__)) +#define fscanf(...) (pthread_testcancel(), fscanf(__VA_ARGS__)) +#define fseek(...) (pthread_testcancel(), fseek(__VA_ARGS__)) +#define fseeko(...) (pthread_testcancel(), fseeko(__VA_ARGS__)) +#define fsetpos(...) (pthread_testcancel(), fsetpos(__VA_ARGS__)) +#define fstat(...) (pthread_testcancel(), fstat(__VA_ARGS__)) +#define ftell(...) (pthread_testcancel(), ftell(__VA_ARGS__)) +#define ftello(...) (pthread_testcancel(), ftello(__VA_ARGS__)) +#define ftw(...) (pthread_testcancel(), ftw(__VA_ARGS__)) +#define fwprintf(...) (pthread_testcancel(), fwprintf(__VA_ARGS__)) +#define fwrite(...) (pthread_testcancel(), fwrite(__VA_ARGS__)) +#define fwscanf(...) (pthread_testcancel(), fwscanf(__VA_ARGS__)) +#define getaddrinfo(...) (pthread_testcancel(), getaddrinfo(__VA_ARGS__)) +#define getc(...) (pthread_testcancel(), getc(__VA_ARGS__)) +#define getc_unlocked(...) (pthread_testcancel(), getc_unlocked(__VA_ARGS__)) +#define getchar(...) (pthread_testcancel(), getchar(__VA_ARGS__)) +#define getchar_unlocked(...) \ + (pthread_testcancel(), getchar_unlocked(__VA_ARGS__)) +#define getcwd(...) (pthread_testcancel(), getcwd(__VA_ARGS__)) +#define getdate(...) (pthread_testcancel(), getdate(__VA_ARGS__)) +#define getgrent(...) (pthread_testcancel(), getgrent(__VA_ARGS__)) +#define getgrgid(...) (pthread_testcancel(), getgrgid(__VA_ARGS__)) +#define getgrgid_r(...) (pthread_testcancel(), getgrgid_r(__VA_ARGS__)) +#define gergrnam(...) (pthread_testcancel(), getgrnam(__VA_ARGS__)) +#define getgrnam_r(...) (pthread_testcancel(), getgrnam_r(__VA_ARGS__)) +#define gethostbyaddr(...) (pthread_testcancel(), gethostbyaddr(__VA_ARGS__)) +#define gethostbyname(...) (pthread_testcancel(), gethostbyname(__VA_ARGS__)) +#define gethostent(...) (pthread_testcancel(), gethostent(__VA_ARGS__)) +#define gethostid(...) (pthread_testcancel(), gethostid(__VA_ARGS__)) +#define gethostname(...) (pthread_testcancel(), gethostname(__VA_ARGS__)) +#define getlogin(...) (pthread_testcancel(), getlogin(__VA_ARGS__)) +#define getlogin_r(...) (pthread_testcancel(), getlogin_r(__VA_ARGS__)) +#define getnameinfo(...) (pthread_testcancel(), getnameinfo(__VA_ARGS__)) +#define getnetbyaddr(...) (pthread_testcancel(), getnetbyaddr(__VA_ARGS__)) +#define getnetbyname(...) (pthread_testcancel(), getnetbyname(__VA_ARGS__)) +#define getnetent(...) (pthread_testcancel(), getnetent(__VA_ARGS__)) +#define getopt(...) (pthread_testcancel(), getopt(__VA_ARGS__)) +#define getprotobyname(...) (pthread_testcancel(), getprotobyname(__VA_ARGS__)) +#define getprotobynumber(...) \ + (pthread_testcancel(), getprotobynumber(__VA_ARGS__)) +#define getprotoent(...) (pthread_testcancel(), getprotoent(__VA_ARGS__)) +#define getpwent(...) (pthread_testcancel(), getpwent(__VA_ARGS__)) +#define getpwnam(...) (pthread_testcancel(), getpwnam(__VA_ARGS__)) +#define getpwnam_r(...) (pthread_testcancel(), getpwnam_r(__VA_ARGS__)) +#define getpwuid(...) (pthread_testcancel(), getpwuid(__VA_ARGS__)) +#define getpwuid_r(...) (pthread_testcancel(), getpwuid_r(__VA_ARGS__)) +#define gets(...) (pthread_testcancel(), gets(__VA_ARGS__)) +#define getservbyname(...) (pthread_testcancel(), getservbyname(__VA_ARGS__)) +#define getservbyport(...) (pthread_testcancel(), getservbyport(__VA_ARGS__)) +#define getservent(...) (pthread_testcancel(), getservent(__VA_ARGS__)) +#define getutxent(...) (pthread_testcancel(), getutxent(__VA_ARGS__)) +#define getutxid(...) (pthread_testcancel(), getutxid(__VA_ARGS__)) +#define getutxline(...) (pthread_testcancel(), getutxline(__VA_ARGS__)) #undef getwc -#define getwc(...) (pthread_testcancel(), getwc(__VA_ARGS__)) +#define getwc(...) (pthread_testcancel(), getwc(__VA_ARGS__)) #undef getwchar -#define getwchar(...) (pthread_testcancel(), getwchar(__VA_ARGS__)) -#define getwd(...) (pthread_testcancel(), getwd(__VA_ARGS__)) -#define glob(...) (pthread_testcancel(), glob(__VA_ARGS__)) -#define iconv_close(...) (pthread_testcancel(), iconv_close(__VA_ARGS__)) -#define iconv_open(...) (pthread_testcancel(), iconv_open(__VA_ARGS__)) -#define ioctl(...) (pthread_testcancel(), ioctl(__VA_ARGS__)) -#define link(...) (pthread_testcancel(), link(__VA_ARGS__)) -#define localtime(...) (pthread_testcancel(), localtime(__VA_ARGS__)) -#define localtime_r(...) (pthread_testcancel(), localtime_r(__VA_ARGS__)) -#define lseek(...) (pthread_testcancel(), lseek(__VA_ARGS__)) -#define lstat(...) (pthread_testcancel(), lstat(__VA_ARGS__)) -#define mkstemp(...) (pthread_testcancel(), mkstemp(__VA_ARGS__)) -#define nftw(...) (pthread_testcancel(), nftw(__VA_ARGS__)) -#define opendir(...) (pthread_testcancel(), opendir(__VA_ARGS__)) -#define openlog(...) (pthread_testcancel(), openlog(__VA_ARGS__)) -#define pathconf(...) (pthread_testcancel(), pathconf(__VA_ARGS__)) -#define pclose(...) (pthread_testcancel(), pclose(__VA_ARGS__)) -#define perror(...) (pthread_testcancel(), perror(__VA_ARGS__)) -#define popen(...) (pthread_testcancel(), popen(__VA_ARGS__)) -#define posix_fadvise(...) (pthread_testcancel(), posix_fadvise(__VA_ARGS__)) -#define posix_fallocate(...) (pthread_testcancel(), posix_fallocate(__VA_ARGS__)) -#define posix_madvise(...) (pthread_testcancel(), posix_madvise(__VA_ARGS__)) -#define posix_openpt(...) (pthread_testcancel(), posix_openpt(__VA_ARGS__)) -#define posix_spawn(...) (pthread_testcancel(), posix_spawn(__VA_ARGS__)) -#define posix_spawnp(...) (pthread_testcancel(), posix_spawnp(__VA_ARGS__)) -#define posix_trace_clear(...) (pthread_testcancel(), posix_trace_clear(__VA_ARGS__)) -#define posix_trace_close(...) (pthread_testcancel(), posix_trace_close(__VA_ARGS__)) -#define posix_trace_create(...) (pthread_testcancel(), posix_trace_create(__VA_ARGS__)) -#define posix_trace_create_withlog(...) (pthread_testcancel(), posix_trace_create_withlog(__VA_ARGS__)) -#define posix_trace_eventtypelist_getne(...) (pthread_testcancel(), posix_trace_eventtypelist_getne(__VA_ARGS__)) -#define posix_trace_eventtypelist_rewin(...) (pthread_testcancel(), posix_trace_eventtypelist_rewin(__VA_ARGS__)) -#define posix_trace_flush(...) (pthread_testcancel(), posix_trace_flush(__VA_ARGS__)) -#define posix_trace_get_attr(...) (pthread_testcancel(), posix_trace_get_attr(__VA_ARGS__)) -#define posix_trace_get_filter(...) (pthread_testcancel(), posix_trace_get_filter(__VA_ARGS__)) -#define posix_trace_get_status(...) (pthread_testcancel(), posix_trace_get_status(__VA_ARGS__)) -#define posix_trace_getnext_event(...) (pthread_testcancel(), posix_trace_getnext_event(__VA_ARGS__)) -#define posix_trace_open(...) (pthread_testcancel(), posix_trace_open(__VA_ARGS__)) -#define posix_trace_rewind(...) (pthread_testcancel(), posix_trace_rewind(__VA_ARGS__)) -#define posix_trace_setfilter(...) (pthread_testcancel(), posix_trace_setfilter(__VA_ARGS__)) -#define posix_trace_shutdown(...) (pthread_testcancel(), posix_trace_shutdown(__VA_ARGS__)) -#define posix_trace_timedgetnext_event(...) (pthread_testcancel(), posix_trace_timedgetnext_event(__VA_ARGS__)) -#define posix_typed_mem_open(...) (pthread_testcancel(), posix_typed_mem_open(__VA_ARGS__)) -#define printf(...) (pthread_testcancel(), printf(__VA_ARGS__)) -#define putc(...) (pthread_testcancel(), putc(__VA_ARGS__)) -#define putc_unlocked(...) (pthread_testcancel(), putc_unlocked(__VA_ARGS__)) -#define putchar(...) (pthread_testcancel(), putchar(__VA_ARGS__)) -#define putchar_unlocked(...) (pthread_testcancel(), putchar_unlocked(__VA_ARGS__)) -#define puts(...) (pthread_testcancel(), puts(__VA_ARGS__)) -#define pututxline(...) (pthread_testcancel(), pututxline(__VA_ARGS__)) +#define getwchar(...) (pthread_testcancel(), getwchar(__VA_ARGS__)) +#define getwd(...) (pthread_testcancel(), getwd(__VA_ARGS__)) +#define glob(...) (pthread_testcancel(), glob(__VA_ARGS__)) +#define iconv_close(...) (pthread_testcancel(), iconv_close(__VA_ARGS__)) +#define iconv_open(...) (pthread_testcancel(), iconv_open(__VA_ARGS__)) +#define ioctl(...) (pthread_testcancel(), ioctl(__VA_ARGS__)) +#define link(...) (pthread_testcancel(), link(__VA_ARGS__)) +#define localtime(...) (pthread_testcancel(), localtime(__VA_ARGS__)) +#define localtime_r(...) (pthread_testcancel(), localtime_r(__VA_ARGS__)) +#define lseek(...) (pthread_testcancel(), lseek(__VA_ARGS__)) +#define lstat(...) (pthread_testcancel(), lstat(__VA_ARGS__)) +#define mkstemp(...) (pthread_testcancel(), mkstemp(__VA_ARGS__)) +#define nftw(...) (pthread_testcancel(), nftw(__VA_ARGS__)) +#define opendir(...) (pthread_testcancel(), opendir(__VA_ARGS__)) +#define openlog(...) (pthread_testcancel(), openlog(__VA_ARGS__)) +#define pathconf(...) (pthread_testcancel(), pathconf(__VA_ARGS__)) +#define pclose(...) (pthread_testcancel(), pclose(__VA_ARGS__)) +#define perror(...) (pthread_testcancel(), perror(__VA_ARGS__)) +#define popen(...) (pthread_testcancel(), popen(__VA_ARGS__)) +#define posix_fadvise(...) (pthread_testcancel(), posix_fadvise(__VA_ARGS__)) +#define posix_fallocate(...) \ + (pthread_testcancel(), posix_fallocate(__VA_ARGS__)) +#define posix_madvise(...) (pthread_testcancel(), posix_madvise(__VA_ARGS__)) +#define posix_openpt(...) (pthread_testcancel(), posix_openpt(__VA_ARGS__)) +#define posix_spawn(...) (pthread_testcancel(), posix_spawn(__VA_ARGS__)) +#define posix_spawnp(...) (pthread_testcancel(), posix_spawnp(__VA_ARGS__)) +#define posix_trace_clear(...) \ + (pthread_testcancel(), posix_trace_clear(__VA_ARGS__)) +#define posix_trace_close(...) \ + (pthread_testcancel(), posix_trace_close(__VA_ARGS__)) +#define posix_trace_create(...) \ + (pthread_testcancel(), posix_trace_create(__VA_ARGS__)) +#define posix_trace_create_withlog(...) \ + (pthread_testcancel(), posix_trace_create_withlog(__VA_ARGS__)) +#define posix_trace_eventtypelist_getne(...) \ + (pthread_testcancel(), posix_trace_eventtypelist_getne(__VA_ARGS__)) +#define posix_trace_eventtypelist_rewin(...) \ + (pthread_testcancel(), posix_trace_eventtypelist_rewin(__VA_ARGS__)) +#define posix_trace_flush(...) \ + (pthread_testcancel(), posix_trace_flush(__VA_ARGS__)) +#define posix_trace_get_attr(...) \ + (pthread_testcancel(), posix_trace_get_attr(__VA_ARGS__)) +#define posix_trace_get_filter(...) \ + (pthread_testcancel(), posix_trace_get_filter(__VA_ARGS__)) +#define posix_trace_get_status(...) \ + (pthread_testcancel(), posix_trace_get_status(__VA_ARGS__)) +#define posix_trace_getnext_event(...) \ + (pthread_testcancel(), posix_trace_getnext_event(__VA_ARGS__)) +#define posix_trace_open(...) \ + (pthread_testcancel(), posix_trace_open(__VA_ARGS__)) +#define posix_trace_rewind(...) \ + (pthread_testcancel(), posix_trace_rewind(__VA_ARGS__)) +#define posix_trace_setfilter(...) \ + (pthread_testcancel(), posix_trace_setfilter(__VA_ARGS__)) +#define posix_trace_shutdown(...) \ + (pthread_testcancel(), posix_trace_shutdown(__VA_ARGS__)) +#define posix_trace_timedgetnext_event(...) \ + (pthread_testcancel(), posix_trace_timedgetnext_event(__VA_ARGS__)) +#define posix_typed_mem_open(...) \ + (pthread_testcancel(), posix_typed_mem_open(__VA_ARGS__)) +#define printf(...) (pthread_testcancel(), printf(__VA_ARGS__)) +#define putc(...) (pthread_testcancel(), putc(__VA_ARGS__)) +#define putc_unlocked(...) (pthread_testcancel(), putc_unlocked(__VA_ARGS__)) +#define putchar(...) (pthread_testcancel(), putchar(__VA_ARGS__)) +#define putchar_unlocked(...) \ + (pthread_testcancel(), putchar_unlocked(__VA_ARGS__)) +#define puts(...) (pthread_testcancel(), puts(__VA_ARGS__)) +#define pututxline(...) (pthread_testcancel(), pututxline(__VA_ARGS__)) #undef putwc -#define putwc(...) (pthread_testcancel(), putwc(__VA_ARGS__)) +#define putwc(...) (pthread_testcancel(), putwc(__VA_ARGS__)) #undef putwchar -#define putwchar(...) (pthread_testcancel(), putwchar(__VA_ARGS__)) -#define readdir(...) (pthread_testcancel(), readdir(__VA_ARSG__)) -#define readdir_r(...) (pthread_testcancel(), readdir_r(__VA_ARGS__)) -#define remove(...) (pthread_testcancel(), remove(__VA_ARGS__)) -#define rename(...) (pthread_testcancel(), rename(__VA_ARGS__)) -#define rewind(...) (pthread_testcancel(), rewind(__VA_ARGS__)) -#define rewinddir(...) (pthread_testcancel(), rewinddir(__VA_ARGS__)) -#define scanf(...) (pthread_testcancel(), scanf(__VA_ARGS__)) -#define seekdir(...) (pthread_testcancel(), seekdir(__VA_ARGS__)) -#define semop(...) (pthread_testcancel(), semop(__VA_ARGS__)) -#define setgrent(...) (pthread_testcancel(), setgrent(__VA_ARGS__)) -#define sethostent(...) (pthread_testcancel(), sethostemt(__VA_ARGS__)) -#define setnetent(...) (pthread_testcancel(), setnetent(__VA_ARGS__)) -#define setprotoent(...) (pthread_testcancel(), setprotoent(__VA_ARGS__)) -#define setpwent(...) (pthread_testcancel(), setpwent(__VA_ARGS__)) -#define setservent(...) (pthread_testcancel(), setservent(__VA_ARGS__)) -#define setutxent(...) (pthread_testcancel(), setutxent(__VA_ARGS__)) -#define stat(...) (pthread_testcancel(), stat(__VA_ARGS__)) -#define strerror(...) (pthread_testcancel(), strerror(__VA_ARGS__)) -#define strerror_r(...) (pthread_testcancel(), strerror_r(__VA_ARGS__)) -#define strftime(...) (pthread_testcancel(), strftime(__VA_ARGS__)) -#define symlink(...) (pthread_testcancel(), symlink(__VA_ARGS__)) -#define sync(...) (pthread_testcancel(), sync(__VA_ARGS__)) -#define syslog(...) (pthread_testcancel(), syslog(__VA_ARGS__)) -#define tmpfile(...) (pthread_testcancel(), tmpfile(__VA_ARGS__)) -#define tmpnam(...) (pthread_testcancel(), tmpnam(__VA_ARGS__)) -#define ttyname(...) (pthread_testcancel(), ttyname(__VA_ARGS__)) -#define ttyname_r(...) (pthread_testcancel(), ttyname_r(__VA_ARGS__)) -#define tzset(...) (pthread_testcancel(), tzset(__VA_ARGS__)) -#define ungetc(...) (pthread_testcancel(), ungetc(__VA_ARGS__)) -#define ungetwc(...) (pthread_testcancel(), ungetwc(__VA_ARGS__)) -#define unlink(...) (pthread_testcancel(), unlink(__VA_ARGS__)) -#define vfprintf(...) (pthread_testcancel(), vfprintf(__VA_ARGS__)) -#define vfwprintf(...) (pthread_testcancel(), vfwprintf(__VA_ARGS__)) -#define vprintf(...) (pthread_testcancel(), vprintf(__VA_ARGS__)) -#define vwprintf(...) (pthread_testcancel(), vwprintf(__VA_ARGS__)) -#define wcsftime(...) (pthread_testcancel(), wcsftime(__VA_ARGS__)) -#define wordexp(...) (pthread_testcancel(), wordexp(__VA_ARGS__)) -#define wprintf(...) (pthread_testcancel(), wprintf(__VA_ARGS__)) -#define wscanf(...) (pthread_testcancel(), wscanf(__VA_ARGS__)) +#define putwchar(...) (pthread_testcancel(), putwchar(__VA_ARGS__)) +#define readdir(...) (pthread_testcancel(), readdir(__VA_ARSG__)) +#define readdir_r(...) (pthread_testcancel(), readdir_r(__VA_ARGS__)) +#define remove(...) (pthread_testcancel(), remove(__VA_ARGS__)) +#define rename(...) (pthread_testcancel(), rename(__VA_ARGS__)) +#define rewind(...) (pthread_testcancel(), rewind(__VA_ARGS__)) +#define rewinddir(...) (pthread_testcancel(), rewinddir(__VA_ARGS__)) +#define scanf(...) (pthread_testcancel(), scanf(__VA_ARGS__)) +#define seekdir(...) (pthread_testcancel(), seekdir(__VA_ARGS__)) +#define semop(...) (pthread_testcancel(), semop(__VA_ARGS__)) +#define setgrent(...) (pthread_testcancel(), setgrent(__VA_ARGS__)) +#define sethostent(...) (pthread_testcancel(), sethostemt(__VA_ARGS__)) +#define setnetent(...) (pthread_testcancel(), setnetent(__VA_ARGS__)) +#define setprotoent(...) (pthread_testcancel(), setprotoent(__VA_ARGS__)) +#define setpwent(...) (pthread_testcancel(), setpwent(__VA_ARGS__)) +#define setservent(...) (pthread_testcancel(), setservent(__VA_ARGS__)) +#define setutxent(...) (pthread_testcancel(), setutxent(__VA_ARGS__)) +#define stat(...) (pthread_testcancel(), stat(__VA_ARGS__)) +#define strerror(...) (pthread_testcancel(), strerror(__VA_ARGS__)) +#define strerror_r(...) (pthread_testcancel(), strerror_r(__VA_ARGS__)) +#define strftime(...) (pthread_testcancel(), strftime(__VA_ARGS__)) +#define symlink(...) (pthread_testcancel(), symlink(__VA_ARGS__)) +#define sync(...) (pthread_testcancel(), sync(__VA_ARGS__)) +#define syslog(...) (pthread_testcancel(), syslog(__VA_ARGS__)) +#define tmpfile(...) (pthread_testcancel(), tmpfile(__VA_ARGS__)) +#define tmpnam(...) (pthread_testcancel(), tmpnam(__VA_ARGS__)) +#define ttyname(...) (pthread_testcancel(), ttyname(__VA_ARGS__)) +#define ttyname_r(...) (pthread_testcancel(), ttyname_r(__VA_ARGS__)) +#define tzset(...) (pthread_testcancel(), tzset(__VA_ARGS__)) +#define ungetc(...) (pthread_testcancel(), ungetc(__VA_ARGS__)) +#define ungetwc(...) (pthread_testcancel(), ungetwc(__VA_ARGS__)) +#define unlink(...) (pthread_testcancel(), unlink(__VA_ARGS__)) +#define vfprintf(...) (pthread_testcancel(), vfprintf(__VA_ARGS__)) +#define vfwprintf(...) (pthread_testcancel(), vfwprintf(__VA_ARGS__)) +#define vprintf(...) (pthread_testcancel(), vprintf(__VA_ARGS__)) +#define vwprintf(...) (pthread_testcancel(), vwprintf(__VA_ARGS__)) +#define wcsftime(...) (pthread_testcancel(), wcsftime(__VA_ARGS__)) +#define wordexp(...) (pthread_testcancel(), wordexp(__VA_ARGS__)) +#define wprintf(...) (pthread_testcancel(), wprintf(__VA_ARGS__)) +#define wscanf(...) (pthread_testcancel(), wscanf(__VA_ARGS__)) #endif #if __clang__ diff --git a/lib/os/windows/libuuid/all-io.h b/lib/os/windows/libuuid/all-io.h index fed357dfb11..29959b56888 100644 --- a/lib/os/windows/libuuid/all-io.h +++ b/lib/os/windows/libuuid/all-io.h @@ -7,7 +7,7 @@ */ #ifndef UTIL_LINUX_ALL_IO_H -#define UTIL_LINUX_ALL_IO_H +#define UTIL_LINUX_ALL_IO_H #include #include @@ -26,17 +26,17 @@ static inline int write_all(int fd, const void *buf, size_t count) if (tmp > 0) { count -= tmp; if (count) - buf = (void *) ((char *) buf + tmp); + buf = (void *)((char *)buf + tmp); } else if (errno != EINTR && errno != EAGAIN) - return -1; + return (-1); if (errno == EAGAIN) /* Try later, *sigh* */ usleep(10000); } - return 0; + return (0); } static inline int fwrite_all(const void *ptr, size_t size, - size_t nmemb, FILE *stream) + size_t nmemb, FILE *stream) { while (nmemb) { size_t tmp; @@ -46,13 +46,13 @@ static inline int fwrite_all(const void *ptr, size_t size, if (tmp > 0) { nmemb -= tmp; if (nmemb) - ptr = (void *) ((char *) ptr + (tmp * size)); + ptr = (void *)((char *)ptr + (tmp * size)); } else if (errno != EINTR && errno != EAGAIN) - return -1; + return (-1); if (errno == EAGAIN) /* Try later, *sigh* */ usleep(10000); } - return 0; + return (0); } static inline ssize_t read_all(int fd, char *buf, size_t count) @@ -68,7 +68,7 @@ static inline ssize_t read_all(int fd, char *buf, size_t count) if ((errno == EAGAIN || errno == EINTR || ret == 0) && (tries++ < 5)) continue; - return c ? c : -1; + return (c ? c : -1); } if (ret > 0) tries = 0; @@ -76,7 +76,7 @@ static inline ssize_t read_all(int fd, char *buf, size_t count) buf += ret; c += ret; } - return c; + return (c); } diff --git a/lib/os/windows/libuuid/c.h b/lib/os/windows/libuuid/c.h index 15ee2ad4254..4bd5798bf0b 100644 --- a/lib/os/windows/libuuid/c.h +++ b/lib/os/windows/libuuid/c.h @@ -3,7 +3,7 @@ */ #ifndef UTIL_LINUX_C_H -#define UTIL_LINUX_C_H +#define UTIL_LINUX_C_H #ifdef HAVE_CONFIG_H #include "config.h" @@ -15,9 +15,9 @@ #ifdef HAVE_STDINT_H #include #else -# ifdef HAVE_INTTYPES_H -# include -# endif +#ifdef HAVE_INTTYPES_H +#include +#endif #endif #include @@ -28,86 +28,89 @@ #include #ifdef HAVE_ERR_H -# include +#include #endif #ifndef HAVE_USLEEP -# include +#include #endif /* * Compiler specific stuff */ #ifndef __GNUC_PREREQ -# if defined __GNUC__ && defined __GNUC_MINOR__ -# define __GNUC_PREREQ(maj, min) \ +#if defined __GNUC__ && defined __GNUC_MINOR__ +#define __GNUC_PREREQ(maj, min) \ ((__GNUC__ << 16) + __GNUC_MINOR__ >= ((maj) << 16) + (min)) -# else -# define __GNUC_PREREQ(maj, min) 0 -# endif +#else +#define __GNUC_PREREQ(maj, min) 0 +#endif #endif #ifdef __GNUC__ /* &a[0] degrades to a pointer: a different type from an array */ -# define __must_be_array(a) \ - UL_BUILD_BUG_ON_ZERO(__builtin_types_compatible_p(__typeof__(a), __typeof__(&a[0]))) +#define __must_be_array(a) \ + UL_BUILD_BUG_ON_ZERO(__builtin_types_compatible_p(__typeof__(a), \ + __typeof__(&a[0]))) -# define ignore_result(x) ({ \ - __typeof__(x) __dummy __attribute__((__unused__)) = (x); (void) __dummy; \ +#define ignore_result(x) (/* */ {__typeof__(x) __dummy \ + __attribute__((__unused__)) = (x); (void) __dummy; \ }) #else /* !__GNUC__ */ -# define __must_be_array(a) 0 -# define __attribute__(_arg_) -# define ignore_result(x) ((void) (x)) +#define __must_be_array(a) 0 +#define __attribute__(_arg_) +#define ignore_result(x) ((void) (x)) #endif /* !__GNUC__ */ /* * Function attributes */ #ifndef __ul_alloc_size -# if __GNUC_PREREQ (4, 3) -# define __ul_alloc_size(s) __attribute__((alloc_size(s))) -# else -# define __ul_alloc_size(s) -# endif +#if __GNUC_PREREQ(4, 3) +#define __ul_alloc_size(s) __attribute__((alloc_size(s))) +#else +#define __ul_alloc_size(s) +#endif #endif #ifndef __ul_calloc_size -# if __GNUC_PREREQ (4, 3) -# define __ul_calloc_size(n, s) __attribute__((alloc_size(n, s))) -# else -# define __ul_calloc_size(n, s) -# endif +#if __GNUC_PREREQ(4, 3) +#define __ul_calloc_size(n, s) __attribute__((alloc_size(n, s))) +#else +#define __ul_calloc_size(n, s) +#endif #endif -/* Force a compilation error if condition is true, but also produce a +/* + * Force a compilation error if condition is true, but also produce a * result (of value 0 and type size_t), so the expression can be used * e.g. in a structure initializer (or where-ever else comma expressions * aren't permitted). */ -#define UL_BUILD_BUG_ON_ZERO(e) (sizeof(struct { int:-!!(e); })) -#define BUILD_BUG_ON_NULL(e) ((void *)sizeof(struct { int:-!!(e); })) +#define UL_BUILD_BUG_ON_ZERO(e) (sizeof (struct { int:-!!(e); })) +#define BUILD_BUG_ON_NULL(e) ((void *)sizeof (struct { int:-!!(e); })) #ifndef ARRAY_SIZE -# define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) + __must_be_array(arr)) +#define ARRAY_SIZE(arr) \ + (sizeof (arr) / sizeof ((arr)[0]) + __must_be_array(arr)) #endif #ifndef PATH_MAX -# define PATH_MAX 4096 +#define PATH_MAX 4096 #endif #ifndef TRUE -# define TRUE 1 +#define TRUE 1 #endif #ifndef FALSE -# define FALSE 0 +#define FALSE 0 #endif #ifndef min -# define min(x, y) ({ \ +#define min(x, y) (/* */ { \ __typeof__(x) _min1 = (x); \ __typeof__(y) _min2 = (y); \ (void) (&_min1 == &_min2); \ @@ -115,7 +118,7 @@ #endif #ifndef max -# define max(x, y) ({ \ +#define max(x, y) (/* */ { \ __typeof__(x) _max1 = (x); \ __typeof__(y) _max2 = (y); \ (void) (&_max1 == &_max2); \ @@ -123,27 +126,27 @@ #endif #ifndef offsetof -#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER) +#define offsetof(TYPE, MEMBER) ((size_t)&((TYPE *)0)->MEMBER) #endif #ifndef container_of -#define container_of(ptr, type, member) ({ \ - const __typeof__( ((type *)0)->member ) *__mptr = (ptr); \ - (type *)( (char *)__mptr - offsetof(type,member) );}) +#define container_of(ptr, type, member) (/* */ { \ + const __typeof__(((type *)0)->member) *__mptr = (ptr); \ + (type *)((char *)__mptr - offsetof(type, member)); }) #endif #ifndef HAVE_PROGRAM_INVOCATION_SHORT_NAME -# ifdef HAVE___PROGNAME +#ifdef HAVE___PROGNAME extern char *__progname; -# define program_invocation_short_name __progname -# else -# ifdef HAVE_GETEXECNAME -# define program_invocation_short_name \ +#define program_invocation_short_name __progname +#else +#ifdef HAVE_GETEXECNAME +#define program_invocation_short_name \ prog_inv_sh_nm_from_file(getexecname(), 0) -# else -# define program_invocation_short_name \ +#else +#define program_invocation_short_name \ prog_inv_sh_nm_from_file(__FILE__, 1) -# endif +#endif static char prog_inv_sh_nm_buf[256]; static inline char * prog_inv_sh_nm_from_file(char *f, char stripext) @@ -155,15 +158,15 @@ prog_inv_sh_nm_from_file(char *f, char stripext) else t = f; - strncpy(prog_inv_sh_nm_buf, t, sizeof(prog_inv_sh_nm_buf) - 1); - prog_inv_sh_nm_buf[sizeof(prog_inv_sh_nm_buf) - 1] = '\0'; + strncpy(prog_inv_sh_nm_buf, t, sizeof (prog_inv_sh_nm_buf) - 1); + prog_inv_sh_nm_buf[sizeof (prog_inv_sh_nm_buf) - 1] = '\0'; if (stripext && (t = strrchr(prog_inv_sh_nm_buf, '.')) != NULL) *t = '\0'; - return prog_inv_sh_nm_buf; + return (prog_inv_sh_nm_buf); } -# endif +#endif #endif @@ -188,19 +191,19 @@ errmsg(char doexit, int excode, char adderr, const char *fmt, ...) } #ifndef HAVE_ERR -# define err(E, FMT, ...) errmsg(1, E, 1, FMT) +#define err(E, FMT, ...) errmsg(1, E, 1, FMT) #endif #ifndef HAVE_ERRX -# define errx(E, FMT, ...) errmsg(1, E, 0, FMT) +#define errx(E, FMT, ...) errmsg(1, E, 0, FMT) #endif #ifndef HAVE_WARN -# define warn(FMT, ...) errmsg(0, 0, 1, FMT) +#define warn(FMT, ...) errmsg(0, 0, 1, FMT) #endif #ifndef HAVE_WARNX -# define warnx(FMT, ...) errmsg(0, 0, 0, FMT) +#define warnx(FMT, ...) errmsg(0, 0, 0, FMT) #endif #endif /* !HAVE_ERR_H */ @@ -214,12 +217,14 @@ static inline __attribute__((const)) int is_power_of_2(unsigned long num) typedef int64_t loff_t; #endif -#if !defined(HAVE_DIRFD) && (!defined(HAVE_DECL_DIRFD) || HAVE_DECL_DIRFD == 0) && defined(HAVE_DIR_DD_FD) +#if !defined(HAVE_DIRFD) && \ + (!defined(HAVE_DECL_DIRFD) || HAVE_DECL_DIRFD == 0) && \ + defined(HAVE_DIR_DD_FD) #include #include static inline int dirfd(DIR *d) { - return d->dd_fd; + return (d->dd_fd); } #endif @@ -229,22 +234,22 @@ static inline int dirfd(DIR *d) #include #ifdef O_CLOEXEC -#define UL_CLOEXECSTR "e" +#define UL_CLOEXECSTR "e" #else -#define UL_CLOEXECSTR "" +#define UL_CLOEXECSTR "" #endif #ifndef O_CLOEXEC -#define O_CLOEXEC 0 +#define O_CLOEXEC 0 #endif #ifndef AI_ADDRCONFIG -#define AI_ADDRCONFIG 0x0020 +#define AI_ADDRCONFIG 0x0020 #endif #ifndef IUTF8 -#define IUTF8 0040000 +#define IUTF8 0040000 #endif /* @@ -256,15 +261,15 @@ static inline size_t get_hostname_max(void) long len = sysconf(_SC_HOST_NAME_MAX); if (0 < len) - return len; + return (len); #endif #ifdef MAXHOSTNAMELEN - return MAXHOSTNAMELEN; + return (MAXHOSTNAMELEN); #elif HOST_NAME_MAX - return HOST_NAME_MAX; + return (HOST_NAME_MAX); #endif - return 64; + return (64); } #ifndef HAVE_USLEEP @@ -277,7 +282,7 @@ static inline int usleep(__int64 usec) HANDLE timer; LARGE_INTEGER ft; - ft.QuadPart = -(10 * usec); // Convert to 100 nanosecond interval, negative value indicates relative time + ft.QuadPart = -(10 * usec); timer = CreateWaitableTimer(NULL, TRUE, NULL); SetWaitableTimer(timer, &ft, 0, NULL, NULL, 0); @@ -290,32 +295,34 @@ static inline int usleep(__int64 usec) * Constant strings for usage() functions. For more info see * Documentation/howto-usage-function.txt and disk-utils/delpart.c */ -#define USAGE_HEADER _("\nUsage:\n") -#define USAGE_OPTIONS _("\nOptions:\n") -#define USAGE_SEPARATOR _("\n") -#define USAGE_HELP _(" -h, --help display this help and exit\n") -#define USAGE_VERSION _(" -V, --version output version information and exit\n") -#define USAGE_MAN_TAIL(_man) _("\nFor more details see %s.\n"), _man +#define USAGE_HEADER _("\nUsage:\n") +#define USAGE_OPTIONS _("\nOptions:\n") +#define USAGE_SEPARATOR _("\n") +#define USAGE_HELP _(" -h, --help display this help and exit\n") +#define USAGE_VERSION \ + _(" -V, --version output version information and exit\n") +#define USAGE_MAN_TAIL(_man) _("\nFor more details see %s.\n"), _man -#define UTIL_LINUX_VERSION _("%s from %s\n"), program_invocation_short_name, PACKAGE_STRING +#define UTIL_LINUX_VERSION \ + _("%s from %s\n"), program_invocation_short_name, PACKAGE_STRING /* * scanf modifiers for "strings allocation" */ #ifdef HAVE_SCANF_MS_MODIFIER -#define UL_SCNsA "%ms" +#define UL_SCNsA "%ms" #elif defined(HAVE_SCANF_AS_MODIFIER) -#define UL_SCNsA "%as" +#define UL_SCNsA "%as" #endif /* * seek stuff */ #ifndef SEEK_DATA -# define SEEK_DATA 3 +#define SEEK_DATA 3 #endif #ifndef SEEK_HOLE -# define SEEK_HOLE 4 +#define SEEK_HOLE 4 #endif #endif /* UTIL_LINUX_C_H */ diff --git a/lib/os/windows/libuuid/clear.c b/lib/os/windows/libuuid/clear.c index 2d91fee9399..3d1ef1fe378 100644 --- a/lib/os/windows/libuuid/clear.c +++ b/lib/os/windows/libuuid/clear.c @@ -36,8 +36,8 @@ #include "uuidP.h" -void uuid_clear(uuid_t uu) +void +uuid_clear(uuid_t uu) { memset(uu, 0, 16); } - diff --git a/lib/os/windows/libuuid/compare.c b/lib/os/windows/libuuid/compare.c index 8f3437a2d78..b9159acc288 100644 --- a/lib/os/windows/libuuid/compare.c +++ b/lib/os/windows/libuuid/compare.c @@ -37,9 +37,10 @@ #include "uuidP.h" #include -#define UUCMP(u1,u2) if (u1 != u2) return((u1 < u2) ? -1 : 1); +#define UUCMP(u1, u2) if (u1 != u2) return ((u1 < u2) ? -1 : 1); -int uuid_compare(const uuid_t uu1, const uuid_t uu2) +int +uuid_compare(const uuid_t uu1, const uuid_t uu2) { struct uuid uuid1, uuid2; @@ -50,6 +51,5 @@ int uuid_compare(const uuid_t uu1, const uuid_t uu2) UUCMP(uuid1.time_mid, uuid2.time_mid); UUCMP(uuid1.time_hi_and_version, uuid2.time_hi_and_version); UUCMP(uuid1.clock_seq, uuid2.clock_seq); - return memcmp(uuid1.node, uuid2.node, 6); + return (memcmp(uuid1.node, uuid2.node, 6)); } - diff --git a/lib/os/windows/libuuid/copy.c b/lib/os/windows/libuuid/copy.c index ead33aa26e8..6938aa17f7e 100644 --- a/lib/os/windows/libuuid/copy.c +++ b/lib/os/windows/libuuid/copy.c @@ -34,12 +34,13 @@ #include "uuidP.h" -void uuid_copy(uuid_t dst, const uuid_t src) +void +uuid_copy(uuid_t dst, const uuid_t src) { unsigned char *cp1; const unsigned char *cp2; int i; - for (i=0, cp1 = dst, cp2 = src; i < 16; i++) + for (i = 0, cp1 = dst, cp2 = src; i < 16; i++) *cp1++ = *cp2++; } diff --git a/lib/os/windows/libuuid/gen_uuid.c b/lib/os/windows/libuuid/gen_uuid.c index 1e84b1efbda..f7488916e37 100644 --- a/lib/os/windows/libuuid/gen_uuid.c +++ b/lib/os/windows/libuuid/gen_uuid.c @@ -36,12 +36,12 @@ * Force inclusion of SVID stuff since we need it if we're compiling in * gcc-wall wall mode */ -#define _SVID_SOURCE +#define _SVID_SOURCE #ifdef _WIN32 -#define _WIN32_WINNT 0x0500 +#define _WIN32_WINNT 0x0500 #include -#define UUID MYUUID +#define UUID MYUUID #endif #include #ifdef HAVE_UNISTD_H @@ -96,51 +96,51 @@ #include "c.h" #ifdef HAVE_TLS -#define THREAD_LOCAL static __thread +#define THREAD_LOCAL static __thread #else -#define THREAD_LOCAL static +#define THREAD_LOCAL static #endif #ifndef LOCK_EX /* flock() replacement */ -#define LOCK_EX 1 -#define LOCK_SH 2 -#define LOCK_UN 3 -#define LOCK_NB 4 +#define LOCK_EX 1 +#define LOCK_SH 2 +#define LOCK_UN 3 +#define LOCK_NB 4 static int flock(int fd, int op) { - int rc = 0; + int rc = 0; #if defined(F_SETLK) && defined(F_SETLKW) - struct flock fl = {0}; + struct flock fl = {0}; - switch (op & (LOCK_EX|LOCK_SH|LOCK_UN)) { - case LOCK_EX: - fl.l_type = F_WRLCK; - break; + switch (op & (LOCK_EX|LOCK_SH|LOCK_UN)) { + case LOCK_EX: + fl.l_type = F_WRLCK; + break; - case LOCK_SH: - fl.l_type = F_RDLCK; - break; + case LOCK_SH: + fl.l_type = F_RDLCK; + break; - case LOCK_UN: - fl.l_type = F_UNLCK; - break; + case LOCK_UN: + fl.l_type = F_UNLCK; + break; - default: - errno = EINVAL; - return -1; - } + default: + errno = EINVAL; + return (-1); + } - fl.l_whence = SEEK_SET; - rc = fcntl (fd, op & LOCK_NB ? F_SETLK : F_SETLKW, &fl); + fl.l_whence = SEEK_SET; + rc = fcntl(fd, op & LOCK_NB ? F_SETLK : F_SETLKW, &fl); - if (rc && (errno == EAGAIN)) - errno = EWOULDBLOCK; + if (rc && (errno == EAGAIN)) + errno = EWOULDBLOCK; #endif /* defined(F_SETLK) && defined(F_SETLKW) */ - return rc; + return (rc); } #endif /* LOCK_EX */ @@ -173,26 +173,26 @@ static int get_node_id(unsigned char *node_id) * just sizeof(struct ifreq) */ #ifdef HAVE_SA_LEN -#define ifreq_size(i) max(sizeof(struct ifreq),\ - sizeof((i).ifr_name)+(i).ifr_addr.sa_len) +#define ifreq_size(i) max(sizeof (struct ifreq),\ + sizeof ((i).ifr_name)+(i).ifr_addr.sa_len) #else -#define ifreq_size(i) sizeof(struct ifreq) +#define ifreq_size(i) sizeof (struct ifreq) #endif /* HAVE_SA_LEN */ sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP); if (sd < 0) { - return -1; + return (-1); } - memset(buf, 0, sizeof(buf)); - ifc.ifc_len = sizeof(buf); + memset(buf, 0, sizeof (buf)); + ifc.ifc_len = sizeof (buf); ifc.ifc_buf = buf; - if (ioctl (sd, SIOCGIFCONF, (char *)&ifc) < 0) { + if (ioctl(sd, SIOCGIFCONF, (char *)&ifc) < 0) { close(sd); - return -1; + return (-1); } n = ifc.ifc_len; - for (i = 0; i < n; i+= ifreq_size(*ifrp) ) { - ifrp = (struct ifreq *)((char *) ifc.ifc_buf+i); + for (i = 0; i < n; i += ifreq_size(*ifrp)) { + ifrp = (struct ifreq *)((char *)ifc.ifc_buf+i); strncpy(ifr.ifr_name, ifrp->ifr_name, IFNAMSIZ); #ifdef SIOCGIFHWADDR if (ioctl(sd, SIOCGIFHWADDR, &ifr) < 0) @@ -205,17 +205,17 @@ static int get_node_id(unsigned char *node_id) a = (unsigned char *) ifr.ifr_enaddr; #else #ifdef HAVE_NET_IF_DL_H - sdlp = (struct sockaddr_dl *) &ifrp->ifr_addr; + sdlp = (struct sockaddr_dl *)&ifrp->ifr_addr; if ((sdlp->sdl_family != AF_LINK) || (sdlp->sdl_alen != 6)) continue; - a = (unsigned char *) &sdlp->sdl_data[sdlp->sdl_nlen]; + a = (unsigned char *)&sdlp->sdl_data[sdlp->sdl_nlen]; #else /* * XXX we don't have a way of getting the hardware * address */ close(sd); - return 0; + return (0); #endif /* HAVE_NET_IF_DL_H */ #endif /* SIOCGENADDR */ #endif /* SIOCGIFHWADDR */ @@ -224,16 +224,16 @@ static int get_node_id(unsigned char *node_id) if (node_id) { memcpy(node_id, a, 6); close(sd); - return 1; + return (1); } } close(sd); #endif - return 0; + return (0); } /* Assume that the gettimeofday() has microsecond granularity */ -#define MAX_ADJUSTMENT 10 +#define MAX_ADJUSTMENT 10 /* * Get clock from global sequence clock counter. @@ -241,8 +241,9 @@ static int get_node_id(unsigned char *node_id) * Return -1 if the clock counter could not be opened/locked (in this case * pseudorandom value is returned in @ret_clock_seq), otherwise return 0. */ -static int get_clock(uint32_t *clock_high, uint32_t *clock_low, - uint16_t *ret_clock_seq, int *num) +static int +get_clock(uint32_t *clock_high, uint32_t *clock_low, + uint16_t *ret_clock_seq, int *num) { THREAD_LOCAL int adjustment = 0; THREAD_LOCAL struct timeval last = {0, 0}; @@ -257,7 +258,8 @@ static int get_clock(uint32_t *clock_high, uint32_t *clock_low, if (state_fd == -2) { save_umask = _umask(0); - state_fd = open(LIBUUID_CLOCK_FILE, O_RDWR|O_CREAT|O_CLOEXEC, 0660); + state_fd = open(LIBUUID_CLOCK_FILE, O_RDWR|O_CREAT|O_CLOEXEC, + 0660); (void) _umask(save_umask); if (state_fd != -1) { state_f = fdopen(state_fd, "r+" UL_CLOEXECSTR); @@ -266,8 +268,7 @@ static int get_clock(uint32_t *clock_high, uint32_t *clock_low, state_fd = -1; ret = -1; } - } - else + } else ret = -1; } if (state_fd >= 0) { @@ -288,7 +289,7 @@ static int get_clock(uint32_t *clock_high, uint32_t *clock_low, int a; if (fscanf(state_f, "clock: %04x tv: %lu %lu adj: %d\n", - &cl, &tv1, &tv2, &a) == 4) { + &cl, &tv1, &tv2, &a) == 4) { clock_seq = cl & 0x3FFF; last.tv_sec = tv1; last.tv_usec = tv2; @@ -297,7 +298,7 @@ static int get_clock(uint32_t *clock_high, uint32_t *clock_low, } if ((last.tv_sec == 0) && (last.tv_usec == 0)) { - random_get_bytes(&clock_seq, sizeof(clock_seq)); + random_get_bytes(&clock_seq, sizeof (clock_seq)); clock_seq &= 0x3FFF; gettimeofday(&last, 0); last.tv_sec--; @@ -307,7 +308,7 @@ static int get_clock(uint32_t *clock_high, uint32_t *clock_low, gettimeofday(&tv, 0); if ((tv.tv_sec < last.tv_sec) || ((tv.tv_sec == last.tv_sec) && - (tv.tv_usec < last.tv_usec))) { + (tv.tv_usec < last.tv_usec))) { clock_seq = (clock_seq+1) & 0x3FFF; adjustment = 0; last = tv; @@ -322,8 +323,8 @@ static int get_clock(uint32_t *clock_high, uint32_t *clock_low, } clock_reg = tv.tv_usec*10 + adjustment; - clock_reg += ((uint64_t) tv.tv_sec)*10000000; - clock_reg += (((uint64_t) 0x01B21DD2) << 32) + 0x13814000; + clock_reg += ((uint64_t)tv.tv_sec)*10000000; + clock_reg += (((uint64_t)0x01B21DD2) << 32) + 0x13814000; if (num && (*num > 1)) { adjustment += *num - 1; @@ -336,8 +337,8 @@ static int get_clock(uint32_t *clock_high, uint32_t *clock_low, if (state_fd >= 0) { rewind(state_f); len = fprintf(state_f, - "clock: %04x tv: %016lu %08lu adj: %08d\n", - clock_seq, last.tv_sec, last.tv_usec, adjustment); + "clock: %04x tv: %016lu %08lu adj: %08d\n", + clock_seq, last.tv_sec, last.tv_usec, adjustment); fflush(state_f); if (ftruncate(state_fd, len) < 0) { fprintf(state_f, " \n"); @@ -350,7 +351,7 @@ static int get_clock(uint32_t *clock_high, uint32_t *clock_low, *clock_high = clock_reg >> 32; *clock_low = clock_reg; *ret_clock_seq = clock_seq; - return ret; + return (ret); } #if defined(HAVE_UUIDD) && defined(HAVE_SYS_UN_H) @@ -359,7 +360,8 @@ static int get_clock(uint32_t *clock_high, uint32_t *clock_low, * * Returns 0 on success, non-zero on failure. */ -static int get_uuid_via_daemon(int op, uuid_t out, int *num) +static int +get_uuid_via_daemon(int op, uuid_t out, int *num) { char op_buf[64]; int op_len; @@ -369,28 +371,28 @@ static int get_uuid_via_daemon(int op, uuid_t out, int *num) struct sockaddr_un srv_addr; if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) - return -1; + return (-1); srv_addr.sun_family = AF_UNIX; strcpy(srv_addr.sun_path, UUIDD_SOCKET_PATH); - if (connect(s, (const struct sockaddr *) &srv_addr, - sizeof(struct sockaddr_un)) < 0) + if (connect(s, (const struct sockaddr *)&srv_addr, + sizeof (struct sockaddr_un)) < 0) goto fail; op_buf[0] = op; op_len = 1; if (op == UUIDD_OP_BULK_TIME_UUID) { - memcpy(op_buf+1, num, sizeof(*num)); - op_len += sizeof(*num); - expected += sizeof(*num); + memcpy(op_buf+1, num, sizeof (*num)); + op_len += sizeof (*num); + expected += sizeof (*num); } ret = write(s, op_buf, op_len); if (ret < 1) goto fail; - ret = read_all(s, (char *) &reply_len, sizeof(reply_len)); + ret = read_all(s, (char *)&reply_len, sizeof (reply_len)); if (ret < 0) goto fail; @@ -400,7 +402,7 @@ static int get_uuid_via_daemon(int op, uuid_t out, int *num) ret = read_all(s, op_buf, reply_len); if (op == UUIDD_OP_BULK_TIME_UUID) - memcpy(op_buf+16, num, sizeof(int)); + memcpy(op_buf+16, num, sizeof (int)); memcpy(out, op_buf, 16); @@ -409,17 +411,19 @@ static int get_uuid_via_daemon(int op, uuid_t out, int *num) fail: close(s); - return -1; + return (-1); } #else /* !defined(HAVE_UUIDD) && defined(HAVE_SYS_UN_H) */ -static int get_uuid_via_daemon(int op, uuid_t out, int *num) +static int +get_uuid_via_daemon(int op, uuid_t out, int *num) { - return -1; + return (-1); } #endif -int __uuid_generate_time(uuid_t out, int *num) +int +__uuid_generate_time(uuid_t out, int *num) { static unsigned char node_id[6]; static int has_init = 0; @@ -441,22 +445,25 @@ int __uuid_generate_time(uuid_t out, int *num) } ret = get_clock(&clock_mid, &uu.time_low, &uu.clock_seq, num); uu.clock_seq |= 0x8000; - uu.time_mid = (uint16_t) clock_mid; + uu.time_mid = (uint16_t)clock_mid; uu.time_hi_and_version = ((clock_mid >> 16) & 0x0FFF) | 0x1000; memcpy(uu.node, node_id, 6); uuid_pack(&uu, out); - return ret; + return (ret); } /* * Generate time-based UUID and store it to @out * - * Tries to guarantee uniqueness of the generated UUIDs by obtaining them from the uuidd daemon, - * or, if uuidd is not usable, by using the global clock state counter (see get_clock()). - * If neither of these is possible (e.g. because of insufficient permissions), it generates + * Tries to guarantee uniqueness of the generated UUIDs by obtaining + * them from the uuidd daemon, or, if uuidd is not usable, by using + * the global clock state counter (see get_clock()). If neither of + * these is possible (e.g. because of insufficient permissions), it generates * the UUID anyway, but returns -1. Otherwise, returns 0. */ -static int uuid_generate_time_generic(uuid_t out) { +static int +uuid_generate_time_generic(uuid_t out) +{ #ifdef HAVE_TLS THREAD_LOCAL int num = 0; THREAD_LOCAL struct uuid uu; @@ -471,11 +478,11 @@ static int uuid_generate_time_generic(uuid_t out) { if (num <= 0) { num = 1000; if (get_uuid_via_daemon(UUIDD_OP_BULK_TIME_UUID, - out, &num) == 0) { + out, &num) == 0) { last_time = time(0); uuid_unpack(out, &uu); num--; - return 0; + return (0); } num = 0; } @@ -488,14 +495,14 @@ static int uuid_generate_time_generic(uuid_t out) { } num--; uuid_pack(&uu, out); - return 0; + return (0); } #else if (get_uuid_via_daemon(UUIDD_OP_TIME_UUID, out, 0) == 0) - return 0; + return (0); #endif - return __uuid_generate_time(out, 0); + return (__uuid_generate_time(out, 0)); } /* @@ -503,19 +510,20 @@ static int uuid_generate_time_generic(uuid_t out) { * * Discards return value from uuid_generate_time_generic() */ -void uuid_generate_time(uuid_t out) +void +uuid_generate_time(uuid_t out) { - (void)uuid_generate_time_generic(out); + (void) uuid_generate_time_generic(out); } - -int uuid_generate_time_safe(uuid_t out) +int +uuid_generate_time_safe(uuid_t out) { - return uuid_generate_time_generic(out); + return (uuid_generate_time_generic(out)); } - -void __uuid_generate_random(uuid_t out, int *num) +void +__uuid_generate_random(uuid_t out, int *num) { uuid_t buf; struct uuid uu; @@ -527,18 +535,19 @@ void __uuid_generate_random(uuid_t out, int *num) n = *num; for (i = 0; i < n; i++) { - random_get_bytes(buf, sizeof(buf)); + random_get_bytes(buf, sizeof (buf)); uuid_unpack(buf, &uu); uu.clock_seq = (uu.clock_seq & 0x3FFF) | 0x8000; uu.time_hi_and_version = (uu.time_hi_and_version & 0x0FFF) - | 0x4000; + | 0x4000; uuid_pack(&uu, out); - out += sizeof(uuid_t); + out += sizeof (uuid_t); } } -void uuid_generate_random(uuid_t out) +void +uuid_generate_random(uuid_t out) { int num = 1; /* No real reason to use the daemon for random uuid's -- yet */ @@ -550,7 +559,8 @@ void uuid_generate_random(uuid_t out) * Check whether good random source (/dev/random or /dev/urandom) * is available. */ -static int have_random_source(void) +static int +have_random_source(void) { struct stat s; @@ -564,7 +574,8 @@ static int have_random_source(void) * /dev/urandom is available, since otherwise we won't have * high-quality randomness. */ -void uuid_generate(uuid_t out) +void +uuid_generate(uuid_t out) { if (have_random_source()) uuid_generate_random(out); diff --git a/lib/os/windows/libuuid/isnull.c b/lib/os/windows/libuuid/isnull.c index 931e7e7dba2..866d8a06e7f 100644 --- a/lib/os/windows/libuuid/isnull.c +++ b/lib/os/windows/libuuid/isnull.c @@ -35,14 +35,14 @@ #include "uuidP.h" /* Returns 1 if the uuid is the NULL uuid */ -int uuid_is_null(const uuid_t uu) +int +uuid_is_null(const uuid_t uu) { const unsigned char *cp; int i; - for (i=0, cp = uu; i < 16; i++) + for (i = 0, cp = uu; i < 16; i++) if (*cp++) - return 0; - return 1; + return (0); + return (1); } - diff --git a/lib/os/windows/libuuid/pack.c b/lib/os/windows/libuuid/pack.c index 6e12476690f..509867ecf81 100644 --- a/lib/os/windows/libuuid/pack.c +++ b/lib/os/windows/libuuid/pack.c @@ -35,7 +35,8 @@ #include #include "uuidP.h" -void uuid_pack(const struct uuid *uu, uuid_t ptr) +void +uuid_pack(const struct uuid *uu, uuid_t ptr) { uint32_t tmp; unsigned char *out = ptr; @@ -66,4 +67,3 @@ void uuid_pack(const struct uuid *uu, uuid_t ptr) memcpy(out+10, uu->node, 6); } - diff --git a/lib/os/windows/libuuid/parse.c b/lib/os/windows/libuuid/parse.c index 074383efae7..9948c4d3056 100644 --- a/lib/os/windows/libuuid/parse.c +++ b/lib/os/windows/libuuid/parse.c @@ -39,7 +39,8 @@ #include "uuidP.h" -int uuid_parse(const char *in, uuid_t uu) +int +uuid_parse(const char *in, uuid_t uu) { struct uuid uuid; int i; @@ -47,20 +48,20 @@ int uuid_parse(const char *in, uuid_t uu) char buf[3]; if (strlen(in) != 36) - return -1; - for (i=0, cp = in; i <= 36; i++,cp++) { + return (-1); + for (i = 0, cp = in; i <= 36; i++, cp++) { if ((i == 8) || (i == 13) || (i == 18) || (i == 23)) { if (*cp == '-') continue; else - return -1; + return (-1); } - if (i== 36) + if (i == 36) if (*cp == 0) continue; if (!isxdigit(*cp)) - return -1; + return (-1); } uuid.time_low = strtoul(in, NULL, 16); uuid.time_mid = strtoul(in+9, NULL, 16); @@ -68,12 +69,12 @@ int uuid_parse(const char *in, uuid_t uu) uuid.clock_seq = strtoul(in+19, NULL, 16); cp = in+24; buf[2] = 0; - for (i=0; i < 6; i++) { + for (i = 0; i < 6; i++) { buf[0] = *cp++; buf[1] = *cp++; uuid.node[i] = strtoul(buf, NULL, 16); } uuid_pack(&uuid, uu); - return 0; + return (0); } diff --git a/lib/os/windows/libuuid/randutils.c b/lib/os/windows/libuuid/randutils.c index 8364ac203ec..b3a618e3b9b 100644 --- a/lib/os/windows/libuuid/randutils.c +++ b/lib/os/windows/libuuid/randutils.c @@ -13,23 +13,22 @@ #include #include -//#include - #include "randutils.h" #ifdef HAVE_TLS -#define THREAD_LOCAL static __thread +#define THREAD_LOCAL static __thread #else -#define THREAD_LOCAL static +#define THREAD_LOCAL static #endif #if defined(__linux__) && defined(__NR_gettid) && defined(HAVE_JRAND48) -#define DO_JRAND_MIX +#define DO_JRAND_MIX THREAD_LOCAL unsigned short ul_jrand_seed[3]; #endif #ifndef _WIN32 -int random_get_fd(void) +int +random_get_fd(void) { int i, fd; struct timeval tv; @@ -54,7 +53,7 @@ int random_get_fd(void) gettimeofday(&tv, 0); for (i = (tv.tv_sec ^ tv.tv_usec) & 0x1F; i > 0; i--) rand(); - return fd; + return (fd); } #endif @@ -64,7 +63,8 @@ int random_get_fd(void) * use glibc pseudo-random functions. */ #ifndef _WIN32 -void random_get_bytes(void *buf, size_t nbytes) +void +random_get_bytes(void *buf, size_t nbytes) { size_t i, n = nbytes; int fd = random_get_fd(); @@ -97,31 +97,30 @@ void random_get_bytes(void *buf, size_t nbytes) { unsigned short tmp_seed[3]; - memcpy(tmp_seed, ul_jrand_seed, sizeof(tmp_seed)); + memcpy(tmp_seed, ul_jrand_seed, sizeof (tmp_seed)); ul_jrand_seed[2] = ul_jrand_seed[2] ^ syscall(__NR_gettid); for (cp = buf, i = 0; i < nbytes; i++) *cp++ ^= (jrand48(tmp_seed) >> 7) & 0xFF; memcpy(ul_jrand_seed, tmp_seed, - sizeof(ul_jrand_seed)-sizeof(unsigned short)); + sizeof (ul_jrand_seed)-sizeof (unsigned short)); } #endif - - return; } #endif #ifdef TEST_PROGRAM -int main(int argc __attribute__ ((__unused__)), - char *argv[] __attribute__ ((__unused__))) +int +main(int argc __attribute__((__unused__)), + char *argv[] __attribute__((__unused__))) { unsigned int v, i; /* generate and print 10 random numbers */ for (i = 0; i < 10; i++) { - random_get_bytes(&v, sizeof(v)); + random_get_bytes(&v, sizeof (v)); printf("%d\n", v); } - return EXIT_SUCCESS; + return (EXIT_SUCCESS); } #endif /* TEST_PROGRAM */ diff --git a/lib/os/windows/libuuid/randutils.h b/lib/os/windows/libuuid/randutils.h index dec5e355a43..e27456c61bc 100644 --- a/lib/os/windows/libuuid/randutils.h +++ b/lib/os/windows/libuuid/randutils.h @@ -1,9 +1,10 @@ + #ifndef UTIL_LINUX_RANDUTILS -#define UTIL_LINUX_RANDUTILS +#define UTIL_LINUX_RANDUTILS #ifdef HAVE_SRANDOM -#define srand(x) srandom(x) -#define rand() random() +#define srand(x) srandom(x) +#define rand() random() #endif extern int random_get_fd(void); diff --git a/lib/os/windows/libuuid/test_uuid.c b/lib/os/windows/libuuid/test_uuid.c index e03138f7d18..a9d8b327b1b 100644 --- a/lib/os/windows/libuuid/test_uuid.c +++ b/lib/os/windows/libuuid/test_uuid.c @@ -33,9 +33,9 @@ */ #ifdef _WIN32 -#define _WIN32_WINNT 0x0500 +#define _WIN32_WINNT 0x0500 #include -#define UUID MYUUID +#define UUID MYUUID #endif #include @@ -43,9 +43,10 @@ #include "uuid.h" -static int test_uuid(const char * uuid, int isValid) +static int +test_uuid(const char *uuid, int isValid) { - static const char * validStr[2] = {"invalid", "valid"}; + static const char *validStr[2] = {"invalid", "valid"}; uuid_t uuidBits; int parsedOk; @@ -54,20 +55,20 @@ static int test_uuid(const char * uuid, int isValid) printf("%s is %s", uuid, validStr[isValid]); if (parsedOk != isValid) { printf(" but uuid_parse says %s\n", validStr[parsedOk]); - return 1; + return (1); } printf(", OK\n"); - return 0; + return (0); } #ifdef __GNUC__ -#define ATTR(x) __attribute__(x) +#define ATTR(x) __attribute__(x) #else -#define ATTR(x) +#define ATTR(x) #endif int -main(int argc ATTR((unused)) , char **argv ATTR((unused))) +main(int argc ATTR((unused)), char **argv ATTR((unused))) { uuid_t buf, tst; char str[100]; @@ -82,7 +83,7 @@ main(int argc ATTR((unused)) , char **argv ATTR((unused))) uuid_unparse(buf, str); printf("UUID generate = %s\n", str); printf("UUID: "); - for (i=0, cp = (unsigned char *) &buf; i < 16; i++) { + for (i = 0, cp = (unsigned char *) &buf; i < 16; i++) { printf("%02x", *cp++); } printf("\n"); @@ -98,7 +99,7 @@ main(int argc ATTR((unused)) , char **argv ATTR((unused))) uuid_unparse(buf, str); printf("UUID random string = %s\n", str); printf("UUID: "); - for (i=0, cp = (unsigned char *) &buf; i < 16; i++) { + for (i = 0, cp = (unsigned char *) &buf; i < 16; i++) { printf("%02x", *cp++); } printf("\n"); @@ -110,7 +111,7 @@ main(int argc ATTR((unused)) , char **argv ATTR((unused))) } if (type != 4) { printf("Incorrect UUID type; was expecting " - "4 (random type)!\n"); + "4 (random type)!\n"); failed++; } printf("\n"); @@ -119,7 +120,7 @@ main(int argc ATTR((unused)) , char **argv ATTR((unused))) uuid_unparse(buf, str); printf("UUID string = %s\n", str); printf("UUID time: "); - for (i=0, cp = (unsigned char *) &buf; i < 16; i++) { + for (i = 0, cp = (unsigned char *)&buf; i < 16; i++) { printf("%02x", *cp++); } printf("\n"); @@ -131,14 +132,14 @@ main(int argc ATTR((unused)) , char **argv ATTR((unused))) } if (type != 1) { printf("Incorrect UUID type; was expecting " - "1 (time-based type)!\\n"); + "1 (time-based type)!\\n"); failed++; } tv.tv_sec = 0; tv.tv_usec = 0; time_reg = uuid_time(buf, &tv); printf("UUID time is: (%ld, %ld): %s\n", tv.tv_sec, tv.tv_usec, - ctime(&time_reg)); + ctime(&time_reg)); uuid_parse(str, tst); if (!uuid_compare(buf, tst)) printf("UUID parse and compare succeeded.\n"); @@ -176,5 +177,5 @@ main(int argc ATTR((unused)) , char **argv ATTR((unused))) printf("%d failures.\n", failed); exit(1); } - return 0; + return (0); } diff --git a/lib/os/windows/libuuid/unpack.c b/lib/os/windows/libuuid/unpack.c index beaaff3ca8a..5b27f035df7 100644 --- a/lib/os/windows/libuuid/unpack.c +++ b/lib/os/windows/libuuid/unpack.c @@ -35,7 +35,8 @@ #include #include "uuidP.h" -void uuid_unpack(const uuid_t in, struct uuid *uu) +void +uuid_unpack(const uuid_t in, struct uuid *uu) { const uint8_t *ptr = in; uint32_t tmp; @@ -60,4 +61,3 @@ void uuid_unpack(const uuid_t in, struct uuid *uu) memcpy(uu->node, ptr, 6); } - diff --git a/lib/os/windows/libuuid/unparse.c b/lib/os/windows/libuuid/unparse.c index a95bbb04258..34fc18eb5e7 100644 --- a/lib/os/windows/libuuid/unparse.c +++ b/lib/os/windows/libuuid/unparse.c @@ -43,34 +43,38 @@ static const char *fmt_upper = "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X"; #ifdef UUID_UNPARSE_DEFAULT_UPPER -#define FMT_DEFAULT fmt_upper +#define FMT_DEFAULT fmt_upper #else -#define FMT_DEFAULT fmt_lower +#define FMT_DEFAULT fmt_lower #endif -static void uuid_unparse_x(const uuid_t uu, char *out, const char *fmt) +static void +uuid_unparse_x(const uuid_t uu, char *out, const char *fmt) { struct uuid uuid; uuid_unpack(uu, &uuid); sprintf(out, fmt, - uuid.time_low, uuid.time_mid, uuid.time_hi_and_version, - uuid.clock_seq >> 8, uuid.clock_seq & 0xFF, - uuid.node[0], uuid.node[1], uuid.node[2], - uuid.node[3], uuid.node[4], uuid.node[5]); + uuid.time_low, uuid.time_mid, uuid.time_hi_and_version, + uuid.clock_seq >> 8, uuid.clock_seq & 0xFF, + uuid.node[0], uuid.node[1], uuid.node[2], + uuid.node[3], uuid.node[4], uuid.node[5]); } -void uuid_unparse_lower(const uuid_t uu, char *out) +void +uuid_unparse_lower(const uuid_t uu, char *out) { uuid_unparse_x(uu, out, fmt_lower); } -void uuid_unparse_upper(const uuid_t uu, char *out) +void +uuid_unparse_upper(const uuid_t uu, char *out) { uuid_unparse_x(uu, out, fmt_upper); } -void uuid_unparse(const uuid_t uu, char *out) +void +uuid_unparse(const uuid_t uu, char *out) { uuid_unparse_x(uu, out, FMT_DEFAULT); } diff --git a/lib/os/windows/libuuid/uuid.h b/lib/os/windows/libuuid/uuid.h index 874d65a196d..7d0b6add494 100644 --- a/lib/os/windows/libuuid/uuid.h +++ b/lib/os/windows/libuuid/uuid.h @@ -33,7 +33,7 @@ */ #ifndef _UUID_UUID_H -#define _UUID_UUID_H +#define _UUID_UUID_H #include #ifndef _WIN32 @@ -44,22 +44,26 @@ typedef unsigned char uuid_t[16]; /* UUID Variant definitions */ -#define UUID_VARIANT_NCS 0 -#define UUID_VARIANT_DCE 1 -#define UUID_VARIANT_MICROSOFT 2 -#define UUID_VARIANT_OTHER 3 +#define UUID_VARIANT_NCS 0 +#define UUID_VARIANT_DCE 1 +#define UUID_VARIANT_MICROSOFT 2 +#define UUID_VARIANT_OTHER 3 /* UUID Type definitions */ -#define UUID_TYPE_DCE_TIME 1 -#define UUID_TYPE_DCE_RANDOM 4 +#define UUID_TYPE_DCE_TIME 1 +#define UUID_TYPE_DCE_RANDOM 4 /* Allow UUID constants to be defined */ #ifdef __GNUC__ -#define UUID_DEFINE(name,u0,u1,u2,u3,u4,u5,u6,u7,u8,u9,u10,u11,u12,u13,u14,u15) \ - static const uuid_t name __attribute__ ((unused)) = {u0,u1,u2,u3,u4,u5,u6,u7,u8,u9,u10,u11,u12,u13,u14,u15} +#define UUID_DEFINE(name, u0, u1, u2, u3, u4, u5, u6, u7, u8, u9, u10, \ + u11, u12, u13, u14, u15) \ + static const uuid_t name __attribute__((unused)) = {u0, u1, u2, u3, \ + u4, u5, u6, u7, u8, u9, u10, u11, u12, u13, u14, u15} #else -#define UUID_DEFINE(name,u0,u1,u2,u3,u4,u5,u6,u7,u8,u9,u10,u11,u12,u13,u14,u15) \ - static const uuid_t name = {u0,u1,u2,u3,u4,u5,u6,u7,u8,u9,u10,u11,u12,u13,u14,u15} +#define UUID_DEFINE(name, u0, u1, u2, u3, u4, u5, u6, u7, u8, u9, u10, \ + u11, u12, u13, u14, u15) \ + static const uuid_t name = {u0, u1, u2, u3, u4, u5, u6, u7, u8, u9, \ + u10, u11, u12, u13, u14, u15} #endif #ifdef __cplusplus diff --git a/lib/os/windows/libuuid/uuidP.h b/lib/os/windows/libuuid/uuidP.h index 86a5e266f00..9ab5b7e53d7 100644 --- a/lib/os/windows/libuuid/uuidP.h +++ b/lib/os/windows/libuuid/uuidP.h @@ -37,13 +37,13 @@ #include "uuid.h" -#define LIBUUID_CLOCK_FILE "/var/lib/libuuid/clock.txt" +#define LIBUUID_CLOCK_FILE "/var/lib/libuuid/clock.txt" /* * Offset between 15-Oct-1582 and 1-Jan-70 */ -#define TIME_OFFSET_HIGH 0x01B21DD2 -#define TIME_OFFSET_LOW 0x13814000 +#define TIME_OFFSET_HIGH 0x01B21DD2 +#define TIME_OFFSET_LOW 0x13814000 struct uuid { uint32_t time_low; diff --git a/lib/os/windows/libuuid/uuid_time.c b/lib/os/windows/libuuid/uuid_time.c index f25f5c90fe5..3691edd4668 100644 --- a/lib/os/windows/libuuid/uuid_time.c +++ b/lib/os/windows/libuuid/uuid_time.c @@ -35,9 +35,9 @@ */ #ifdef _WIN32 -#define _WIN32_WINNT 0x0500 +#define _WIN32_WINNT 0x0500 #include -#define UUID MYUUID +#define UUID MYUUID #endif #include @@ -53,7 +53,8 @@ #include "uuidP.h" -time_t uuid_time(const uuid_t uu, struct timeval *ret_tv) +time_t +uuid_time(const uuid_t uu, struct timeval *ret_tv) { struct timeval tv; struct uuid uuid; @@ -63,19 +64,20 @@ time_t uuid_time(const uuid_t uu, struct timeval *ret_tv) uuid_unpack(uu, &uuid); high = uuid.time_mid | ((uuid.time_hi_and_version & 0xFFF) << 16); - clock_reg = uuid.time_low | ((uint64_t) high << 32); + clock_reg = uuid.time_low | ((uint64_t)high << 32); - clock_reg -= (((uint64_t) 0x01B21DD2) << 32) + 0x13814000; + clock_reg -= (((uint64_t)0x01B21DD2) << 32) + 0x13814000; tv.tv_sec = clock_reg / 10000000; tv.tv_usec = (clock_reg % 10000000) / 10; if (ret_tv) *ret_tv = tv; - return tv.tv_sec; + return (tv.tv_sec); } -int uuid_type(const uuid_t uu) +int +uuid_type(const uuid_t uu) { struct uuid uuid; @@ -83,7 +85,8 @@ int uuid_type(const uuid_t uu) return ((uuid.time_hi_and_version >> 12) & 0xF); } -int uuid_variant(const uuid_t uu) +int +uuid_variant(const uuid_t uu) { struct uuid uuid; int var; @@ -92,26 +95,27 @@ int uuid_variant(const uuid_t uu) var = uuid.clock_seq; if ((var & 0x8000) == 0) - return UUID_VARIANT_NCS; + return (UUID_VARIANT_NCS); if ((var & 0x4000) == 0) - return UUID_VARIANT_DCE; + return (UUID_VARIANT_DCE); if ((var & 0x2000) == 0) - return UUID_VARIANT_MICROSOFT; - return UUID_VARIANT_OTHER; + return (UUID_VARIANT_MICROSOFT); + return (UUID_VARIANT_OTHER); } #ifdef DEBUG -static const char *variant_string(int variant) +static const char * +variant_string(int variant) { switch (variant) { case UUID_VARIANT_NCS: - return "NCS"; + return ("NCS"); case UUID_VARIANT_DCE: - return "DCE"; + return ("DCE"); case UUID_VARIANT_MICROSOFT: - return "Microsoft"; + return ("Microsoft"); default: - return "Other"; + return ("Other"); } } @@ -139,8 +143,8 @@ main(int argc, char **argv) printf("UUID variant is %d (%s)\n", variant, variant_string(variant)); if (variant != UUID_VARIANT_DCE) { printf("Warning: This program only knows how to interpret " - "DCE UUIDs.\n\tThe rest of the output is likely " - "to be incorrect!!\n"); + "DCE UUIDs.\n\tThe rest of the output is likely " + "to be incorrect!!\n"); } printf("UUID type is %d", type); switch (type) { @@ -161,11 +165,11 @@ main(int argc, char **argv) } if (type != 1) { printf("Warning: not a time-based UUID, so UUID time " - "decoding will likely not work!\n"); + "decoding will likely not work!\n"); } printf("UUID time is: (%ld, %ld): %s\n", tv.tv_sec, tv.tv_usec, - ctime(&time_reg)); + ctime(&time_reg)); - return 0; + return (0); } #endif diff --git a/lib/os/windows/libuuid/uuidd.h b/lib/os/windows/libuuid/uuidd.h index 2f709680bb2..b71983768ea 100644 --- a/lib/os/windows/libuuid/uuidd.h +++ b/lib/os/windows/libuuid/uuidd.h @@ -33,20 +33,20 @@ */ #ifndef _UUID_UUIDD_H -#define _UUID_UUIDD_H +#define _UUID_UUIDD_H -#define UUIDD_DIR _PATH_LOCALSTATEDIR "/uuidd" -#define UUIDD_SOCKET_PATH UUIDD_DIR "/request" -#define UUIDD_PIDFILE_PATH UUIDD_DIR "/uuidd.pid" -#define UUIDD_PATH "/usr/sbin/uuidd" +#define UUIDD_DIR _PATH_LOCALSTATEDIR "/uuidd" +#define UUIDD_SOCKET_PATH UUIDD_DIR "/request" +#define UUIDD_PIDFILE_PATH UUIDD_DIR "/uuidd.pid" +#define UUIDD_PATH "/usr/sbin/uuidd" -#define UUIDD_OP_GETPID 0 -#define UUIDD_OP_GET_MAXOP 1 -#define UUIDD_OP_TIME_UUID 2 -#define UUIDD_OP_RANDOM_UUID 3 -#define UUIDD_OP_BULK_TIME_UUID 4 -#define UUIDD_OP_BULK_RANDOM_UUID 5 -#define UUIDD_MAX_OP UUIDD_OP_BULK_RANDOM_UUID +#define UUIDD_OP_GETPID 0 +#define UUIDD_OP_GET_MAXOP 1 +#define UUIDD_OP_TIME_UUID 2 +#define UUIDD_OP_RANDOM_UUID 3 +#define UUIDD_OP_BULK_TIME_UUID 4 +#define UUIDD_OP_BULK_RANDOM_UUID 5 +#define UUIDD_MAX_OP UUIDD_OP_BULK_RANDOM_UUID extern int __uuid_generate_time(uuid_t out, int *num); extern void __uuid_generate_random(uuid_t out, int *num); diff --git a/lib/os/windows/zlib-1.2.3/adler32.c b/lib/os/windows/zlib-1.2.3/adler32.c index 007ba26277c..0dbc9c41550 100644 --- a/lib/os/windows/zlib-1.2.3/adler32.c +++ b/lib/os/windows/zlib-1.2.3/adler32.c @@ -1,149 +1,153 @@ -/* adler32.c -- compute the Adler-32 checksum of a data stream +/* + * adler32.c -- compute the Adler-32 checksum of a data stream * Copyright (C) 1995-2004 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* @(#) $Id$ */ -#define ZLIB_INTERNAL +#define ZLIB_INTERNAL #include "zlib.h" -#define BASE 65521UL /* largest prime smaller than 65536 */ -#define NMAX 5552 +#define BASE 65521UL /* largest prime smaller than 65536 */ +#define NMAX 5552 /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ -#define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;} -#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1); -#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2); -#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4); -#define DO16(buf) DO8(buf,0); DO8(buf,8); +#define DO1(buf, i) {adler += (buf)[i]; sum2 += adler; } +#define DO2(buf, i) DO1(buf, i); DO1(buf, i+1); +#define DO4(buf, i) DO2(buf, i); DO2(buf, i+2); +#define DO8(buf, i) DO4(buf, i); DO4(buf, i+4); +#define DO16(buf) DO8(buf, 0); DO8(buf, 8); /* use NO_DIVIDE if your processor does not do division in hardware */ #ifdef NO_DIVIDE -# define MOD(a) \ +#define MOD(a) \ do { \ - if (a >= (BASE << 16)) a -= (BASE << 16); \ - if (a >= (BASE << 15)) a -= (BASE << 15); \ - if (a >= (BASE << 14)) a -= (BASE << 14); \ - if (a >= (BASE << 13)) a -= (BASE << 13); \ - if (a >= (BASE << 12)) a -= (BASE << 12); \ - if (a >= (BASE << 11)) a -= (BASE << 11); \ - if (a >= (BASE << 10)) a -= (BASE << 10); \ - if (a >= (BASE << 9)) a -= (BASE << 9); \ - if (a >= (BASE << 8)) a -= (BASE << 8); \ - if (a >= (BASE << 7)) a -= (BASE << 7); \ - if (a >= (BASE << 6)) a -= (BASE << 6); \ - if (a >= (BASE << 5)) a -= (BASE << 5); \ - if (a >= (BASE << 4)) a -= (BASE << 4); \ - if (a >= (BASE << 3)) a -= (BASE << 3); \ - if (a >= (BASE << 2)) a -= (BASE << 2); \ - if (a >= (BASE << 1)) a -= (BASE << 1); \ - if (a >= BASE) a -= BASE; \ - } while (0) -# define MOD4(a) \ + if (a >= (BASE << 16)) a -= (BASE << 16); \ + if (a >= (BASE << 15)) a -= (BASE << 15); \ + if (a >= (BASE << 14)) a -= (BASE << 14); \ + if (a >= (BASE << 13)) a -= (BASE << 13); \ + if (a >= (BASE << 12)) a -= (BASE << 12); \ + if (a >= (BASE << 11)) a -= (BASE << 11); \ + if (a >= (BASE << 10)) a -= (BASE << 10); \ + if (a >= (BASE << 9)) a -= (BASE << 9); \ + if (a >= (BASE << 8)) a -= (BASE << 8); \ + if (a >= (BASE << 7)) a -= (BASE << 7); \ + if (a >= (BASE << 6)) a -= (BASE << 6); \ + if (a >= (BASE << 5)) a -= (BASE << 5); \ + if (a >= (BASE << 4)) a -= (BASE << 4); \ + if (a >= (BASE << 3)) a -= (BASE << 3); \ + if (a >= (BASE << 2)) a -= (BASE << 2); \ + if (a >= (BASE << 1)) a -= (BASE << 1); \ + if (a >= BASE) a -= BASE; \ + } while (0) +#define MOD4(a) \ do { \ - if (a >= (BASE << 4)) a -= (BASE << 4); \ - if (a >= (BASE << 3)) a -= (BASE << 3); \ - if (a >= (BASE << 2)) a -= (BASE << 2); \ - if (a >= (BASE << 1)) a -= (BASE << 1); \ - if (a >= BASE) a -= BASE; \ - } while (0) + if (a >= (BASE << 4)) a -= (BASE << 4); \ + if (a >= (BASE << 3)) a -= (BASE << 3); \ + if (a >= (BASE << 2)) a -= (BASE << 2); \ + if (a >= (BASE << 1)) a -= (BASE << 1); \ + if (a >= BASE) a -= BASE; \ + } while (0) #else -# define MOD(a) a %= BASE -# define MOD4(a) a %= BASE +#define MOD(a) a %= BASE +#define MOD4(a) a %= BASE #endif /* ========================================================================= */ -uLong ZEXPORT adler32(adler, buf, len) - uLong adler; - const Bytef *buf; - uInt len; +uLong ZEXPORT +adler32( + uLong adler, + const Bytef *buf, + uInt len) { - unsigned long sum2; - unsigned n; + unsigned long sum2; + unsigned n; - /* split Adler-32 into component sums */ - sum2 = (adler >> 16) & 0xffff; - adler &= 0xffff; + /* split Adler-32 into component sums */ + sum2 = (adler >> 16) & 0xffff; + adler &= 0xffff; - /* in case user likes doing a byte at a time, keep it fast */ - if (len == 1) { - adler += buf[0]; - if (adler >= BASE) - adler -= BASE; - sum2 += adler; - if (sum2 >= BASE) - sum2 -= BASE; - return adler | (sum2 << 16); - } + /* in case user likes doing a byte at a time, keep it fast */ + if (len == 1) { + adler += buf[0]; + if (adler >= BASE) + adler -= BASE; + sum2 += adler; + if (sum2 >= BASE) + sum2 -= BASE; + return (adler | (sum2 << 16)); + } - /* initial Adler-32 value (deferred check for len == 1 speed) */ - if (buf == Z_NULL) - return 1L; + /* initial Adler-32 value (deferred check for len == 1 speed) */ + if (buf == Z_NULL) + return (1L); - /* in case short lengths are provided, keep it somewhat fast */ - if (len < 16) { - while (len--) { - adler += *buf++; - sum2 += adler; - } - if (adler >= BASE) - adler -= BASE; - MOD4(sum2); /* only added so many BASE's */ - return adler | (sum2 << 16); - } + /* in case short lengths are provided, keep it somewhat fast */ + if (len < 16) { + while (len--) { + adler += *buf++; + sum2 += adler; + } + if (adler >= BASE) + adler -= BASE; + MOD4(sum2); /* only added so many BASE's */ + return (adler | (sum2 << 16)); + } - /* do length NMAX blocks -- requires just one modulo operation */ - while (len >= NMAX) { - len -= NMAX; - n = NMAX / 16; /* NMAX is divisible by 16 */ - do { - DO16(buf); /* 16 sums unrolled */ - buf += 16; - } while (--n); - MOD(adler); - MOD(sum2); - } + /* do length NMAX blocks -- requires just one modulo operation */ + while (len >= NMAX) { + len -= NMAX; + n = NMAX / 16; /* NMAX is divisible by 16 */ + do { + DO16(buf); /* 16 sums unrolled */ + buf += 16; + } while (--n); + MOD(adler); + MOD(sum2); + } - /* do remaining bytes (less than NMAX, still just one modulo) */ - if (len) { /* avoid modulos if none remaining */ - while (len >= 16) { - len -= 16; - DO16(buf); - buf += 16; - } - while (len--) { - adler += *buf++; - sum2 += adler; - } - MOD(adler); - MOD(sum2); - } + /* do remaining bytes (less than NMAX, still just one modulo) */ + if (len) { /* avoid modulos if none remaining */ + while (len >= 16) { + len -= 16; + DO16(buf); + buf += 16; + } + while (len--) { + adler += *buf++; + sum2 += adler; + } + MOD(adler); + MOD(sum2); + } - /* return recombined sums */ - return adler | (sum2 << 16); + /* return recombined sums */ + return (adler | (sum2 << 16)); } /* ========================================================================= */ -uLong ZEXPORT adler32_combine(adler1, adler2, len2) - uLong adler1; - uLong adler2; - z_off_t len2; +uLong ZEXPORT +adler32_combine( + uLong adler1, + uLong adler2, + z_off_t len2) { - unsigned long sum1; - unsigned long sum2; - unsigned rem; + unsigned long sum1; + unsigned long sum2; + unsigned rem; - /* the derivation of this formula is left as an exercise for the reader */ - rem = (unsigned)(len2 % BASE); - sum1 = adler1 & 0xffff; - sum2 = rem * sum1; - MOD(sum2); - sum1 += (adler2 & 0xffff) + BASE - 1; - sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem; - if (sum1 > BASE) sum1 -= BASE; - if (sum1 > BASE) sum1 -= BASE; - if (sum2 > (BASE << 1)) sum2 -= (BASE << 1); - if (sum2 > BASE) sum2 -= BASE; - return sum1 | (sum2 << 16); +/* the derivation of this formula is left as an exercise for the reader */ + rem = (unsigned)(len2 % BASE); + sum1 = adler1 & 0xffff; + sum2 = rem * sum1; + MOD(sum2); + sum1 += (adler2 & 0xffff) + BASE - 1; + sum2 += ((adler1 >> 16) & 0xffff) + + ((adler2 >> 16) & 0xffff) + BASE - rem; + if (sum1 > BASE) sum1 -= BASE; + if (sum1 > BASE) sum1 -= BASE; + if (sum2 > (BASE << 1)) sum2 -= (BASE << 1); + if (sum2 > BASE) sum2 -= BASE; + return (sum1 | (sum2 << 16)); } diff --git a/lib/os/windows/zlib-1.2.3/compress.c b/lib/os/windows/zlib-1.2.3/compress.c index df04f0148e6..f1c12d9b42c 100644 --- a/lib/os/windows/zlib-1.2.3/compress.c +++ b/lib/os/windows/zlib-1.2.3/compress.c @@ -1,79 +1,88 @@ -/* compress.c -- compress a memory buffer +/* + * compress.c -- compress a memory buffer * Copyright (C) 1995-2003 Jean-loup Gailly. * For conditions of distribution and use, see copyright notice in zlib.h */ /* @(#) $Id$ */ -#define ZLIB_INTERNAL +#define ZLIB_INTERNAL #include "zlib.h" -/* =========================================================================== - Compresses the source buffer into the destination buffer. The level - parameter has the same meaning as in deflateInit. sourceLen is the byte - length of the source buffer. Upon entry, destLen is the total size of the - destination buffer, which must be at least 0.1% larger than sourceLen plus - 12 bytes. Upon exit, destLen is the actual size of the compressed buffer. - - compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_BUF_ERROR if there was not enough room in the output buffer, - Z_STREAM_ERROR if the level parameter is invalid. -*/ -int ZEXPORT compress2 (dest, destLen, source, sourceLen, level) - Bytef *dest; - uLongf *destLen; - const Bytef *source; - uLong sourceLen; - int level; +/* + * Compresses the source buffer into the destination buffer. The level + * parameter has the same meaning as in deflateInit. sourceLen is the byte + * length of the source buffer. Upon entry, destLen is the total size of the + * destination buffer, which must be at least 0.1% larger than sourceLen plus + * 12 bytes. Upon exit, destLen is the actual size of the compressed buffer. + * + * compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + * memory, Z_BUF_ERROR if there was not enough room in the output buffer, + * Z_STREAM_ERROR if the level parameter is invalid. + */ +int ZEXPORT +compress2( + Bytef *dest, + uLongf *destLen, + const Bytef *source, + uLong sourceLen, + int level) { - z_stream stream; - int err; + z_stream stream; + int err; - stream.next_in = (Bytef*)source; - stream.avail_in = (uInt)sourceLen; + stream.next_in = (Bytef*)source; + stream.avail_in = (uInt)sourceLen; #ifdef MAXSEG_64K - /* Check for source > 64K on 16-bit machine: */ - if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR; + /* Check for source > 64K on 16-bit machine: */ + if ((uLong)stream.avail_in != sourceLen) + return (Z_BUF_ERROR); #endif - stream.next_out = dest; - stream.avail_out = (uInt)*destLen; - if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR; + stream.next_out = dest; + stream.avail_out = (uInt)*destLen; + if ((uLong)stream.avail_out != *destLen) + return (Z_BUF_ERROR); - stream.zalloc = (alloc_func)0; - stream.zfree = (free_func)0; - stream.opaque = (voidpf)0; + stream.zalloc = (alloc_func)0; + stream.zfree = (free_func)0; + stream.opaque = (voidpf)0; - err = deflateInit(&stream, level); - if (err != Z_OK) return err; + err = deflateInit(&stream, level); + if (err != Z_OK) + return (err); - err = deflate(&stream, Z_FINISH); - if (err != Z_STREAM_END) { - deflateEnd(&stream); - return err == Z_OK ? Z_BUF_ERROR : err; - } - *destLen = stream.total_out; + err = deflate(&stream, Z_FINISH); + if (err != Z_STREAM_END) { + deflateEnd(&stream); + return (err == Z_OK ? Z_BUF_ERROR : err); + } + *destLen = stream.total_out; - err = deflateEnd(&stream); - return err; + err = deflateEnd(&stream); + return (err); } -/* =========================================================================== +/* + * */ -int ZEXPORT compress (dest, destLen, source, sourceLen) - Bytef *dest; - uLongf *destLen; - const Bytef *source; - uLong sourceLen; +int ZEXPORT +compress( + Bytef *dest, + uLongf *destLen, + const Bytef *source, + uLong sourceLen) { - return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION); + return (compress2(dest, destLen, source, sourceLen, + Z_DEFAULT_COMPRESSION)); } -/* =========================================================================== - If the default memLevel or windowBits for deflateInit() is changed, then - this function needs to be updated. +/* + * If the default memLevel or windowBits for deflateInit() is changed, then + * this function needs to be updated. */ -uLong ZEXPORT compressBound (sourceLen) - uLong sourceLen; +uLong ZEXPORT +compressBound( + uLong sourceLen) { - return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11; + return (sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11); } diff --git a/lib/os/windows/zlib-1.2.3/contrib/masmx64/inffas8664.c b/lib/os/windows/zlib-1.2.3/contrib/masmx64/inffas8664.c index 3b54555f411..29e38b5b35a 100644 --- a/lib/os/windows/zlib-1.2.3/contrib/masmx64/inffas8664.c +++ b/lib/os/windows/zlib-1.2.3/contrib/masmx64/inffas8664.c @@ -1,4 +1,5 @@ -/* inffas8664.c is a hand tuned assembler version of inffast.c - fast decoding +/* + * inffas8664.c is a hand tuned assembler version of inffast.c - fast decoding * version for AMD64 on Windows using Microsoft C compiler * * Copyright (C) 1995-2003 Mark Adler @@ -41,146 +42,147 @@ /* Mark Adler's comments from inffast.c: */ /* - Decode literal, length, and distance codes and write out the resulting - literal and match bytes until either not enough input or output is - available, an end-of-block is encountered, or a data error is encountered. - When large enough input and output buffers are supplied to inflate(), for - example, a 16K input buffer and a 64K output buffer, more than 95% of the - inflate execution time is spent in this routine. - - Entry assumptions: - - state->mode == LEN - strm->avail_in >= 6 - strm->avail_out >= 258 - start >= strm->avail_out - state->bits < 8 - - On return, state->mode is one of: - - LEN -- ran out of enough output space or enough available input - TYPE -- reached end of block code, inflate() to interpret next block - BAD -- error in block data - - Notes: - - - The maximum input bits used by a length/distance pair is 15 bits for the - length code, 5 bits for the length extra, 15 bits for the distance code, - and 13 bits for the distance extra. This totals 48 bits, or six bytes. - Therefore if strm->avail_in >= 6, then there is enough input to avoid - checking for available input while decoding. - - - The maximum bytes that a single length/distance pair can output is 258 - bytes, which is the maximum length that can be coded. inflate_fast() - requires strm->avail_out >= 258 for each loop to avoid checking for - output space. + * Decode literal, length, and distance codes and write out the resulting + * literal and match bytes until either not enough input or output is + * available, an end-of-block is encountered, or a data error is encountered. + * When large enough input and output buffers are supplied to inflate(), for + * example, a 16K input buffer and a 64K output buffer, more than 95% of the + * inflate execution time is spent in this routine. + * + * Entry assumptions: + * + * state->mode == LEN + * strm->avail_in >= 6 + * strm->avail_out >= 258 + * start >= strm->avail_out + * state->bits < 8 + * + * On return, state->mode is one of: + * + * LEN -- ran out of enough output space or enough available input + * TYPE -- reached end of block code, inflate() to interpret next block + * BAD -- error in block data + * + * Notes: + * + * - The maximum input bits used by a length/distance pair is 15 bits for the + * length code, 5 bits for the length extra, 15 bits for the distance code, + * and 13 bits for the distance extra. This totals 48 bits, or six bytes. + * Therefore if strm->avail_in >= 6, then there is enough input to avoid + * checking for available input while decoding. + * + * - The maximum bytes that a single length/distance pair can output is 258 + * bytes, which is the maximum length that can be coded. inflate_fast() + * requires strm->avail_out >= 258 for each loop to avoid checking for + * output space. */ typedef struct inffast_ar { -/* 64 32 x86 x86_64 */ -/* ar offset register */ -/* 0 0 */ void *esp; /* esp save */ -/* 8 4 */ void *ebp; /* ebp save */ -/* 16 8 */ unsigned char FAR *in; /* esi rsi local strm->next_in */ -/* 24 12 */ unsigned char FAR *last; /* r9 while in < last */ -/* 32 16 */ unsigned char FAR *out; /* edi rdi local strm->next_out */ -/* 40 20 */ unsigned char FAR *beg; /* inflate()'s init next_out */ -/* 48 24 */ unsigned char FAR *end; /* r10 while out < end */ -/* 56 28 */ unsigned char FAR *window;/* size of window, wsize!=0 */ -/* 64 32 */ code const FAR *lcode; /* ebp rbp local strm->lencode */ -/* 72 36 */ code const FAR *dcode; /* r11 local strm->distcode */ -/* 80 40 */ size_t /*unsigned long */hold; /* edx rdx local strm->hold */ -/* 88 44 */ unsigned bits; /* ebx rbx local strm->bits */ -/* 92 48 */ unsigned wsize; /* window size */ -/* 96 52 */ unsigned write; /* window write index */ -/*100 56 */ unsigned lmask; /* r12 mask for lcode */ -/*104 60 */ unsigned dmask; /* r13 mask for dcode */ -/*108 64 */ unsigned len; /* r14 match length */ -/*112 68 */ unsigned dist; /* r15 match distance */ -/*116 72 */ unsigned status; /* set when state chng*/ - } type_ar; +/* 64 32 x86 x86_64 */ +/* ar offset register */ +/* 0 0 */ void *esp; /* esp save */ +/* 8 4 */ void *ebp; /* ebp save */ +/* 16 8 */ unsigned char FAR *in; /* esi rsi local strm->next_in */ +/* 24 12 */ unsigned char FAR *last; /* r9 while in < last */ +/* 32 16 */ unsigned char FAR *out; /* edi rdi local strm->next_out */ +/* 40 20 */ unsigned char FAR *beg; /* inflate()'s init next_out */ +/* 48 24 */ unsigned char FAR *end; /* r10 while out < end */ +/* 56 28 */ unsigned char FAR *window; /* size of window, wsize!=0 */ +/* 64 32 */ code const FAR *lcode; /* ebp rbp local strm->lencode */ +/* 72 36 */ code const FAR *dcode; /* r11 local strm->distcode */ +/* 80 40 */ size_t /* unsigned long */ hold; /* edx rdx local strm->hold */ +/* 88 44 */ unsigned bits; /* ebx rbx local strm->bits */ +/* 92 48 */ unsigned wsize; /* window size */ +/* 96 52 */ unsigned write; /* window write index */ +/* 100 56 */ unsigned lmask; /* r12 mask for lcode */ +/* 104 60 */ unsigned dmask; /* r13 mask for dcode */ +/* 108 64 */ unsigned len; /* r14 match length */ +/* 112 68 */ unsigned dist; /* r15 match distance */ +/* 116 72 */ unsigned status; /* set when state chng */ + } type_ar; #ifdef ASMINF -void inflate_fast(strm, start) -z_streamp strm; -unsigned start; /* inflate()'s starting value for strm->avail_out */ +void +inflate_fast( + z_streamp strm, + unsigned start) { - struct inflate_state FAR *state; - type_ar ar; - void inffas8664fnc(struct inffast_ar * par); + struct inflate_state FAR *state; + type_ar ar; + void inffas8664fnc(struct inffast_ar *par); - -#if (defined( __GNUC__ ) && defined( __amd64__ ) && ! defined( __i386 )) || (defined(_MSC_VER) && defined(_M_AMD64)) -#define PAD_AVAIL_IN 6 -#define PAD_AVAIL_OUT 258 +#if (defined(__GNUC__) && defined(__amd64__) && \ + ! defined(__i386)) || (defined(_MSC_VER) && defined(_M_AMD64)) +#define PAD_AVAIL_IN 6 +#define PAD_AVAIL_OUT 258 #else -#define PAD_AVAIL_IN 5 -#define PAD_AVAIL_OUT 257 +#define PAD_AVAIL_IN 5 +#define PAD_AVAIL_OUT 257 #endif - /* copy state to local variables */ - state = (struct inflate_state FAR *)strm->state; - - ar.in = strm->next_in; - ar.last = ar.in + (strm->avail_in - PAD_AVAIL_IN); - ar.out = strm->next_out; - ar.beg = ar.out - (start - strm->avail_out); - ar.end = ar.out + (strm->avail_out - PAD_AVAIL_OUT); - ar.wsize = state->wsize; - ar.write = state->write; - ar.window = state->window; - ar.hold = state->hold; - ar.bits = state->bits; - ar.lcode = state->lencode; - ar.dcode = state->distcode; - ar.lmask = (1U << state->lenbits) - 1; - ar.dmask = (1U << state->distbits) - 1; - - /* decode literals and length/distances until end-of-block or not enough - input data or output space */ - - /* align in on 1/2 hold size boundary */ - while (((size_t)(void *)ar.in & (sizeof(ar.hold) / 2 - 1)) != 0) { - ar.hold += (unsigned long)*ar.in++ << ar.bits; - ar.bits += 8; - } - - inffas8664fnc(&ar); - - if (ar.status > 1) { - if (ar.status == 2) - strm->msg = "invalid literal/length code"; - else if (ar.status == 3) - strm->msg = "invalid distance code"; - else - strm->msg = "invalid distance too far back"; - state->mode = BAD; - } - else if ( ar.status == 1 ) { - state->mode = TYPE; - } - - /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ - ar.len = ar.bits >> 3; - ar.in -= ar.len; - ar.bits -= ar.len << 3; - ar.hold &= (1U << ar.bits) - 1; - - /* update state and return */ - strm->next_in = ar.in; - strm->next_out = ar.out; - strm->avail_in = (unsigned)(ar.in < ar.last ? - PAD_AVAIL_IN + (ar.last - ar.in) : - PAD_AVAIL_IN - (ar.in - ar.last)); - strm->avail_out = (unsigned)(ar.out < ar.end ? - PAD_AVAIL_OUT + (ar.end - ar.out) : - PAD_AVAIL_OUT - (ar.out - ar.end)); - state->hold = (unsigned long)ar.hold; - state->bits = ar.bits; - return; + /* copy state to local variables */ + state = (struct inflate_state FAR *)strm->state; + + ar.in = strm->next_in; + ar.last = ar.in + (strm->avail_in - PAD_AVAIL_IN); + ar.out = strm->next_out; + ar.beg = ar.out - (start - strm->avail_out); + ar.end = ar.out + (strm->avail_out - PAD_AVAIL_OUT); + ar.wsize = state->wsize; + ar.write = state->write; + ar.window = state->window; + ar.hold = state->hold; + ar.bits = state->bits; + ar.lcode = state->lencode; + ar.dcode = state->distcode; + ar.lmask = (1U << state->lenbits) - 1; + ar.dmask = (1U << state->distbits) - 1; + + /* + * decode literals and length/distances until end-of-block or not enough + * input data or output space + */ + + /* align in on 1/2 hold size boundary */ + while (((size_t)(void *)ar.in & (sizeof (ar.hold) / 2 - 1)) != 0) { + ar.hold += (unsigned long)*ar.in++ << ar.bits; + ar.bits += 8; + } + + inffas8664fnc(&ar); + + if (ar.status > 1) { + if (ar.status == 2) + strm->msg = "invalid literal/length code"; + else if (ar.status == 3) + strm->msg = "invalid distance code"; + else + strm->msg = "invalid distance too far back"; + state->mode = BAD; + } else if (ar.status == 1) { + state->mode = TYPE; + } + +/* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + ar.len = ar.bits >> 3; + ar.in -= ar.len; + ar.bits -= ar.len << 3; + ar.hold &= (1U << ar.bits) - 1; + + /* update state and return */ + strm->next_in = ar.in; + strm->next_out = ar.out; + strm->avail_in = (unsigned)(ar.in < ar.last ? + PAD_AVAIL_IN + (ar.last - ar.in) : + PAD_AVAIL_IN - (ar.in - ar.last)); + strm->avail_out = (unsigned)(ar.out < ar.end ? + PAD_AVAIL_OUT + (ar.end - ar.out) : + PAD_AVAIL_OUT - (ar.out - ar.end)); + state->hold = (unsigned long)ar.hold; + state->bits = ar.bits; } #endif diff --git a/lib/os/windows/zlib-1.2.3/contrib/masmx86/gvmat32c.c b/lib/os/windows/zlib-1.2.3/contrib/masmx86/gvmat32c.c index 89f525cd502..1def0435401 100644 --- a/lib/os/windows/zlib-1.2.3/contrib/masmx86/gvmat32c.c +++ b/lib/os/windows/zlib-1.2.3/contrib/masmx86/gvmat32c.c @@ -1,4 +1,5 @@ -/* gvmat32.c -- C portion of the optimized longest_match for 32 bits x86 +/* + * gvmat32.c -- C portion of the optimized longest_match for 32 bits x86 * Copyright (C) 1995-1996 Jean-loup Gailly and Gilles Vollant. * File written by Gilles Vollant, by modifiying the longest_match * from Jean-loup Gailly in deflate.c @@ -12,12 +13,14 @@ #if defined(ASMV) && (!defined(NOOLDPENTIUMCODE)) #include "deflate.h" -/* if your C compiler don't add underline before function name, - define ADD_UNDERLINE_ASMFUNC */ +/* + * if your C compiler don't add underline before function name, + * define ADD_UNDERLINE_ASMFUNC + */ #ifdef ADD_UNDERLINE_ASMFUNC -#define longest_match_7fff _longest_match_7fff -#define longest_match_686 _longest_match_686 -#define cpudetect32 _cpudetect32 +#define longest_match_7fff _longest_match_7fff +#define longest_match_686 _longest_match_686 +#define cpudetect32 _cpudetect32 #endif @@ -25,37 +28,39 @@ unsigned long cpudetect32(); uInt longest_match_c( deflate_state *s, - IPos cur_match); /* current match */ + IPos cur_match); /* current match */ uInt longest_match_7fff( deflate_state *s, - IPos cur_match); /* current match */ + IPos cur_match); /* current match */ uInt longest_match_686( deflate_state *s, - IPos cur_match); /* current match */ + IPos cur_match); /* current match */ -static uInt iIsPPro=2; +static uInt iIsPPro = 2; -void match_init () +void +match_init() { - iIsPPro = (((cpudetect32()/0x100)&0xf)>=6) ? 1 : 0; + iIsPPro = (((cpudetect32()/0x100)&0xf) >= 6) ? 1 : 0; } -uInt longest_match( +uInt +longest_match( deflate_state *s, - IPos cur_match) /* current match */ + IPos cur_match) /* current match */ { - if (iIsPPro!=0) - return longest_match_686(s,cur_match); + if (iIsPPro != 0) + return (longest_match_686(s, cur_match)); - if (s->w_mask != 0x7fff) - return longest_match_686(s,cur_match); + if (s->w_mask != 0x7fff) + return (longest_match_686(s, cur_match)); - /* now ((s->w_mask == 0x7fff) && (iIsPPro==0)) */ - return longest_match_7fff(s,cur_match); + /* now ((s->w_mask == 0x7fff) && (iIsPPro==0)) */ + return (longest_match_7fff(s, cur_match)); } diff --git a/lib/os/windows/zlib-1.2.3/contrib/minizip/crypt.h b/lib/os/windows/zlib-1.2.3/contrib/minizip/crypt.h index 622f4bc2ec4..0324e408bac 100644 --- a/lib/os/windows/zlib-1.2.3/contrib/minizip/crypt.h +++ b/lib/os/windows/zlib-1.2.3/contrib/minizip/crypt.h @@ -1,132 +1,134 @@ -/* crypt.h -- base code for crypt/uncrypt ZIPfile - - - Version 1.01e, February 12th, 2005 - - Copyright (C) 1998-2005 Gilles Vollant - - This code is a modified version of crypting code in Infozip distribution - - The encryption/decryption parts of this source code (as opposed to the - non-echoing password parts) were originally written in Europe. The - whole source package can be freely distributed, including from the USA. - (Prior to January 2000, re-export from the US was a violation of US law.) - - This encryption code is a direct transcription of the algorithm from - Roger Schlafly, described by Phil Katz in the file appnote.txt. This - file (appnote.txt) is distributed with the PKZIP program (even in the - version without encryption capabilities). - - If you don't need crypting in your application, just define symbols - NOCRYPT and NOUNCRYPT. - - This code support the "Traditional PKWARE Encryption". - - The new AES encryption added on Zip format by Winzip (see the page - http://www.winzip.com/aes_info.htm ) and PKWare PKZip 5.x Strong - Encryption is not supported. -*/ +/* + * crypt.h -- base code for crypt/uncrypt ZIPfile + * + * + * Version 1.01e, February 12th, 2005 + * + * Copyright (C) 1998-2005 Gilles Vollant + * + * This code is a modified version of crypting code in Infozip distribution + * + * The encryption/decryption parts of this source code (as opposed to the + * non-echoing password parts) were originally written in Europe. The + * whole source package can be freely distributed, including from the USA. + * (Prior to January 2000, re-export from the US was a violation of US law.) + * + * This encryption code is a direct transcription of the algorithm from + * Roger Schlafly, described by Phil Katz in the file appnote.txt. This + * file (appnote.txt) is distributed with the PKZIP program (even in the + * version without encryption capabilities). + * + * If you don't need crypting in your application, just define symbols + * NOCRYPT and NOUNCRYPT. + * + * This code support the "Traditional PKWARE Encryption". + * + * The new AES encryption added on Zip format by Winzip (see the page + * http:/ /www.winzip.com/aes_info.htm ) and PKWare PKZip 5.x Strong + * Encryption is not supported. + */ -#define CRC32(c, b) ((*(pcrc_32_tab+(((int)(c) ^ (b)) & 0xff))) ^ ((c) >> 8)) +#define CRC32(c, b) ((*(pcrc_32_tab+(((int)(c) ^ (b)) & 0xff))) ^ ((c) >> 8)) -/*********************************************************************** +/* * Return the next byte in the pseudo-random sequence */ -static int decrypt_byte(unsigned long* pkeys, const unsigned long* pcrc_32_tab) +static int decrypt_byte(unsigned long *pkeys, const unsigned long *pcrc_32_tab) { - unsigned temp; /* POTENTIAL BUG: temp*(temp^1) may overflow in an - * unpredictable manner on 16-bit systems; not a problem - * with any known compiler so far, though */ - - temp = ((unsigned)(*(pkeys+2)) & 0xffff) | 2; - return (int)(((temp * (temp ^ 1)) >> 8) & 0xff); + unsigned temp; + temp = ((unsigned)(*(pkeys+2)) & 0xffff) | 2; + return ((int)(((temp * (temp ^ 1)) >> 8) & 0xff)); } -/*********************************************************************** +/* * Update the encryption keys with the next byte of plain text */ -static int update_keys(unsigned long* pkeys,const unsigned long* pcrc_32_tab,int c) +static int update_keys(unsigned long *pkeys, + const unsigned long *pcrc_32_tab, int c) { - (*(pkeys+0)) = CRC32((*(pkeys+0)), c); - (*(pkeys+1)) += (*(pkeys+0)) & 0xff; - (*(pkeys+1)) = (*(pkeys+1)) * 134775813L + 1; - { - register int keyshift = (int)((*(pkeys+1)) >> 24); - (*(pkeys+2)) = CRC32((*(pkeys+2)), keyshift); - } - return c; + (*(pkeys+0)) = CRC32((*(pkeys+0)), c); + (*(pkeys+1)) += (*(pkeys+0)) & 0xff; + (*(pkeys+1)) = (*(pkeys+1)) * 134775813L + 1; + { + register int keyshift = (int)((*(pkeys+1)) >> 24); + (*(pkeys+2)) = CRC32((*(pkeys+2)), keyshift); + } + return (c); } -/*********************************************************************** +/* * Initialize the encryption keys and the random header according to * the given password. */ -static void init_keys(const char* passwd,unsigned long* pkeys,const unsigned long* pcrc_32_tab) +static void init_keys(const char *passwd, unsigned long *pkeys, + const unsigned long *pcrc_32_tab) { - *(pkeys+0) = 305419896L; - *(pkeys+1) = 591751049L; - *(pkeys+2) = 878082192L; - while (*passwd != '\0') { - update_keys(pkeys,pcrc_32_tab,(int)*passwd); - passwd++; - } + *(pkeys+0) = 305419896L; + *(pkeys+1) = 591751049L; + *(pkeys+2) = 878082192L; + while (*passwd != '\0') { + update_keys(pkeys, pcrc_32_tab, (int)*passwd); + passwd++; + } } -#define zdecode(pkeys,pcrc_32_tab,c) \ - (update_keys(pkeys,pcrc_32_tab,c ^= decrypt_byte(pkeys,pcrc_32_tab))) +#define zdecode(pkeys, pcrc_32_tab, c) \ + (update_keys(pkeys, pcrc_32_tab, c ^= decrypt_byte(pkeys, pcrc_32_tab))) -#define zencode(pkeys,pcrc_32_tab,c,t) \ - (t=decrypt_byte(pkeys,pcrc_32_tab), update_keys(pkeys,pcrc_32_tab,c), t^(c)) +#define zencode(pkeys, pcrc_32_tab, c, t) \ + (t = decrypt_byte(pkeys, pcrc_32_tab), \ + update_keys(pkeys, pcrc_32_tab, c), t^(c)) #ifdef INCLUDECRYPTINGCODE_IFCRYPTALLOWED -#define RAND_HEAD_LEN 12 - /* "last resort" source for second part of crypt seed pattern */ -# ifndef ZCR_SEED2 -# define ZCR_SEED2 3141592654UL /* use PI as default pattern */ -# endif +#define RAND_HEAD_LEN 12 +/* "last resort" source for second part of crypt seed pattern */ +#ifndef ZCR_SEED2 +#define ZCR_SEED2 3141592654UL /* use PI as default pattern */ +#endif static int crypthead(passwd, buf, bufSize, pkeys, pcrc_32_tab, crcForCrypting) - const char *passwd; /* password string */ - unsigned char *buf; /* where to write header */ + const char *passwd; /* password string */ + unsigned char *buf; /* where to write header */ int bufSize; - unsigned long* pkeys; - const unsigned long* pcrc_32_tab; + unsigned long *pkeys; + const unsigned long *pcrc_32_tab; unsigned long crcForCrypting; { - int n; /* index in random header */ - int t; /* temporary */ - int c; /* random byte */ - unsigned char header[RAND_HEAD_LEN-2]; /* random header */ - static unsigned calls = 0; /* ensure different random header each time */ - - if (bufSize> 7) & 0xff; - header[n] = (unsigned char)zencode(pkeys, pcrc_32_tab, c, t); - } - /* Encrypt random header (last two bytes is high word of crc) */ - init_keys(passwd, pkeys, pcrc_32_tab); - for (n = 0; n < RAND_HEAD_LEN-2; n++) - { - buf[n] = (unsigned char)zencode(pkeys, pcrc_32_tab, header[n], t); - } - buf[n++] = zencode(pkeys, pcrc_32_tab, (int)(crcForCrypting >> 16) & 0xff, t); - buf[n++] = zencode(pkeys, pcrc_32_tab, (int)(crcForCrypting >> 24) & 0xff, t); - return n; + int n; /* index in random header */ + int t; /* temporary */ + int c; /* random byte */ + unsigned char header[RAND_HEAD_LEN-2]; /* random header */ + static unsigned calls = 0; + + if (bufSize < RAND_HEAD_LEN) + return (0); + + /* + * First generate RAND_HEAD_LEN-2 random bytes. We encrypt the + * output of rand() to get less predictability, since rand() is + * often poorly implemented. + */ + if (++calls == 1) { + srand((unsigned)(time(NULL) ^ ZCR_SEED2)); + } + init_keys(passwd, pkeys, pcrc_32_tab); + for (n = 0; n < RAND_HEAD_LEN-2; n++) { + c = (rand() >> 7) & 0xff; + header[n] = (unsigned char)zencode(pkeys, pcrc_32_tab, c, t); + } + /* Encrypt random header (last two bytes is high word of crc) */ + init_keys(passwd, pkeys, pcrc_32_tab); + for (n = 0; n < RAND_HEAD_LEN-2; n++) { + buf[n] = (unsigned char)zencode(pkeys, pcrc_32_tab, + header[n], t); + } + buf[n++] = zencode(pkeys, pcrc_32_tab, + (int)(crcForCrypting >> 16) & 0xff, t); + buf[n++] = zencode(pkeys, pcrc_32_tab, + (int)(crcForCrypting >> 24) & 0xff, t); + return (n); } #endif diff --git a/lib/os/windows/zlib-1.2.3/contrib/minizip/ioapi.c b/lib/os/windows/zlib-1.2.3/contrib/minizip/ioapi.c index f1bee23e64b..4287d008e6c 100644 --- a/lib/os/windows/zlib-1.2.3/contrib/minizip/ioapi.c +++ b/lib/os/windows/zlib-1.2.3/contrib/minizip/ioapi.c @@ -1,10 +1,11 @@ -/* ioapi.c -- IO base function header for compress/uncompress .zip - files using zlib + zip or unzip API - - Version 1.01e, February 12th, 2005 - - Copyright (C) 1998-2005 Gilles Vollant -*/ +/* + * ioapi.c -- IO base function header for compress/uncompress .zip + * files using zlib + zip or unzip API + * + * Version 1.01e, February 12th, 2005 + * + * Copyright (C) 1998-2005 Gilles Vollant + */ #include #include @@ -18,160 +19,168 @@ /* I've found an old Unix (a SunOS 4.1.3_U1) without all SEEK_* defined.... */ #ifndef SEEK_CUR -#define SEEK_CUR 1 +#define SEEK_CUR 1 #endif #ifndef SEEK_END -#define SEEK_END 2 +#define SEEK_END 2 #endif #ifndef SEEK_SET -#define SEEK_SET 0 +#define SEEK_SET 0 #endif voidpf ZCALLBACK fopen_file_func OF(( - voidpf opaque, - const char* filename, - int mode)); + voidpf opaque, + const char *filename, + int mode)); uLong ZCALLBACK fread_file_func OF(( - voidpf opaque, - voidpf stream, - void* buf, - uLong size)); + voidpf opaque, + voidpf stream, + void *buf, + uLong size)); uLong ZCALLBACK fwrite_file_func OF(( - voidpf opaque, - voidpf stream, - const void* buf, - uLong size)); + voidpf opaque, + voidpf stream, + const void *buf, + uLong size)); long ZCALLBACK ftell_file_func OF(( - voidpf opaque, - voidpf stream)); + voidpf opaque, + voidpf stream)); long ZCALLBACK fseek_file_func OF(( - voidpf opaque, - voidpf stream, - uLong offset, - int origin)); + voidpf opaque, + voidpf stream, + uLong offset, + int origin)); int ZCALLBACK fclose_file_func OF(( - voidpf opaque, - voidpf stream)); + voidpf opaque, + voidpf stream)); int ZCALLBACK ferror_file_func OF(( - voidpf opaque, - voidpf stream)); + voidpf opaque, + voidpf stream)); -voidpf ZCALLBACK fopen_file_func (opaque, filename, mode) - voidpf opaque; - const char* filename; - int mode; +voidpf ZCALLBACK +fopen_file_func( + voidpf opaque, + const char *filename, + int mode) { - FILE* file = NULL; - const char* mode_fopen = NULL; - if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ) - mode_fopen = "rb"; - else - if (mode & ZLIB_FILEFUNC_MODE_EXISTING) - mode_fopen = "r+b"; - else - if (mode & ZLIB_FILEFUNC_MODE_CREATE) - mode_fopen = "wb"; - - if ((filename!=NULL) && (mode_fopen != NULL)) - file = fopen(filename, mode_fopen); - return file; + FILE *file = NULL; + const char *mode_fopen = NULL; + if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER) == + ZLIB_FILEFUNC_MODE_READ) + mode_fopen = "rb"; + else + if (mode & ZLIB_FILEFUNC_MODE_EXISTING) + mode_fopen = "r+b"; + else + if (mode & ZLIB_FILEFUNC_MODE_CREATE) + mode_fopen = "wb"; + + if ((filename != NULL) && (mode_fopen != NULL)) + file = fopen(filename, mode_fopen); + return (file); } -uLong ZCALLBACK fread_file_func (opaque, stream, buf, size) - voidpf opaque; - voidpf stream; - void* buf; - uLong size; +uLong ZCALLBACK +fread_file_func( + voidpf opaque, + voidpf stream, + void *buf, + uLong size) { - uLong ret; - ret = (uLong)fread(buf, 1, (size_t)size, (FILE *)stream); - return ret; + uLong ret; + ret = (uLong)fread(buf, 1, (size_t)size, (FILE *)stream); + return (ret); } -uLong ZCALLBACK fwrite_file_func (opaque, stream, buf, size) - voidpf opaque; - voidpf stream; - const void* buf; - uLong size; +uLong ZCALLBACK +fwrite_file_func( + voidpf opaque, + voidpf stream, + const void *buf, + uLong size) { - uLong ret; - ret = (uLong)fwrite(buf, 1, (size_t)size, (FILE *)stream); - return ret; + uLong ret; + ret = (uLong)fwrite(buf, 1, (size_t)size, (FILE *)stream); + return (ret); } -long ZCALLBACK ftell_file_func (opaque, stream) - voidpf opaque; - voidpf stream; +long ZCALLBACK +ftell_file_func( + voidpf opaque, + voidpf stream) { - long ret; - ret = ftell((FILE *)stream); - return ret; + long ret; + ret = ftell((FILE *)stream); + return (ret); } -long ZCALLBACK fseek_file_func (opaque, stream, offset, origin) - voidpf opaque; - voidpf stream; - uLong offset; - int origin; +long ZCALLBACK +fseek_file_func( + voidpf opaque, + voidpf stream, + uLong offset, + int origin) { - int fseek_origin=0; - long ret; - switch (origin) - { - case ZLIB_FILEFUNC_SEEK_CUR : - fseek_origin = SEEK_CUR; - break; - case ZLIB_FILEFUNC_SEEK_END : - fseek_origin = SEEK_END; - break; - case ZLIB_FILEFUNC_SEEK_SET : - fseek_origin = SEEK_SET; - break; - default: return -1; - } - ret = 0; - fseek((FILE *)stream, offset, fseek_origin); - return ret; + int fseek_origin = 0; + long ret; + switch (origin) { + case ZLIB_FILEFUNC_SEEK_CUR: + fseek_origin = SEEK_CUR; + break; + case ZLIB_FILEFUNC_SEEK_END: + fseek_origin = SEEK_END; + break; + case ZLIB_FILEFUNC_SEEK_SET: + fseek_origin = SEEK_SET; + break; + default: + return (-1); + } + ret = 0; + fseek((FILE *)stream, offset, fseek_origin); + return (ret); } -int ZCALLBACK fclose_file_func (opaque, stream) - voidpf opaque; - voidpf stream; +int ZCALLBACK +fclose_file_func( + voidpf opaque, + voidpf stream) { - int ret; - ret = fclose((FILE *)stream); - return ret; + int ret; + ret = fclose((FILE *)stream); + return (ret); } -int ZCALLBACK ferror_file_func (opaque, stream) - voidpf opaque; - voidpf stream; +int ZCALLBACK +ferror_file_func( + voidpf opaque, + voidpf stream) { - int ret; - ret = ferror((FILE *)stream); - return ret; + int ret; + ret = ferror((FILE *)stream); + return (ret); } -void fill_fopen_filefunc (pzlib_filefunc_def) - zlib_filefunc_def* pzlib_filefunc_def; +void +fill_fopen_filefunc(zlib_filefunc_def *pzlib_filefunc_def) { - pzlib_filefunc_def->zopen_file = fopen_file_func; - pzlib_filefunc_def->zread_file = fread_file_func; - pzlib_filefunc_def->zwrite_file = fwrite_file_func; - pzlib_filefunc_def->ztell_file = ftell_file_func; - pzlib_filefunc_def->zseek_file = fseek_file_func; - pzlib_filefunc_def->zclose_file = fclose_file_func; - pzlib_filefunc_def->zerror_file = ferror_file_func; - pzlib_filefunc_def->opaque = NULL; + pzlib_filefunc_def->zopen_file = fopen_file_func; + pzlib_filefunc_def->zread_file = fread_file_func; + pzlib_filefunc_def->zwrite_file = fwrite_file_func; + pzlib_filefunc_def->ztell_file = ftell_file_func; + pzlib_filefunc_def->zseek_file = fseek_file_func; + pzlib_filefunc_def->zclose_file = fclose_file_func; + pzlib_filefunc_def->zerror_file = ferror_file_func; + pzlib_filefunc_def->opaque = NULL; } diff --git a/lib/os/windows/zlib-1.2.3/contrib/minizip/ioapi.h b/lib/os/windows/zlib-1.2.3/contrib/minizip/ioapi.h index 7d457baab34..df79cd504cb 100644 --- a/lib/os/windows/zlib-1.2.3/contrib/minizip/ioapi.h +++ b/lib/os/windows/zlib-1.2.3/contrib/minizip/ioapi.h @@ -1,33 +1,34 @@ -/* ioapi.h -- IO base function header for compress/uncompress .zip - files using zlib + zip or unzip API - - Version 1.01e, February 12th, 2005 - - Copyright (C) 1998-2005 Gilles Vollant -*/ +/* + * ioapi.h -- IO base function header for compress/uncompress .zip + * files using zlib + zip or unzip API + * + * Version 1.01e, February 12th, 2005 + * + * Copyright (C) 1998-2005 Gilles Vollant + */ #ifndef _ZLIBIOAPI_H -#define _ZLIBIOAPI_H - +#define _ZLIBIOAPI_H -#define ZLIB_FILEFUNC_SEEK_CUR (1) -#define ZLIB_FILEFUNC_SEEK_END (2) -#define ZLIB_FILEFUNC_SEEK_SET (0) -#define ZLIB_FILEFUNC_MODE_READ (1) -#define ZLIB_FILEFUNC_MODE_WRITE (2) -#define ZLIB_FILEFUNC_MODE_READWRITEFILTER (3) +#define ZLIB_FILEFUNC_SEEK_CUR (1) +#define ZLIB_FILEFUNC_SEEK_END (2) +#define ZLIB_FILEFUNC_SEEK_SET (0) -#define ZLIB_FILEFUNC_MODE_EXISTING (4) -#define ZLIB_FILEFUNC_MODE_CREATE (8) +#define ZLIB_FILEFUNC_MODE_READ (1) +#define ZLIB_FILEFUNC_MODE_WRITE (2) +#define ZLIB_FILEFUNC_MODE_READWRITEFILTER (3) +#define ZLIB_FILEFUNC_MODE_EXISTING (4) +#define ZLIB_FILEFUNC_MODE_CREATE (8) #ifndef ZCALLBACK -#if (defined(WIN32) || defined (WINDOWS) || defined (_WINDOWS)) && defined(CALLBACK) && defined (USEWINDOWS_CALLBACK) -#define ZCALLBACK CALLBACK +#if (defined(WIN32) || defined(WINDOWS) || defined(_WINDOWS)) && \ + defined(CALLBACK) && defined(USEWINDOWS_CALLBACK) +#define ZCALLBACK CALLBACK #else -#define ZCALLBACK +#define ZCALLBACK #endif #endif @@ -35,41 +36,51 @@ extern "C" { #endif -typedef voidpf (ZCALLBACK *open_file_func) OF((voidpf opaque, const char* filename, int mode)); -typedef uLong (ZCALLBACK *read_file_func) OF((voidpf opaque, voidpf stream, void* buf, uLong size)); -typedef uLong (ZCALLBACK *write_file_func) OF((voidpf opaque, voidpf stream, const void* buf, uLong size)); -typedef long (ZCALLBACK *tell_file_func) OF((voidpf opaque, voidpf stream)); -typedef long (ZCALLBACK *seek_file_func) OF((voidpf opaque, voidpf stream, uLong offset, int origin)); -typedef int (ZCALLBACK *close_file_func) OF((voidpf opaque, voidpf stream)); -typedef int (ZCALLBACK *testerror_file_func) OF((voidpf opaque, voidpf stream)); +typedef void *(ZCALLBACK *open_file_func) OF((voidpf opaque, + const char *filename, int mode)); +typedef uLong (ZCALLBACK *read_file_func) OF((voidpf opaque, + voidpf stream, void *buf, uLong size)); +typedef uLong (ZCALLBACK *write_file_func) OF((voidpf opaque, + voidpf stream, const void *buf, uLong size)); +typedef long (ZCALLBACK *tell_file_func) OF((voidpf opaque, + voidpf stream)); +typedef long (ZCALLBACK *seek_file_func) OF((voidpf opaque, + voidpf stream, uLong offset, int origin)); +typedef int (ZCALLBACK *close_file_func) OF((voidpf opaque, + voidpf stream)); +typedef int (ZCALLBACK *testerror_file_func) OF((voidpf opaque, + voidpf stream)); typedef struct zlib_filefunc_def_s { - open_file_func zopen_file; - read_file_func zread_file; - write_file_func zwrite_file; - tell_file_func ztell_file; - seek_file_func zseek_file; - close_file_func zclose_file; - testerror_file_func zerror_file; - voidpf opaque; + open_file_func zopen_file; + read_file_func zread_file; + write_file_func zwrite_file; + tell_file_func ztell_file; + seek_file_func zseek_file; + close_file_func zclose_file; + testerror_file_func zerror_file; + voidpf opaque; } zlib_filefunc_def; +void fill_fopen_filefunc OF((zlib_filefunc_def *pzlib_filefunc_def)); -void fill_fopen_filefunc OF((zlib_filefunc_def* pzlib_filefunc_def)); - -#define ZREAD(filefunc,filestream,buf,size) ((*((filefunc).zread_file))((filefunc).opaque,filestream,buf,size)) -#define ZWRITE(filefunc,filestream,buf,size) ((*((filefunc).zwrite_file))((filefunc).opaque,filestream,buf,size)) -#define ZTELL(filefunc,filestream) ((*((filefunc).ztell_file))((filefunc).opaque,filestream)) -#define ZSEEK(filefunc,filestream,pos,mode) ((*((filefunc).zseek_file))((filefunc).opaque,filestream,pos,mode)) -#define ZCLOSE(filefunc,filestream) ((*((filefunc).zclose_file))((filefunc).opaque,filestream)) -#define ZERROR(filefunc,filestream) ((*((filefunc).zerror_file))((filefunc).opaque,filestream)) - +#define ZREAD(filefunc, filestream, buf, size) \ + ((*((filefunc).zread_file))((filefunc).opaque, filestream, buf, size)) +#define ZWRITE(filefunc, filestream, buf, size) \ + ((*((filefunc).zwrite_file))((filefunc).opaque, filestream, buf, size)) +#define ZTELL(filefunc, filestream) \ + ((*((filefunc).ztell_file))((filefunc).opaque, filestream)) +#define ZSEEK(filefunc, filestream, pos, mode) \ + ((*((filefunc).zseek_file))((filefunc).opaque, filestream, pos, mode)) +#define ZCLOSE(filefunc, filestream) \ + ((*((filefunc).zclose_file))((filefunc).opaque, filestream)) +#define ZERROR(filefunc, filestream) \ + ((*((filefunc).zerror_file))((filefunc).opaque, filestream)) #ifdef __cplusplus } #endif #endif - diff --git a/lib/os/windows/zlib-1.2.3/contrib/minizip/unzip.c b/lib/os/windows/zlib-1.2.3/contrib/minizip/unzip.c index 9ad4766d8db..d120657ead5 100644 --- a/lib/os/windows/zlib-1.2.3/contrib/minizip/unzip.c +++ b/lib/os/windows/zlib-1.2.3/contrib/minizip/unzip.c @@ -1,37 +1,39 @@ -/* unzip.c -- IO for uncompress .zip files using zlib - Version 1.01e, February 12th, 2005 - - Copyright (C) 1998-2005 Gilles Vollant - - Read unzip.h for more info -*/ - -/* Decryption code comes from crypt.c by Info-ZIP but has been greatly reduced in terms of -compatibility with older software. The following is from the original crypt.c. Code -woven in by Terry Thorsen 1/2003. -*/ /* - Copyright (c) 1990-2000 Info-ZIP. All rights reserved. + * unzip.c -- IO for uncompress .zip files using zlib + * Version 1.01e, February 12th, 2005 + * + * Copyright (C) 1998-2005 Gilles Vollant + * + * Read unzip.h for more info + */ - See the accompanying file LICENSE, version 2000-Apr-09 or later - (the contents of which are also included in zip.h) for terms of use. - If, for some reason, all these files are missing, the Info-ZIP license - also may be found at: ftp://ftp.info-zip.org/pub/infozip/license.html -*/ /* - crypt.c (full version) by Info-ZIP. Last revised: [see crypt.h] - - The encryption/decryption parts of this source code (as opposed to the - non-echoing password parts) were originally written in Europe. The - whole source package can be freely distributed, including from the USA. - (Prior to January 2000, re-export from the US was a violation of US law.) + * Decryption code comes from crypt.c by Info-ZIP but has been greatly + * reduced in terms of compatibility with older software. The following + * is from the original crypt.c. Code woven in by Terry Thorsen 1/2003. + */ +/* + * Copyright (c) 1990-2000 Info-ZIP. All rights reserved. + * + * See the accompanying file LICENSE, version 2000-Apr-09 or later + * (the contents of which are also included in zip.h) for terms of use. + * If, for some reason, all these files are missing, the Info-ZIP license + * also may be found at: ftp://ftp.info-zip.org/pub/infozip/license.html + */ +/* + * crypt.c (full version) by Info-ZIP. Last revised: [see crypt.h] + * + * The encryption/decryption parts of this source code (as opposed to the + * non-echoing password parts) were originally written in Europe. The + * whole source package can be freely distributed, including from the USA. + * (Prior to January 2000, re-export from the US was a violation of US law.) */ /* - This encryption code is a direct transcription of the algorithm from - Roger Schlafly, described by Phil Katz in the file appnote.txt. This - file (appnote.txt) is distributed with the PKZIP program (even in the - version without encryption capabilities). + * This encryption code is a direct transcription of the algorithm from + * Roger Schlafly, described by Phil Katz in the file appnote.txt. This + * file (appnote.txt) is distributed with the PKZIP program (even in the + * version without encryption capabilities). */ @@ -42,113 +44,130 @@ woven in by Terry Thorsen 1/2003. #include "unzip.h" #ifdef STDC -# include -# include -# include +#include +#include +#include #endif #ifdef NO_ERRNO_H extern int errno; #else -# include +#include #endif #ifndef local -# define local static +#define local static #endif /* compile with -Dlocal if your debugger can't find static symbols */ #ifndef CASESENSITIVITYDEFAULT_NO -# if !defined(unix) && !defined(CASESENSITIVITYDEFAULT_YES) -# define CASESENSITIVITYDEFAULT_NO -# endif +#if !defined(unix) && !defined(CASESENSITIVITYDEFAULT_YES) +#define CASESENSITIVITYDEFAULT_NO +#endif #endif #ifndef UNZ_BUFSIZE -#define UNZ_BUFSIZE (16384) +#define UNZ_BUFSIZE (16384) #endif #ifndef UNZ_MAXFILENAMEINZIP -#define UNZ_MAXFILENAMEINZIP (256) +#define UNZ_MAXFILENAMEINZIP (256) #endif #ifndef ALLOC -# define ALLOC(size) (malloc(size)) +#define ALLOC(size) (malloc(size)) #endif #ifndef TRYFREE -# define TRYFREE(p) {if (p) free(p);} +#define TRYFREE(p) { if (p) free(p); } #endif -#define SIZECENTRALDIRITEM (0x2e) -#define SIZEZIPLOCALHEADER (0x1e) +#define SIZECENTRALDIRITEM (0x2e) +#define SIZEZIPLOCALHEADER (0x1e) const char unz_copyright[] = - " unzip 1.01 Copyright 1998-2004 Gilles Vollant - http://www.winimage.com/zLibDll"; + " unzip 1.01 Copyright 1998-2004 Gilles Vollant - " + "http://www.winimage.com/zLibDll"; -/* unz_file_info_interntal contain internal info about a file in zipfile*/ +/* unz_file_info_interntal contain internal info about a file in zipfile */ typedef struct unz_file_info_internal_s { - uLong offset_curfile;/* relative offset of local header 4 bytes */ + uLong offset_curfile; /* relative offset of local header 4 bytes */ } unz_file_info_internal; -/* file_in_zip_read_info_s contain internal information about a file in zipfile, - when reading and decompress it */ +/* + * file_in_zip_read_info_s contain internal information about a file + * in zipfile, when reading and decompress it + */ typedef struct { - char *read_buffer; /* internal buffer for compressed data */ - z_stream stream; /* zLib stream structure for inflate */ - - uLong pos_in_zipfile; /* position in byte on the zipfile, for fseek*/ - uLong stream_initialised; /* flag set if stream structure is initialised*/ - - uLong offset_local_extrafield;/* offset of the local extra field */ - uInt size_local_extrafield;/* size of the local extra field */ - uLong pos_local_extrafield; /* position in the local extra field in read*/ - - uLong crc32; /* crc32 of all data uncompressed */ - uLong crc32_wait; /* crc32 we must obtain after decompress all */ - uLong rest_read_compressed; /* number of byte to be decompressed */ - uLong rest_read_uncompressed;/*number of byte to be obtained after decomp*/ - zlib_filefunc_def z_filefunc; - voidpf filestream; /* io structore of the zipfile */ - uLong compression_method; /* compression method (0==store) */ - uLong byte_before_the_zipfile;/* byte before the zipfile, (>0 for sfx)*/ - int raw; + char *read_buffer; /* internal buffer for compressed data */ + z_stream stream; /* zLib stream structure for inflate */ + /* position in byte on the zipfile, for fseek */ + uLong pos_in_zipfile; + /* flag set if stream structure is initialised */ + uLong stream_initialised; + + uLong offset_local_extrafield; /* offset of the local extra field */ + uInt size_local_extrafield; /* size of the local extra field */ + /* position in the local extra field in read */ + uLong pos_local_extrafield; + + uLong crc32; /* crc32 of all data uncompressed */ + uLong crc32_wait; /* crc32 we must obtain after decompress all */ + uLong rest_read_compressed; /* number of byte to be decompressed */ + /* number of byte to be obtained after decomp */ + uLong rest_read_uncompressed; + zlib_filefunc_def z_filefunc; + voidpf filestream; /* io structore of the zipfile */ + uLong compression_method; /* compression method (0==store) */ + /* byte before the zipfile, (>0 for sfx) */ + uLong byte_before_the_zipfile; + int raw; } file_in_zip_read_info_s; -/* unz_s contain internal information about the zipfile -*/ +/* + * unz_s contain internal information about the zipfile + */ typedef struct { - zlib_filefunc_def z_filefunc; - voidpf filestream; /* io structore of the zipfile */ - unz_global_info gi; /* public global information */ - uLong byte_before_the_zipfile;/* byte before the zipfile, (>0 for sfx)*/ - uLong num_file; /* number of the current file in the zipfile*/ - uLong pos_in_central_dir; /* pos of the current file in the central dir*/ - uLong current_file_ok; /* flag about the usability of the current file*/ - uLong central_pos; /* position of the beginning of the central dir*/ - - uLong size_central_dir; /* size of the central directory */ - uLong offset_central_dir; /* offset of start of central directory with - respect to the starting disk number */ - - unz_file_info cur_file_info; /* public info about the current file in zip*/ - unz_file_info_internal cur_file_info_internal; /* private info about it*/ - file_in_zip_read_info_s* pfile_in_zip_read; /* structure about the current - file if we are decompressing it */ - int encrypted; -# ifndef NOUNCRYPT - unsigned long keys[3]; /* keys defining the pseudo-random sequence */ - const unsigned long* pcrc_32_tab; -# endif + zlib_filefunc_def z_filefunc; + voidpf filestream; /* io structore of the zipfile */ + unz_global_info gi; /* public global information */ + /* byte before the zipfile, (>0 for sfx) */ + uLong byte_before_the_zipfile; + uLong num_file; /* number of the current file in the zipfile */ + /* pos of the current file in the central dir */ + uLong pos_in_central_dir; + /* flag about the usability of the current file */ + uLong current_file_ok; + uLong central_pos; /* position of the beginning of the central dir */ + + uLong size_central_dir; /* size of the central directory */ + uLong offset_central_dir; + /* + * offset of start of central directory with + * respect to the starting disk number + */ + + /* public info about the current file in zip */ + unz_file_info cur_file_info; + /* private info about it */ + unz_file_info_internal cur_file_info_internal; + /* structure about the current file if we are decompressing it */ + file_in_zip_read_info_s* pfile_in_zip_read; + + int encrypted; +#ifndef NOUNCRYPT + unsigned long keys[3]; /* keys defining the pseudo-random sequence */ + const unsigned long *pcrc_32_tab; +#endif } unz_s; @@ -156,11 +175,11 @@ typedef struct #include "crypt.h" #endif -/* =========================================================================== - Read a byte from a gz_stream; update next_in and avail_in. Return EOF - for end of file. - IN assertion: the stream s has been sucessfully opened for reading. -*/ +/* + * Read a byte from a gz_stream; update next_in and avail_in. Return EOF + * for end of file. + * IN assertion: the stream s has been sucessfully opened for reading. + */ local int unzlocal_getByte OF(( @@ -168,57 +187,57 @@ local int unzlocal_getByte OF(( voidpf filestream, int *pi)); -local int unzlocal_getByte(pzlib_filefunc_def,filestream,pi) - const zlib_filefunc_def* pzlib_filefunc_def; - voidpf filestream; - int *pi; +local int +unzlocal_getByte( + const zlib_filefunc_def *pzlib_filefunc_def, + voidpf filestream, + int *pi) { - unsigned char c; - int err = (int)ZREAD(*pzlib_filefunc_def,filestream,&c,1); - if (err==1) - { - *pi = (int)c; - return UNZ_OK; - } - else - { - if (ZERROR(*pzlib_filefunc_def,filestream)) - return UNZ_ERRNO; - else - return UNZ_EOF; - } + unsigned char c; + int err = (int)ZREAD(*pzlib_filefunc_def, filestream, &c, 1); + if (err == 1) { + *pi = (int)c; + return (UNZ_OK); + } else { + if (ZERROR(*pzlib_filefunc_def, filestream)) + return (UNZ_ERRNO); + else + return (UNZ_EOF); + } } -/* =========================================================================== - Reads a long in LSB order from the given gz_stream. Sets -*/ -local int unzlocal_getShort OF(( - const zlib_filefunc_def* pzlib_filefunc_def, +/* + * Reads a long in LSB order from the given gz_stream. Sets + */ +local int +unzlocal_getShort OF(( + const zlib_filefunc_def *pzlib_filefunc_def, voidpf filestream, uLong *pX)); -local int unzlocal_getShort (pzlib_filefunc_def,filestream,pX) - const zlib_filefunc_def* pzlib_filefunc_def; - voidpf filestream; - uLong *pX; +local int +unzlocal_getShort( + const zlib_filefunc_def *pzlib_filefunc_def, + voidpf filestream, + uLong *pX) { - uLong x ; - int i; - int err; - - err = unzlocal_getByte(pzlib_filefunc_def,filestream,&i); - x = (uLong)i; - - if (err==UNZ_OK) - err = unzlocal_getByte(pzlib_filefunc_def,filestream,&i); - x += ((uLong)i)<<8; - - if (err==UNZ_OK) - *pX = x; - else - *pX = 0; - return err; + uLong x; + int i; + int err; + + err = unzlocal_getByte(pzlib_filefunc_def, filestream, &i); + x = (uLong)i; + + if (err == UNZ_OK) + err = unzlocal_getByte(pzlib_filefunc_def, filestream, &i); + x += ((uLong)i)<<8; + + if (err == UNZ_OK) + *pX = x; + else + *pX = 0; + return (err); } local int unzlocal_getLong OF(( @@ -226,1373 +245,1424 @@ local int unzlocal_getLong OF(( voidpf filestream, uLong *pX)); -local int unzlocal_getLong (pzlib_filefunc_def,filestream,pX) - const zlib_filefunc_def* pzlib_filefunc_def; - voidpf filestream; - uLong *pX; +local int +unzlocal_getLong( + const zlib_filefunc_def *pzlib_filefunc_def, + voidpf filestream, + uLong *pX) { - uLong x ; - int i; - int err; - - err = unzlocal_getByte(pzlib_filefunc_def,filestream,&i); - x = (uLong)i; - - if (err==UNZ_OK) - err = unzlocal_getByte(pzlib_filefunc_def,filestream,&i); - x += ((uLong)i)<<8; - - if (err==UNZ_OK) - err = unzlocal_getByte(pzlib_filefunc_def,filestream,&i); - x += ((uLong)i)<<16; - - if (err==UNZ_OK) - err = unzlocal_getByte(pzlib_filefunc_def,filestream,&i); - x += ((uLong)i)<<24; - - if (err==UNZ_OK) - *pX = x; - else - *pX = 0; - return err; + uLong x; + int i; + int err; + + err = unzlocal_getByte(pzlib_filefunc_def, filestream, &i); + x = (uLong)i; + + if (err == UNZ_OK) + err = unzlocal_getByte(pzlib_filefunc_def, filestream, &i); + x += ((uLong)i)<<8; + + if (err == UNZ_OK) + err = unzlocal_getByte(pzlib_filefunc_def, filestream, &i); + x += ((uLong)i)<<16; + + if (err == UNZ_OK) + err = unzlocal_getByte(pzlib_filefunc_def, filestream, &i); + x += ((uLong)i)<<24; + + if (err == UNZ_OK) + *pX = x; + else + *pX = 0; + return (err); } /* My own strcmpi / strcasecmp */ -local int strcmpcasenosensitive_internal (fileName1,fileName2) - const char* fileName1; - const char* fileName2; +local int +strcmpcasenosensitive_internal( + const char *fileName1, + const char *fileName2) { - for (;;) - { - char c1=*(fileName1++); - char c2=*(fileName2++); - if ((c1>='a') && (c1<='z')) - c1 -= 0x20; - if ((c2>='a') && (c2<='z')) - c2 -= 0x20; - if (c1=='\0') - return ((c2=='\0') ? 0 : -1); - if (c2=='\0') - return 1; - if (c1c2) - return 1; - } + for (;;) { + char c1 = *(fileName1++); + char c2 = *(fileName2++); + if ((c1 >= 'a') && (c1 <= 'z')) + c1 -= 0x20; + if ((c2 >= 'a') && (c2 <= 'z')) + c2 -= 0x20; + if (c1 == '\0') + return ((c2 == '\0') ? 0 : -1); + if (c2 == '\0') + return (1); + if (c1 < c2) + return (-1); + if (c1 > c2) + return (1); + } } #ifdef CASESENSITIVITYDEFAULT_NO -#define CASESENSITIVITYDEFAULTVALUE 2 +#define CASESENSITIVITYDEFAULTVALUE 2 #else -#define CASESENSITIVITYDEFAULTVALUE 1 +#define CASESENSITIVITYDEFAULTVALUE 1 #endif #ifndef STRCMPCASENOSENTIVEFUNCTION -#define STRCMPCASENOSENTIVEFUNCTION strcmpcasenosensitive_internal +#define STRCMPCASENOSENTIVEFUNCTION strcmpcasenosensitive_internal #endif /* - Compare two filename (fileName1,fileName2). - If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp) - If iCaseSenisivity = 2, comparision is not case sensitivity (like strcmpi - or strcasecmp) - If iCaseSenisivity = 0, case sensitivity is defaut of your operating system - (like 1 on Unix, 2 on Windows) - -*/ -extern int ZEXPORT unzStringFileNameCompare (fileName1,fileName2,iCaseSensitivity) - const char* fileName1; - const char* fileName2; - int iCaseSensitivity; + * Compare two filename (fileName1,fileName2). + * If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp) + * If iCaseSenisivity = 2, comparision is not case sensitivity + * (like strcmpi or strcasecmp) + * If iCaseSensitivity = 0, case sensitivity is defaut of your + * operating system + * (like 1 on Unix, 2 on Windows) + * + */ +extern int ZEXPORT +unzStringFileNameCompare( + const char *fileName1, + const char *fileName2, + int iCaseSensitivity) { - if (iCaseSensitivity==0) - iCaseSensitivity=CASESENSITIVITYDEFAULTVALUE; + if (iCaseSensitivity == 0) + iCaseSensitivity = CASESENSITIVITYDEFAULTVALUE; - if (iCaseSensitivity==1) - return strcmp(fileName1,fileName2); + if (iCaseSensitivity == 1) + return (strcmp(fileName1, fileName2)); - return STRCMPCASENOSENTIVEFUNCTION(fileName1,fileName2); + return (STRCMPCASENOSENTIVEFUNCTION(fileName1, fileName2)); } #ifndef BUFREADCOMMENT -#define BUFREADCOMMENT (0x400) +#define BUFREADCOMMENT (0x400) #endif /* - Locate the Central directory of a zipfile (at the end, just before - the global comment) -*/ + * Locate the Central directory of a zipfile (at the end, just before + * the global comment) + */ local uLong unzlocal_SearchCentralDir OF(( - const zlib_filefunc_def* pzlib_filefunc_def, + const zlib_filefunc_def *pzlib_filefunc_def, voidpf filestream)); -local uLong unzlocal_SearchCentralDir(pzlib_filefunc_def,filestream) - const zlib_filefunc_def* pzlib_filefunc_def; - voidpf filestream; +local uLong +unzlocal_SearchCentralDir( + const zlib_filefunc_def *pzlib_filefunc_def, + voidpf filestream) { - unsigned char* buf; - uLong uSizeFile; - uLong uBackRead; - uLong uMaxBack=0xffff; /* maximum size of global comment */ - uLong uPosFound=0; - - if (ZSEEK(*pzlib_filefunc_def,filestream,0,ZLIB_FILEFUNC_SEEK_END) != 0) - return 0; - - - uSizeFile = ZTELL(*pzlib_filefunc_def,filestream); - - if (uMaxBack>uSizeFile) - uMaxBack = uSizeFile; - - buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4); - if (buf==NULL) - return 0; - - uBackRead = 4; - while (uBackReaduMaxBack) - uBackRead = uMaxBack; - else - uBackRead+=BUFREADCOMMENT; - uReadPos = uSizeFile-uBackRead ; - - uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ? - (BUFREADCOMMENT+4) : (uSizeFile-uReadPos); - if (ZSEEK(*pzlib_filefunc_def,filestream,uReadPos,ZLIB_FILEFUNC_SEEK_SET)!=0) - break; - - if (ZREAD(*pzlib_filefunc_def,filestream,buf,uReadSize)!=uReadSize) - break; - - for (i=(int)uReadSize-3; (i--)>0;) - if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) && - ((*(buf+i+2))==0x05) && ((*(buf+i+3))==0x06)) - { - uPosFound = uReadPos+i; - break; - } - - if (uPosFound!=0) - break; - } - TRYFREE(buf); - return uPosFound; + unsigned char *buf; + uLong uSizeFile; + uLong uBackRead; + uLong uMaxBack = 0xffff; /* maximum size of global comment */ + uLong uPosFound = 0; + + if (ZSEEK(*pzlib_filefunc_def, filestream, 0, + ZLIB_FILEFUNC_SEEK_END) != 0) + return (0); + + + uSizeFile = ZTELL(*pzlib_filefunc_def, filestream); + + if (uMaxBack > uSizeFile) + uMaxBack = uSizeFile; + + buf = (unsigned char *)ALLOC(BUFREADCOMMENT+4); + if (buf == NULL) + return (0); + + uBackRead = 4; + while (uBackRead < uMaxBack) { + uLong uReadSize, uReadPos; + int i; + if (uBackRead+BUFREADCOMMENT > uMaxBack) + uBackRead = uMaxBack; + else + uBackRead += BUFREADCOMMENT; + uReadPos = uSizeFile-uBackRead; + + uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ? + (BUFREADCOMMENT+4) : (uSizeFile-uReadPos); + if (ZSEEK(*pzlib_filefunc_def, filestream, uReadPos, + ZLIB_FILEFUNC_SEEK_SET) != 0) + break; + + if (ZREAD(*pzlib_filefunc_def, filestream, buf, + uReadSize) != uReadSize) + break; + + for (i = (int)uReadSize-3; (i--) > 0; ) + if (((*(buf+i)) == 0x50) && ((*(buf+i+1)) == 0x4b) && + ((*(buf+i+2)) == 0x05) && ((*(buf+i+3)) == 0x06)) { + uPosFound = uReadPos+i; + break; + } + + if (uPosFound != 0) + break; + } + TRYFREE(buf); + return (uPosFound); } /* - Open a Zip file. path contain the full pathname (by example, - on a Windows NT computer "c:\\test\\zlib114.zip" or on an Unix computer - "zlib/zlib114.zip". - If the zipfile cannot be opened (file doesn't exist or in not valid), the - return value is NULL. - Else, the return value is a unzFile Handle, usable with other function - of this unzip package. -*/ -extern unzFile ZEXPORT unzOpen2 (path, pzlib_filefunc_def) - const char *path; - zlib_filefunc_def* pzlib_filefunc_def; + * Open a Zip file. path contain the full pathname (by example, + * on a Windows NT computer "c:\\test\\zlib114.zip" or on an Unix computer + * "zlib/zlib114.zip". + * If the zipfile cannot be opened (file doesn't exist or in not valid), the + * return value is NULL. + * Else, the return value is a unzFile Handle, usable with other function + * of this unzip package. + */ +extern unzFile ZEXPORT +unzOpen2( + const char *path, + zlib_filefunc_def *pzlib_filefunc_def) { - unz_s us; - unz_s *s; - uLong central_pos,uL; - - uLong number_disk; /* number of the current dist, used for - spaning ZIP, unsupported, always 0*/ - uLong number_disk_with_CD; /* number the the disk with central dir, used - for spaning ZIP, unsupported, always 0*/ - uLong number_entry_CD; /* total number of entries in - the central dir - (same than number_entry on nospan) */ - - int err=UNZ_OK; - - if (unz_copyright[0]!=' ') - return NULL; - - if (pzlib_filefunc_def==NULL) - fill_fopen_filefunc(&us.z_filefunc); - else - us.z_filefunc = *pzlib_filefunc_def; - - us.filestream= (*(us.z_filefunc.zopen_file))(us.z_filefunc.opaque, - path, - ZLIB_FILEFUNC_MODE_READ | - ZLIB_FILEFUNC_MODE_EXISTING); - if (us.filestream==NULL) - return NULL; - - central_pos = unzlocal_SearchCentralDir(&us.z_filefunc,us.filestream); - if (central_pos==0) - err=UNZ_ERRNO; - - if (ZSEEK(us.z_filefunc, us.filestream, - central_pos,ZLIB_FILEFUNC_SEEK_SET)!=0) - err=UNZ_ERRNO; - - /* the signature, already checked */ - if (unzlocal_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK) - err=UNZ_ERRNO; - - /* number of this disk */ - if (unzlocal_getShort(&us.z_filefunc, us.filestream,&number_disk)!=UNZ_OK) - err=UNZ_ERRNO; - - /* number of the disk with the start of the central directory */ - if (unzlocal_getShort(&us.z_filefunc, us.filestream,&number_disk_with_CD)!=UNZ_OK) - err=UNZ_ERRNO; - - /* total number of entries in the central dir on this disk */ - if (unzlocal_getShort(&us.z_filefunc, us.filestream,&us.gi.number_entry)!=UNZ_OK) - err=UNZ_ERRNO; - - /* total number of entries in the central dir */ - if (unzlocal_getShort(&us.z_filefunc, us.filestream,&number_entry_CD)!=UNZ_OK) - err=UNZ_ERRNO; - - if ((number_entry_CD!=us.gi.number_entry) || - (number_disk_with_CD!=0) || - (number_disk!=0)) - err=UNZ_BADZIPFILE; - - /* size of the central directory */ - if (unzlocal_getLong(&us.z_filefunc, us.filestream,&us.size_central_dir)!=UNZ_OK) - err=UNZ_ERRNO; - - /* offset of start of central directory with respect to the - starting disk number */ - if (unzlocal_getLong(&us.z_filefunc, us.filestream,&us.offset_central_dir)!=UNZ_OK) - err=UNZ_ERRNO; - - /* zipfile comment length */ - if (unzlocal_getShort(&us.z_filefunc, us.filestream,&us.gi.size_comment)!=UNZ_OK) - err=UNZ_ERRNO; - - if ((central_pospfile_in_zip_read!=NULL) - unzCloseCurrentFile(file); + if (s->pfile_in_zip_read != NULL) + unzCloseCurrentFile(file); - ZCLOSE(s->z_filefunc, s->filestream); - TRYFREE(s); - return UNZ_OK; + ZCLOSE(s->z_filefunc, s->filestream); + TRYFREE(s); + return (UNZ_OK); } /* - Write info about the ZipFile in the *pglobal_info structure. - No preparation of the structure is needed - return UNZ_OK if there is no problem. */ -extern int ZEXPORT unzGetGlobalInfo (file,pglobal_info) - unzFile file; - unz_global_info *pglobal_info; + * Write info about the ZipFile in the *pglobal_info structure. + * No preparation of the structure is needed + * return UNZ_OK if there is no problem. + */ +extern int ZEXPORT +unzGetGlobalInfo( + unzFile file, + unz_global_info *pglobal_info) { - unz_s* s; - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz_s*)file; - *pglobal_info=s->gi; - return UNZ_OK; + unz_s *s; + if (file == NULL) + return (UNZ_PARAMERROR); + s = (unz_s *)file; + *pglobal_info = s->gi; + return (UNZ_OK); } /* - Translate date/time from Dos format to tm_unz (readable more easilty) -*/ -local void unzlocal_DosDateToTmuDate (ulDosDate, ptm) - uLong ulDosDate; - tm_unz* ptm; + * Translate date/time from Dos format to tm_unz (readable more easilty) + */ +local void +unzlocal_DosDateToTmuDate( + uLong ulDosDate, + tm_unz *ptm) { - uLong uDate; - uDate = (uLong)(ulDosDate>>16); - ptm->tm_mday = (uInt)(uDate&0x1f) ; - ptm->tm_mon = (uInt)((((uDate)&0x1E0)/0x20)-1) ; - ptm->tm_year = (uInt)(((uDate&0x0FE00)/0x0200)+1980) ; - - ptm->tm_hour = (uInt) ((ulDosDate &0xF800)/0x800); - ptm->tm_min = (uInt) ((ulDosDate&0x7E0)/0x20) ; - ptm->tm_sec = (uInt) (2*(ulDosDate&0x1f)) ; + uLong uDate; + uDate = (uLong)(ulDosDate>>16); + ptm->tm_mday = (uInt)(uDate&0x1f); + ptm->tm_mon = (uInt)((((uDate)&0x1E0)/0x20)-1); + ptm->tm_year = (uInt)(((uDate&0x0FE00)/0x0200)+1980); + + ptm->tm_hour = (uInt) ((ulDosDate &0xF800)/0x800); + ptm->tm_min = (uInt) ((ulDosDate&0x7E0)/0x20); + ptm->tm_sec = (uInt) (2*(ulDosDate&0x1f)); } /* - Get Info about the current file in the zipfile, with internal only info -*/ -local int unzlocal_GetCurrentFileInfoInternal OF((unzFile file, - unz_file_info *pfile_info, - unz_file_info_internal - *pfile_info_internal, - char *szFileName, - uLong fileNameBufferSize, - void *extraField, - uLong extraFieldBufferSize, - char *szComment, - uLong commentBufferSize)); - -local int unzlocal_GetCurrentFileInfoInternal (file, - pfile_info, - pfile_info_internal, - szFileName, fileNameBufferSize, - extraField, extraFieldBufferSize, - szComment, commentBufferSize) - unzFile file; - unz_file_info *pfile_info; - unz_file_info_internal *pfile_info_internal; - char *szFileName; - uLong fileNameBufferSize; - void *extraField; - uLong extraFieldBufferSize; - char *szComment; - uLong commentBufferSize; + * Get Info about the current file in the zipfile, with internal only info + */ +local int +unzlocal_GetCurrentFileInfoInternal OF((unzFile file, + unz_file_info *pfile_info, + unz_file_info_internal *pfile_info_internal, + char *szFileName, + uLong fileNameBufferSize, + void *extraField, + uLong extraFieldBufferSize, + char *szComment, + uLong commentBufferSize)); + +local int +unzlocal_GetCurrentFileInfoInternal( + unzFile file, + unz_file_info *pfile_info, + unz_file_info_internal *pfile_info_internal, + char *szFileName, + uLong fileNameBufferSize, + void *extraField, + uLong extraFieldBufferSize, + char *szComment, + uLong commentBufferSize) { - unz_s* s; - unz_file_info file_info; - unz_file_info_internal file_info_internal; - int err=UNZ_OK; - uLong uMagic; - long lSeek=0; - - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz_s*)file; - if (ZSEEK(s->z_filefunc, s->filestream, - s->pos_in_central_dir+s->byte_before_the_zipfile, - ZLIB_FILEFUNC_SEEK_SET)!=0) - err=UNZ_ERRNO; - - - /* we check the magic */ - if (err==UNZ_OK) - if (unzlocal_getLong(&s->z_filefunc, s->filestream,&uMagic) != UNZ_OK) - err=UNZ_ERRNO; - else if (uMagic!=0x02014b50) - err=UNZ_BADZIPFILE; - - if (unzlocal_getShort(&s->z_filefunc, s->filestream,&file_info.version) != UNZ_OK) - err=UNZ_ERRNO; - - if (unzlocal_getShort(&s->z_filefunc, s->filestream,&file_info.version_needed) != UNZ_OK) - err=UNZ_ERRNO; - - if (unzlocal_getShort(&s->z_filefunc, s->filestream,&file_info.flag) != UNZ_OK) - err=UNZ_ERRNO; - - if (unzlocal_getShort(&s->z_filefunc, s->filestream,&file_info.compression_method) != UNZ_OK) - err=UNZ_ERRNO; - - if (unzlocal_getLong(&s->z_filefunc, s->filestream,&file_info.dosDate) != UNZ_OK) - err=UNZ_ERRNO; - - unzlocal_DosDateToTmuDate(file_info.dosDate,&file_info.tmu_date); - - if (unzlocal_getLong(&s->z_filefunc, s->filestream,&file_info.crc) != UNZ_OK) - err=UNZ_ERRNO; - - if (unzlocal_getLong(&s->z_filefunc, s->filestream,&file_info.compressed_size) != UNZ_OK) - err=UNZ_ERRNO; - - if (unzlocal_getLong(&s->z_filefunc, s->filestream,&file_info.uncompressed_size) != UNZ_OK) - err=UNZ_ERRNO; - - if (unzlocal_getShort(&s->z_filefunc, s->filestream,&file_info.size_filename) != UNZ_OK) - err=UNZ_ERRNO; - - if (unzlocal_getShort(&s->z_filefunc, s->filestream,&file_info.size_file_extra) != UNZ_OK) - err=UNZ_ERRNO; - - if (unzlocal_getShort(&s->z_filefunc, s->filestream,&file_info.size_file_comment) != UNZ_OK) - err=UNZ_ERRNO; - - if (unzlocal_getShort(&s->z_filefunc, s->filestream,&file_info.disk_num_start) != UNZ_OK) - err=UNZ_ERRNO; - - if (unzlocal_getShort(&s->z_filefunc, s->filestream,&file_info.internal_fa) != UNZ_OK) - err=UNZ_ERRNO; - - if (unzlocal_getLong(&s->z_filefunc, s->filestream,&file_info.external_fa) != UNZ_OK) - err=UNZ_ERRNO; - - if (unzlocal_getLong(&s->z_filefunc, s->filestream,&file_info_internal.offset_curfile) != UNZ_OK) - err=UNZ_ERRNO; - - lSeek+=file_info.size_filename; - if ((err==UNZ_OK) && (szFileName!=NULL)) - { - uLong uSizeRead ; - if (file_info.size_filename0) && (fileNameBufferSize>0)) - if (ZREAD(s->z_filefunc, s->filestream,szFileName,uSizeRead)!=uSizeRead) - err=UNZ_ERRNO; - lSeek -= uSizeRead; - } - - - if ((err==UNZ_OK) && (extraField!=NULL)) - { - uLong uSizeRead ; - if (file_info.size_file_extraz_filefunc, s->filestream,lSeek,ZLIB_FILEFUNC_SEEK_CUR)==0) - lSeek=0; - else - err=UNZ_ERRNO; - if ((file_info.size_file_extra>0) && (extraFieldBufferSize>0)) - if (ZREAD(s->z_filefunc, s->filestream,extraField,uSizeRead)!=uSizeRead) - err=UNZ_ERRNO; - lSeek += file_info.size_file_extra - uSizeRead; - } - else - lSeek+=file_info.size_file_extra; - - - if ((err==UNZ_OK) && (szComment!=NULL)) - { - uLong uSizeRead ; - if (file_info.size_file_commentz_filefunc, s->filestream,lSeek,ZLIB_FILEFUNC_SEEK_CUR)==0) - lSeek=0; - else - err=UNZ_ERRNO; - if ((file_info.size_file_comment>0) && (commentBufferSize>0)) - if (ZREAD(s->z_filefunc, s->filestream,szComment,uSizeRead)!=uSizeRead) - err=UNZ_ERRNO; - lSeek+=file_info.size_file_comment - uSizeRead; - } - else - lSeek+=file_info.size_file_comment; - - if ((err==UNZ_OK) && (pfile_info!=NULL)) - *pfile_info=file_info; - - if ((err==UNZ_OK) && (pfile_info_internal!=NULL)) - *pfile_info_internal=file_info_internal; - - return err; + unz_s *s; + unz_file_info file_info; + unz_file_info_internal file_info_internal; + int err = UNZ_OK; + uLong uMagic; + long lSeek = 0; + + if (file == NULL) + return (UNZ_PARAMERROR); + s = (unz_s*)file; + if (ZSEEK(s->z_filefunc, s->filestream, + s->pos_in_central_dir+s->byte_before_the_zipfile, + ZLIB_FILEFUNC_SEEK_SET) != 0) + err = UNZ_ERRNO; + + + /* we check the magic */ + if (err == UNZ_OK) + if (unzlocal_getLong(&s->z_filefunc, s->filestream, + &uMagic) != UNZ_OK) + err = UNZ_ERRNO; + else if (uMagic != 0x02014b50) + err = UNZ_BADZIPFILE; + if (unzlocal_getShort(&s->z_filefunc, s->filestream, + &file_info.version) != UNZ_OK) + err = UNZ_ERRNO; + + if (unzlocal_getShort(&s->z_filefunc, s->filestream, + &file_info.version_needed) != UNZ_OK) + err = UNZ_ERRNO; + + if (unzlocal_getShort(&s->z_filefunc, s->filestream, + &file_info.flag) != UNZ_OK) + err = UNZ_ERRNO; + + if (unzlocal_getShort(&s->z_filefunc, s->filestream, + &file_info.compression_method) != UNZ_OK) + err = UNZ_ERRNO; + + if (unzlocal_getLong(&s->z_filefunc, s->filestream, + &file_info.dosDate) != UNZ_OK) + err = UNZ_ERRNO; + + unzlocal_DosDateToTmuDate(file_info.dosDate, &file_info.tmu_date); + + if (unzlocal_getLong(&s->z_filefunc, s->filestream, + &file_info.crc) != UNZ_OK) + err = UNZ_ERRNO; + + if (unzlocal_getLong(&s->z_filefunc, s->filestream, + &file_info.compressed_size) != UNZ_OK) + err = UNZ_ERRNO; + + if (unzlocal_getLong(&s->z_filefunc, s->filestream, + &file_info.uncompressed_size) != UNZ_OK) + err = UNZ_ERRNO; + + if (unzlocal_getShort(&s->z_filefunc, s->filestream, + &file_info.size_filename) != UNZ_OK) + err = UNZ_ERRNO; + + if (unzlocal_getShort(&s->z_filefunc, s->filestream, + &file_info.size_file_extra) != UNZ_OK) + err = UNZ_ERRNO; + + if (unzlocal_getShort(&s->z_filefunc, s->filestream, + &file_info.size_file_comment) != UNZ_OK) + err = UNZ_ERRNO; + + if (unzlocal_getShort(&s->z_filefunc, s->filestream, + &file_info.disk_num_start) != UNZ_OK) + err = UNZ_ERRNO; + + if (unzlocal_getShort(&s->z_filefunc, s->filestream, + &file_info.internal_fa) != UNZ_OK) + err = UNZ_ERRNO; + + if (unzlocal_getLong(&s->z_filefunc, s->filestream, + &file_info.external_fa) != UNZ_OK) + err = UNZ_ERRNO; + + if (unzlocal_getLong(&s->z_filefunc, s->filestream, + &file_info_internal.offset_curfile) != UNZ_OK) + err = UNZ_ERRNO; + + lSeek += file_info.size_filename; + if ((err == UNZ_OK) && (szFileName != NULL)) { + uLong uSizeRead; + if (file_info.size_filename < fileNameBufferSize) { + *(szFileName+file_info.size_filename) = '\0'; + uSizeRead = file_info.size_filename; + } else + uSizeRead = fileNameBufferSize; + + if ((file_info.size_filename > 0) && (fileNameBufferSize > 0)) + if (ZREAD(s->z_filefunc, s->filestream, + szFileName, uSizeRead) != uSizeRead) + err = UNZ_ERRNO; + lSeek -= uSizeRead; + } + + + if ((err == UNZ_OK) && (extraField != NULL)) { + uLong uSizeRead; + if (file_info.size_file_extra < extraFieldBufferSize) + uSizeRead = file_info.size_file_extra; + else + uSizeRead = extraFieldBufferSize; + + if (lSeek != 0) + if (ZSEEK(s->z_filefunc, s->filestream, + lSeek, ZLIB_FILEFUNC_SEEK_CUR) == 0) + lSeek = 0; + else + err = UNZ_ERRNO; + if ((file_info.size_file_extra > 0) && + (extraFieldBufferSize > 0)) + if (ZREAD(s->z_filefunc, s->filestream, + extraField, uSizeRead) != uSizeRead) + err = UNZ_ERRNO; + lSeek += file_info.size_file_extra - uSizeRead; + } else + lSeek += file_info.size_file_extra; + + + if ((err == UNZ_OK) && (szComment != NULL)) { + uLong uSizeRead; + if (file_info.size_file_comment < commentBufferSize) { + *(szComment+file_info.size_file_comment) = '\0'; + uSizeRead = file_info.size_file_comment; + } else + uSizeRead = commentBufferSize; + + if (lSeek != 0) + if (ZSEEK(s->z_filefunc, s->filestream, + lSeek, ZLIB_FILEFUNC_SEEK_CUR) == 0) + lSeek = 0; + else + err = UNZ_ERRNO; + if ((file_info.size_file_comment > 0) && + (commentBufferSize > 0)) + if (ZREAD(s->z_filefunc, s->filestream, + szComment, uSizeRead) != uSizeRead) + err = UNZ_ERRNO; + lSeek += file_info.size_file_comment - uSizeRead; + } else + lSeek += file_info.size_file_comment; + + if ((err == UNZ_OK) && (pfile_info != NULL)) + *pfile_info = file_info; + + if ((err == UNZ_OK) && (pfile_info_internal != NULL)) + *pfile_info_internal = file_info_internal; + + return (err); } - - /* - Write info about the ZipFile in the *pglobal_info structure. - No preparation of the structure is needed - return UNZ_OK if there is no problem. -*/ -extern int ZEXPORT unzGetCurrentFileInfo (file, - pfile_info, - szFileName, fileNameBufferSize, - extraField, extraFieldBufferSize, - szComment, commentBufferSize) - unzFile file; - unz_file_info *pfile_info; - char *szFileName; - uLong fileNameBufferSize; - void *extraField; - uLong extraFieldBufferSize; - char *szComment; - uLong commentBufferSize; + * Write info about the ZipFile in the *pglobal_info structure. + * No preparation of the structure is needed + * return UNZ_OK if there is no problem. + */ +extern int ZEXPORT +unzGetCurrentFileInfo( + unzFile file, + unz_file_info *pfile_info, + char *szFileName, + uLong fileNameBufferSize, + void *extraField, + uLong extraFieldBufferSize, + char *szComment, + uLong commentBufferSize) { - return unzlocal_GetCurrentFileInfoInternal(file,pfile_info,NULL, - szFileName,fileNameBufferSize, - extraField,extraFieldBufferSize, - szComment,commentBufferSize); + return (unzlocal_GetCurrentFileInfoInternal(file, + pfile_info, NULL, szFileName, fileNameBufferSize, + extraField, extraFieldBufferSize, szComment, + commentBufferSize)); } /* - Set the current file of the zipfile to the first file. - return UNZ_OK if there is no problem -*/ -extern int ZEXPORT unzGoToFirstFile (file) - unzFile file; + * Set the current file of the zipfile to the first file. + * return UNZ_OK if there is no problem + */ +extern int ZEXPORT unzGoToFirstFile( + unzFile file) { - int err=UNZ_OK; - unz_s* s; - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz_s*)file; - s->pos_in_central_dir=s->offset_central_dir; - s->num_file=0; - err=unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info, - &s->cur_file_info_internal, - NULL,0,NULL,0,NULL,0); - s->current_file_ok = (err == UNZ_OK); - return err; + int err = UNZ_OK; + unz_s *s; + if (file == NULL) + return (UNZ_PARAMERROR); + s = (unz_s*)file; + s->pos_in_central_dir = s->offset_central_dir; + s->num_file = 0; + err = unzlocal_GetCurrentFileInfoInternal(file, &s->cur_file_info, + &s->cur_file_info_internal, + NULL, 0, NULL, 0, NULL, 0); + s->current_file_ok = (err == UNZ_OK); + return (err); } /* - Set the current file of the zipfile to the next file. - return UNZ_OK if there is no problem - return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest. -*/ -extern int ZEXPORT unzGoToNextFile (file) - unzFile file; + * Set the current file of the zipfile to the next file. + * return UNZ_OK if there is no problem + * return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest. + */ +extern int ZEXPORT +unzGoToNextFile( + unzFile file) { - unz_s* s; - int err; - - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz_s*)file; - if (!s->current_file_ok) - return UNZ_END_OF_LIST_OF_FILE; - if (s->gi.number_entry != 0xffff) /* 2^16 files overflow hack */ - if (s->num_file+1==s->gi.number_entry) - return UNZ_END_OF_LIST_OF_FILE; - - s->pos_in_central_dir += SIZECENTRALDIRITEM + s->cur_file_info.size_filename + - s->cur_file_info.size_file_extra + s->cur_file_info.size_file_comment ; - s->num_file++; - err = unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info, - &s->cur_file_info_internal, - NULL,0,NULL,0,NULL,0); - s->current_file_ok = (err == UNZ_OK); - return err; + unz_s *s; + int err; + + if (file == NULL) + return (UNZ_PARAMERROR); + s = (unz_s*)file; + if (!s->current_file_ok) + return (UNZ_END_OF_LIST_OF_FILE); + if (s->gi.number_entry != 0xffff) /* 2^16 files overflow hack */ + if (s->num_file+1 == s->gi.number_entry) + return (UNZ_END_OF_LIST_OF_FILE); + + s->pos_in_central_dir += SIZECENTRALDIRITEM + + s->cur_file_info.size_filename + + s->cur_file_info.size_file_extra + + s->cur_file_info.size_file_comment; + s->num_file++; + err = unzlocal_GetCurrentFileInfoInternal(file, &s->cur_file_info, + &s->cur_file_info_internal, + NULL, 0, NULL, 0, NULL, 0); + s->current_file_ok = (err == UNZ_OK); + return (err); } /* - Try locate the file szFileName in the zipfile. - For the iCaseSensitivity signification, see unzipStringFileNameCompare - - return value : - UNZ_OK if the file is found. It becomes the current file. - UNZ_END_OF_LIST_OF_FILE if the file is not found -*/ -extern int ZEXPORT unzLocateFile (file, szFileName, iCaseSensitivity) - unzFile file; - const char *szFileName; - int iCaseSensitivity; + * Try locate the file szFileName in the zipfile. + * For the iCaseSensitivity signification,see unzipStringFileNameCompare + * return value : + * UNZ_OK if the file is found. It becomes the current file. + * UNZ_END_OF_LIST_OF_FILE if the file is not found + */ +extern int ZEXPORT +unzLocateFile( + unzFile file, + const char *szFileName, + int iCaseSensitivity) { - unz_s* s; - int err; - - /* We remember the 'current' position in the file so that we can jump - * back there if we fail. - */ - unz_file_info cur_file_infoSaved; - unz_file_info_internal cur_file_info_internalSaved; - uLong num_fileSaved; - uLong pos_in_central_dirSaved; - - - if (file==NULL) - return UNZ_PARAMERROR; - - if (strlen(szFileName)>=UNZ_MAXFILENAMEINZIP) - return UNZ_PARAMERROR; - - s=(unz_s*)file; - if (!s->current_file_ok) - return UNZ_END_OF_LIST_OF_FILE; - - /* Save the current state */ - num_fileSaved = s->num_file; - pos_in_central_dirSaved = s->pos_in_central_dir; - cur_file_infoSaved = s->cur_file_info; - cur_file_info_internalSaved = s->cur_file_info_internal; - - err = unzGoToFirstFile(file); - - while (err == UNZ_OK) - { - char szCurrentFileName[UNZ_MAXFILENAMEINZIP+1]; - err = unzGetCurrentFileInfo(file,NULL, - szCurrentFileName,sizeof(szCurrentFileName)-1, - NULL,0,NULL,0); - if (err == UNZ_OK) - { - if (unzStringFileNameCompare(szCurrentFileName, - szFileName,iCaseSensitivity)==0) - return UNZ_OK; - err = unzGoToNextFile(file); - } - } - - /* We failed, so restore the state of the 'current file' to where we - * were. - */ - s->num_file = num_fileSaved ; - s->pos_in_central_dir = pos_in_central_dirSaved ; - s->cur_file_info = cur_file_infoSaved; - s->cur_file_info_internal = cur_file_info_internalSaved; - return err; + unz_s *s; + int err; + + /* + * We remember the 'current' position in the file so that we can jump + * back there if we fail. + */ + unz_file_info cur_file_infoSaved; + unz_file_info_internal cur_file_info_internalSaved; + uLong num_fileSaved; + uLong pos_in_central_dirSaved; + + + if (file == NULL) + return (UNZ_PARAMERROR); + + if (strlen(szFileName) >= UNZ_MAXFILENAMEINZIP) + return (UNZ_PARAMERROR); + + s = (unz_s*)file; + if (!s->current_file_ok) + return (UNZ_END_OF_LIST_OF_FILE); + + /* Save the current state */ + num_fileSaved = s->num_file; + pos_in_central_dirSaved = s->pos_in_central_dir; + cur_file_infoSaved = s->cur_file_info; + cur_file_info_internalSaved = s->cur_file_info_internal; + + err = unzGoToFirstFile(file); + + while (err == UNZ_OK) { + char szCurrentFileName[UNZ_MAXFILENAMEINZIP+1]; + err = unzGetCurrentFileInfo(file, NULL, + szCurrentFileName, sizeof (szCurrentFileName)-1, + NULL, 0, NULL, 0); + if (err == UNZ_OK) { + if (unzStringFileNameCompare(szCurrentFileName, + szFileName, iCaseSensitivity) == 0) + return (UNZ_OK); + err = unzGoToNextFile(file); + } + } + + /* + * We failed, so restore the state of the 'current file' to where we + * were. + */ + s->num_file = num_fileSaved; + s->pos_in_central_dir = pos_in_central_dirSaved; + s->cur_file_info = cur_file_infoSaved; + s->cur_file_info_internal = cur_file_info_internalSaved; + return (err); } /* -/////////////////////////////////////////// -// Contributed by Ryan Haksi (mailto://cryogen@infoserve.net) -// I need random access -// -// Further optimization could be realized by adding an ability -// to cache the directory in memory. The goal being a single -// comprehensive file read to put the file I need in a memory. -*/ + * + * Contributed by Ryan Haksi (mailto://cryogen@infoserve.net) + * I need random access + * + * Further optimization could be realized by adding an ability + * to cache the directory in memory. The goal being a single + * comprehensive file read to put the file I need in a memory. + */ /* -typedef struct unz_file_pos_s -{ - uLong pos_in_zip_directory; // offset in file - uLong num_of_file; // # of file -} unz_file_pos; -*/ - -extern int ZEXPORT unzGetFilePos(file, file_pos) - unzFile file; - unz_file_pos* file_pos; + * typedef struct unz_file_pos_s + * { + * uLong pos_in_zip_directory; // offset in file + * uLong num_of_file; // #of file + * } unz_file_pos; + */ + +extern int ZEXPORT +unzGetFilePos( + unzFile file, + unz_file_pos *file_pos) { - unz_s* s; + unz_s *s; - if (file==NULL || file_pos==NULL) - return UNZ_PARAMERROR; - s=(unz_s*)file; - if (!s->current_file_ok) - return UNZ_END_OF_LIST_OF_FILE; + if (file == NULL || file_pos == NULL) + return (UNZ_PARAMERROR); + s = (unz_s*)file; + if (!s->current_file_ok) + return (UNZ_END_OF_LIST_OF_FILE); - file_pos->pos_in_zip_directory = s->pos_in_central_dir; - file_pos->num_of_file = s->num_file; + file_pos->pos_in_zip_directory = s->pos_in_central_dir; + file_pos->num_of_file = s->num_file; - return UNZ_OK; + return (UNZ_OK); } -extern int ZEXPORT unzGoToFilePos(file, file_pos) - unzFile file; - unz_file_pos* file_pos; +extern int ZEXPORT +unzGoToFilePos( + unzFile file, + unz_file_pos *file_pos) { - unz_s* s; - int err; - - if (file==NULL || file_pos==NULL) - return UNZ_PARAMERROR; - s=(unz_s*)file; - - /* jump to the right spot */ - s->pos_in_central_dir = file_pos->pos_in_zip_directory; - s->num_file = file_pos->num_of_file; - - /* set the current file */ - err = unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info, - &s->cur_file_info_internal, - NULL,0,NULL,0,NULL,0); - /* return results */ - s->current_file_ok = (err == UNZ_OK); - return err; + unz_s *s; + int err; + + if (file == NULL || file_pos == NULL) + return (UNZ_PARAMERROR); + s = (unz_s*)file; + + /* jump to the right spot */ + s->pos_in_central_dir = file_pos->pos_in_zip_directory; + s->num_file = file_pos->num_of_file; + + /* set the current file */ + err = unzlocal_GetCurrentFileInfoInternal(file, &s->cur_file_info, + &s->cur_file_info_internal, + NULL, 0, NULL, 0, NULL, 0); + /* return results */ + s->current_file_ok = (err == UNZ_OK); + return (err); } /* -// Unzip Helper Functions - should be here? -/////////////////////////////////////////// -*/ + * Unzip Helper Functions - should be here? + */ /* - Read the local header of the current zipfile - Check the coherency of the local header and info in the end of central - directory about this file - store in *piSizeVar the size of extra info in local header - (filename and size of extra field data) -*/ -local int unzlocal_CheckCurrentFileCoherencyHeader (s,piSizeVar, - poffset_local_extrafield, - psize_local_extrafield) - unz_s* s; - uInt* piSizeVar; - uLong *poffset_local_extrafield; - uInt *psize_local_extrafield; + * Read the local header of the current zipfile + * Check the coherency of the local header and info in the end of central + * directory about this file + * store in *piSizeVar the size of extra info in local header + * (filename and size of extra field data) + */ +local int +unzlocal_CheckCurrentFileCoherencyHeader( + unz_s *s, + uInt *piSizeVar, + uLong *poffset_local_extrafield, + uInt *psize_local_extrafield) { - uLong uMagic,uData,uFlags; - uLong size_filename; - uLong size_extra_field; - int err=UNZ_OK; - - *piSizeVar = 0; - *poffset_local_extrafield = 0; - *psize_local_extrafield = 0; - - if (ZSEEK(s->z_filefunc, s->filestream,s->cur_file_info_internal.offset_curfile + - s->byte_before_the_zipfile,ZLIB_FILEFUNC_SEEK_SET)!=0) - return UNZ_ERRNO; - - - if (err==UNZ_OK) - if (unzlocal_getLong(&s->z_filefunc, s->filestream,&uMagic) != UNZ_OK) - err=UNZ_ERRNO; - else if (uMagic!=0x04034b50) - err=UNZ_BADZIPFILE; - - if (unzlocal_getShort(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) - err=UNZ_ERRNO; + uLong uMagic, uData, uFlags; + uLong size_filename; + uLong size_extra_field; + int err = UNZ_OK; + + *piSizeVar = 0; + *poffset_local_extrafield = 0; + *psize_local_extrafield = 0; + + if (ZSEEK(s->z_filefunc, s->filestream, + s->cur_file_info_internal.offset_curfile + + s->byte_before_the_zipfile, ZLIB_FILEFUNC_SEEK_SET) != 0) + return (UNZ_ERRNO); + + if (err == UNZ_OK) + if (unzlocal_getLong(&s->z_filefunc, s->filestream, + &uMagic) != UNZ_OK) + err = UNZ_ERRNO; + else if (uMagic != 0x04034b50) + err = UNZ_BADZIPFILE; + + if (unzlocal_getShort(&s->z_filefunc, s->filestream, + &uData) != UNZ_OK) + err = UNZ_ERRNO; /* - else if ((err==UNZ_OK) && (uData!=s->cur_file_info.wVersion)) - err=UNZ_BADZIPFILE; -*/ - if (unzlocal_getShort(&s->z_filefunc, s->filestream,&uFlags) != UNZ_OK) - err=UNZ_ERRNO; - - if (unzlocal_getShort(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) - err=UNZ_ERRNO; - else if ((err==UNZ_OK) && (uData!=s->cur_file_info.compression_method)) - err=UNZ_BADZIPFILE; - - if ((err==UNZ_OK) && (s->cur_file_info.compression_method!=0) && - (s->cur_file_info.compression_method!=Z_DEFLATED)) - err=UNZ_BADZIPFILE; - - if (unzlocal_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* date/time */ - err=UNZ_ERRNO; - - if (unzlocal_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* crc */ - err=UNZ_ERRNO; - else if ((err==UNZ_OK) && (uData!=s->cur_file_info.crc) && - ((uFlags & 8)==0)) - err=UNZ_BADZIPFILE; - - if (unzlocal_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* size compr */ - err=UNZ_ERRNO; - else if ((err==UNZ_OK) && (uData!=s->cur_file_info.compressed_size) && - ((uFlags & 8)==0)) - err=UNZ_BADZIPFILE; - - if (unzlocal_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* size uncompr */ - err=UNZ_ERRNO; - else if ((err==UNZ_OK) && (uData!=s->cur_file_info.uncompressed_size) && - ((uFlags & 8)==0)) - err=UNZ_BADZIPFILE; - - - if (unzlocal_getShort(&s->z_filefunc, s->filestream,&size_filename) != UNZ_OK) - err=UNZ_ERRNO; - else if ((err==UNZ_OK) && (size_filename!=s->cur_file_info.size_filename)) - err=UNZ_BADZIPFILE; - - *piSizeVar += (uInt)size_filename; - - if (unzlocal_getShort(&s->z_filefunc, s->filestream,&size_extra_field) != UNZ_OK) - err=UNZ_ERRNO; - *poffset_local_extrafield= s->cur_file_info_internal.offset_curfile + - SIZEZIPLOCALHEADER + size_filename; - *psize_local_extrafield = (uInt)size_extra_field; - - *piSizeVar += (uInt)size_extra_field; - - return err; + * else if ((err==UNZ_OK) && (uData!=s->cur_file_info.wVersion)) + * err=UNZ_BADZIPFILE; + */ + if (unzlocal_getShort(&s->z_filefunc, s->filestream, + &uFlags) != UNZ_OK) + err = UNZ_ERRNO; + + if (unzlocal_getShort(&s->z_filefunc, s->filestream, + &uData) != UNZ_OK) + err = UNZ_ERRNO; + else if ((err == UNZ_OK) && + (uData != s->cur_file_info.compression_method)) + err = UNZ_BADZIPFILE; + + if ((err == UNZ_OK) && (s->cur_file_info.compression_method != 0) && + (s->cur_file_info.compression_method != Z_DEFLATED)) + err = UNZ_BADZIPFILE; + + if (unzlocal_getLong(&s->z_filefunc, s->filestream, + &uData) != UNZ_OK) /* date/time */ + err = UNZ_ERRNO; + + if (unzlocal_getLong(&s->z_filefunc, s->filestream, + &uData) != UNZ_OK) /* crc */ + err = UNZ_ERRNO; + else if ((err == UNZ_OK) && (uData != s->cur_file_info.crc) && + ((uFlags & 8) == 0)) + err = UNZ_BADZIPFILE; + + if (unzlocal_getLong(&s->z_filefunc, s->filestream, + &uData) != UNZ_OK) /* size compr */ + err = UNZ_ERRNO; + else if ((err == UNZ_OK) && + (uData != s->cur_file_info.compressed_size) && + ((uFlags & 8) == 0)) + err = UNZ_BADZIPFILE; + + if (unzlocal_getLong(&s->z_filefunc, s->filestream, + &uData) != UNZ_OK) /* size uncompr */ + err = UNZ_ERRNO; + else if ((err == UNZ_OK) && + (uData != s->cur_file_info.uncompressed_size) && + ((uFlags & 8) == 0)) + err = UNZ_BADZIPFILE; + + + if (unzlocal_getShort(&s->z_filefunc, s->filestream, + &size_filename) != UNZ_OK) + err = UNZ_ERRNO; + else if ((err == UNZ_OK) && + (size_filename != s->cur_file_info.size_filename)) + err = UNZ_BADZIPFILE; + + *piSizeVar += (uInt)size_filename; + + if (unzlocal_getShort(&s->z_filefunc, s->filestream, + &size_extra_field) != UNZ_OK) + err = UNZ_ERRNO; + *poffset_local_extrafield = s->cur_file_info_internal.offset_curfile + + SIZEZIPLOCALHEADER + size_filename; + *psize_local_extrafield = (uInt)size_extra_field; + + *piSizeVar += (uInt)size_extra_field; + + return (err); } /* - Open for reading data the current file in the zipfile. - If there is no error and the file is opened, the return value is UNZ_OK. -*/ -extern int ZEXPORT unzOpenCurrentFile3 (file, method, level, raw, password) - unzFile file; - int* method; - int* level; - int raw; - const char* password; + * Open for reading data the current file in the zipfile. + * If there is no error and the file is opened, the return value is UNZ_OK. + */ +extern int ZEXPORT +unzOpenCurrentFile3( + unzFile file, + int *method, + int *level, + int raw, + const char *password) { - int err=UNZ_OK; - uInt iSizeVar; - unz_s* s; - file_in_zip_read_info_s* pfile_in_zip_read_info; - uLong offset_local_extrafield; /* offset of the local extra field */ - uInt size_local_extrafield; /* size of the local extra field */ -# ifndef NOUNCRYPT - char source[12]; -# else - if (password != NULL) - return UNZ_PARAMERROR; -# endif - - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz_s*)file; - if (!s->current_file_ok) - return UNZ_PARAMERROR; - - if (s->pfile_in_zip_read != NULL) - unzCloseCurrentFile(file); - - if (unzlocal_CheckCurrentFileCoherencyHeader(s,&iSizeVar, - &offset_local_extrafield,&size_local_extrafield)!=UNZ_OK) - return UNZ_BADZIPFILE; - - pfile_in_zip_read_info = (file_in_zip_read_info_s*) - ALLOC(sizeof(file_in_zip_read_info_s)); - if (pfile_in_zip_read_info==NULL) - return UNZ_INTERNALERROR; - - pfile_in_zip_read_info->read_buffer=(char*)ALLOC(UNZ_BUFSIZE); - pfile_in_zip_read_info->offset_local_extrafield = offset_local_extrafield; - pfile_in_zip_read_info->size_local_extrafield = size_local_extrafield; - pfile_in_zip_read_info->pos_local_extrafield=0; - pfile_in_zip_read_info->raw=raw; - - if (pfile_in_zip_read_info->read_buffer==NULL) - { - TRYFREE(pfile_in_zip_read_info); - return UNZ_INTERNALERROR; - } - - pfile_in_zip_read_info->stream_initialised=0; - - if (method!=NULL) - *method = (int)s->cur_file_info.compression_method; - - if (level!=NULL) - { - *level = 6; - switch (s->cur_file_info.flag & 0x06) - { - case 6 : *level = 1; break; - case 4 : *level = 2; break; - case 2 : *level = 9; break; - } - } - - if ((s->cur_file_info.compression_method!=0) && - (s->cur_file_info.compression_method!=Z_DEFLATED)) - err=UNZ_BADZIPFILE; - - pfile_in_zip_read_info->crc32_wait=s->cur_file_info.crc; - pfile_in_zip_read_info->crc32=0; - pfile_in_zip_read_info->compression_method = - s->cur_file_info.compression_method; - pfile_in_zip_read_info->filestream=s->filestream; - pfile_in_zip_read_info->z_filefunc=s->z_filefunc; - pfile_in_zip_read_info->byte_before_the_zipfile=s->byte_before_the_zipfile; - - pfile_in_zip_read_info->stream.total_out = 0; - - if ((s->cur_file_info.compression_method==Z_DEFLATED) && - (!raw)) - { - pfile_in_zip_read_info->stream.zalloc = (alloc_func)0; - pfile_in_zip_read_info->stream.zfree = (free_func)0; - pfile_in_zip_read_info->stream.opaque = (voidpf)0; - pfile_in_zip_read_info->stream.next_in = (voidpf)0; - pfile_in_zip_read_info->stream.avail_in = 0; - - err=inflateInit2(&pfile_in_zip_read_info->stream, -MAX_WBITS); - if (err == Z_OK) - pfile_in_zip_read_info->stream_initialised=1; - else - { - TRYFREE(pfile_in_zip_read_info); - return err; - } - /* windowBits is passed < 0 to tell that there is no zlib header. - * Note that in this case inflate *requires* an extra "dummy" byte - * after the compressed stream in order to complete decompression and - * return Z_STREAM_END. - * In unzip, i don't wait absolutely Z_STREAM_END because I known the - * size of both compressed and uncompressed data - */ - } - pfile_in_zip_read_info->rest_read_compressed = - s->cur_file_info.compressed_size ; - pfile_in_zip_read_info->rest_read_uncompressed = - s->cur_file_info.uncompressed_size ; - - - pfile_in_zip_read_info->pos_in_zipfile = - s->cur_file_info_internal.offset_curfile + SIZEZIPLOCALHEADER + - iSizeVar; - - pfile_in_zip_read_info->stream.avail_in = (uInt)0; - - s->pfile_in_zip_read = pfile_in_zip_read_info; - -# ifndef NOUNCRYPT - if (password != NULL) - { - int i; - s->pcrc_32_tab = get_crc_table(); - init_keys(password,s->keys,s->pcrc_32_tab); - if (ZSEEK(s->z_filefunc, s->filestream, - s->pfile_in_zip_read->pos_in_zipfile + - s->pfile_in_zip_read->byte_before_the_zipfile, - SEEK_SET)!=0) - return UNZ_INTERNALERROR; - if(ZREAD(s->z_filefunc, s->filestream,source, 12)<12) - return UNZ_INTERNALERROR; - - for (i = 0; i<12; i++) - zdecode(s->keys,s->pcrc_32_tab,source[i]); - - s->pfile_in_zip_read->pos_in_zipfile+=12; - s->encrypted=1; - } -# endif - - - return UNZ_OK; + int err = UNZ_OK; + uInt iSizeVar; + unz_s *s; + file_in_zip_read_info_s *pfile_in_zip_read_info; + uLong offset_local_extrafield; /* offset of the local extra field */ + uInt size_local_extrafield; /* size of the local extra field */ +#ifndef NOUNCRYPT + char source[12]; +#else + if (password != NULL) + return (UNZ_PARAMERROR); +#endif + + if (file == NULL) + return (UNZ_PARAMERROR); + s = (unz_s*)file; + if (!s->current_file_ok) + return (UNZ_PARAMERROR); + + if (s->pfile_in_zip_read != NULL) + unzCloseCurrentFile(file); + + if (unzlocal_CheckCurrentFileCoherencyHeader(s, &iSizeVar, + &offset_local_extrafield, &size_local_extrafield) != UNZ_OK) + return (UNZ_BADZIPFILE); + + pfile_in_zip_read_info = (file_in_zip_read_info_s *) + ALLOC(sizeof (file_in_zip_read_info_s)); + if (pfile_in_zip_read_info == NULL) + return (UNZ_INTERNALERROR); + + pfile_in_zip_read_info->read_buffer = (char *)ALLOC(UNZ_BUFSIZE); + pfile_in_zip_read_info->offset_local_extrafield = + offset_local_extrafield; + pfile_in_zip_read_info->size_local_extrafield = size_local_extrafield; + pfile_in_zip_read_info->pos_local_extrafield = 0; + pfile_in_zip_read_info->raw = raw; + + if (pfile_in_zip_read_info->read_buffer == NULL) { + TRYFREE(pfile_in_zip_read_info); + return (UNZ_INTERNALERROR); + } + + pfile_in_zip_read_info->stream_initialised = 0; + + if (method != NULL) + *method = (int)s->cur_file_info.compression_method; + + if (level != NULL) { + *level = 6; + switch (s->cur_file_info.flag & 0x06) { + case 6 : *level = 1; break; + case 4 : *level = 2; break; + case 2 : *level = 9; break; + } + } + + if ((s->cur_file_info.compression_method != 0) && + (s->cur_file_info.compression_method != Z_DEFLATED)) + err = UNZ_BADZIPFILE; + + pfile_in_zip_read_info->crc32_wait = s->cur_file_info.crc; + pfile_in_zip_read_info->crc32 = 0; + pfile_in_zip_read_info->compression_method = + s->cur_file_info.compression_method; + pfile_in_zip_read_info->filestream = s->filestream; + pfile_in_zip_read_info->z_filefunc = s->z_filefunc; + pfile_in_zip_read_info->byte_before_the_zipfile = + s->byte_before_the_zipfile; + + pfile_in_zip_read_info->stream.total_out = 0; + + if ((s->cur_file_info.compression_method == Z_DEFLATED) && + (!raw)) { + pfile_in_zip_read_info->stream.zalloc = (alloc_func)0; + pfile_in_zip_read_info->stream.zfree = (free_func)0; + pfile_in_zip_read_info->stream.opaque = (voidpf)0; + pfile_in_zip_read_info->stream.next_in = (voidpf)0; + pfile_in_zip_read_info->stream.avail_in = 0; + + err = inflateInit2(&pfile_in_zip_read_info->stream, -MAX_WBITS); + if (err == Z_OK) + pfile_in_zip_read_info->stream_initialised = 1; + else { + TRYFREE(pfile_in_zip_read_info); + return (err); + } + /* + * windowBits is passed < 0 to tell that there is no zlib header. + * Note that in this case inflate *requires* an extra "dummy" byte + * after the compressed stream in order to complete decompression and + * return Z_STREAM_END. + * In unzip, i don't wait absolutely Z_STREAM_END because I known the + * size of both compressed and uncompressed data + */ + } + pfile_in_zip_read_info->rest_read_compressed = + s->cur_file_info.compressed_size; + pfile_in_zip_read_info->rest_read_uncompressed = + s->cur_file_info.uncompressed_size; + + + pfile_in_zip_read_info->pos_in_zipfile = + s->cur_file_info_internal.offset_curfile + SIZEZIPLOCALHEADER + + iSizeVar; + + pfile_in_zip_read_info->stream.avail_in = (uInt)0; + + s->pfile_in_zip_read = pfile_in_zip_read_info; + +#ifndef NOUNCRYPT + if (password != NULL) { + int i; + s->pcrc_32_tab = get_crc_table(); + init_keys(password, s->keys, s->pcrc_32_tab); + if (ZSEEK(s->z_filefunc, s->filestream, + s->pfile_in_zip_read->pos_in_zipfile + + s->pfile_in_zip_read->byte_before_the_zipfile, + SEEK_SET) != 0) + return (UNZ_INTERNALERROR); + if (ZREAD(s->z_filefunc, s->filestream, source, 12) < 12) + return (UNZ_INTERNALERROR); + + for (i = 0; i < 12; i++) + zdecode(s->keys, s->pcrc_32_tab, source[i]); + + s->pfile_in_zip_read->pos_in_zipfile += 12; + s->encrypted = 1; + } +#endif + + return (UNZ_OK); } -extern int ZEXPORT unzOpenCurrentFile (file) - unzFile file; +extern int ZEXPORT +unzOpenCurrentFile( + unzFile file) { - return unzOpenCurrentFile3(file, NULL, NULL, 0, NULL); + return (unzOpenCurrentFile3(file, NULL, NULL, 0, NULL)); } -extern int ZEXPORT unzOpenCurrentFilePassword (file, password) - unzFile file; - const char* password; +extern int ZEXPORT +unzOpenCurrentFilePassword( + unzFile file, + const char *password) { - return unzOpenCurrentFile3(file, NULL, NULL, 0, password); + return (unzOpenCurrentFile3(file, NULL, NULL, 0, password)); } -extern int ZEXPORT unzOpenCurrentFile2 (file,method,level,raw) - unzFile file; - int* method; - int* level; - int raw; +extern int ZEXPORT +unzOpenCurrentFile2( + unzFile file, + int *method, + int *level, + int raw) { - return unzOpenCurrentFile3(file, method, level, raw, NULL); + return (unzOpenCurrentFile3(file, method, level, raw, NULL)); } /* - Read bytes from the current file. - buf contain buffer where data must be copied - len the size of buf. - - return the number of byte copied if somes bytes are copied - return 0 if the end of file was reached - return <0 with error code if there is an error - (UNZ_ERRNO for IO error, or zLib error for uncompress error) -*/ -extern int ZEXPORT unzReadCurrentFile (file, buf, len) - unzFile file; - voidp buf; - unsigned len; + * Read bytes from the current file. + * buf contain buffer where data must be copied + * len the size of buf. + * + * return the number of byte copied if somes bytes are copied + * return 0 if the end of file was reached + * return <0 with error code if there is an error + * (UNZ_ERRNO for IO error, or zLib error for uncompress error) + */ +extern int ZEXPORT +unzReadCurrentFile( + unzFile file, + voidp buf, + unsigned len) { - int err=UNZ_OK; - uInt iRead = 0; - unz_s* s; - file_in_zip_read_info_s* pfile_in_zip_read_info; - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz_s*)file; - pfile_in_zip_read_info=s->pfile_in_zip_read; - - if (pfile_in_zip_read_info==NULL) - return UNZ_PARAMERROR; - - - if ((pfile_in_zip_read_info->read_buffer == NULL)) - return UNZ_END_OF_LIST_OF_FILE; - if (len==0) - return 0; - - pfile_in_zip_read_info->stream.next_out = (Bytef*)buf; - - pfile_in_zip_read_info->stream.avail_out = (uInt)len; - - if ((len>pfile_in_zip_read_info->rest_read_uncompressed) && - (!(pfile_in_zip_read_info->raw))) - pfile_in_zip_read_info->stream.avail_out = - (uInt)pfile_in_zip_read_info->rest_read_uncompressed; - - if ((len>pfile_in_zip_read_info->rest_read_compressed+ - pfile_in_zip_read_info->stream.avail_in) && - (pfile_in_zip_read_info->raw)) - pfile_in_zip_read_info->stream.avail_out = - (uInt)pfile_in_zip_read_info->rest_read_compressed+ - pfile_in_zip_read_info->stream.avail_in; - - while (pfile_in_zip_read_info->stream.avail_out>0) - { - if ((pfile_in_zip_read_info->stream.avail_in==0) && - (pfile_in_zip_read_info->rest_read_compressed>0)) - { - uInt uReadThis = UNZ_BUFSIZE; - if (pfile_in_zip_read_info->rest_read_compressedrest_read_compressed; - if (uReadThis == 0) - return UNZ_EOF; - if (ZSEEK(pfile_in_zip_read_info->z_filefunc, - pfile_in_zip_read_info->filestream, - pfile_in_zip_read_info->pos_in_zipfile + - pfile_in_zip_read_info->byte_before_the_zipfile, - ZLIB_FILEFUNC_SEEK_SET)!=0) - return UNZ_ERRNO; - if (ZREAD(pfile_in_zip_read_info->z_filefunc, - pfile_in_zip_read_info->filestream, - pfile_in_zip_read_info->read_buffer, - uReadThis)!=uReadThis) - return UNZ_ERRNO; - - -# ifndef NOUNCRYPT - if(s->encrypted) - { - uInt i; - for(i=0;iread_buffer[i] = - zdecode(s->keys,s->pcrc_32_tab, - pfile_in_zip_read_info->read_buffer[i]); - } -# endif - - - pfile_in_zip_read_info->pos_in_zipfile += uReadThis; - - pfile_in_zip_read_info->rest_read_compressed-=uReadThis; - - pfile_in_zip_read_info->stream.next_in = - (Bytef*)pfile_in_zip_read_info->read_buffer; - pfile_in_zip_read_info->stream.avail_in = (uInt)uReadThis; - } - - if ((pfile_in_zip_read_info->compression_method==0) || (pfile_in_zip_read_info->raw)) - { - uInt uDoCopy,i ; - - if ((pfile_in_zip_read_info->stream.avail_in == 0) && - (pfile_in_zip_read_info->rest_read_compressed == 0)) - return (iRead==0) ? UNZ_EOF : iRead; - - if (pfile_in_zip_read_info->stream.avail_out < - pfile_in_zip_read_info->stream.avail_in) - uDoCopy = pfile_in_zip_read_info->stream.avail_out ; - else - uDoCopy = pfile_in_zip_read_info->stream.avail_in ; - - for (i=0;istream.next_out+i) = - *(pfile_in_zip_read_info->stream.next_in+i); - - pfile_in_zip_read_info->crc32 = crc32(pfile_in_zip_read_info->crc32, - pfile_in_zip_read_info->stream.next_out, - uDoCopy); - pfile_in_zip_read_info->rest_read_uncompressed-=uDoCopy; - pfile_in_zip_read_info->stream.avail_in -= uDoCopy; - pfile_in_zip_read_info->stream.avail_out -= uDoCopy; - pfile_in_zip_read_info->stream.next_out += uDoCopy; - pfile_in_zip_read_info->stream.next_in += uDoCopy; - pfile_in_zip_read_info->stream.total_out += uDoCopy; - iRead += uDoCopy; - } - else - { - uLong uTotalOutBefore,uTotalOutAfter; - const Bytef *bufBefore; - uLong uOutThis; - int flush=Z_SYNC_FLUSH; - - uTotalOutBefore = pfile_in_zip_read_info->stream.total_out; - bufBefore = pfile_in_zip_read_info->stream.next_out; - - /* - if ((pfile_in_zip_read_info->rest_read_uncompressed == - pfile_in_zip_read_info->stream.avail_out) && - (pfile_in_zip_read_info->rest_read_compressed == 0)) - flush = Z_FINISH; - */ - err=inflate(&pfile_in_zip_read_info->stream,flush); - - if ((err>=0) && (pfile_in_zip_read_info->stream.msg!=NULL)) - err = Z_DATA_ERROR; - - uTotalOutAfter = pfile_in_zip_read_info->stream.total_out; - uOutThis = uTotalOutAfter-uTotalOutBefore; - - pfile_in_zip_read_info->crc32 = - crc32(pfile_in_zip_read_info->crc32,bufBefore, - (uInt)(uOutThis)); - - pfile_in_zip_read_info->rest_read_uncompressed -= - uOutThis; - - iRead += (uInt)(uTotalOutAfter - uTotalOutBefore); - - if (err==Z_STREAM_END) - return (iRead==0) ? UNZ_EOF : iRead; - if (err!=Z_OK) - break; - } - } - - if (err==Z_OK) - return iRead; - return err; + int err = UNZ_OK; + uInt iRead = 0; + unz_s *s; + file_in_zip_read_info_s *pfile_in_zip_read_info; + if (file == NULL) + return (UNZ_PARAMERROR); + s = (unz_s*)file; + pfile_in_zip_read_info = s->pfile_in_zip_read; + + if (pfile_in_zip_read_info == NULL) + return (UNZ_PARAMERROR); + + + if ((pfile_in_zip_read_info->read_buffer == NULL)) + return (UNZ_END_OF_LIST_OF_FILE); + if (len == 0) + return (0); + + pfile_in_zip_read_info->stream.next_out = (Bytef*)buf; + + pfile_in_zip_read_info->stream.avail_out = (uInt)len; + + if ((len > pfile_in_zip_read_info->rest_read_uncompressed) && + (!(pfile_in_zip_read_info->raw))) + pfile_in_zip_read_info->stream.avail_out = + (uInt)pfile_in_zip_read_info->rest_read_uncompressed; + + if ((len > pfile_in_zip_read_info->rest_read_compressed + + pfile_in_zip_read_info->stream.avail_in) && + (pfile_in_zip_read_info->raw)) + pfile_in_zip_read_info->stream.avail_out = + (uInt)pfile_in_zip_read_info->rest_read_compressed+ + pfile_in_zip_read_info->stream.avail_in; + + while (pfile_in_zip_read_info->stream.avail_out > 0) { + if ((pfile_in_zip_read_info->stream.avail_in == 0) && + (pfile_in_zip_read_info->rest_read_compressed > 0)) { + uInt uReadThis = UNZ_BUFSIZE; + if (pfile_in_zip_read_info->rest_read_compressed < + uReadThis) + uReadThis = (uInt)pfile_in_zip_read_info-> + rest_read_compressed; + if (uReadThis == 0) + return (UNZ_EOF); + if (ZSEEK(pfile_in_zip_read_info->z_filefunc, + pfile_in_zip_read_info->filestream, + pfile_in_zip_read_info->pos_in_zipfile + + pfile_in_zip_read_info->byte_before_the_zipfile, + ZLIB_FILEFUNC_SEEK_SET) != 0) + return (UNZ_ERRNO); + if (ZREAD(pfile_in_zip_read_info->z_filefunc, + pfile_in_zip_read_info->filestream, + pfile_in_zip_read_info->read_buffer, + uReadThis) != uReadThis) + return (UNZ_ERRNO); + +#ifndef NOUNCRYPT + if (s->encrypted) { + uInt i; + for (i = 0; i < uReadThis; i++) + pfile_in_zip_read_info->read_buffer[i] = + zdecode(s->keys, s->pcrc_32_tab, + pfile_in_zip_read_info-> + read_buffer[i]); + } +#endif + + + pfile_in_zip_read_info->pos_in_zipfile += uReadThis; + + pfile_in_zip_read_info->rest_read_compressed -= + uReadThis; + + pfile_in_zip_read_info->stream.next_in = + (Bytef*)pfile_in_zip_read_info->read_buffer; + pfile_in_zip_read_info->stream.avail_in = + (uInt)uReadThis; + } + + if ((pfile_in_zip_read_info->compression_method == 0) || + (pfile_in_zip_read_info->raw)) { + uInt uDoCopy, i; + + if ((pfile_in_zip_read_info->stream.avail_in == 0) && + (pfile_in_zip_read_info->rest_read_compressed == 0)) + return ((iRead == 0) ? UNZ_EOF : iRead); + + if (pfile_in_zip_read_info->stream.avail_out < + pfile_in_zip_read_info->stream.avail_in) + uDoCopy = + pfile_in_zip_read_info->stream.avail_out; + else + uDoCopy = + pfile_in_zip_read_info->stream.avail_in; + + for (i = 0; i < uDoCopy; i++) + *(pfile_in_zip_read_info->stream.next_out+i) = + *(pfile_in_zip_read_info->stream.next_in+i); + + pfile_in_zip_read_info->crc32 = + crc32(pfile_in_zip_read_info->crc32, + pfile_in_zip_read_info->stream.next_out, + uDoCopy); + pfile_in_zip_read_info->rest_read_uncompressed -= + uDoCopy; + pfile_in_zip_read_info->stream.avail_in -= uDoCopy; + pfile_in_zip_read_info->stream.avail_out -= uDoCopy; + pfile_in_zip_read_info->stream.next_out += uDoCopy; + pfile_in_zip_read_info->stream.next_in += uDoCopy; + pfile_in_zip_read_info->stream.total_out += uDoCopy; + iRead += uDoCopy; + } else { + uLong uTotalOutBefore, uTotalOutAfter; + const Bytef *bufBefore; + uLong uOutThis; + int flush = Z_SYNC_FLUSH; + + uTotalOutBefore = + pfile_in_zip_read_info->stream.total_out; + bufBefore = pfile_in_zip_read_info->stream.next_out; + + /* + * if ((pfile_in_zip_read_info->rest_read_uncompressed + * == pfile_in_zip_read_info->stream.avail_out) && + * (pfile_in_zip_read_info->rest_read_compressed == 0)) + * flush = Z_FINISH; + */ + err = inflate(&pfile_in_zip_read_info->stream, flush); + + if ((err >= 0) && + (pfile_in_zip_read_info->stream.msg != NULL)) + err = Z_DATA_ERROR; + + uTotalOutAfter = + pfile_in_zip_read_info->stream.total_out; + uOutThis = uTotalOutAfter-uTotalOutBefore; + + pfile_in_zip_read_info->crc32 = + crc32(pfile_in_zip_read_info->crc32, bufBefore, + (uInt)(uOutThis)); + + pfile_in_zip_read_info->rest_read_uncompressed -= + uOutThis; + + iRead += (uInt)(uTotalOutAfter - uTotalOutBefore); + + if (err == Z_STREAM_END) + return ((iRead == 0) ? UNZ_EOF : iRead); + if (err != Z_OK) + break; + } + } + + if (err == Z_OK) + return (iRead); + return (err); } /* - Give the current position in uncompressed data -*/ -extern z_off_t ZEXPORT unztell (file) - unzFile file; + * Give the current position in uncompressed data + */ +extern z_off_t ZEXPORT +unztell( + unzFile file) { - unz_s* s; - file_in_zip_read_info_s* pfile_in_zip_read_info; - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz_s*)file; - pfile_in_zip_read_info=s->pfile_in_zip_read; + unz_s *s; + file_in_zip_read_info_s *pfile_in_zip_read_info; + if (file == NULL) + return (UNZ_PARAMERROR); + s = (unz_s*)file; + pfile_in_zip_read_info = s->pfile_in_zip_read; - if (pfile_in_zip_read_info==NULL) - return UNZ_PARAMERROR; + if (pfile_in_zip_read_info == NULL) + return (UNZ_PARAMERROR); - return (z_off_t)pfile_in_zip_read_info->stream.total_out; + return ((z_off_t)pfile_in_zip_read_info->stream.total_out); } /* - return 1 if the end of file was reached, 0 elsewhere -*/ -extern int ZEXPORT unzeof (file) - unzFile file; + * return 1 if the end of file was reached, 0 elsewhere + */ +extern int ZEXPORT +unzeof( + unzFile file) { - unz_s* s; - file_in_zip_read_info_s* pfile_in_zip_read_info; - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz_s*)file; - pfile_in_zip_read_info=s->pfile_in_zip_read; - - if (pfile_in_zip_read_info==NULL) - return UNZ_PARAMERROR; - - if (pfile_in_zip_read_info->rest_read_uncompressed == 0) - return 1; - else - return 0; + unz_s *s; + file_in_zip_read_info_s *pfile_in_zip_read_info; + if (file == NULL) + return (UNZ_PARAMERROR); + s = (unz_s*)file; + pfile_in_zip_read_info = s->pfile_in_zip_read; + + if (pfile_in_zip_read_info == NULL) + return (UNZ_PARAMERROR); + + if (pfile_in_zip_read_info->rest_read_uncompressed == 0) + return (1); + else + return (0); } /* - Read extra field from the current file (opened by unzOpenCurrentFile) - This is the local-header version of the extra field (sometimes, there is - more info in the local-header version than in the central-header) - - if buf==NULL, it return the size of the local extra field that can be read - - if buf!=NULL, len is the size of the buffer, the extra header is copied in - buf. - the return value is the number of bytes copied in buf, or (if <0) - the error code -*/ -extern int ZEXPORT unzGetLocalExtrafield (file,buf,len) - unzFile file; - voidp buf; - unsigned len; + * Read extra field from the current file (opened by unzOpenCurrentFile) + * This is the local-header version of the extra field (sometimes, there is + * more info in the local-header version than in the central-header) + * + * if buf==NULL, it return the size of the local extra field that + * can be read if buf!=NULL, len is the size of the buffer, + * the extra header is copied in buf. + * the return value is the number of bytes copied in buf, or (if <0) + * the error code + */ +extern int ZEXPORT +unzGetLocalExtrafield( + unzFile file, + voidp buf, + unsigned len) { - unz_s* s; - file_in_zip_read_info_s* pfile_in_zip_read_info; - uInt read_now; - uLong size_to_read; - - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz_s*)file; - pfile_in_zip_read_info=s->pfile_in_zip_read; - - if (pfile_in_zip_read_info==NULL) - return UNZ_PARAMERROR; - - size_to_read = (pfile_in_zip_read_info->size_local_extrafield - - pfile_in_zip_read_info->pos_local_extrafield); - - if (buf==NULL) - return (int)size_to_read; - - if (len>size_to_read) - read_now = (uInt)size_to_read; - else - read_now = (uInt)len ; - - if (read_now==0) - return 0; - - if (ZSEEK(pfile_in_zip_read_info->z_filefunc, - pfile_in_zip_read_info->filestream, - pfile_in_zip_read_info->offset_local_extrafield + - pfile_in_zip_read_info->pos_local_extrafield, - ZLIB_FILEFUNC_SEEK_SET)!=0) - return UNZ_ERRNO; - - if (ZREAD(pfile_in_zip_read_info->z_filefunc, - pfile_in_zip_read_info->filestream, - buf,read_now)!=read_now) - return UNZ_ERRNO; - - return (int)read_now; + unz_s *s; + file_in_zip_read_info_s *pfile_in_zip_read_info; + uInt read_now; + uLong size_to_read; + + if (file == NULL) + return (UNZ_PARAMERROR); + s = (unz_s*)file; + pfile_in_zip_read_info = s->pfile_in_zip_read; + + if (pfile_in_zip_read_info == NULL) + return (UNZ_PARAMERROR); + + size_to_read = (pfile_in_zip_read_info->size_local_extrafield - + pfile_in_zip_read_info->pos_local_extrafield); + + if (buf == NULL) + return ((int)size_to_read); + + if (len > size_to_read) + read_now = (uInt)size_to_read; + else + read_now = (uInt)len; + + if (read_now == 0) + return (0); + + if (ZSEEK(pfile_in_zip_read_info->z_filefunc, + pfile_in_zip_read_info->filestream, + pfile_in_zip_read_info->offset_local_extrafield + + pfile_in_zip_read_info->pos_local_extrafield, + ZLIB_FILEFUNC_SEEK_SET) != 0) + return (UNZ_ERRNO); + + if (ZREAD(pfile_in_zip_read_info->z_filefunc, + pfile_in_zip_read_info->filestream, + buf, read_now) != read_now) + return (UNZ_ERRNO); + + return ((int)read_now); } /* - Close the file in zip opened with unzipOpenCurrentFile - Return UNZ_CRCERROR if all the file was read but the CRC is not good -*/ -extern int ZEXPORT unzCloseCurrentFile (file) - unzFile file; + * Close the file in zip opened with unzipOpenCurrentFile + * Return UNZ_CRCERROR if all the file was read but the CRC is not good + */ +extern int ZEXPORT +unzCloseCurrentFile( + unzFile file) { - int err=UNZ_OK; + int err = UNZ_OK; - unz_s* s; - file_in_zip_read_info_s* pfile_in_zip_read_info; - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz_s*)file; - pfile_in_zip_read_info=s->pfile_in_zip_read; + unz_s *s; + file_in_zip_read_info_s *pfile_in_zip_read_info; + if (file == NULL) + return (UNZ_PARAMERROR); + s = (unz_s*)file; + pfile_in_zip_read_info = s->pfile_in_zip_read; - if (pfile_in_zip_read_info==NULL) - return UNZ_PARAMERROR; + if (pfile_in_zip_read_info == NULL) + return (UNZ_PARAMERROR); - if ((pfile_in_zip_read_info->rest_read_uncompressed == 0) && - (!pfile_in_zip_read_info->raw)) - { - if (pfile_in_zip_read_info->crc32 != pfile_in_zip_read_info->crc32_wait) - err=UNZ_CRCERROR; - } + if ((pfile_in_zip_read_info->rest_read_uncompressed == 0) && + (!pfile_in_zip_read_info->raw)) { + if (pfile_in_zip_read_info->crc32 != + pfile_in_zip_read_info->crc32_wait) + err = UNZ_CRCERROR; + } - TRYFREE(pfile_in_zip_read_info->read_buffer); - pfile_in_zip_read_info->read_buffer = NULL; - if (pfile_in_zip_read_info->stream_initialised) - inflateEnd(&pfile_in_zip_read_info->stream); + TRYFREE(pfile_in_zip_read_info->read_buffer); + pfile_in_zip_read_info->read_buffer = NULL; + if (pfile_in_zip_read_info->stream_initialised) + inflateEnd(&pfile_in_zip_read_info->stream); - pfile_in_zip_read_info->stream_initialised = 0; - TRYFREE(pfile_in_zip_read_info); + pfile_in_zip_read_info->stream_initialised = 0; + TRYFREE(pfile_in_zip_read_info); - s->pfile_in_zip_read=NULL; + s->pfile_in_zip_read = NULL; - return err; + return (err); } /* - Get the global comment string of the ZipFile, in the szComment buffer. - uSizeBuf is the size of the szComment buffer. - return the number of byte copied or an error code <0 -*/ -extern int ZEXPORT unzGetGlobalComment (file, szComment, uSizeBuf) - unzFile file; - char *szComment; - uLong uSizeBuf; + * Get the global comment string of the ZipFile, in the szComment buffer. + * uSizeBuf is the size of the szComment buffer. + * return the number of byte copied or an error code <0 + */ +extern int ZEXPORT +unzGetGlobalComment( + unzFile file, + char *szComment, + uLong uSizeBuf) { - int err=UNZ_OK; - unz_s* s; - uLong uReadThis ; - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz_s*)file; - - uReadThis = uSizeBuf; - if (uReadThis>s->gi.size_comment) - uReadThis = s->gi.size_comment; - - if (ZSEEK(s->z_filefunc,s->filestream,s->central_pos+22,ZLIB_FILEFUNC_SEEK_SET)!=0) - return UNZ_ERRNO; - - if (uReadThis>0) - { - *szComment='\0'; - if (ZREAD(s->z_filefunc,s->filestream,szComment,uReadThis)!=uReadThis) - return UNZ_ERRNO; - } - - if ((szComment != NULL) && (uSizeBuf > s->gi.size_comment)) - *(szComment+s->gi.size_comment)='\0'; - return (int)uReadThis; + int err = UNZ_OK; + unz_s *s; + uLong uReadThis; + if (file == NULL) + return (UNZ_PARAMERROR); + s = (unz_s*)file; + + uReadThis = uSizeBuf; + if (uReadThis > s->gi.size_comment) + uReadThis = s->gi.size_comment; + + if (ZSEEK(s->z_filefunc, s->filestream, s->central_pos+22, + ZLIB_FILEFUNC_SEEK_SET) != 0) + return (UNZ_ERRNO); + + if (uReadThis > 0) { + *szComment = '\0'; + if (ZREAD(s->z_filefunc, s->filestream, szComment, + uReadThis) != uReadThis) + return (UNZ_ERRNO); + } + + if ((szComment != NULL) && (uSizeBuf > s->gi.size_comment)) + *(szComment+s->gi.size_comment) = '\0'; + return ((int)uReadThis); } /* Additions by RX '2004 */ -extern uLong ZEXPORT unzGetOffset (file) - unzFile file; +extern uLong ZEXPORT +unzGetOffset( + unzFile file) { - unz_s* s; - - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz_s*)file; - if (!s->current_file_ok) - return 0; - if (s->gi.number_entry != 0 && s->gi.number_entry != 0xffff) - if (s->num_file==s->gi.number_entry) - return 0; - return s->pos_in_central_dir; + unz_s *s; + + if (file == NULL) + return (UNZ_PARAMERROR); + s = (unz_s*)file; + if (!s->current_file_ok) + return (0); + if (s->gi.number_entry != 0 && s->gi.number_entry != 0xffff) + if (s->num_file == s->gi.number_entry) + return (0); + return (s->pos_in_central_dir); } -extern int ZEXPORT unzSetOffset (file, pos) - unzFile file; - uLong pos; +extern int ZEXPORT +unzSetOffset( + unzFile file, + uLong pos) { - unz_s* s; - int err; - - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz_s*)file; - - s->pos_in_central_dir = pos; - s->num_file = s->gi.number_entry; /* hack */ - err = unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info, - &s->cur_file_info_internal, - NULL,0,NULL,0,NULL,0); - s->current_file_ok = (err == UNZ_OK); - return err; + unz_s *s; + int err; + + if (file == NULL) + return (UNZ_PARAMERROR); + s = (unz_s*)file; + + s->pos_in_central_dir = pos; + s->num_file = s->gi.number_entry; /* hack */ + err = unzlocal_GetCurrentFileInfoInternal(file, &s->cur_file_info, + &s->cur_file_info_internal, + NULL, 0, NULL, 0, NULL, 0); + s->current_file_ok = (err == UNZ_OK); + return (err); } diff --git a/lib/os/windows/zlib-1.2.3/contrib/minizip/unzip.h b/lib/os/windows/zlib-1.2.3/contrib/minizip/unzip.h index b247937c807..fcb95117977 100644 --- a/lib/os/windows/zlib-1.2.3/contrib/minizip/unzip.h +++ b/lib/os/windows/zlib-1.2.3/contrib/minizip/unzip.h @@ -1,49 +1,51 @@ -/* unzip.h -- IO for uncompress .zip files using zlib - Version 1.01e, February 12th, 2005 - - Copyright (C) 1998-2005 Gilles Vollant - - This unzip package allow extract file from .ZIP file, compatible with PKZip 2.04g - WinZip, InfoZip tools and compatible. - - Multi volume ZipFile (span) are not supported. - Encryption compatible with pkzip 2.04g only supported - Old compressions used by old PKZip 1.x are not supported - - - I WAIT FEEDBACK at mail info@winimage.com - Visit also http://www.winimage.com/zLibDll/unzip.htm for evolution - - Condition of use and distribution are the same than zlib : - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - -*/ +/* + * unzip.h -- IO for uncompress .zip files using zlib + * Version 1.01e, February 12th, 2005 + * + * Copyright (C) 1998-2005 Gilles Vollant + * + * This unzip package allow extract file from .ZIP file, + * compatible with PKZip 2.04g + * WinZip, InfoZip tools and compatible. + * + * Multi volume ZipFile (span) are not supported. + * Encryption compatible with pkzip 2.04g only supported + * Old compressions used by old PKZip 1.x are not supported + * + * + * I WAIT FEEDBACK at mail info@winimage.com + * Visit also http://www.winimage.com/zLibDll/unzip.htm for evolution + * + * Condition of use and distribution are the same than zlib : + * + * This software is provided 'as-is', without any express or implied + * warranty. In no event will the authors be held liable for any damages + * arising from the use of this software. + * + * Permission is granted to anyone to use this software for any purpose, + * including commercial applications, and to alter it and redistribute it + * freely, subject to the following restrictions: + * + * 1. The origin of this software must not be misrepresented; you must not + * claim that you wrote the original software. If you use this software + * in a product, an acknowledgment in the product documentation would be + * appreciated but is not required. + * 2. Altered source versions must be plainly marked as such, and must not be + * misrepresented as being the original software. + * 3. This notice may not be removed or altered from any source distribution. + * + */ -/* for more info about .ZIP format, see - http://www.info-zip.org/pub/infozip/doc/appnote-981119-iz.zip - http://www.info-zip.org/pub/infozip/doc/ - PkWare has also a specification at : - ftp://ftp.pkware.com/probdesc.zip -*/ +/* + * for more info about .ZIP format, see + * http://www.info-zip.org/pub/infozip/doc/appnote-981119-iz.zip + * http://www.info-zip.org/pub/infozip/doc/ + * PkWare has also a specification at : + * ftp://ftp.pkware.com/probdesc.zip + */ #ifndef _unz_H -#define _unz_H +#define _unz_H #ifdef __cplusplus extern "C" { @@ -58,8 +60,10 @@ extern "C" { #endif #if defined(STRICTUNZIP) || defined(STRICTZIPUNZIP) -/* like the STRICT of WIN32, we define a pointer that cannot be converted - from (void*) without cast */ +/* + * like the STRICT of WIN32, we define a pointer that cannot be converted + * from (void*) without cast + */ typedef struct TagunzFile__ { int unused; } unzFile__; typedef unzFile__ *unzFile; #else @@ -67,155 +71,152 @@ typedef voidp unzFile; #endif -#define UNZ_OK (0) -#define UNZ_END_OF_LIST_OF_FILE (-100) -#define UNZ_ERRNO (Z_ERRNO) -#define UNZ_EOF (0) -#define UNZ_PARAMERROR (-102) -#define UNZ_BADZIPFILE (-103) -#define UNZ_INTERNALERROR (-104) -#define UNZ_CRCERROR (-105) +#define UNZ_OK (0) +#define UNZ_END_OF_LIST_OF_FILE (-100) +#define UNZ_ERRNO (Z_ERRNO) +#define UNZ_EOF (0) +#define UNZ_PARAMERROR (-102) +#define UNZ_BADZIPFILE (-103) +#define UNZ_INTERNALERROR (-104) +#define UNZ_CRCERROR (-105) /* tm_unz contain date/time info */ typedef struct tm_unz_s { - uInt tm_sec; /* seconds after the minute - [0,59] */ - uInt tm_min; /* minutes after the hour - [0,59] */ - uInt tm_hour; /* hours since midnight - [0,23] */ - uInt tm_mday; /* day of the month - [1,31] */ - uInt tm_mon; /* months since January - [0,11] */ - uInt tm_year; /* years - [1980..2044] */ + uInt tm_sec; /* seconds after the minute - [0,59] */ + uInt tm_min; /* minutes after the hour - [0,59] */ + uInt tm_hour; /* hours since midnight - [0,23] */ + uInt tm_mday; /* day of the month - [1,31] */ + uInt tm_mon; /* months since January - [0,11] */ + uInt tm_year; /* years - [1980..2044] */ } tm_unz; -/* unz_global_info structure contain global data about the ZIPfile - These data comes from the end of central dir */ +/* + * unz_global_info structure contain global data about the ZIPfile + * These data comes from the end of central dir + */ typedef struct unz_global_info_s { - uLong number_entry; /* total number of entries in - the central dir on this disk */ - uLong size_comment; /* size of the global comment of the zipfile */ + uLong number_entry; + uLong size_comment; } unz_global_info; - /* unz_file_info contain information about a file in the zipfile */ typedef struct unz_file_info_s { - uLong version; /* version made by 2 bytes */ - uLong version_needed; /* version needed to extract 2 bytes */ - uLong flag; /* general purpose bit flag 2 bytes */ - uLong compression_method; /* compression method 2 bytes */ - uLong dosDate; /* last mod file date in Dos fmt 4 bytes */ - uLong crc; /* crc-32 4 bytes */ - uLong compressed_size; /* compressed size 4 bytes */ - uLong uncompressed_size; /* uncompressed size 4 bytes */ - uLong size_filename; /* filename length 2 bytes */ - uLong size_file_extra; /* extra field length 2 bytes */ - uLong size_file_comment; /* file comment length 2 bytes */ - - uLong disk_num_start; /* disk number start 2 bytes */ - uLong internal_fa; /* internal file attributes 2 bytes */ - uLong external_fa; /* external file attributes 4 bytes */ - - tm_unz tmu_date; + uLong version; + uLong version_needed; + uLong flag; + uLong compression_method; + uLong dosDate; + uLong crc; + uLong compressed_size; + uLong uncompressed_size; + uLong size_filename; + uLong size_file_extra; + uLong size_file_comment; + uLong disk_num_start; + uLong internal_fa; + uLong external_fa; + tm_unz tmu_date; } unz_file_info; -extern int ZEXPORT unzStringFileNameCompare OF ((const char* fileName1, - const char* fileName2, - int iCaseSensitivity)); +extern int ZEXPORT unzStringFileNameCompare OF((const char *fileName1, + const char *fileName2, + int iCaseSensitivity)); /* - Compare two filename (fileName1,fileName2). - If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp) - If iCaseSenisivity = 2, comparision is not case sensitivity (like strcmpi - or strcasecmp) - If iCaseSenisivity = 0, case sensitivity is defaut of your operating system - (like 1 on Unix, 2 on Windows) -*/ - + * Compare two filename (fileName1,fileName2). + * If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp) + * If iCaseSenisivity = 2, comparision is not case sensitivity (like strcmpi + * or strcasecmp) + * If iCaseSenisivity = 0, case sensitivity is defaut of your operating system + * (like 1 on Unix, 2 on Windows) + */ extern unzFile ZEXPORT unzOpen OF((const char *path)); /* - Open a Zip file. path contain the full pathname (by example, - on a Windows XP computer "c:\\zlib\\zlib113.zip" or on an Unix computer - "zlib/zlib113.zip". - If the zipfile cannot be opened (file don't exist or in not valid), the - return value is NULL. - Else, the return value is a unzFile Handle, usable with other function - of this unzip package. -*/ + * Open a Zip file. path contain the full pathname (by example, + * on a Windows XP computer "c:\\zlib\\zlib113.zip" or on an Unix computer + * "zlib/zlib113.zip". + * If the zipfile cannot be opened (file don't exist or in not valid), the + * return value is NULL. + * Else, the return value is a unzFile Handle, usable with other function + * of this unzip package. + */ extern unzFile ZEXPORT unzOpen2 OF((const char *path, - zlib_filefunc_def* pzlib_filefunc_def)); + zlib_filefunc_def* pzlib_filefunc_def)); /* - Open a Zip file, like unzOpen, but provide a set of file low level API - for read/write the zip file (see ioapi.h) -*/ + * Open a Zip file, like unzOpen, but provide a set of file low level API + * for read/write the zip file (see ioapi.h) + */ extern int ZEXPORT unzClose OF((unzFile file)); /* - Close a ZipFile opened with unzipOpen. - If there is files inside the .Zip opened with unzOpenCurrentFile (see later), - these files MUST be closed with unzipCloseCurrentFile before call unzipClose. - return UNZ_OK if there is no problem. */ + * Close a ZipFile opened with unzipOpen. + * If there is files inside the .Zip opened with unzOpenCurrentFile + * these files MUST be closed with unzipCloseCurrentFile before + * call unzipClose. + * return UNZ_OK if there is no problem. + */ extern int ZEXPORT unzGetGlobalInfo OF((unzFile file, - unz_global_info *pglobal_info)); + unz_global_info *pglobal_info)); /* - Write info about the ZipFile in the *pglobal_info structure. - No preparation of the structure is needed - return UNZ_OK if there is no problem. */ + * Write info about the ZipFile in the *pglobal_info structure. + * No preparation of the structure is needed + * return UNZ_OK if there is no problem. + */ extern int ZEXPORT unzGetGlobalComment OF((unzFile file, - char *szComment, - uLong uSizeBuf)); + char *szComment, + uLong uSizeBuf)); /* - Get the global comment string of the ZipFile, in the szComment buffer. - uSizeBuf is the size of the szComment buffer. - return the number of byte copied or an error code <0 -*/ + * Get the global comment string of the ZipFile, in the szComment buffer. + * uSizeBuf is the size of the szComment buffer. + * return the number of byte copied or an error code <0 + */ - -/***************************************************************************/ /* Unzip package allow you browse the directory of the zipfile */ extern int ZEXPORT unzGoToFirstFile OF((unzFile file)); /* - Set the current file of the zipfile to the first file. - return UNZ_OK if there is no problem -*/ + * Set the current file of the zipfile to the first file. + * return UNZ_OK if there is no problem + */ extern int ZEXPORT unzGoToNextFile OF((unzFile file)); /* - Set the current file of the zipfile to the next file. - return UNZ_OK if there is no problem - return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest. -*/ + * Set the current file of the zipfile to the next file. + * return UNZ_OK if there is no problem + * return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest. + */ extern int ZEXPORT unzLocateFile OF((unzFile file, - const char *szFileName, - int iCaseSensitivity)); + const char *szFileName, + int iCaseSensitivity)); /* - Try locate the file szFileName in the zipfile. - For the iCaseSensitivity signification, see unzStringFileNameCompare - - return value : - UNZ_OK if the file is found. It becomes the current file. - UNZ_END_OF_LIST_OF_FILE if the file is not found -*/ - + * Try locate the file szFileName in the zipfile. + * For the iCaseSensitivity signification, see unzStringFileNameCompare + * + * return value : + * UNZ_OK if the file is found. It becomes the current file. + * UNZ_END_OF_LIST_OF_FILE if the file is not found + */ /* ****************************************** */ /* Ryan supplied functions */ /* unz_file_info contain information about a file in the zipfile */ typedef struct unz_file_pos_s { - uLong pos_in_zip_directory; /* offset in zip file directory */ - uLong num_of_file; /* # of file */ + uLong pos_in_zip_directory; /* offset in zip file directory */ + uLong num_of_file; /* # of file */ } unz_file_pos; extern int ZEXPORT unzGetFilePos( unzFile file, - unz_file_pos* file_pos); + unz_file_pos *file_pos); extern int ZEXPORT unzGoToFilePos( unzFile file, @@ -224,128 +225,125 @@ extern int ZEXPORT unzGoToFilePos( /* ****************************************** */ extern int ZEXPORT unzGetCurrentFileInfo OF((unzFile file, - unz_file_info *pfile_info, - char *szFileName, - uLong fileNameBufferSize, - void *extraField, - uLong extraFieldBufferSize, - char *szComment, - uLong commentBufferSize)); + unz_file_info *pfile_info, + char *szFileName, + uLong fileNameBufferSize, + void *extraField, + uLong extraFieldBufferSize, + char *szComment, + uLong commentBufferSize)); +/* + * Get Info about the current file + * if pfile_info!=NULL, the *pfile_info structure will contain somes info about + * the current file + * if szFileName!=NULL, the filemane string will be copied in szFileName + * (fileNameBufferSize is the size of the buffer) + * if extraField!=NULL, the extra field information will be copied in + * extraField + * (extraFieldBufferSize is the size of the buffer). + * This is the Central-header version of the extra field + * if szComment!=NULL, the comment string of the file will be copied in + * szComment + * (commentBufferSize is the size of the buffer) + */ + /* - Get Info about the current file - if pfile_info!=NULL, the *pfile_info structure will contain somes info about - the current file - if szFileName!=NULL, the filemane string will be copied in szFileName - (fileNameBufferSize is the size of the buffer) - if extraField!=NULL, the extra field information will be copied in extraField - (extraFieldBufferSize is the size of the buffer). - This is the Central-header version of the extra field - if szComment!=NULL, the comment string of the file will be copied in szComment - (commentBufferSize is the size of the buffer) -*/ - -/***************************************************************************/ -/* for reading the content of the current zipfile, you can open it, read data - from it, and close it (you can close it before reading all the file) - */ + * for reading the content of the current zipfile, you can open it, read data + * from it, and close it (you can close it before reading all the file) + */ extern int ZEXPORT unzOpenCurrentFile OF((unzFile file)); /* - Open for reading data the current file in the zipfile. - If there is no error, the return value is UNZ_OK. -*/ + * Open for reading data the current file in the zipfile. + * If there is no error, the return value is UNZ_OK. + */ extern int ZEXPORT unzOpenCurrentFilePassword OF((unzFile file, - const char* password)); + const char *password)); /* - Open for reading data the current file in the zipfile. - password is a crypting password - If there is no error, the return value is UNZ_OK. -*/ + * Open for reading data the current file in the zipfile. + * password is a crypting password + * If there is no error, the return value is UNZ_OK. + */ extern int ZEXPORT unzOpenCurrentFile2 OF((unzFile file, - int* method, - int* level, - int raw)); + int *method, + int *level, + int raw)); /* - Same than unzOpenCurrentFile, but open for read raw the file (not uncompress) - if raw==1 - *method will receive method of compression, *level will receive level of - compression - note : you can set level parameter as NULL (if you did not want known level, - but you CANNOT set method parameter as NULL -*/ + * Same than unzOpenCurrentFile, but open for read raw the file + * if raw==1 + * *method will receive method of compression, *level will receive level of + * compression + * note : you can set level parameter as NULL (if you did not want known level, + * but you CANNOT set method parameter as NULL + */ extern int ZEXPORT unzOpenCurrentFile3 OF((unzFile file, - int* method, - int* level, - int raw, - const char* password)); + int *method, + int *level, + int raw, + const char *password)); /* - Same than unzOpenCurrentFile, but open for read raw the file (not uncompress) - if raw==1 - *method will receive method of compression, *level will receive level of - compression - note : you can set level parameter as NULL (if you did not want known level, - but you CANNOT set method parameter as NULL -*/ - + * Same than unzOpenCurrentFile, but open for read raw the file + * if raw==1 + * *method will receive method of compression, *level will receive level of + * compression + * note : you can set level parameter as NULL (if you did not want known level, + * but you CANNOT set method parameter as NULL + */ extern int ZEXPORT unzCloseCurrentFile OF((unzFile file)); /* - Close the file in zip opened with unzOpenCurrentFile - Return UNZ_CRCERROR if all the file was read but the CRC is not good -*/ + * Close the file in zip opened with unzOpenCurrentFile + * Return UNZ_CRCERROR if all the file was read but the CRC is not good + */ extern int ZEXPORT unzReadCurrentFile OF((unzFile file, - voidp buf, - unsigned len)); + voidp buf, + unsigned len)); /* - Read bytes from the current file (opened by unzOpenCurrentFile) - buf contain buffer where data must be copied - len the size of buf. - - return the number of byte copied if somes bytes are copied - return 0 if the end of file was reached - return <0 with error code if there is an error - (UNZ_ERRNO for IO error, or zLib error for uncompress error) -*/ + * Read bytes from the current file (opened by unzOpenCurrentFile) + * buf contain buffer where data must be copied + * len the size of buf. + * + * return the number of byte copied if somes bytes are copied + * return 0 if the end of file was reached + * return <0 with error code if there is an error + * (UNZ_ERRNO for IO error, or zLib error for uncompress error) + */ extern z_off_t ZEXPORT unztell OF((unzFile file)); /* - Give the current position in uncompressed data -*/ + * Give the current position in uncompressed data + */ extern int ZEXPORT unzeof OF((unzFile file)); /* - return 1 if the end of file was reached, 0 elsewhere -*/ + * return 1 if the end of file was reached, 0 elsewhere + */ extern int ZEXPORT unzGetLocalExtrafield OF((unzFile file, - voidp buf, - unsigned len)); + voidp buf, + unsigned len)); /* - Read extra field from the current file (opened by unzOpenCurrentFile) - This is the local-header version of the extra field (sometimes, there is - more info in the local-header version than in the central-header) - - if buf==NULL, it return the size of the local extra field - - if buf!=NULL, len is the size of the buffer, the extra header is copied in - buf. - the return value is the number of bytes copied in buf, or (if <0) - the error code -*/ - -/***************************************************************************/ + * Read extra field from the current file (opened by unzOpenCurrentFile) + * This is the local-header version of the extra field (sometimes, there is + * more info in the local-header version than in the central-header) + * + * if buf==NULL, it return the size of the local extra field + * + * if buf!=NULL, len is the size of the buffer, the extra header is copied in + * buf. + * the return value is the number of bytes copied in buf, or (if <0) + * the error code + */ /* Get the current file offset */ -extern uLong ZEXPORT unzGetOffset (unzFile file); +extern uLong ZEXPORT unzGetOffset(unzFile file); /* Set the current file offset */ -extern int ZEXPORT unzSetOffset (unzFile file, uLong pos); - - +extern int ZEXPORT unzSetOffset(unzFile file, uLong pos); #ifdef __cplusplus } diff --git a/lib/os/windows/zlib-1.2.3/contrib/minizip/zip.c b/lib/os/windows/zlib-1.2.3/contrib/minizip/zip.c index a7e7e869d6f..9764a25c3c1 100644 --- a/lib/os/windows/zlib-1.2.3/contrib/minizip/zip.c +++ b/lib/os/windows/zlib-1.2.3/contrib/minizip/zip.c @@ -1,14 +1,14 @@ -/* zip.c -- IO on .zip files using zlib - Version 1.01e, February 12th, 2005 - - 27 Dec 2004 Rolf Kalbermatter - Modification to zipOpen2 to support globalComment retrieval. - - Copyright (C) 1998-2005 Gilles Vollant - - Read zip.h for more info -*/ - +/* + * zip.c -- IO on .zip files using zlib + * Version 1.01e, February 12th, 2005 + * + * 27 Dec 2004 Rolf Kalbermatter + * Modification to zipOpen2 to support globalComment retrieval. + * + * Copyright (C) 1998-2005 Gilles Vollant + * + * Read zip.h for more info + */ #include #include @@ -19,1202 +19,1245 @@ #include "zutil.h" #ifdef STDC -# include -# include -# include +#include +#include +#include #endif #ifdef NO_ERRNO_H - extern int errno; +extern int errno; #else -# include +#include #endif #ifndef local -# define local static +#define local static #endif /* compile with -Dlocal if your debugger can't find static symbols */ #ifndef VERSIONMADEBY -# define VERSIONMADEBY (0x0) /* platform depedent */ +#define VERSIONMADEBY (0x0) /* platform depedent */ #endif #ifndef Z_BUFSIZE -#define Z_BUFSIZE (16384) +#define Z_BUFSIZE (16384) #endif #ifndef Z_MAXFILENAMEINZIP -#define Z_MAXFILENAMEINZIP (256) +#define Z_MAXFILENAMEINZIP (256) #endif #ifndef ALLOC -# define ALLOC(size) (malloc(size)) +#define ALLOC(size) (malloc(size)) #endif #ifndef TRYFREE -# define TRYFREE(p) {if (p) free(p);} +#define TRYFREE(p) { if (p) free(p); } #endif /* -#define SIZECENTRALDIRITEM (0x2e) -#define SIZEZIPLOCALHEADER (0x1e) -*/ + * #define SIZECENTRALDIRITEM (0x2e) + * #define SIZEZIPLOCALHEADER (0x1e) + */ -/* I've found an old Unix (a SunOS 4.1.3_U1) without all SEEK_* defined.... */ +/* + * I've found an old Unix (a SunOS 4.1.3_U1) without all SEEK_* defined.... + */ #ifndef SEEK_CUR -#define SEEK_CUR 1 +#define SEEK_CUR 1 #endif #ifndef SEEK_END -#define SEEK_END 2 +#define SEEK_END 2 #endif #ifndef SEEK_SET -#define SEEK_SET 0 +#define SEEK_SET 0 #endif #ifndef DEF_MEM_LEVEL #if MAX_MEM_LEVEL >= 8 -# define DEF_MEM_LEVEL 8 +#define DEF_MEM_LEVEL 8 #else -# define DEF_MEM_LEVEL MAX_MEM_LEVEL +#define DEF_MEM_LEVEL MAX_MEM_LEVEL #endif #endif const char zip_copyright[] = - " zip 1.01 Copyright 1998-2004 Gilles Vollant - http://www.winimage.com/zLibDll"; + " zip 1.01 Copyright 1998-2004 Gilles Vollant - " + "http://www.winimage.com/zLibDll"; -#define SIZEDATA_INDATABLOCK (4096-(4*4)) +#define SIZEDATA_INDATABLOCK (4096-(4*4)) -#define LOCALHEADERMAGIC (0x04034b50) -#define CENTRALHEADERMAGIC (0x02014b50) -#define ENDHEADERMAGIC (0x06054b50) +#define LOCALHEADERMAGIC (0x04034b50) +#define CENTRALHEADERMAGIC (0x02014b50) +#define ENDHEADERMAGIC (0x06054b50) -#define FLAG_LOCALHEADER_OFFSET (0x06) -#define CRC_LOCALHEADER_OFFSET (0x0e) +#define FLAG_LOCALHEADER_OFFSET (0x06) +#define CRC_LOCALHEADER_OFFSET (0x0e) -#define SIZECENTRALHEADER (0x2e) /* 46 */ +#define SIZECENTRALHEADER (0x2e) /* 46 */ typedef struct linkedlist_datablock_internal_s { - struct linkedlist_datablock_internal_s* next_datablock; - uLong avail_in_this_block; - uLong filled_in_this_block; - uLong unused; /* for future use and alignement */ - unsigned char data[SIZEDATA_INDATABLOCK]; + struct linkedlist_datablock_internal_s *next_datablock; + uLong avail_in_this_block; + uLong filled_in_this_block; + uLong unused; /* for future use and alignement */ + unsigned char data[SIZEDATA_INDATABLOCK]; } linkedlist_datablock_internal; typedef struct linkedlist_data_s { - linkedlist_datablock_internal* first_block; - linkedlist_datablock_internal* last_block; + linkedlist_datablock_internal* first_block; + linkedlist_datablock_internal* last_block; } linkedlist_data; typedef struct { - z_stream stream; /* zLib stream structure for inflate */ - int stream_initialised; /* 1 is stream is initialised */ - uInt pos_in_buffered_data; /* last written byte in buffered_data */ - - uLong pos_local_header; /* offset of the local header of the file - currenty writing */ - char* central_header; /* central header data for the current file */ - uLong size_centralheader; /* size of the central header for cur file */ - uLong flag; /* flag of the file currently writing */ - - int method; /* compression method of file currenty wr.*/ - int raw; /* 1 for directly writing raw data */ - Byte buffered_data[Z_BUFSIZE];/* buffer contain compressed data to be writ*/ - uLong dosDate; - uLong crc32; - int encrypt; + z_stream stream; /* zLib stream structure for inflate */ + int stream_initialised; /* 1 is stream is initialised */ + uInt pos_in_buffered_data; /* last written byte in buffered_data */ + + /* offset of the local header of the file currenty writing */ + uLong pos_local_header; + char *central_header; /* central header data for the current file */ + uLong size_centralheader; /* size of the central header for cur file */ + uLong flag; /* flag of the file currently writing */ + + int method; /* compression method of file currenty wr. */ + int raw; /* 1 for directly writing raw data */ + /* buffer contain compressed data to be writ */ + Byte buffered_data[Z_BUFSIZE]; + uLong dosDate; + uLong crc32; + int encrypt; #ifndef NOCRYPT - unsigned long keys[3]; /* keys defining the pseudo-random sequence */ - const unsigned long* pcrc_32_tab; - int crypt_header_size; + unsigned long keys[3]; /* keys defining the pseudo-random sequence */ + const unsigned long *pcrc_32_tab; + int crypt_header_size; #endif } curfile_info; typedef struct { - zlib_filefunc_def z_filefunc; - voidpf filestream; /* io structore of the zipfile */ - linkedlist_data central_dir;/* datablock with central dir in construction*/ - int in_opened_file_inzip; /* 1 if a file in the zip is currently writ.*/ - curfile_info ci; /* info on the file curretly writing */ - - uLong begin_pos; /* position of the beginning of the zipfile */ - uLong add_position_when_writting_offset; - uLong number_entry; + zlib_filefunc_def z_filefunc; + voidpf filestream; /* io structore of the zipfile */ + /* datablock with central dir in construction */ + linkedlist_data central_dir; + /* 1 if a file in the zip is currently writ. */ + int in_opened_file_inzip; + curfile_info ci; /* info on the file curretly writing */ + + uLong begin_pos; /* position of the beginning of the zipfile */ + uLong add_position_when_writting_offset; + uLong number_entry; #ifndef NO_ADDFILEINEXISTINGZIP - char *globalcomment; + char *globalcomment; #endif } zip_internal; #ifndef NOCRYPT -#define INCLUDECRYPTINGCODE_IFCRYPTALLOWED +#define INCLUDECRYPTINGCODE_IFCRYPTALLOWED #include "crypt.h" #endif -local linkedlist_datablock_internal* allocate_new_datablock() +local linkedlist_datablock_internal * +allocate_new_datablock() { - linkedlist_datablock_internal* ldi; - ldi = (linkedlist_datablock_internal*) - ALLOC(sizeof(linkedlist_datablock_internal)); - if (ldi!=NULL) - { - ldi->next_datablock = NULL ; - ldi->filled_in_this_block = 0 ; - ldi->avail_in_this_block = SIZEDATA_INDATABLOCK ; - } - return ldi; + linkedlist_datablock_internal* ldi; + ldi = (linkedlist_datablock_internal*) + ALLOC(sizeof (linkedlist_datablock_internal)); + if (ldi != NULL) { + ldi->next_datablock = NULL; + ldi->filled_in_this_block = 0; + ldi->avail_in_this_block = SIZEDATA_INDATABLOCK; + } + return (ldi); } -local void free_datablock(ldi) - linkedlist_datablock_internal* ldi; +local void +free_datablock(linkedlist_datablock_internal *ldi) { - while (ldi!=NULL) - { - linkedlist_datablock_internal* ldinext = ldi->next_datablock; - TRYFREE(ldi); - ldi = ldinext; - } + while (ldi != NULL) { + linkedlist_datablock_internal *ldinext = ldi->next_datablock; + TRYFREE(ldi); + ldi = ldinext; + } } -local void init_linkedlist(ll) - linkedlist_data* ll; +local void +init_linkedlist(linkedlist_data *ll) { - ll->first_block = ll->last_block = NULL; + ll->first_block = ll->last_block = NULL; } -local void free_linkedlist(ll) - linkedlist_data* ll; +local void +free_linkedlist(linkedlist_data *ll) { - free_datablock(ll->first_block); - ll->first_block = ll->last_block = NULL; + free_datablock(ll->first_block); + ll->first_block = ll->last_block = NULL; } -local int add_data_in_datablock(ll,buf,len) - linkedlist_data* ll; - const void* buf; - uLong len; +local int +add_data_in_datablock( + linkedlist_data *ll, + const void *buf, + uLong len) { - linkedlist_datablock_internal* ldi; - const unsigned char* from_copy; - - if (ll==NULL) - return ZIP_INTERNALERROR; - - if (ll->last_block == NULL) - { - ll->first_block = ll->last_block = allocate_new_datablock(); - if (ll->first_block == NULL) - return ZIP_INTERNALERROR; - } - - ldi = ll->last_block; - from_copy = (unsigned char*)buf; - - while (len>0) - { - uInt copy_this; - uInt i; - unsigned char* to_copy; - - if (ldi->avail_in_this_block==0) - { - ldi->next_datablock = allocate_new_datablock(); - if (ldi->next_datablock == NULL) - return ZIP_INTERNALERROR; - ldi = ldi->next_datablock ; - ll->last_block = ldi; - } - - if (ldi->avail_in_this_block < len) - copy_this = (uInt)ldi->avail_in_this_block; - else - copy_this = (uInt)len; - - to_copy = &(ldi->data[ldi->filled_in_this_block]); - - for (i=0;ifilled_in_this_block += copy_this; - ldi->avail_in_this_block -= copy_this; - from_copy += copy_this ; - len -= copy_this; - } - return ZIP_OK; + linkedlist_datablock_internal *ldi; + const unsigned char *from_copy; + + if (ll == NULL) + return (ZIP_INTERNALERROR); + + if (ll->last_block == NULL) { + ll->first_block = ll->last_block = allocate_new_datablock(); + if (ll->first_block == NULL) + return (ZIP_INTERNALERROR); + } + + ldi = ll->last_block; + from_copy = (unsigned char *)buf; + + while (len > 0) { + uInt copy_this; + uInt i; + unsigned char *to_copy; + + if (ldi->avail_in_this_block == 0) { + ldi->next_datablock = allocate_new_datablock(); + if (ldi->next_datablock == NULL) + return (ZIP_INTERNALERROR); + ldi = ldi->next_datablock; + ll->last_block = ldi; + } + + if (ldi->avail_in_this_block < len) + copy_this = (uInt)ldi->avail_in_this_block; + else + copy_this = (uInt)len; + + to_copy = &(ldi->data[ldi->filled_in_this_block]); + + for (i = 0; i < copy_this; i++) + *(to_copy+i) = *(from_copy+i); + + ldi->filled_in_this_block += copy_this; + ldi->avail_in_this_block -= copy_this; + from_copy += copy_this; + len -= copy_this; + } + return (ZIP_OK); } -/****************************************************************************/ - #ifndef NO_ADDFILEINEXISTINGZIP -/* =========================================================================== - Inputs a long in LSB order to the given file - nbByte == 1, 2 or 4 (byte, short or long) -*/ - -local int ziplocal_putValue OF((const zlib_filefunc_def* pzlib_filefunc_def, - voidpf filestream, uLong x, int nbByte)); -local int ziplocal_putValue (pzlib_filefunc_def, filestream, x, nbByte) - const zlib_filefunc_def* pzlib_filefunc_def; - voidpf filestream; - uLong x; - int nbByte; +/* + * Inputs a long in LSB order to the given file + * nbByte == 1, 2 or 4 (byte, short or long) + */ + +local int ziplocal_putValue OF((const zlib_filefunc_def *pzlib_filefunc_def, + voidpf filestream, uLong x, int nbByte)); +local int +ziplocal_putValue( + const zlib_filefunc_def *pzlib_filefunc_def, + voidpf filestream, + uLong x, + int nbByte) { - unsigned char buf[4]; - int n; - for (n = 0; n < nbByte; n++) - { - buf[n] = (unsigned char)(x & 0xff); - x >>= 8; - } - if (x != 0) - { /* data overflow - hack for ZIP64 (X Roche) */ - for (n = 0; n < nbByte; n++) - { - buf[n] = 0xff; - } - } - - if (ZWRITE(*pzlib_filefunc_def,filestream,buf,nbByte)!=(uLong)nbByte) - return ZIP_ERRNO; - else - return ZIP_OK; + unsigned char buf[4]; + int n; + for (n = 0; n < nbByte; n++) { + buf[n] = (unsigned char)(x & 0xff); + x >>= 8; + } + if (x != 0) { /* data overflow - hack for ZIP64 (X Roche) */ + for (n = 0; n < nbByte; n++) { + buf[n] = 0xff; + } + } + + if (ZWRITE(*pzlib_filefunc_def, filestream, buf, nbByte) != + (uLong)nbByte) + return (ZIP_ERRNO); + else + return (ZIP_OK); } -local void ziplocal_putValue_inmemory OF((void* dest, uLong x, int nbByte)); -local void ziplocal_putValue_inmemory (dest, x, nbByte) - void* dest; - uLong x; - int nbByte; +local void ziplocal_putValue_inmemory OF((void *dest, uLong x, int nbByte)); +local void +ziplocal_putValue_inmemory( + void *dest, + uLong x, + int nbByte) { - unsigned char* buf=(unsigned char*)dest; - int n; - for (n = 0; n < nbByte; n++) { - buf[n] = (unsigned char)(x & 0xff); - x >>= 8; - } - - if (x != 0) - { /* data overflow - hack for ZIP64 */ - for (n = 0; n < nbByte; n++) - { - buf[n] = 0xff; - } - } + unsigned char *buf = (unsigned char *)dest; + int n; + for (n = 0; n < nbByte; n++) { + buf[n] = (unsigned char)(x & 0xff); + x >>= 8; + } + + if (x != 0) { /* data overflow - hack for ZIP64 */ + for (n = 0; n < nbByte; n++) { + buf[n] = 0xff; + } + } } -/****************************************************************************/ - -local uLong ziplocal_TmzDateToDosDate(ptm,dosDate) - const tm_zip* ptm; - uLong dosDate; +local uLong +ziplocal_TmzDateToDosDate( + const tm_zip *ptm, + uLong dosDate) { - uLong year = (uLong)ptm->tm_year; - if (year>1980) - year-=1980; - else if (year>80) - year-=80; - return - (uLong) (((ptm->tm_mday) + (32 * (ptm->tm_mon+1)) + (512 * year)) << 16) | - ((ptm->tm_sec/2) + (32* ptm->tm_min) + (2048 * (uLong)ptm->tm_hour)); + uLong year = (uLong)ptm->tm_year; + if (year > 1980) + year -= 1980; + else if (year > 80) + year -= 80; + return + ((uLong)(((ptm->tm_mday) + (32 * (ptm->tm_mon+1)) + + (512 * year)) << 16) | + ((ptm->tm_sec/2) + (32* ptm->tm_min) + + (2048 * (uLong)ptm->tm_hour))); } -/****************************************************************************/ - local int ziplocal_getByte OF(( - const zlib_filefunc_def* pzlib_filefunc_def, + const zlib_filefunc_def *pzlib_filefunc_def, voidpf filestream, int *pi)); -local int ziplocal_getByte(pzlib_filefunc_def,filestream,pi) - const zlib_filefunc_def* pzlib_filefunc_def; - voidpf filestream; - int *pi; +local int +ziplocal_getByte( + const zlib_filefunc_def *pzlib_filefunc_def, + voidpf filestream, + int *pi) { - unsigned char c; - int err = (int)ZREAD(*pzlib_filefunc_def,filestream,&c,1); - if (err==1) - { - *pi = (int)c; - return ZIP_OK; - } - else - { - if (ZERROR(*pzlib_filefunc_def,filestream)) - return ZIP_ERRNO; - else - return ZIP_EOF; - } + unsigned char c; + int err = (int)ZREAD(*pzlib_filefunc_def, filestream, &c, 1); + if (err == 1) { + *pi = (int)c; + return (ZIP_OK); + } else { + if (ZERROR(*pzlib_filefunc_def, filestream)) + return (ZIP_ERRNO); + else + return (ZIP_EOF); + } } -/* =========================================================================== - Reads a long in LSB order from the given gz_stream. Sets -*/ +/* + * Reads a long in LSB order from the given gz_stream. Sets + */ local int ziplocal_getShort OF(( - const zlib_filefunc_def* pzlib_filefunc_def, + const zlib_filefunc_def *pzlib_filefunc_def, voidpf filestream, uLong *pX)); -local int ziplocal_getShort (pzlib_filefunc_def,filestream,pX) - const zlib_filefunc_def* pzlib_filefunc_def; - voidpf filestream; - uLong *pX; +local int +ziplocal_getShort( + const zlib_filefunc_def *pzlib_filefunc_def, + voidpf filestream, + uLong *pX) { - uLong x ; - int i; - int err; - - err = ziplocal_getByte(pzlib_filefunc_def,filestream,&i); - x = (uLong)i; - - if (err==ZIP_OK) - err = ziplocal_getByte(pzlib_filefunc_def,filestream,&i); - x += ((uLong)i)<<8; - - if (err==ZIP_OK) - *pX = x; - else - *pX = 0; - return err; + uLong x; + int i; + int err; + + err = ziplocal_getByte(pzlib_filefunc_def, filestream, &i); + x = (uLong)i; + + if (err == ZIP_OK) + err = ziplocal_getByte(pzlib_filefunc_def, filestream, &i); + x += ((uLong)i)<<8; + + if (err == ZIP_OK) + *pX = x; + else + *pX = 0; + return (err); } local int ziplocal_getLong OF(( - const zlib_filefunc_def* pzlib_filefunc_def, + const zlib_filefunc_def *pzlib_filefunc_def, voidpf filestream, uLong *pX)); -local int ziplocal_getLong (pzlib_filefunc_def,filestream,pX) - const zlib_filefunc_def* pzlib_filefunc_def; - voidpf filestream; - uLong *pX; +local int +ziplocal_getLong( + const zlib_filefunc_def *pzlib_filefunc_def, + voidpf filestream, + uLong *pX) { - uLong x ; - int i; - int err; - - err = ziplocal_getByte(pzlib_filefunc_def,filestream,&i); - x = (uLong)i; - - if (err==ZIP_OK) - err = ziplocal_getByte(pzlib_filefunc_def,filestream,&i); - x += ((uLong)i)<<8; - - if (err==ZIP_OK) - err = ziplocal_getByte(pzlib_filefunc_def,filestream,&i); - x += ((uLong)i)<<16; - - if (err==ZIP_OK) - err = ziplocal_getByte(pzlib_filefunc_def,filestream,&i); - x += ((uLong)i)<<24; - - if (err==ZIP_OK) - *pX = x; - else - *pX = 0; - return err; + uLong x; + int i; + int err; + + err = ziplocal_getByte(pzlib_filefunc_def, filestream, &i); + x = (uLong)i; + + if (err == ZIP_OK) + err = ziplocal_getByte(pzlib_filefunc_def, filestream, &i); + x += ((uLong)i)<<8; + + if (err == ZIP_OK) + err = ziplocal_getByte(pzlib_filefunc_def, filestream, &i); + x += ((uLong)i)<<16; + + if (err == ZIP_OK) + err = ziplocal_getByte(pzlib_filefunc_def, filestream, &i); + x += ((uLong)i)<<24; + + if (err == ZIP_OK) + *pX = x; + else + *pX = 0; + return (err); } #ifndef BUFREADCOMMENT -#define BUFREADCOMMENT (0x400) +#define BUFREADCOMMENT (0x400) #endif /* - Locate the Central directory of a zipfile (at the end, just before - the global comment) -*/ + * Locate the Central directory of a zipfile (at the end, just before + * the global comment) + */ local uLong ziplocal_SearchCentralDir OF(( - const zlib_filefunc_def* pzlib_filefunc_def, + const zlib_filefunc_def *pzlib_filefunc_def, voidpf filestream)); -local uLong ziplocal_SearchCentralDir(pzlib_filefunc_def,filestream) - const zlib_filefunc_def* pzlib_filefunc_def; - voidpf filestream; +local uLong +ziplocal_SearchCentralDir( + const zlib_filefunc_def *pzlib_filefunc_def, + voidpf filestream) { - unsigned char* buf; - uLong uSizeFile; - uLong uBackRead; - uLong uMaxBack=0xffff; /* maximum size of global comment */ - uLong uPosFound=0; - - if (ZSEEK(*pzlib_filefunc_def,filestream,0,ZLIB_FILEFUNC_SEEK_END) != 0) - return 0; - - - uSizeFile = ZTELL(*pzlib_filefunc_def,filestream); - - if (uMaxBack>uSizeFile) - uMaxBack = uSizeFile; - - buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4); - if (buf==NULL) - return 0; - - uBackRead = 4; - while (uBackReaduMaxBack) - uBackRead = uMaxBack; - else - uBackRead+=BUFREADCOMMENT; - uReadPos = uSizeFile-uBackRead ; - - uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ? - (BUFREADCOMMENT+4) : (uSizeFile-uReadPos); - if (ZSEEK(*pzlib_filefunc_def,filestream,uReadPos,ZLIB_FILEFUNC_SEEK_SET)!=0) - break; - - if (ZREAD(*pzlib_filefunc_def,filestream,buf,uReadSize)!=uReadSize) - break; - - for (i=(int)uReadSize-3; (i--)>0;) - if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) && - ((*(buf+i+2))==0x05) && ((*(buf+i+3))==0x06)) - { - uPosFound = uReadPos+i; - break; - } - - if (uPosFound!=0) - break; - } - TRYFREE(buf); - return uPosFound; + unsigned char *buf; + uLong uSizeFile; + uLong uBackRead; + uLong uMaxBack = 0xffff; /* maximum size of global comment */ + uLong uPosFound = 0; + + if (ZSEEK(*pzlib_filefunc_def, filestream, 0, + ZLIB_FILEFUNC_SEEK_END) != 0) + return (0); + + + uSizeFile = ZTELL(*pzlib_filefunc_def, filestream); + + if (uMaxBack > uSizeFile) + uMaxBack = uSizeFile; + + buf = (unsigned char *)ALLOC(BUFREADCOMMENT+4); + if (buf == NULL) + return (0); + + uBackRead = 4; + while (uBackRead < uMaxBack) { + uLong uReadSize, uReadPos; + int i; + if (uBackRead+BUFREADCOMMENT > uMaxBack) + uBackRead = uMaxBack; + else + uBackRead += BUFREADCOMMENT; + uReadPos = uSizeFile-uBackRead; + + uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ? + (BUFREADCOMMENT+4) : (uSizeFile-uReadPos); + if (ZSEEK(*pzlib_filefunc_def, filestream, uReadPos, + ZLIB_FILEFUNC_SEEK_SET) != 0) + break; + + if (ZREAD(*pzlib_filefunc_def, filestream, buf, uReadSize) != + uReadSize) + break; + + for (i = (int)uReadSize-3; (i--) > 0; ) + if (((*(buf+i)) == 0x50) && ((*(buf+i+1)) == 0x4b) && + ((*(buf+i+2)) == 0x05) && ((*(buf+i+3)) == 0x06)) { + uPosFound = uReadPos+i; + break; + } + + if (uPosFound != 0) + break; + } + TRYFREE(buf); + return (uPosFound); } -#endif /* !NO_ADDFILEINEXISTINGZIP*/ - -/************************************************************/ -extern zipFile ZEXPORT zipOpen2 (pathname, append, globalcomment, pzlib_filefunc_def) - const char *pathname; - int append; - zipcharpc* globalcomment; - zlib_filefunc_def* pzlib_filefunc_def; +#endif /* !NO_ADDFILEINEXISTINGZIP */ + +extern zipFile ZEXPORT +zipOpen2( + const char *pathname, + int append, + zipcharpc *globalcomment, + zlib_filefunc_def *pzlib_filefunc_def) { - zip_internal ziinit; - zip_internal* zi; - int err=ZIP_OK; - - - if (pzlib_filefunc_def==NULL) - fill_fopen_filefunc(&ziinit.z_filefunc); - else - ziinit.z_filefunc = *pzlib_filefunc_def; - - ziinit.filestream = (*(ziinit.z_filefunc.zopen_file)) - (ziinit.z_filefunc.opaque, - pathname, - (append == APPEND_STATUS_CREATE) ? - (ZLIB_FILEFUNC_MODE_READ | ZLIB_FILEFUNC_MODE_WRITE | ZLIB_FILEFUNC_MODE_CREATE) : - (ZLIB_FILEFUNC_MODE_READ | ZLIB_FILEFUNC_MODE_WRITE | ZLIB_FILEFUNC_MODE_EXISTING)); - - if (ziinit.filestream == NULL) - return NULL; - ziinit.begin_pos = ZTELL(ziinit.z_filefunc,ziinit.filestream); - ziinit.in_opened_file_inzip = 0; - ziinit.ci.stream_initialised = 0; - ziinit.number_entry = 0; - ziinit.add_position_when_writting_offset = 0; - init_linkedlist(&(ziinit.central_dir)); - - - zi = (zip_internal*)ALLOC(sizeof(zip_internal)); - if (zi==NULL) - { - ZCLOSE(ziinit.z_filefunc,ziinit.filestream); - return NULL; - } - - /* now we add file in a zipfile */ -# ifndef NO_ADDFILEINEXISTINGZIP - ziinit.globalcomment = NULL; - if (append == APPEND_STATUS_ADDINZIP) - { - uLong byte_before_the_zipfile;/* byte before the zipfile, (>0 for sfx)*/ - - uLong size_central_dir; /* size of the central directory */ - uLong offset_central_dir; /* offset of start of central directory */ - uLong central_pos,uL; - - uLong number_disk; /* number of the current dist, used for - spaning ZIP, unsupported, always 0*/ - uLong number_disk_with_CD; /* number the the disk with central dir, used - for spaning ZIP, unsupported, always 0*/ - uLong number_entry; - uLong number_entry_CD; /* total number of entries in - the central dir - (same than number_entry on nospan) */ - uLong size_comment; - - central_pos = ziplocal_SearchCentralDir(&ziinit.z_filefunc,ziinit.filestream); - if (central_pos==0) - err=ZIP_ERRNO; - - if (ZSEEK(ziinit.z_filefunc, ziinit.filestream, - central_pos,ZLIB_FILEFUNC_SEEK_SET)!=0) - err=ZIP_ERRNO; - - /* the signature, already checked */ - if (ziplocal_getLong(&ziinit.z_filefunc, ziinit.filestream,&uL)!=ZIP_OK) - err=ZIP_ERRNO; - - /* number of this disk */ - if (ziplocal_getShort(&ziinit.z_filefunc, ziinit.filestream,&number_disk)!=ZIP_OK) - err=ZIP_ERRNO; - - /* number of the disk with the start of the central directory */ - if (ziplocal_getShort(&ziinit.z_filefunc, ziinit.filestream,&number_disk_with_CD)!=ZIP_OK) - err=ZIP_ERRNO; - - /* total number of entries in the central dir on this disk */ - if (ziplocal_getShort(&ziinit.z_filefunc, ziinit.filestream,&number_entry)!=ZIP_OK) - err=ZIP_ERRNO; - - /* total number of entries in the central dir */ - if (ziplocal_getShort(&ziinit.z_filefunc, ziinit.filestream,&number_entry_CD)!=ZIP_OK) - err=ZIP_ERRNO; - - if ((number_entry_CD!=number_entry) || - (number_disk_with_CD!=0) || - (number_disk!=0)) - err=ZIP_BADZIPFILE; - - /* size of the central directory */ - if (ziplocal_getLong(&ziinit.z_filefunc, ziinit.filestream,&size_central_dir)!=ZIP_OK) - err=ZIP_ERRNO; - - /* offset of start of central directory with respect to the - starting disk number */ - if (ziplocal_getLong(&ziinit.z_filefunc, ziinit.filestream,&offset_central_dir)!=ZIP_OK) - err=ZIP_ERRNO; - - /* zipfile global comment length */ - if (ziplocal_getShort(&ziinit.z_filefunc, ziinit.filestream,&size_comment)!=ZIP_OK) - err=ZIP_ERRNO; - - if ((central_pos0) - { - ziinit.globalcomment = ALLOC(size_comment+1); - if (ziinit.globalcomment) - { - size_comment = ZREAD(ziinit.z_filefunc, ziinit.filestream,ziinit.globalcomment,size_comment); - ziinit.globalcomment[size_comment]=0; - } - } - - byte_before_the_zipfile = central_pos - - (offset_central_dir+size_central_dir); - ziinit.add_position_when_writting_offset = byte_before_the_zipfile; - - { - uLong size_central_dir_to_read = size_central_dir; - size_t buf_size = SIZEDATA_INDATABLOCK; - void* buf_read = (void*)ALLOC(buf_size); - if (ZSEEK(ziinit.z_filefunc, ziinit.filestream, - offset_central_dir + byte_before_the_zipfile, - ZLIB_FILEFUNC_SEEK_SET) != 0) - err=ZIP_ERRNO; - - while ((size_central_dir_to_read>0) && (err==ZIP_OK)) - { - uLong read_this = SIZEDATA_INDATABLOCK; - if (read_this > size_central_dir_to_read) - read_this = size_central_dir_to_read; - if (ZREAD(ziinit.z_filefunc, ziinit.filestream,buf_read,read_this) != read_this) - err=ZIP_ERRNO; - - if (err==ZIP_OK) - err = add_data_in_datablock(&ziinit.central_dir,buf_read, - (uLong)read_this); - size_central_dir_to_read-=read_this; - } - TRYFREE(buf_read); - } - ziinit.begin_pos = byte_before_the_zipfile; - ziinit.number_entry = number_entry_CD; - - if (ZSEEK(ziinit.z_filefunc, ziinit.filestream, - offset_central_dir+byte_before_the_zipfile,ZLIB_FILEFUNC_SEEK_SET)!=0) - err=ZIP_ERRNO; - } - - if (globalcomment) - { - *globalcomment = ziinit.globalcomment; - } -# endif /* !NO_ADDFILEINEXISTINGZIP*/ - - if (err != ZIP_OK) - { -# ifndef NO_ADDFILEINEXISTINGZIP - TRYFREE(ziinit.globalcomment); -# endif /* !NO_ADDFILEINEXISTINGZIP*/ - TRYFREE(zi); - return NULL; - } - else - { - *zi = ziinit; - return (zipFile)zi; - } + zip_internal ziinit; + zip_internal *zi; + int err = ZIP_OK; + + + if (pzlib_filefunc_def == NULL) + fill_fopen_filefunc(&ziinit.z_filefunc); + else + ziinit.z_filefunc = *pzlib_filefunc_def; + + ziinit.filestream = (*(ziinit.z_filefunc.zopen_file)) + (ziinit.z_filefunc.opaque, + pathname, + (append == APPEND_STATUS_CREATE) ? + (ZLIB_FILEFUNC_MODE_READ | ZLIB_FILEFUNC_MODE_WRITE | + ZLIB_FILEFUNC_MODE_CREATE) : + (ZLIB_FILEFUNC_MODE_READ | ZLIB_FILEFUNC_MODE_WRITE | + ZLIB_FILEFUNC_MODE_EXISTING)); + + if (ziinit.filestream == NULL) + return (NULL); + ziinit.begin_pos = ZTELL(ziinit.z_filefunc, ziinit.filestream); + ziinit.in_opened_file_inzip = 0; + ziinit.ci.stream_initialised = 0; + ziinit.number_entry = 0; + ziinit.add_position_when_writting_offset = 0; + init_linkedlist(&(ziinit.central_dir)); + + + zi = (zip_internal *)ALLOC(sizeof (zip_internal)); + if (zi == NULL) { + ZCLOSE(ziinit.z_filefunc, ziinit.filestream); + return (NULL); + } + + /* now we add file in a zipfile */ +#ifndef NO_ADDFILEINEXISTINGZIP + ziinit.globalcomment = NULL; + if (append == APPEND_STATUS_ADDINZIP) { + /* byte before the zipfile, (>0 for sfx) */ + uLong byte_before_the_zipfile; + + uLong size_central_dir; /* size of the central directory */ + /* offset of start of central directory */ + uLong offset_central_dir; + uLong central_pos, uL; + + uLong number_disk; + uLong number_disk_with_CD; + uLong number_entry; + uLong number_entry_CD; + uLong size_comment; + + central_pos = ziplocal_SearchCentralDir(&ziinit.z_filefunc, + ziinit.filestream); + if (central_pos == 0) + err = ZIP_ERRNO; + + if (ZSEEK(ziinit.z_filefunc, ziinit.filestream, + central_pos, ZLIB_FILEFUNC_SEEK_SET) != 0) + err = ZIP_ERRNO; + + /* the signature, already checked */ + if (ziplocal_getLong(&ziinit.z_filefunc, + ziinit.filestream, &uL) != ZIP_OK) + err = ZIP_ERRNO; + + /* number of this disk */ + if (ziplocal_getShort(&ziinit.z_filefunc, + ziinit.filestream, &number_disk) != ZIP_OK) + err = ZIP_ERRNO; + + /* number of the disk with the start of the central directory */ + if (ziplocal_getShort(&ziinit.z_filefunc, + ziinit.filestream, &number_disk_with_CD) != ZIP_OK) + err = ZIP_ERRNO; + + /* total number of entries in the central dir on this disk */ + if (ziplocal_getShort(&ziinit.z_filefunc, + ziinit.filestream, &number_entry) != ZIP_OK) + err = ZIP_ERRNO; + + /* total number of entries in the central dir */ + if (ziplocal_getShort(&ziinit.z_filefunc, + ziinit.filestream, &number_entry_CD) != ZIP_OK) + err = ZIP_ERRNO; + + if ((number_entry_CD != number_entry) || + (number_disk_with_CD != 0) || + (number_disk != 0)) + err = ZIP_BADZIPFILE; + + /* size of the central directory */ + if (ziplocal_getLong(&ziinit.z_filefunc, + ziinit.filestream, &size_central_dir) != ZIP_OK) + err = ZIP_ERRNO; + + /* + * offset of start of central directory with respect to the + * starting disk number + */ + if (ziplocal_getLong(&ziinit.z_filefunc, + ziinit.filestream, &offset_central_dir) != ZIP_OK) + err = ZIP_ERRNO; + + /* zipfile global comment length */ + if (ziplocal_getShort(&ziinit.z_filefunc, + ziinit.filestream, &size_comment) != ZIP_OK) + err = ZIP_ERRNO; + + if ((central_pos < offset_central_dir+size_central_dir) && + (err == ZIP_OK)) + err = ZIP_BADZIPFILE; + + if (err != ZIP_OK) { + ZCLOSE(ziinit.z_filefunc, ziinit.filestream); + return (NULL); + } + + if (size_comment > 0) { + ziinit.globalcomment = ALLOC(size_comment+1); + if (ziinit.globalcomment) { + size_comment = ZREAD(ziinit.z_filefunc, + ziinit.filestream, ziinit.globalcomment, + size_comment); + ziinit.globalcomment[size_comment] = 0; + } + } + + byte_before_the_zipfile = central_pos - + (offset_central_dir+size_central_dir); + ziinit.add_position_when_writting_offset = + byte_before_the_zipfile; + + { + uLong size_central_dir_to_read = size_central_dir; + size_t buf_size = SIZEDATA_INDATABLOCK; + void *buf_read = (void *)ALLOC(buf_size); + if (ZSEEK(ziinit.z_filefunc, ziinit.filestream, + offset_central_dir + byte_before_the_zipfile, + ZLIB_FILEFUNC_SEEK_SET) != 0) + err = ZIP_ERRNO; + + while ((size_central_dir_to_read > 0) && + (err == ZIP_OK)) { + uLong read_this = SIZEDATA_INDATABLOCK; + if (read_this > size_central_dir_to_read) + read_this = size_central_dir_to_read; + if (ZREAD(ziinit.z_filefunc, ziinit.filestream, + buf_read, read_this) != read_this) + err = ZIP_ERRNO; + + if (err == ZIP_OK) + err = add_data_in_datablock( + &ziinit.central_dir, + buf_read, (uLong)read_this); + size_central_dir_to_read -= read_this; + } + TRYFREE(buf_read); + } + ziinit.begin_pos = byte_before_the_zipfile; + ziinit.number_entry = number_entry_CD; + + if (ZSEEK(ziinit.z_filefunc, ziinit.filestream, + offset_central_dir+byte_before_the_zipfile, + ZLIB_FILEFUNC_SEEK_SET) != 0) + err = ZIP_ERRNO; + } + + if (globalcomment) { + *globalcomment = ziinit.globalcomment; + } +#endif /* !NO_ADDFILEINEXISTINGZIP */ + + if (err != ZIP_OK) { +#ifndef NO_ADDFILEINEXISTINGZIP + TRYFREE(ziinit.globalcomment); +#endif /* !NO_ADDFILEINEXISTINGZIP */ + TRYFREE(zi); + return (NULL); + } else { + *zi = ziinit; + return ((zipFile)zi); + } } -extern zipFile ZEXPORT zipOpen (pathname, append) - const char *pathname; - int append; +extern zipFile ZEXPORT +zipOpen( + const char *pathname, + int append) { - return zipOpen2(pathname,append,NULL,NULL); + return (zipOpen2(pathname, append, NULL, NULL)); } -extern int ZEXPORT zipOpenNewFileInZip3 (file, filename, zipfi, - extrafield_local, size_extrafield_local, - extrafield_global, size_extrafield_global, - comment, method, level, raw, - windowBits, memLevel, strategy, - password, crcForCrypting) - zipFile file; - const char* filename; - const zip_fileinfo* zipfi; - const void* extrafield_local; - uInt size_extrafield_local; - const void* extrafield_global; - uInt size_extrafield_global; - const char* comment; - int method; - int level; - int raw; - int windowBits; - int memLevel; - int strategy; - const char* password; - uLong crcForCrypting; +extern int ZEXPORT +zipOpenNewFileInZip3( + zipFile file, + const char *filename, + const zip_fileinfo *zipfi, + const void *extrafield_local, + uInt size_extrafield_local, + const void *extrafield_global, + uInt size_extrafield_global, + const char *comment, + int method, + int level, + int raw, + int windowBits, + int memLevel, + int strategy, + const char *password, + uLong crcForCrypting) { - zip_internal* zi; - uInt size_filename; - uInt size_comment; - uInt i; - int err = ZIP_OK; - -# ifdef NOCRYPT - if (password != NULL) - return ZIP_PARAMERROR; -# endif - - if (file == NULL) - return ZIP_PARAMERROR; - if ((method!=0) && (method!=Z_DEFLATED)) - return ZIP_PARAMERROR; - - zi = (zip_internal*)file; - - if (zi->in_opened_file_inzip == 1) - { - err = zipCloseFileInZip (file); - if (err != ZIP_OK) - return err; - } - - - if (filename==NULL) - filename="-"; - - if (comment==NULL) - size_comment = 0; - else - size_comment = (uInt)strlen(comment); - - size_filename = (uInt)strlen(filename); - - if (zipfi == NULL) - zi->ci.dosDate = 0; - else - { - if (zipfi->dosDate != 0) - zi->ci.dosDate = zipfi->dosDate; - else zi->ci.dosDate = ziplocal_TmzDateToDosDate(&zipfi->tmz_date,zipfi->dosDate); - } - - zi->ci.flag = 0; - if ((level==8) || (level==9)) - zi->ci.flag |= 2; - if ((level==2)) - zi->ci.flag |= 4; - if ((level==1)) - zi->ci.flag |= 6; - if (password != NULL) - zi->ci.flag |= 1; - - zi->ci.crc32 = 0; - zi->ci.method = method; - zi->ci.encrypt = 0; - zi->ci.stream_initialised = 0; - zi->ci.pos_in_buffered_data = 0; - zi->ci.raw = raw; - zi->ci.pos_local_header = ZTELL(zi->z_filefunc,zi->filestream) ; - zi->ci.size_centralheader = SIZECENTRALHEADER + size_filename + - size_extrafield_global + size_comment; - zi->ci.central_header = (char*)ALLOC((uInt)zi->ci.size_centralheader); - - ziplocal_putValue_inmemory(zi->ci.central_header,(uLong)CENTRALHEADERMAGIC,4); - /* version info */ - ziplocal_putValue_inmemory(zi->ci.central_header+4,(uLong)VERSIONMADEBY,2); - ziplocal_putValue_inmemory(zi->ci.central_header+6,(uLong)20,2); - ziplocal_putValue_inmemory(zi->ci.central_header+8,(uLong)zi->ci.flag,2); - ziplocal_putValue_inmemory(zi->ci.central_header+10,(uLong)zi->ci.method,2); - ziplocal_putValue_inmemory(zi->ci.central_header+12,(uLong)zi->ci.dosDate,4); - ziplocal_putValue_inmemory(zi->ci.central_header+16,(uLong)0,4); /*crc*/ - ziplocal_putValue_inmemory(zi->ci.central_header+20,(uLong)0,4); /*compr size*/ - ziplocal_putValue_inmemory(zi->ci.central_header+24,(uLong)0,4); /*uncompr size*/ - ziplocal_putValue_inmemory(zi->ci.central_header+28,(uLong)size_filename,2); - ziplocal_putValue_inmemory(zi->ci.central_header+30,(uLong)size_extrafield_global,2); - ziplocal_putValue_inmemory(zi->ci.central_header+32,(uLong)size_comment,2); - ziplocal_putValue_inmemory(zi->ci.central_header+34,(uLong)0,2); /*disk nm start*/ - - if (zipfi==NULL) - ziplocal_putValue_inmemory(zi->ci.central_header+36,(uLong)0,2); - else - ziplocal_putValue_inmemory(zi->ci.central_header+36,(uLong)zipfi->internal_fa,2); - - if (zipfi==NULL) - ziplocal_putValue_inmemory(zi->ci.central_header+38,(uLong)0,4); - else - ziplocal_putValue_inmemory(zi->ci.central_header+38,(uLong)zipfi->external_fa,4); - - ziplocal_putValue_inmemory(zi->ci.central_header+42,(uLong)zi->ci.pos_local_header- zi->add_position_when_writting_offset,4); - - for (i=0;ici.central_header+SIZECENTRALHEADER+i) = *(filename+i); - - for (i=0;ici.central_header+SIZECENTRALHEADER+size_filename+i) = - *(((const char*)extrafield_global)+i); - - for (i=0;ici.central_header+SIZECENTRALHEADER+size_filename+ - size_extrafield_global+i) = *(comment+i); - if (zi->ci.central_header == NULL) - return ZIP_INTERNALERROR; - - /* write the local header */ - err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)LOCALHEADERMAGIC,4); - - if (err==ZIP_OK) - err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)20,2);/* version needed to extract */ - if (err==ZIP_OK) - err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->ci.flag,2); - - if (err==ZIP_OK) - err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->ci.method,2); - - if (err==ZIP_OK) - err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->ci.dosDate,4); - - if (err==ZIP_OK) - err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); /* crc 32, unknown */ - if (err==ZIP_OK) - err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); /* compressed size, unknown */ - if (err==ZIP_OK) - err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); /* uncompressed size, unknown */ - - if (err==ZIP_OK) - err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_filename,2); - - if (err==ZIP_OK) - err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_extrafield_local,2); - - if ((err==ZIP_OK) && (size_filename>0)) - if (ZWRITE(zi->z_filefunc,zi->filestream,filename,size_filename)!=size_filename) - err = ZIP_ERRNO; - - if ((err==ZIP_OK) && (size_extrafield_local>0)) - if (ZWRITE(zi->z_filefunc,zi->filestream,extrafield_local,size_extrafield_local) - !=size_extrafield_local) - err = ZIP_ERRNO; - - zi->ci.stream.avail_in = (uInt)0; - zi->ci.stream.avail_out = (uInt)Z_BUFSIZE; - zi->ci.stream.next_out = zi->ci.buffered_data; - zi->ci.stream.total_in = 0; - zi->ci.stream.total_out = 0; - - if ((err==ZIP_OK) && (zi->ci.method == Z_DEFLATED) && (!zi->ci.raw)) - { - zi->ci.stream.zalloc = (alloc_func)0; - zi->ci.stream.zfree = (free_func)0; - zi->ci.stream.opaque = (voidpf)0; - - if (windowBits>0) - windowBits = -windowBits; - - err = deflateInit2(&zi->ci.stream, level, - Z_DEFLATED, windowBits, memLevel, strategy); - - if (err==Z_OK) - zi->ci.stream_initialised = 1; - } -# ifndef NOCRYPT - zi->ci.crypt_header_size = 0; - if ((err==Z_OK) && (password != NULL)) - { - unsigned char bufHead[RAND_HEAD_LEN]; - unsigned int sizeHead; - zi->ci.encrypt = 1; - zi->ci.pcrc_32_tab = get_crc_table(); - /*init_keys(password,zi->ci.keys,zi->ci.pcrc_32_tab);*/ - - sizeHead=crypthead(password,bufHead,RAND_HEAD_LEN,zi->ci.keys,zi->ci.pcrc_32_tab,crcForCrypting); - zi->ci.crypt_header_size = sizeHead; - - if (ZWRITE(zi->z_filefunc,zi->filestream,bufHead,sizeHead) != sizeHead) - err = ZIP_ERRNO; - } -# endif - - if (err==Z_OK) - zi->in_opened_file_inzip = 1; - return err; + zip_internal *zi; + uInt size_filename; + uInt size_comment; + uInt i; + int err = ZIP_OK; + +#ifdef NOCRYPT + if (password != NULL) + return (ZIP_PARAMERROR); +#endif + + if (file == NULL) + return (ZIP_PARAMERROR); + if ((method != 0) && (method != Z_DEFLATED)) + return (ZIP_PARAMERROR); + + zi = (zip_internal *)file; + + if (zi->in_opened_file_inzip == 1) { + err = zipCloseFileInZip(file); + if (err != ZIP_OK) + return (err); + } + + if (filename == NULL) + filename = "-"; + + if (comment == NULL) + size_comment = 0; + else + size_comment = (uInt)strlen(comment); + + size_filename = (uInt)strlen(filename); + + if (zipfi == NULL) + zi->ci.dosDate = 0; + else { + if (zipfi->dosDate != 0) + zi->ci.dosDate = zipfi->dosDate; + else zi->ci.dosDate = + ziplocal_TmzDateToDosDate(&zipfi->tmz_date, + zipfi->dosDate); + } + + zi->ci.flag = 0; + if ((level == 8) || (level == 9)) + zi->ci.flag |= 2; + if ((level == 2)) + zi->ci.flag |= 4; + if ((level == 1)) + zi->ci.flag |= 6; + if (password != NULL) + zi->ci.flag |= 1; + + zi->ci.crc32 = 0; + zi->ci.method = method; + zi->ci.encrypt = 0; + zi->ci.stream_initialised = 0; + zi->ci.pos_in_buffered_data = 0; + zi->ci.raw = raw; + zi->ci.pos_local_header = ZTELL(zi->z_filefunc, zi->filestream); + zi->ci.size_centralheader = SIZECENTRALHEADER + size_filename + + size_extrafield_global + size_comment; + zi->ci.central_header = (char *)ALLOC((uInt)zi->ci.size_centralheader); + + ziplocal_putValue_inmemory(zi->ci.central_header, + (uLong)CENTRALHEADERMAGIC, 4); + /* version info */ + ziplocal_putValue_inmemory(zi->ci.central_header+4, + (uLong)VERSIONMADEBY, 2); + ziplocal_putValue_inmemory(zi->ci.central_header+6, + (uLong)20, 2); + ziplocal_putValue_inmemory(zi->ci.central_header+8, + (uLong)zi->ci.flag, 2); + ziplocal_putValue_inmemory(zi->ci.central_header+10, + (uLong)zi->ci.method, 2); + ziplocal_putValue_inmemory(zi->ci.central_header+12, + (uLong)zi->ci.dosDate, 4); + ziplocal_putValue_inmemory(zi->ci.central_header+16, + (uLong)0, 4); /* crc */ + ziplocal_putValue_inmemory(zi->ci.central_header+20, + (uLong)0, 4); /* compr size */ + ziplocal_putValue_inmemory(zi->ci.central_header+24, + (uLong)0, 4); /* uncompr size */ + ziplocal_putValue_inmemory(zi->ci.central_header+28, + (uLong)size_filename, 2); + ziplocal_putValue_inmemory(zi->ci.central_header+30, + (uLong)size_extrafield_global, 2); + ziplocal_putValue_inmemory(zi->ci.central_header+32, + (uLong)size_comment, 2); + ziplocal_putValue_inmemory(zi->ci.central_header+34, + (uLong)0, 2); /* disk nm start */ + + if (zipfi == NULL) + ziplocal_putValue_inmemory(zi->ci.central_header+36, + (uLong)0, 2); + else + ziplocal_putValue_inmemory(zi->ci.central_header+36, + (uLong)zipfi->internal_fa, 2); + + if (zipfi == NULL) + ziplocal_putValue_inmemory(zi->ci.central_header+38, + (uLong)0, 4); + else + ziplocal_putValue_inmemory(zi->ci.central_header+38, + (uLong)zipfi->external_fa, 4); + + ziplocal_putValue_inmemory(zi->ci.central_header+42, + (uLong)zi->ci.pos_local_header- + zi->add_position_when_writting_offset, 4); + + for (i = 0; i < size_filename; i++) + *(zi->ci.central_header+SIZECENTRALHEADER+i) = *(filename+i); + + for (i = 0; i < size_extrafield_global; i++) + *(zi->ci.central_header+SIZECENTRALHEADER+size_filename+i) = + *(((const char *)extrafield_global)+i); + + for (i = 0; i < size_comment; i++) + *(zi->ci.central_header+SIZECENTRALHEADER+size_filename+ + size_extrafield_global+i) = *(comment+i); + if (zi->ci.central_header == NULL) + return (ZIP_INTERNALERROR); + + /* write the local header */ + err = ziplocal_putValue(&zi->z_filefunc, zi->filestream, + (uLong)LOCALHEADERMAGIC, 4); + + if (err == ZIP_OK) + err = ziplocal_putValue(&zi->z_filefunc, zi->filestream, + (uLong)20, 2); /* version needed to extract */ + if (err == ZIP_OK) + err = ziplocal_putValue(&zi->z_filefunc, zi->filestream, + (uLong)zi->ci.flag, 2); + + if (err == ZIP_OK) + err = ziplocal_putValue(&zi->z_filefunc, zi->filestream, + (uLong)zi->ci.method, 2); + + if (err == ZIP_OK) + err = ziplocal_putValue(&zi->z_filefunc, zi->filestream, + (uLong)zi->ci.dosDate, 4); + + if (err == ZIP_OK) + err = ziplocal_putValue(&zi->z_filefunc, zi->filestream, + (uLong)0, 4); /* crc 32, unknown */ + if (err == ZIP_OK) + err = ziplocal_putValue(&zi->z_filefunc, zi->filestream, + (uLong)0, 4); /* compressed size, unknown */ + if (err == ZIP_OK) + err = ziplocal_putValue(&zi->z_filefunc, zi->filestream, + (uLong)0, 4); /* uncompressed size, unknown */ + + if (err == ZIP_OK) + err = ziplocal_putValue(&zi->z_filefunc, zi->filestream, + (uLong)size_filename, 2); + + if (err == ZIP_OK) + err = ziplocal_putValue(&zi->z_filefunc, zi->filestream, + (uLong)size_extrafield_local, 2); + + if ((err == ZIP_OK) && (size_filename > 0)) + if (ZWRITE(zi->z_filefunc, zi->filestream, filename, + size_filename) != size_filename) + err = ZIP_ERRNO; + + if ((err == ZIP_OK) && (size_extrafield_local > 0)) + if (ZWRITE(zi->z_filefunc, zi->filestream, extrafield_local, + size_extrafield_local) != size_extrafield_local) + err = ZIP_ERRNO; + + zi->ci.stream.avail_in = (uInt)0; + zi->ci.stream.avail_out = (uInt)Z_BUFSIZE; + zi->ci.stream.next_out = zi->ci.buffered_data; + zi->ci.stream.total_in = 0; + zi->ci.stream.total_out = 0; + + if ((err == ZIP_OK) && (zi->ci.method == Z_DEFLATED) && + (!zi->ci.raw)) { + zi->ci.stream.zalloc = (alloc_func)0; + zi->ci.stream.zfree = (free_func)0; + zi->ci.stream.opaque = (voidpf)0; + + if (windowBits > 0) + windowBits = -windowBits; + + err = deflateInit2(&zi->ci.stream, level, + Z_DEFLATED, windowBits, memLevel, strategy); + + if (err == Z_OK) + zi->ci.stream_initialised = 1; + } +#ifndef NOCRYPT + zi->ci.crypt_header_size = 0; + if ((err == Z_OK) && (password != NULL)) { + unsigned char bufHead[RAND_HEAD_LEN]; + unsigned int sizeHead; + zi->ci.encrypt = 1; + zi->ci.pcrc_32_tab = get_crc_table(); + /* init_keys(password,zi->ci.keys,zi->ci.pcrc_32_tab); */ + + sizeHead = crypthead(password, bufHead, RAND_HEAD_LEN, + zi->ci.keys, zi->ci.pcrc_32_tab, crcForCrypting); + zi->ci.crypt_header_size = sizeHead; + + if (ZWRITE(zi->z_filefunc, zi->filestream, bufHead, + sizeHead) != sizeHead) + err = ZIP_ERRNO; + } +#endif + + if (err == Z_OK) + zi->in_opened_file_inzip = 1; + return (err); } -extern int ZEXPORT zipOpenNewFileInZip2(file, filename, zipfi, - extrafield_local, size_extrafield_local, - extrafield_global, size_extrafield_global, - comment, method, level, raw) - zipFile file; - const char* filename; - const zip_fileinfo* zipfi; - const void* extrafield_local; - uInt size_extrafield_local; - const void* extrafield_global; - uInt size_extrafield_global; - const char* comment; - int method; - int level; - int raw; +extern int ZEXPORT +zipOpenNewFileInZip2( + zipFile file, + const char *filename, + const zip_fileinfo *zipfi, + const void *extrafield_local, + uInt size_extrafield_local, + const void *extrafield_global, + uInt size_extrafield_global, + const char *comment, + int method, + int level, + int raw) { - return zipOpenNewFileInZip3 (file, filename, zipfi, - extrafield_local, size_extrafield_local, - extrafield_global, size_extrafield_global, - comment, method, level, raw, - -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, - NULL, 0); + return zipOpenNewFileInZip3(file, filename, zipfi, + extrafield_local, size_extrafield_local, + extrafield_global, size_extrafield_global, + comment, method, level, raw, + -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, + NULL, 0); } -extern int ZEXPORT zipOpenNewFileInZip (file, filename, zipfi, - extrafield_local, size_extrafield_local, - extrafield_global, size_extrafield_global, - comment, method, level) - zipFile file; - const char* filename; - const zip_fileinfo* zipfi; - const void* extrafield_local; - uInt size_extrafield_local; - const void* extrafield_global; - uInt size_extrafield_global; - const char* comment; - int method; - int level; +extern int ZEXPORT +zipOpenNewFileInZip( + zipFile file, + const char *filename, + const zip_fileinfo *zipfi, + const void *extrafield_local, + uInt size_extrafield_local, + const void *extrafield_global, + uInt size_extrafield_global, + const char *comment, + int method, + int level) { - return zipOpenNewFileInZip2 (file, filename, zipfi, - extrafield_local, size_extrafield_local, - extrafield_global, size_extrafield_global, - comment, method, level, 0); + return zipOpenNewFileInZip2(file, filename, zipfi, + extrafield_local, size_extrafield_local, + extrafield_global, size_extrafield_global, + comment, method, level, 0); } -local int zipFlushWriteBuffer(zi) - zip_internal* zi; +local int +zipFlushWriteBuffer(zip_internal *zi) { - int err=ZIP_OK; + int err = ZIP_OK; - if (zi->ci.encrypt != 0) - { + if (zi->ci.encrypt != 0) { #ifndef NOCRYPT - uInt i; - int t; - for (i=0;ici.pos_in_buffered_data;i++) - zi->ci.buffered_data[i] = zencode(zi->ci.keys, zi->ci.pcrc_32_tab, - zi->ci.buffered_data[i],t); + uInt i; + int t; + for (i = 0; i < zi->ci.pos_in_buffered_data; i++) + zi->ci.buffered_data[i] = + zencode(zi->ci.keys, zi->ci.pcrc_32_tab, + zi->ci.buffered_data[i], t); #endif - } - if (ZWRITE(zi->z_filefunc,zi->filestream,zi->ci.buffered_data,zi->ci.pos_in_buffered_data) - !=zi->ci.pos_in_buffered_data) - err = ZIP_ERRNO; - zi->ci.pos_in_buffered_data = 0; - return err; + } + if (ZWRITE(zi->z_filefunc, zi->filestream, + zi->ci.buffered_data, zi->ci.pos_in_buffered_data) != + zi->ci.pos_in_buffered_data) + err = ZIP_ERRNO; + zi->ci.pos_in_buffered_data = 0; + return (err); } -extern int ZEXPORT zipWriteInFileInZip (file, buf, len) - zipFile file; - const void* buf; - unsigned len; +extern int ZEXPORT +zipWriteInFileInZip( + zipFile file, + const void *buf, + unsigned len) { - zip_internal* zi; - int err=ZIP_OK; - - if (file == NULL) - return ZIP_PARAMERROR; - zi = (zip_internal*)file; - - if (zi->in_opened_file_inzip == 0) - return ZIP_PARAMERROR; - - zi->ci.stream.next_in = (void*)buf; - zi->ci.stream.avail_in = len; - zi->ci.crc32 = crc32(zi->ci.crc32,buf,len); - - while ((err==ZIP_OK) && (zi->ci.stream.avail_in>0)) - { - if (zi->ci.stream.avail_out == 0) - { - if (zipFlushWriteBuffer(zi) == ZIP_ERRNO) - err = ZIP_ERRNO; - zi->ci.stream.avail_out = (uInt)Z_BUFSIZE; - zi->ci.stream.next_out = zi->ci.buffered_data; - } - - - if(err != ZIP_OK) - break; - - if ((zi->ci.method == Z_DEFLATED) && (!zi->ci.raw)) - { - uLong uTotalOutBefore = zi->ci.stream.total_out; - err=deflate(&zi->ci.stream, Z_NO_FLUSH); - zi->ci.pos_in_buffered_data += (uInt)(zi->ci.stream.total_out - uTotalOutBefore) ; - - } - else - { - uInt copy_this,i; - if (zi->ci.stream.avail_in < zi->ci.stream.avail_out) - copy_this = zi->ci.stream.avail_in; - else - copy_this = zi->ci.stream.avail_out; - for (i=0;ici.stream.next_out)+i) = - *(((const char*)zi->ci.stream.next_in)+i); - { - zi->ci.stream.avail_in -= copy_this; - zi->ci.stream.avail_out-= copy_this; - zi->ci.stream.next_in+= copy_this; - zi->ci.stream.next_out+= copy_this; - zi->ci.stream.total_in+= copy_this; - zi->ci.stream.total_out+= copy_this; - zi->ci.pos_in_buffered_data += copy_this; - } - } - } - - return err; + zip_internal *zi; + int err = ZIP_OK; + + if (file == NULL) + return (ZIP_PARAMERROR); + zi = (zip_internal *)file; + + if (zi->in_opened_file_inzip == 0) + return (ZIP_PARAMERROR); + + zi->ci.stream.next_in = (void *)buf; + zi->ci.stream.avail_in = len; + zi->ci.crc32 = crc32(zi->ci.crc32, buf, len); + + while ((err == ZIP_OK) && (zi->ci.stream.avail_in > 0)) { + if (zi->ci.stream.avail_out == 0) { + if (zipFlushWriteBuffer(zi) == ZIP_ERRNO) + err = ZIP_ERRNO; + zi->ci.stream.avail_out = (uInt)Z_BUFSIZE; + zi->ci.stream.next_out = zi->ci.buffered_data; + } + + + if (err != ZIP_OK) + break; + + if ((zi->ci.method == Z_DEFLATED) && (!zi->ci.raw)) { + uLong uTotalOutBefore = zi->ci.stream.total_out; + err = deflate(&zi->ci.stream, Z_NO_FLUSH); + zi->ci.pos_in_buffered_data += + (uInt)(zi->ci.stream.total_out - uTotalOutBefore); + + } else { + uInt copy_this, i; + if (zi->ci.stream.avail_in < zi->ci.stream.avail_out) + copy_this = zi->ci.stream.avail_in; + else + copy_this = zi->ci.stream.avail_out; + for (i = 0; i < copy_this; i++) + *(((char *)zi->ci.stream.next_out)+i) = + *(((const char *)zi->ci.stream.next_in)+i); + { + zi->ci.stream.avail_in -= copy_this; + zi->ci.stream.avail_out -= copy_this; + zi->ci.stream.next_in += copy_this; + zi->ci.stream.next_out += copy_this; + zi->ci.stream.total_in += copy_this; + zi->ci.stream.total_out += copy_this; + zi->ci.pos_in_buffered_data += copy_this; + } + } + } + + return (err); } -extern int ZEXPORT zipCloseFileInZipRaw (file, uncompressed_size, crc32) - zipFile file; - uLong uncompressed_size; - uLong crc32; +extern int ZEXPORT +zipCloseFileInZipRaw( + zipFile file, + uLong uncompressed_size, + uLong crc32) { - zip_internal* zi; - uLong compressed_size; - int err=ZIP_OK; - - if (file == NULL) - return ZIP_PARAMERROR; - zi = (zip_internal*)file; - - if (zi->in_opened_file_inzip == 0) - return ZIP_PARAMERROR; - zi->ci.stream.avail_in = 0; - - if ((zi->ci.method == Z_DEFLATED) && (!zi->ci.raw)) - while (err==ZIP_OK) - { - uLong uTotalOutBefore; - if (zi->ci.stream.avail_out == 0) - { - if (zipFlushWriteBuffer(zi) == ZIP_ERRNO) - err = ZIP_ERRNO; - zi->ci.stream.avail_out = (uInt)Z_BUFSIZE; - zi->ci.stream.next_out = zi->ci.buffered_data; - } - uTotalOutBefore = zi->ci.stream.total_out; - err=deflate(&zi->ci.stream, Z_FINISH); - zi->ci.pos_in_buffered_data += (uInt)(zi->ci.stream.total_out - uTotalOutBefore) ; - } - - if (err==Z_STREAM_END) - err=ZIP_OK; /* this is normal */ - - if ((zi->ci.pos_in_buffered_data>0) && (err==ZIP_OK)) - if (zipFlushWriteBuffer(zi)==ZIP_ERRNO) - err = ZIP_ERRNO; - - if ((zi->ci.method == Z_DEFLATED) && (!zi->ci.raw)) - { - err=deflateEnd(&zi->ci.stream); - zi->ci.stream_initialised = 0; - } - - if (!zi->ci.raw) - { - crc32 = (uLong)zi->ci.crc32; - uncompressed_size = (uLong)zi->ci.stream.total_in; - } - compressed_size = (uLong)zi->ci.stream.total_out; -# ifndef NOCRYPT - compressed_size += zi->ci.crypt_header_size; -# endif - - ziplocal_putValue_inmemory(zi->ci.central_header+16,crc32,4); /*crc*/ - ziplocal_putValue_inmemory(zi->ci.central_header+20, - compressed_size,4); /*compr size*/ - if (zi->ci.stream.data_type == Z_ASCII) - ziplocal_putValue_inmemory(zi->ci.central_header+36,(uLong)Z_ASCII,2); - ziplocal_putValue_inmemory(zi->ci.central_header+24, - uncompressed_size,4); /*uncompr size*/ - - if (err==ZIP_OK) - err = add_data_in_datablock(&zi->central_dir,zi->ci.central_header, - (uLong)zi->ci.size_centralheader); - free(zi->ci.central_header); - - if (err==ZIP_OK) - { - long cur_pos_inzip = ZTELL(zi->z_filefunc,zi->filestream); - if (ZSEEK(zi->z_filefunc,zi->filestream, - zi->ci.pos_local_header + 14,ZLIB_FILEFUNC_SEEK_SET)!=0) - err = ZIP_ERRNO; - - if (err==ZIP_OK) - err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,crc32,4); /* crc 32, unknown */ - - if (err==ZIP_OK) /* compressed size, unknown */ - err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,compressed_size,4); - - if (err==ZIP_OK) /* uncompressed size, unknown */ - err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,uncompressed_size,4); - - if (ZSEEK(zi->z_filefunc,zi->filestream, - cur_pos_inzip,ZLIB_FILEFUNC_SEEK_SET)!=0) - err = ZIP_ERRNO; - } - - zi->number_entry ++; - zi->in_opened_file_inzip = 0; - - return err; + zip_internal *zi; + uLong compressed_size; + int err = ZIP_OK; + + if (file == NULL) + return (ZIP_PARAMERROR); + zi = (zip_internal *)file; + + if (zi->in_opened_file_inzip == 0) + return (ZIP_PARAMERROR); + zi->ci.stream.avail_in = 0; + + if ((zi->ci.method == Z_DEFLATED) && (!zi->ci.raw)) + while (err == ZIP_OK) { + uLong uTotalOutBefore; + if (zi->ci.stream.avail_out == 0) { + if (zipFlushWriteBuffer(zi) == ZIP_ERRNO) + err = ZIP_ERRNO; + zi->ci.stream.avail_out = (uInt)Z_BUFSIZE; + zi->ci.stream.next_out = zi->ci.buffered_data; + } + uTotalOutBefore = zi->ci.stream.total_out; + err = deflate(&zi->ci.stream, Z_FINISH); + zi->ci.pos_in_buffered_data += + (uInt)(zi->ci.stream.total_out - uTotalOutBefore); + } + + if (err == Z_STREAM_END) + err = ZIP_OK; /* this is normal */ + + if ((zi->ci.pos_in_buffered_data > 0) && (err == ZIP_OK)) + if (zipFlushWriteBuffer(zi) == ZIP_ERRNO) + err = ZIP_ERRNO; + + if ((zi->ci.method == Z_DEFLATED) && (!zi->ci.raw)) { + err = deflateEnd(&zi->ci.stream); + zi->ci.stream_initialised = 0; + } + + if (!zi->ci.raw) { + crc32 = (uLong)zi->ci.crc32; + uncompressed_size = (uLong)zi->ci.stream.total_in; + } + compressed_size = (uLong)zi->ci.stream.total_out; +#ifndef NOCRYPT + compressed_size += zi->ci.crypt_header_size; +#endif + + ziplocal_putValue_inmemory(zi->ci.central_header+16, crc32, 4); + ziplocal_putValue_inmemory(zi->ci.central_header+20, + compressed_size, 4); /* compr size */ + if (zi->ci.stream.data_type == Z_ASCII) + ziplocal_putValue_inmemory(zi->ci.central_header+36, + (uLong)Z_ASCII, 2); + ziplocal_putValue_inmemory(zi->ci.central_header+24, + uncompressed_size, 4); /* uncompr size */ + + if (err == ZIP_OK) + err = add_data_in_datablock(&zi->central_dir, + zi->ci.central_header, (uLong)zi->ci.size_centralheader); + free(zi->ci.central_header); + + if (err == ZIP_OK) { + long cur_pos_inzip = ZTELL(zi->z_filefunc, zi->filestream); + if (ZSEEK(zi->z_filefunc, zi->filestream, + zi->ci.pos_local_header + 14, ZLIB_FILEFUNC_SEEK_SET) != 0) + err = ZIP_ERRNO; + + if (err == ZIP_OK) + err = ziplocal_putValue(&zi->z_filefunc, zi->filestream, + crc32, 4); /* crc 32, unknown */ + + if (err == ZIP_OK) /* compressed size, unknown */ + err = ziplocal_putValue(&zi->z_filefunc, zi->filestream, + compressed_size, 4); + + if (err == ZIP_OK) /* uncompressed size, unknown */ + err = ziplocal_putValue(&zi->z_filefunc, + zi->filestream, uncompressed_size, 4); + + if (ZSEEK(zi->z_filefunc, zi->filestream, + cur_pos_inzip, ZLIB_FILEFUNC_SEEK_SET) != 0) + err = ZIP_ERRNO; + } + + zi->number_entry ++; + zi->in_opened_file_inzip = 0; + + return (err); } -extern int ZEXPORT zipCloseFileInZip (file) - zipFile file; +extern int ZEXPORT +zipCloseFileInZip( + zipFile file) { - return zipCloseFileInZipRaw (file,0,0); + return (zipCloseFileInZipRaw(file, 0, 0)); } -extern int ZEXPORT zipClose (file, global_comment) - zipFile file; - const char* global_comment; +extern int ZEXPORT +zipClose( + zipFile file, + const char *global_comment) { - zip_internal* zi; - int err = 0; - uLong size_centraldir = 0; - uLong centraldir_pos_inzip; - uInt size_global_comment; - if (file == NULL) - return ZIP_PARAMERROR; - zi = (zip_internal*)file; - - if (zi->in_opened_file_inzip == 1) - { - err = zipCloseFileInZip (file); - } + zip_internal *zi; + int err = 0; + uLong size_centraldir = 0; + uLong centraldir_pos_inzip; + uInt size_global_comment; + if (file == NULL) + return (ZIP_PARAMERROR); + zi = (zip_internal *)file; + + if (zi->in_opened_file_inzip == 1) { + err = zipCloseFileInZip(file); + } #ifndef NO_ADDFILEINEXISTINGZIP - if (global_comment==NULL) - global_comment = zi->globalcomment; + if (global_comment == NULL) + global_comment = zi->globalcomment; #endif - if (global_comment==NULL) - size_global_comment = 0; - else - size_global_comment = (uInt)strlen(global_comment); - - centraldir_pos_inzip = ZTELL(zi->z_filefunc,zi->filestream); - if (err==ZIP_OK) - { - linkedlist_datablock_internal* ldi = zi->central_dir.first_block ; - while (ldi!=NULL) - { - if ((err==ZIP_OK) && (ldi->filled_in_this_block>0)) - if (ZWRITE(zi->z_filefunc,zi->filestream, - ldi->data,ldi->filled_in_this_block) - !=ldi->filled_in_this_block ) - err = ZIP_ERRNO; - - size_centraldir += ldi->filled_in_this_block; - ldi = ldi->next_datablock; - } - } - free_datablock(zi->central_dir.first_block); - - if (err==ZIP_OK) /* Magic End */ - err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)ENDHEADERMAGIC,4); - - if (err==ZIP_OK) /* number of this disk */ - err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,2); - - if (err==ZIP_OK) /* number of the disk with the start of the central directory */ - err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,2); - - if (err==ZIP_OK) /* total number of entries in the central dir on this disk */ - err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->number_entry,2); - - if (err==ZIP_OK) /* total number of entries in the central dir */ - err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->number_entry,2); - - if (err==ZIP_OK) /* size of the central directory */ - err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_centraldir,4); - - if (err==ZIP_OK) /* offset of start of central directory with respect to the - starting disk number */ - err = ziplocal_putValue(&zi->z_filefunc,zi->filestream, - (uLong)(centraldir_pos_inzip - zi->add_position_when_writting_offset),4); - - if (err==ZIP_OK) /* zipfile comment length */ - err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_global_comment,2); - - if ((err==ZIP_OK) && (size_global_comment>0)) - if (ZWRITE(zi->z_filefunc,zi->filestream, - global_comment,size_global_comment) != size_global_comment) - err = ZIP_ERRNO; - - if (ZCLOSE(zi->z_filefunc,zi->filestream) != 0) - if (err == ZIP_OK) - err = ZIP_ERRNO; + if (global_comment == NULL) + size_global_comment = 0; + else + size_global_comment = (uInt)strlen(global_comment); + + centraldir_pos_inzip = ZTELL(zi->z_filefunc, zi->filestream); + if (err == ZIP_OK) { + linkedlist_datablock_internal *ldi = + zi->central_dir.first_block; + while (ldi != NULL) { + if ((err == ZIP_OK) && (ldi->filled_in_this_block > 0)) + if (ZWRITE(zi->z_filefunc, zi->filestream, + ldi->data, ldi->filled_in_this_block) != + ldi->filled_in_this_block) + err = ZIP_ERRNO; + + size_centraldir += ldi->filled_in_this_block; + ldi = ldi->next_datablock; + } + } + free_datablock(zi->central_dir.first_block); + + if (err == ZIP_OK) /* Magic End */ + err = ziplocal_putValue(&zi->z_filefunc, zi->filestream, + (uLong)ENDHEADERMAGIC, 4); + + if (err == ZIP_OK) /* number of this disk */ + err = ziplocal_putValue(&zi->z_filefunc, zi->filestream, + (uLong)0, 2); + + /* number of the disk with the start of the central directory */ + if (err == ZIP_OK) + err = ziplocal_putValue(&zi->z_filefunc, zi->filestream, + (uLong)0, 2); + + /* total number of entries in the central dir on this disk */ + if (err == ZIP_OK) + err = ziplocal_putValue(&zi->z_filefunc, zi->filestream, + (uLong)zi->number_entry, 2); + + if (err == ZIP_OK) /* total number of entries in the central dir */ + err = ziplocal_putValue(&zi->z_filefunc, zi->filestream, + (uLong)zi->number_entry, 2); + + if (err == ZIP_OK) /* size of the central directory */ + err = ziplocal_putValue(&zi->z_filefunc, zi->filestream, + (uLong)size_centraldir, 4); + +/* + * offset of start of central directory with respect to the + * starting disk number + */ + if (err == ZIP_OK) + err = ziplocal_putValue(&zi->z_filefunc, zi->filestream, + (uLong)(centraldir_pos_inzip - + zi->add_position_when_writting_offset), 4); + + if (err == ZIP_OK) /* zipfile comment length */ + err = ziplocal_putValue(&zi->z_filefunc, zi->filestream, + (uLong)size_global_comment, 2); + + if ((err == ZIP_OK) && (size_global_comment > 0)) + if (ZWRITE(zi->z_filefunc, zi->filestream, + global_comment, size_global_comment) != size_global_comment) + err = ZIP_ERRNO; + + if (ZCLOSE(zi->z_filefunc, zi->filestream) != 0) + if (err == ZIP_OK) + err = ZIP_ERRNO; #ifndef NO_ADDFILEINEXISTINGZIP - TRYFREE(zi->globalcomment); + TRYFREE(zi->globalcomment); #endif - TRYFREE(zi); + TRYFREE(zi); - return err; + return (err); } diff --git a/lib/os/windows/zlib-1.2.3/contrib/minizip/zip.h b/lib/os/windows/zlib-1.2.3/contrib/minizip/zip.h index acacce83b9b..5dd41320068 100644 --- a/lib/os/windows/zlib-1.2.3/contrib/minizip/zip.h +++ b/lib/os/windows/zlib-1.2.3/contrib/minizip/zip.h @@ -1,50 +1,51 @@ -/* zip.h -- IO for compress .zip files using zlib - Version 1.01e, February 12th, 2005 - - Copyright (C) 1998-2005 Gilles Vollant - - This unzip package allow creates .ZIP file, compatible with PKZip 2.04g - WinZip, InfoZip tools and compatible. - Multi volume ZipFile (span) are not supported. - Encryption compatible with pkzip 2.04g only supported - Old compressions used by old PKZip 1.x are not supported - - For uncompress .zip file, look at unzip.h - - - I WAIT FEEDBACK at mail info@winimage.com - Visit also http://www.winimage.com/zLibDll/unzip.html for evolution - - Condition of use and distribution are the same than zlib : - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - -*/ +/* + * zip.h -- IO for compress .zip files using zlib + * Version 1.01e, February 12th, 2005 + * + * Copyright (C) 1998-2005 Gilles Vollant + * + * This unzip package allow creates .ZIP file, compatible with PKZip 2.04g + * WinZip, InfoZip tools and compatible. + * Multi volume ZipFile (span) are not supported. + * Encryption compatible with pkzip 2.04g only supported + * Old compressions used by old PKZip 1.x are not supported + * + * For uncompress .zip file, look at unzip.h + * + * + * I WAIT FEEDBACK at mail info@winimage.com + * Visit also http://www.winimage.com/zLibDll/unzip.html for evolution + * + * Condition of use and distribution are the same than zlib : + * + * This software is provided 'as-is', without any express or implied + * warranty. In no event will the authors be held liable for any damages + * arising from the use of this software. + * + * Permission is granted to anyone to use this software for any purpose, + * including commercial applications, and to alter it and redistribute it + * freely, subject to the following restrictions: + * + * 1. The origin of this software must not be misrepresented; you must not + * claim that you wrote the original software. If you use this software + * in a product, an acknowledgment in the product documentation would be + * appreciated but is not required. + * 2. Altered source versions must be plainly marked as such, and must not be + * misrepresented as being the original software. + * 3. This notice may not be removed or altered from any source distribution. + * + */ -/* for more info about .ZIP format, see - http://www.info-zip.org/pub/infozip/doc/appnote-981119-iz.zip - http://www.info-zip.org/pub/infozip/doc/ - PkWare has also a specification at : - ftp://ftp.pkware.com/probdesc.zip -*/ +/* + * for more info about .ZIP format, see + * http:/ /www.info-zip.org/pub/infozip/doc/appnote-981119-iz.zip + * http:/ /www.info-zip.org/pub/infozip/doc/ + * PkWare has also a specification at : + * ftp:/ /ftp.pkware.com/probdesc.zip + */ #ifndef _zip_H -#define _zip_H +#define _zip_H #ifdef __cplusplus extern "C" { @@ -59,174 +60,175 @@ extern "C" { #endif #if defined(STRICTZIP) || defined(STRICTZIPUNZIP) -/* like the STRICT of WIN32, we define a pointer that cannot be converted - from (void*) without cast */ +/* + * like the STRICT of WIN32, we define a pointer that cannot be converted + * from (void*) without cast + */ typedef struct TagzipFile__ { int unused; } zipFile__; typedef zipFile__ *zipFile; #else typedef voidp zipFile; #endif -#define ZIP_OK (0) -#define ZIP_EOF (0) -#define ZIP_ERRNO (Z_ERRNO) -#define ZIP_PARAMERROR (-102) -#define ZIP_BADZIPFILE (-103) -#define ZIP_INTERNALERROR (-104) +#define ZIP_OK (0) +#define ZIP_EOF (0) +#define ZIP_ERRNO (Z_ERRNO) +#define ZIP_PARAMERROR (-102) +#define ZIP_BADZIPFILE (-103) +#define ZIP_INTERNALERROR (-104) #ifndef DEF_MEM_LEVEL -# if MAX_MEM_LEVEL >= 8 -# define DEF_MEM_LEVEL 8 -# else -# define DEF_MEM_LEVEL MAX_MEM_LEVEL -# endif +#if MAX_MEM_LEVEL >= 8 +#define DEF_MEM_LEVEL 8 +#else +#define DEF_MEM_LEVEL MAX_MEM_LEVEL +#endif #endif /* default memLevel */ /* tm_zip contain date/time info */ typedef struct tm_zip_s { - uInt tm_sec; /* seconds after the minute - [0,59] */ - uInt tm_min; /* minutes after the hour - [0,59] */ - uInt tm_hour; /* hours since midnight - [0,23] */ - uInt tm_mday; /* day of the month - [1,31] */ - uInt tm_mon; /* months since January - [0,11] */ - uInt tm_year; /* years - [1980..2044] */ + uInt tm_sec; /* seconds after the minute - [0,59] */ + uInt tm_min; /* minutes after the hour - [0,59] */ + uInt tm_hour; /* hours since midnight - [0,23] */ + uInt tm_mday; /* day of the month - [1,31] */ + uInt tm_mon; /* months since January - [0,11] */ + uInt tm_year; /* years - [1980..2044] */ } tm_zip; typedef struct { - tm_zip tmz_date; /* date in understandable format */ - uLong dosDate; /* if dos_date == 0, tmu_date is used */ -/* uLong flag; */ /* general purpose bit flag 2 bytes */ - - uLong internal_fa; /* internal file attributes 2 bytes */ - uLong external_fa; /* external file attributes 4 bytes */ + tm_zip tmz_date; /* date in understandable format */ + uLong dosDate; /* if dos_date == 0, tmu_date is used */ + uLong internal_fa; /* internal file attributes 2 bytes */ + uLong external_fa; /* external file attributes 4 bytes */ } zip_fileinfo; -typedef const char* zipcharpc; - +typedef const char *zipcharpc; -#define APPEND_STATUS_CREATE (0) -#define APPEND_STATUS_CREATEAFTER (1) -#define APPEND_STATUS_ADDINZIP (2) +#define APPEND_STATUS_CREATE (0) +#define APPEND_STATUS_CREATEAFTER (1) +#define APPEND_STATUS_ADDINZIP (2) extern zipFile ZEXPORT zipOpen OF((const char *pathname, int append)); /* - Create a zipfile. - pathname contain on Windows XP a filename like "c:\\zlib\\zlib113.zip" or on - an Unix computer "zlib/zlib113.zip". - if the file pathname exist and append==APPEND_STATUS_CREATEAFTER, the zip - will be created at the end of the file. - (useful if the file contain a self extractor code) - if the file pathname exist and append==APPEND_STATUS_ADDINZIP, we will - add files in existing zip (be sure you don't add file that doesn't exist) - If the zipfile cannot be opened, the return value is NULL. - Else, the return value is a zipFile Handle, usable with other function - of this zip package. -*/ - -/* Note : there is no delete function into a zipfile. - If you want delete file into a zipfile, you must open a zipfile, and create another - Of couse, you can use RAW reading and writing to copy the file you did not want delte -*/ + * Create a zipfile. + * pathname contain on Windows XP a filename like "c:\\zlib\\zlib113.zip" or on + * an Unix computer "zlib/zlib113.zip". + * if the file pathname exist and append==APPEND_STATUS_CREATEAFTER, the zip + * will be created at the end of the file. + * (useful if the file contain a self extractor code) + * if the file pathname exist and append==APPEND_STATUS_ADDINZIP, we will + * add files in existing zip (be sure you don't add file that doesn't exist) + * If the zipfile cannot be opened, the return value is NULL. + * Else, the return value is a zipFile Handle, usable with other function + * of this zip package. + */ + +/* + * Note : there is no delete function into a zipfile. + * If you want delete file into a zipfile, you must open a zipfile, + * and create another. Of couse, you can use RAW reading and writing + * to copy the file you did not want delte + */ extern zipFile ZEXPORT zipOpen2 OF((const char *pathname, - int append, - zipcharpc* globalcomment, - zlib_filefunc_def* pzlib_filefunc_def)); + int append, + zipcharpc *globalcomment, + zlib_filefunc_def *pzlib_filefunc_def)); extern int ZEXPORT zipOpenNewFileInZip OF((zipFile file, - const char* filename, - const zip_fileinfo* zipfi, - const void* extrafield_local, - uInt size_extrafield_local, - const void* extrafield_global, - uInt size_extrafield_global, - const char* comment, - int method, - int level)); + const char *filename, + const zip_fileinfo *zipfi, + const void *extrafield_local, + uInt size_extrafield_local, + const void *extrafield_global, + uInt size_extrafield_global, + const char *comment, + int method, + int level)); /* - Open a file in the ZIP for writing. - filename : the filename in zip (if NULL, '-' without quote will be used - *zipfi contain supplemental information - if extrafield_local!=NULL and size_extrafield_local>0, extrafield_local - contains the extrafield data the the local header - if extrafield_global!=NULL and size_extrafield_global>0, extrafield_global - contains the extrafield data the the local header - if comment != NULL, comment contain the comment string - method contain the compression method (0 for store, Z_DEFLATED for deflate) - level contain the level of compression (can be Z_DEFAULT_COMPRESSION) -*/ + * Open a file in the ZIP for writing. + * filename : the filename in zip (if NULL, '-' without quote will be used + * *zipfi contain supplemental information + * if extrafield_local!=NULL and size_extrafield_local>0, extrafield_local + * contains the extrafield data the the local header + * if extrafield_global!=NULL and size_extrafield_global>0, extrafield_global + * contains the extrafield data the the local header + * if comment != NULL, comment contain the comment string + * method contain the compression method (0 for store, Z_DEFLATED for deflate) + * level contain the level of compression (can be Z_DEFAULT_COMPRESSION) + */ extern int ZEXPORT zipOpenNewFileInZip2 OF((zipFile file, - const char* filename, - const zip_fileinfo* zipfi, - const void* extrafield_local, - uInt size_extrafield_local, - const void* extrafield_global, - uInt size_extrafield_global, - const char* comment, - int method, - int level, - int raw)); + const char *filename, + const zip_fileinfo *zipfi, + const void *extrafield_local, + uInt size_extrafield_local, + const void *extrafield_global, + uInt size_extrafield_global, + const char *comment, + int method, + int level, + int raw)); /* - Same than zipOpenNewFileInZip, except if raw=1, we write raw file + * Same than zipOpenNewFileInZip, except if raw=1, we write raw file */ extern int ZEXPORT zipOpenNewFileInZip3 OF((zipFile file, - const char* filename, - const zip_fileinfo* zipfi, - const void* extrafield_local, - uInt size_extrafield_local, - const void* extrafield_global, - uInt size_extrafield_global, - const char* comment, - int method, - int level, - int raw, - int windowBits, - int memLevel, - int strategy, - const char* password, - uLong crcForCtypting)); + const char *filename, + const zip_fileinfo *zipfi, + const void *extrafield_local, + uInt size_extrafield_local, + const void *extrafield_global, + uInt size_extrafield_global, + const char *comment, + int method, + int level, + int raw, + int windowBits, + int memLevel, + int strategy, + const char *password, + uLong crcForCtypting)); /* - Same than zipOpenNewFileInZip2, except - windowBits,memLevel,,strategy : see parameter strategy in deflateInit2 - password : crypting password (NULL for no crypting) - crcForCtypting : crc of file to compress (needed for crypting) + * Same than zipOpenNewFileInZip2, except + * windowBits,memLevel,,strategy : see parameter strategy in deflateInit2 + * password : crypting password (NULL for no crypting) + * crcForCtypting : crc of file to compress (needed for crypting) */ extern int ZEXPORT zipWriteInFileInZip OF((zipFile file, - const void* buf, - unsigned len)); + const void* buf, + unsigned len)); /* - Write data in the zipfile -*/ + * Write data in the zipfile + */ extern int ZEXPORT zipCloseFileInZip OF((zipFile file)); /* - Close the current file in the zipfile -*/ + * Close the current file in the zipfile + */ extern int ZEXPORT zipCloseFileInZipRaw OF((zipFile file, - uLong uncompressed_size, - uLong crc32)); + uLong uncompressed_size, + uLong crc32)); /* - Close the current file in the zipfile, for fiel opened with - parameter raw=1 in zipOpenNewFileInZip2 - uncompressed_size and crc32 are value for the uncompressed size -*/ + * Close the current file in the zipfile, for fiel opened with + * parameter raw=1 in zipOpenNewFileInZip2 + * uncompressed_size and crc32 are value for the uncompressed size + */ extern int ZEXPORT zipClose OF((zipFile file, - const char* global_comment)); + const char *global_comment)); /* - Close the zipfile -*/ + * Close the zipfile + */ #ifdef __cplusplus } diff --git a/lib/os/windows/zlib-1.2.3/crc32.c b/lib/os/windows/zlib-1.2.3/crc32.c index f658a9ef55e..a539f638f91 100644 --- a/lib/os/windows/zlib-1.2.3/crc32.c +++ b/lib/os/windows/zlib-1.2.3/crc32.c @@ -1,4 +1,5 @@ -/* crc32.c -- compute the CRC-32 of a data stream +/* + * crc32.c -- compute the CRC-32 of a data stream * Copyright (C) 1995-2005 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h * @@ -12,61 +13,61 @@ /* @(#) $Id$ */ /* - Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore - protection on the static variables used to control the first-use generation - of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should - first call get_crc_table() to initialize the tables before allowing more than - one thread to use crc32(). + * Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore + * protection on the static variables used to control the first-use generation + * of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should + * first call get_crc_table() to initialize the tables before allowing + * more than one thread to use crc32(). */ #ifdef MAKECRCH -# include -# ifndef DYNAMIC_CRC_TABLE -# define DYNAMIC_CRC_TABLE -# endif /* !DYNAMIC_CRC_TABLE */ +#include +#ifndef DYNAMIC_CRC_TABLE +#define DYNAMIC_CRC_TABLE +#endif /* !DYNAMIC_CRC_TABLE */ #endif /* MAKECRCH */ -#include "zutil.h" /* for STDC and FAR definitions */ +#include "zutil.h" /* for STDC and FAR definitions */ -#define local static +#define local static /* Find a four-byte integer type for crc32_little() and crc32_big(). */ #ifndef NOBYFOUR -# ifdef STDC /* need ANSI C limits.h to determine sizes */ -# include -# define BYFOUR -# if (UINT_MAX == 0xffffffffUL) - typedef unsigned int u4; -# else -# if (ULONG_MAX == 0xffffffffUL) - typedef unsigned long u4; -# else -# if (USHRT_MAX == 0xffffffffUL) - typedef unsigned short u4; -# else -# undef BYFOUR /* can't find a four-byte integer type! */ -# endif -# endif -# endif -# endif /* STDC */ +#ifdef STDC /* need ANSI C limits.h to determine sizes */ +#include +#define BYFOUR +#if (UINT_MAX == 0xffffffffUL) +typedef unsigned int u4; +#else +#if (ULONG_MAX == 0xffffffffUL) +typedef unsigned long u4; +#else +#if (USHRT_MAX == 0xffffffffUL) +typedef unsigned short u4; +#else +#undef BYFOUR /* can't find a four-byte integer type! */ +#endif +#endif +#endif +#endif /* STDC */ #endif /* !NOBYFOUR */ /* Definitions for doing the crc four data bytes at a time. */ #ifdef BYFOUR -# define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \ - (((w)&0xff00)<<8)+(((w)&0xff)<<24)) - local unsigned long crc32_little OF((unsigned long, - const unsigned char FAR *, unsigned)); - local unsigned long crc32_big OF((unsigned long, - const unsigned char FAR *, unsigned)); -# define TBLS 8 +#define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \ + (((w)&0xff00)<<8)+(((w)&0xff)<<24)) +local unsigned long crc32_little OF((unsigned long, + const unsigned char FAR *, unsigned)); +local unsigned long crc32_big OF((unsigned long, + const unsigned char FAR *, unsigned)); +#define TBLS 8 #else -# define TBLS 1 +#define TBLS 1 #endif /* BYFOUR */ /* Local functions for crc concatenation */ local unsigned long gf2_matrix_times OF((unsigned long *mat, - unsigned long vec)); + unsigned long vec)); local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat)); #ifdef DYNAMIC_CRC_TABLE @@ -75,349 +76,369 @@ local volatile int crc_table_empty = 1; local unsigned long FAR crc_table[TBLS][256]; local void make_crc_table OF((void)); #ifdef MAKECRCH - local void write_table OF((FILE *, const unsigned long FAR *)); +local void write_table OF((FILE *, const unsigned long FAR *)); #endif /* MAKECRCH */ /* - Generate tables for a byte-wise 32-bit CRC calculation on the polynomial: - x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1. - - Polynomials over GF(2) are represented in binary, one bit per coefficient, - with the lowest powers in the most significant bit. Then adding polynomials - is just exclusive-or, and multiplying a polynomial by x is a right shift by - one. If we call the above polynomial p, and represent a byte as the - polynomial q, also with the lowest power in the most significant bit (so the - byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p, - where a mod b means the remainder after dividing a by b. - - This calculation is done using the shift-register method of multiplying and - taking the remainder. The register is initialized to zero, and for each - incoming bit, x^32 is added mod p to the register if the bit is a one (where - x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by - x (which is shifting right by one and adding x^32 mod p if the bit shifted - out is a one). We start with the highest power (least significant bit) of - q and repeat for all eight bits of q. - - The first table is simply the CRC of all possible eight bit values. This is - all the information needed to generate CRCs on data a byte at a time for all - combinations of CRC register values and incoming bytes. The remaining tables - allow for word-at-a-time CRC calculation for both big-endian and little- - endian machines, where a word is four bytes. -*/ -local void make_crc_table() + * Generate tables for a byte-wise 32-bit CRC calculation on the polynomial: + * x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1. + * + * Polynomials over GF(2) are represented in binary, one bit per coefficient, + * with the lowest powers in the most significant bit. Then adding polynomials + * is just exclusive-or, and multiplying a polynomial by x is a right shift by + * one. If we call the above polynomial p, and represent a byte as the + * polynomial q, also with the lowest power in the most significant bit (so the + * byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p, + * where a mod b means the remainder after dividing a by b. + * + * This calculation is done using the shift-register method of multiplying and + * taking the remainder. The register is initialized to zero, and for each + * incoming bit, x^32 is added mod p to the register if the bit is a one (where + * x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by + * x (which is shifting right by one and adding x^32 mod p if the bit shifted + * out is a one). We start with the highest power (least significant bit) of + * q and repeat for all eight bits of q. + * + * The first table is simply the CRC of all possible eight bit values. This is + * all the information needed to generate CRCs on data a byte at a time for all + * combinations of CRC register values and incoming bytes. The remaining tables + * allow for word-at-a-time CRC calculation for both big-endian and little- + * endian machines, where a word is four bytes. + */ +local void +make_crc_table() { - unsigned long c; - int n, k; - unsigned long poly; /* polynomial exclusive-or pattern */ - /* terms of polynomial defining this crc (except x^32): */ - static volatile int first = 1; /* flag to limit concurrent making */ - static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26}; - - /* See if another task is already doing this (not thread-safe, but better - than nothing -- significantly reduces duration of vulnerability in - case the advice about DYNAMIC_CRC_TABLE is ignored) */ - if (first) { - first = 0; - - /* make exclusive-or pattern from polynomial (0xedb88320UL) */ - poly = 0UL; - for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++) - poly |= 1UL << (31 - p[n]); - - /* generate a crc for every 8-bit value */ - for (n = 0; n < 256; n++) { - c = (unsigned long)n; - for (k = 0; k < 8; k++) - c = c & 1 ? poly ^ (c >> 1) : c >> 1; - crc_table[0][n] = c; - } + unsigned long c; + int n, k; + unsigned long poly; /* polynomial exclusive-or pattern */ + /* terms of polynomial defining this crc (except x^32): */ + static volatile int first = 1; /* flag to limit concurrent making */ + static const unsigned char p[] = + {0, 1, 2, 4, 5, 7, 8, 10, 11, 12, 16, 22, 23, 26}; + +/* + * See if another task is already doing this (not thread-safe, but better + * than nothing -- significantly reduces duration of vulnerability in + * case the advice about DYNAMIC_CRC_TABLE is ignored) + */ + if (first) { + first = 0; + + /* make exclusive-or pattern from polynomial (0xedb88320UL) */ + poly = 0UL; + for (n = 0; n < sizeof (p)/sizeof (unsigned char); n++) + poly |= 1UL << (31 - p[n]); + + /* generate a crc for every 8-bit value */ + for (n = 0; n < 256; n++) { + c = (unsigned long)n; + for (k = 0; k < 8; k++) + c = c & 1 ? poly ^ (c >> 1) : c >> 1; + crc_table[0][n] = c; + } #ifdef BYFOUR - /* generate crc for each value followed by one, two, and three zeros, - and then the byte reversal of those as well as the first table */ - for (n = 0; n < 256; n++) { - c = crc_table[0][n]; - crc_table[4][n] = REV(c); - for (k = 1; k < 4; k++) { - c = crc_table[0][c & 0xff] ^ (c >> 8); - crc_table[k][n] = c; - crc_table[k + 4][n] = REV(c); - } - } + /* + * generate crc for each value followed by one, two, and three zeros, + * and then the byte reversal of those as well as the first table + */ + for (n = 0; n < 256; n++) { + c = crc_table[0][n]; + crc_table[4][n] = REV(c); + for (k = 1; k < 4; k++) { + c = crc_table[0][c & 0xff] ^ (c >> 8); + crc_table[k][n] = c; + crc_table[k + 4][n] = REV(c); + } + } #endif /* BYFOUR */ - crc_table_empty = 0; - } - else { /* not first */ - /* wait for the other guy to finish (not efficient, but rare) */ - while (crc_table_empty) - ; - } + crc_table_empty = 0; + } else { /* not first */ + /* wait for the other guy to finish (not efficient, but rare) */ + while (crc_table_empty) + ; + } #ifdef MAKECRCH - /* write out CRC tables to crc32.h */ - { - FILE *out; - - out = fopen("crc32.h", "w"); - if (out == NULL) return; - fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n"); - fprintf(out, " * Generated automatically by crc32.c\n */\n\n"); - fprintf(out, "local const unsigned long FAR "); - fprintf(out, "crc_table[TBLS][256] =\n{\n {\n"); - write_table(out, crc_table[0]); -# ifdef BYFOUR - fprintf(out, "#ifdef BYFOUR\n"); - for (k = 1; k < 8; k++) { - fprintf(out, " },\n {\n"); - write_table(out, crc_table[k]); - } - fprintf(out, "#endif\n"); -# endif /* BYFOUR */ - fprintf(out, " }\n};\n"); - fclose(out); - } + /* write out CRC tables to crc32.h */ + { + FILE *out; + + out = fopen("crc32.h", "w"); + if (out == NULL) + return; + fprintf(out, + "/* crc32.h -- tables for rapid CRC calculation\n"); + fprintf(out, " * Generated automatically by crc32.c\n */\n\n"); + fprintf(out, "local const unsigned long FAR "); + fprintf(out, "crc_table[TBLS][256] =\n{\n {\n"); + write_table(out, crc_table[0]); +#ifdef BYFOUR + fprintf(out, "#ifdef BYFOUR\n"); + for (k = 1; k < 8; k++) { + fprintf(out, " },\n {\n"); + write_table(out, crc_table[k]); + } + fprintf(out, "#endif\n"); +#endif /* BYFOUR */ + fprintf(out, " }\n};\n"); + fclose(out); + } #endif /* MAKECRCH */ } #ifdef MAKECRCH -local void write_table(out, table) - FILE *out; - const unsigned long FAR *table; +local void +write_table( + FILE *out, + const unsigned long FAR *table) { - int n; + int n; - for (n = 0; n < 256; n++) - fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n], - n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", ")); + for (n = 0; n < 256; n++) + fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n], + n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", ")); } #endif /* MAKECRCH */ #else /* !DYNAMIC_CRC_TABLE */ -/* ======================================================================== +/* * Tables of CRC-32s of all single-byte values, made by make_crc_table(). */ #include "crc32.h" #endif /* DYNAMIC_CRC_TABLE */ -/* ========================================================================= +/* * This function can be used by asm versions of crc32() */ -const unsigned long FAR * ZEXPORT get_crc_table() +const unsigned long FAR * ZEXPORT +get_crc_table() { #ifdef DYNAMIC_CRC_TABLE - if (crc_table_empty) - make_crc_table(); + if (crc_table_empty) + make_crc_table(); #endif /* DYNAMIC_CRC_TABLE */ - return (const unsigned long FAR *)crc_table; + return ((const unsigned long FAR *)crc_table); } /* ========================================================================= */ -#define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8) -#define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1 +#define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8) +#define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1 /* ========================================================================= */ -unsigned long ZEXPORT crc32(crc, buf, len) - unsigned long crc; - const unsigned char FAR *buf; - unsigned len; +unsigned long ZEXPORT +crc32( + unsigned long crc, + const unsigned char FAR *buf, + unsigned len) { - if (buf == Z_NULL) return 0UL; + if (buf == Z_NULL) + return (0UL); #ifdef DYNAMIC_CRC_TABLE - if (crc_table_empty) - make_crc_table(); + if (crc_table_empty) + make_crc_table(); #endif /* DYNAMIC_CRC_TABLE */ #ifdef BYFOUR - if (sizeof(void *) == sizeof(ptrdiff_t)) { - u4 endian; - - endian = 1; - if (*((unsigned char *)(&endian))) - return crc32_little(crc, buf, len); - else - return crc32_big(crc, buf, len); - } + if (sizeof (void *) == sizeof (ptrdiff_t)) { + u4 endian; + + endian = 1; + if (*((unsigned char *)(&endian))) + return (crc32_little(crc, buf, len)); + else + return (crc32_big(crc, buf, len)); + } #endif /* BYFOUR */ - crc = crc ^ 0xffffffffUL; - while (len >= 8) { - DO8; - len -= 8; - } - if (len) do { - DO1; - } while (--len); - return crc ^ 0xffffffffUL; + crc = crc ^ 0xffffffffUL; + while (len >= 8) { + DO8; + len -= 8; + } + if (len) + do { + DO1; + } while (--len); + return (crc ^ 0xffffffffUL); } #ifdef BYFOUR /* ========================================================================= */ -#define DOLIT4 c ^= *buf4++; \ - c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \ - crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24] -#define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4 +#define DOLIT4 c ^= *buf4++; \ + c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \ + crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24] +#define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4 /* ========================================================================= */ -local unsigned long crc32_little(crc, buf, len) - unsigned long crc; - const unsigned char FAR *buf; - unsigned len; +local unsigned long +crc32_little( + unsigned long crc, + const unsigned char FAR *buf, + unsigned len) { - register u4 c; - register const u4 FAR *buf4; - - c = (u4)crc; - c = ~c; - while (len && ((ptrdiff_t)buf & 3)) { - c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); - len--; - } - - buf4 = (const u4 FAR *)(const void FAR *)buf; - while (len >= 32) { - DOLIT32; - len -= 32; - } - while (len >= 4) { - DOLIT4; - len -= 4; - } - buf = (const unsigned char FAR *)buf4; - - if (len) do { - c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); - } while (--len); - c = ~c; - return (unsigned long)c; + register u4 c; + register const u4 FAR *buf4; + + c = (u4)crc; + c = ~c; + while (len && ((ptrdiff_t)buf & 3)) { + c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); + len--; + } + + buf4 = (const u4 FAR *)(const void FAR *)buf; + while (len >= 32) { + DOLIT32; + len -= 32; + } + while (len >= 4) { + DOLIT4; + len -= 4; + } + buf = (const unsigned char FAR *)buf4; + + if (len) + do { + c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); + } while (--len); + c = ~c; + return ((unsigned long)c); } /* ========================================================================= */ -#define DOBIG4 c ^= *++buf4; \ - c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \ - crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24] -#define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4 +#define DOBIG4 c ^= *++buf4; \ + c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \ + crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24] +#define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4 /* ========================================================================= */ -local unsigned long crc32_big(crc, buf, len) - unsigned long crc; - const unsigned char FAR *buf; - unsigned len; +local unsigned long +crc32_big( + unsigned long crc, + const unsigned char FAR *buf, + unsigned len) { - register u4 c; - register const u4 FAR *buf4; - - c = REV((u4)crc); - c = ~c; - while (len && ((ptrdiff_t)buf & 3)) { - c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); - len--; - } - - buf4 = (const u4 FAR *)(const void FAR *)buf; - buf4--; - while (len >= 32) { - DOBIG32; - len -= 32; - } - while (len >= 4) { - DOBIG4; - len -= 4; - } - buf4++; - buf = (const unsigned char FAR *)buf4; - - if (len) do { - c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); - } while (--len); - c = ~c; - return (unsigned long)(REV(c)); + register u4 c; + register const u4 FAR *buf4; + + c = REV((u4)crc); + c = ~c; + while (len && ((ptrdiff_t)buf & 3)) { + c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); + len--; + } + + buf4 = (const u4 FAR *)(const void FAR *)buf; + buf4--; + while (len >= 32) { + DOBIG32; + len -= 32; + } + while (len >= 4) { + DOBIG4; + len -= 4; + } + buf4++; + buf = (const unsigned char FAR *)buf4; + + if (len) + do { + c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); + } while (--len); + c = ~c; + return (unsigned long)(REV(c)); } #endif /* BYFOUR */ -#define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */ +#define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */ /* ========================================================================= */ -local unsigned long gf2_matrix_times(mat, vec) - unsigned long *mat; - unsigned long vec; +local unsigned long +gf2_matrix_times( + unsigned long *mat, + unsigned long vec) { - unsigned long sum; - - sum = 0; - while (vec) { - if (vec & 1) - sum ^= *mat; - vec >>= 1; - mat++; - } - return sum; + unsigned long sum; + + sum = 0; + while (vec) { + if (vec & 1) + sum ^= *mat; + vec >>= 1; + mat++; + } + return (sum); } /* ========================================================================= */ -local void gf2_matrix_square(square, mat) - unsigned long *square; - unsigned long *mat; +local void gf2_matrix_square( + unsigned long *square, + unsigned long *mat) { - int n; + int n; - for (n = 0; n < GF2_DIM; n++) - square[n] = gf2_matrix_times(mat, mat[n]); + for (n = 0; n < GF2_DIM; n++) + square[n] = gf2_matrix_times(mat, mat[n]); } /* ========================================================================= */ -uLong ZEXPORT crc32_combine(crc1, crc2, len2) - uLong crc1; - uLong crc2; - z_off_t len2; +uLong ZEXPORT +crc32_combine( + uLong crc1, + uLong crc2, + z_off_t len2) { - int n; - unsigned long row; - unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */ - unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */ - - /* degenerate case */ - if (len2 == 0) - return crc1; - - /* put operator for one zero bit in odd */ - odd[0] = 0xedb88320L; /* CRC-32 polynomial */ - row = 1; - for (n = 1; n < GF2_DIM; n++) { - odd[n] = row; - row <<= 1; - } - - /* put operator for two zero bits in even */ - gf2_matrix_square(even, odd); - - /* put operator for four zero bits in odd */ - gf2_matrix_square(odd, even); - - /* apply len2 zeros to crc1 (first square will put the operator for one - zero byte, eight zero bits, in even) */ - do { - /* apply zeros operator for this bit of len2 */ - gf2_matrix_square(even, odd); - if (len2 & 1) - crc1 = gf2_matrix_times(even, crc1); - len2 >>= 1; - - /* if no more bits set, then done */ - if (len2 == 0) - break; - - /* another iteration of the loop with odd and even swapped */ - gf2_matrix_square(odd, even); - if (len2 & 1) - crc1 = gf2_matrix_times(odd, crc1); - len2 >>= 1; - - /* if no more bits set, then done */ - } while (len2 != 0); - - /* return combined crc */ - crc1 ^= crc2; - return crc1; + int n; + unsigned long row; + unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */ + unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */ + + /* degenerate case */ + if (len2 == 0) + return (crc1); + + /* put operator for one zero bit in odd */ + odd[0] = 0xedb88320L; /* CRC-32 polynomial */ + row = 1; + for (n = 1; n < GF2_DIM; n++) { + odd[n] = row; + row <<= 1; + } + + /* put operator for two zero bits in even */ + gf2_matrix_square(even, odd); + + /* put operator for four zero bits in odd */ + gf2_matrix_square(odd, even); + + /* + * apply len2 zeros to crc1 (first square will put the operator for one + * zero byte, eight zero bits, in even) + */ + do { + /* apply zeros operator for this bit of len2 */ + gf2_matrix_square(even, odd); + if (len2 & 1) + crc1 = gf2_matrix_times(even, crc1); + len2 >>= 1; + + /* if no more bits set, then done */ + if (len2 == 0) + break; + + /* another iteration of the loop with odd and even swapped */ + gf2_matrix_square(odd, even); + if (len2 & 1) + crc1 = gf2_matrix_times(odd, crc1); + len2 >>= 1; + + /* if no more bits set, then done */ + } while (len2 != 0); + + /* return combined crc */ + crc1 ^= crc2; + return (crc1); } diff --git a/lib/os/windows/zlib-1.2.3/crc32.h b/lib/os/windows/zlib-1.2.3/crc32.h index 8053b6117c0..ed80d816698 100644 --- a/lib/os/windows/zlib-1.2.3/crc32.h +++ b/lib/os/windows/zlib-1.2.3/crc32.h @@ -1,10 +1,11 @@ -/* crc32.h -- tables for rapid CRC calculation +/* + * crc32.h -- tables for rapid CRC calculation * Generated automatically by crc32.c */ local const unsigned long FAR crc_table[TBLS][256] = { - { +{ 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL, 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL, 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL, @@ -58,8 +59,8 @@ local const unsigned long FAR crc_table[TBLS][256] = 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL, 0x2d02ef8dUL #ifdef BYFOUR - }, - { +}, +{ 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL, 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL, 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL, @@ -112,8 +113,8 @@ local const unsigned long FAR crc_table[TBLS][256] = 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL, 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL, 0x9324fd72UL - }, - { +}, +{ 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL, 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL, 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL, @@ -166,8 +167,8 @@ local const unsigned long FAR crc_table[TBLS][256] = 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL, 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL, 0xbe9834edUL - }, - { +}, +{ 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL, 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL, 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL, @@ -220,8 +221,8 @@ local const unsigned long FAR crc_table[TBLS][256] = 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL, 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL, 0xde0506f1UL - }, - { +}, +{ 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL, 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL, 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL, @@ -274,8 +275,8 @@ local const unsigned long FAR crc_table[TBLS][256] = 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL, 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL, 0x8def022dUL - }, - { +}, +{ 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL, 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL, 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL, @@ -328,8 +329,8 @@ local const unsigned long FAR crc_table[TBLS][256] = 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL, 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL, 0x72fd2493UL - }, - { +}, +{ 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL, 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL, 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL, @@ -382,8 +383,8 @@ local const unsigned long FAR crc_table[TBLS][256] = 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL, 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL, 0xed3498beUL - }, - { +}, +{ 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL, 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL, 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL, @@ -437,5 +438,5 @@ local const unsigned long FAR crc_table[TBLS][256] = 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL, 0xf10605deUL #endif - } +} }; diff --git a/lib/os/windows/zlib-1.2.3/deflate.c b/lib/os/windows/zlib-1.2.3/deflate.c index 29ce1f64a57..e5544dd4006 100644 --- a/lib/os/windows/zlib-1.2.3/deflate.c +++ b/lib/os/windows/zlib-1.2.3/deflate.c @@ -1,4 +1,5 @@ -/* deflate.c -- compress data using the deflation algorithm +/* + * deflate.c -- compress data using the deflation algorithm * Copyright (C) 1995-2005 Jean-loup Gailly. * For conditions of distribution and use, see copyright notice in zlib.h */ @@ -52,22 +53,22 @@ #include "deflate.h" const char deflate_copyright[] = - " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly "; + " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly "; /* - If you use the zlib library in a product, an acknowledgment is welcome - in the documentation of your product. If for some reason you cannot - include such an acknowledgment, I would appreciate that you keep this - copyright string in the executable of your product. + * If you use the zlib library in a product, an acknowledgment is welcome + * in the documentation of your product. If for some reason you cannot + * include such an acknowledgment, I would appreciate that you keep this + * copyright string in the executable of your product. */ -/* =========================================================================== +/* * Function prototypes. */ typedef enum { - need_more, /* block not completed, need more input or more output */ - block_done, /* block flush performed */ - finish_started, /* finish started, need only more output at next deflate */ - finish_done /* finish done, accept no more input or output */ + need_more, /* block not completed, need more input or more output */ + block_done, /* block flush performed */ + finish_started, /* finish started, need only more output next deflate */ + finish_done /* finish done, accept no more input or output */ } block_state; typedef block_state (*compress_func) OF((deflate_state *s, int flush)); @@ -79,14 +80,14 @@ local block_state deflate_fast OF((deflate_state *s, int flush)); #ifndef FASTEST local block_state deflate_slow OF((deflate_state *s, int flush)); #endif -local void lm_init OF((deflate_state *s)); -local void putShortMSB OF((deflate_state *s, uInt b)); -local void flush_pending OF((z_streamp strm)); -local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size)); +local void lm_init OF((deflate_state *s)); +local void putShortMSB OF((deflate_state *s, uInt b)); +local void flush_pending OF((z_streamp strm)); +local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size)); #ifndef FASTEST #ifdef ASMV - void match_init OF((void)); /* asm code initialization */ - uInt longest_match OF((deflate_state *s, IPos cur_match)); +void match_init OF((void)); /* asm code initialization */ +uInt longest_match OF((deflate_state *s, IPos cur_match)); #else local uInt longest_match OF((deflate_state *s, IPos cur_match)); #endif @@ -95,47 +96,49 @@ local uInt longest_match_fast OF((deflate_state *s, IPos cur_match)); #ifdef DEBUG local void check_match OF((deflate_state *s, IPos start, IPos match, - int length)); + int length)); #endif -/* =========================================================================== +/* * Local data */ -#define NIL 0 +#define NIL 0 /* Tail of hash chains */ #ifndef TOO_FAR -# define TOO_FAR 4096 +#define TOO_FAR 4096 #endif /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */ -#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) -/* Minimum amount of lookahead, except at the end of the input file. +#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) +/* + * Minimum amount of lookahead, except at the end of the input file. * See deflate.c for comments about the MIN_MATCH+1. */ -/* Values for max_lazy_match, good_match and max_chain_length, depending on +/* + * Values for max_lazy_match, good_match and max_chain_length, depending on * the desired pack level (0..9). The values given below have been tuned to * exclude worst case performance for pathological files. Better values may be * found for specific files. */ typedef struct config_s { - ush good_length; /* reduce lazy search above this match length */ - ush max_lazy; /* do not perform lazy search above this match length */ - ush nice_length; /* quit search above this match length */ - ush max_chain; - compress_func func; + ush good_length; /* reduce lazy search above this match length */ + ush max_lazy; /* do not perform lazy search above this match length */ + ush nice_length; /* quit search above this match length */ + ush max_chain; + compress_func func; } config; #ifdef FASTEST local const config configuration_table[2] = { -/* good lazy nice chain */ +/* good lazy nice chain */ /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */ #else local const config configuration_table[10] = { -/* good lazy nice chain */ +/* good lazy nice chain */ /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */ /* 2 */ {4, 5, 16, 8, deflate_fast}, @@ -149,28 +152,30 @@ local const config configuration_table[10] = { /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */ #endif -/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4 +/* + * Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4 * For deflate_fast() (levels <= 3) good is ignored and lazy has a different * meaning. */ -#define EQUAL 0 +#define EQUAL 0 /* result of memcmp for equal strings */ #ifndef NO_DUMMY_DECL -struct static_tree_desc_s {int dummy;}; /* for buggy compilers */ +struct static_tree_desc_s {int dummy; }; /* for buggy compilers */ #endif -/* =========================================================================== +/* * Update a hash value with the given input byte * IN assertion: all calls to to UPDATE_HASH are made with consecutive * input characters, so that a running hash key can be computed from the * previous key instead of complete recalculation each time. */ -#define UPDATE_HASH(s,h,c) (h = (((h)<hash_shift) ^ (c)) & s->hash_mask) +#define UPDATE_HASH(s, h, c) \ + (h = (((h)<hash_shift) ^ (c)) & s->hash_mask) -/* =========================================================================== +/* * Insert string str in the dictionary and set match_head to the previous head * of the hash chain (the most recent string with same hash key). Return * the previous length of the hash chain. @@ -181,295 +186,313 @@ struct static_tree_desc_s {int dummy;}; /* for buggy compilers */ * (except for the last MIN_MATCH-1 bytes of the input file). */ #ifdef FASTEST -#define INSERT_STRING(s, str, match_head) \ - (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ +#define INSERT_STRING(s, str, match_head) \ + (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ match_head = s->head[s->ins_h], \ s->head[s->ins_h] = (Pos)(str)) #else -#define INSERT_STRING(s, str, match_head) \ - (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ +#define INSERT_STRING(s, str, match_head) \ + (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \ s->head[s->ins_h] = (Pos)(str)) #endif -/* =========================================================================== +/* * Initialize the hash table (avoiding 64K overflow for 16 bit systems). * prev[] will be initialized on the fly. */ -#define CLEAR_HASH(s) \ +#define CLEAR_HASH(s) \ s->head[s->hash_size-1] = NIL; \ - zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head)); + zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof (*s->head)); /* ========================================================================= */ -int ZEXPORT deflateInit_(strm, level, version, stream_size) - z_streamp strm; - int level; - const char *version; - int stream_size; +int ZEXPORT +deflateInit_( + z_streamp strm, + int level, + const char *version, + int stream_size) { - return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, - Z_DEFAULT_STRATEGY, version, stream_size); - /* To do: ignore strm->next_in if we use it as window */ + return (deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, + Z_DEFAULT_STRATEGY, version, stream_size)); + /* To do: ignore strm->next_in if we use it as window */ } /* ========================================================================= */ -int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, - version, stream_size) - z_streamp strm; - int level; - int method; - int windowBits; - int memLevel; - int strategy; - const char *version; - int stream_size; +int ZEXPORT +deflateInit2_( + z_streamp strm, + int level, + int method, + int windowBits, + int memLevel, + int strategy, + const char *version, + int stream_size) { - deflate_state *s; - int wrap = 1; - static const char my_version[] = ZLIB_VERSION; - - ushf *overlay; - /* We overlay pending_buf and d_buf+l_buf. This works since the average - * output size for (length,distance) codes is <= 24 bits. - */ - - if (version == Z_NULL || version[0] != my_version[0] || - stream_size != sizeof(z_stream)) { - return Z_VERSION_ERROR; - } - if (strm == Z_NULL) return Z_STREAM_ERROR; - - strm->msg = Z_NULL; - if (strm->zalloc == (alloc_func)0) { - strm->zalloc = zcalloc; - strm->opaque = (voidpf)0; - } - if (strm->zfree == (free_func)0) strm->zfree = zcfree; + deflate_state *s; + int wrap = 1; + static const char my_version[] = ZLIB_VERSION; + + ushf *overlay; + /* + * We overlay pending_buf and d_buf+l_buf. This works since the average + * output size for (length,distance) codes is <= 24 bits. + */ + + if (version == Z_NULL || version[0] != my_version[0] || + stream_size != sizeof (z_stream)) { + return (Z_VERSION_ERROR); + } + if (strm == Z_NULL) + return (Z_STREAM_ERROR); + + strm->msg = Z_NULL; + if (strm->zalloc == (alloc_func)0) { + strm->zalloc = zcalloc; + strm->opaque = (voidpf)0; + } + if (strm->zfree == (free_func)0) strm->zfree = zcfree; #ifdef FASTEST - if (level != 0) level = 1; + if (level != 0) level = 1; #else - if (level == Z_DEFAULT_COMPRESSION) level = 6; + if (level == Z_DEFAULT_COMPRESSION) level = 6; #endif - if (windowBits < 0) { /* suppress zlib wrapper */ - wrap = 0; - windowBits = -windowBits; - } + if (windowBits < 0) { /* suppress zlib wrapper */ + wrap = 0; + windowBits = -windowBits; + } #ifdef GZIP - else if (windowBits > 15) { - wrap = 2; /* write gzip wrapper instead */ - windowBits -= 16; - } + else if (windowBits > 15) { + wrap = 2; /* write gzip wrapper instead */ + windowBits -= 16; + } #endif - if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED || - windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || - strategy < 0 || strategy > Z_FIXED) { - return Z_STREAM_ERROR; - } - if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */ - s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state)); - if (s == Z_NULL) return Z_MEM_ERROR; - strm->state = (struct internal_state FAR *)s; - s->strm = strm; - - s->wrap = wrap; - s->gzhead = Z_NULL; - s->w_bits = windowBits; - s->w_size = 1 << s->w_bits; - s->w_mask = s->w_size - 1; - - s->hash_bits = memLevel + 7; - s->hash_size = 1 << s->hash_bits; - s->hash_mask = s->hash_size - 1; - s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH); - - s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte)); - s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos)); - s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos)); - - s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ - - overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); - s->pending_buf = (uchf *) overlay; - s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L); - - if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL || - s->pending_buf == Z_NULL) { - s->status = FINISH_STATE; - strm->msg = (char*)ERR_MSG(Z_MEM_ERROR); - deflateEnd (strm); - return Z_MEM_ERROR; - } - s->d_buf = overlay + s->lit_bufsize/sizeof(ush); - s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; - - s->level = level; - s->strategy = strategy; - s->method = (Byte)method; - - return deflateReset(strm); + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED || + windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || + strategy < 0 || strategy > Z_FIXED) { + return (Z_STREAM_ERROR); + } + /* until 256-byte window bug fixed */ + if (windowBits == 8) windowBits = 9; + s = (deflate_state *) ZALLOC(strm, 1, sizeof (deflate_state)); + if (s == Z_NULL) + return (Z_MEM_ERROR); + strm->state = (struct internal_state FAR *)s; + s->strm = strm; + + s->wrap = wrap; + s->gzhead = Z_NULL; + s->w_bits = windowBits; + s->w_size = 1 << s->w_bits; + s->w_mask = s->w_size - 1; + + s->hash_bits = memLevel + 7; + s->hash_size = 1 << s->hash_bits; + s->hash_mask = s->hash_size - 1; + s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH); + + s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof (Byte)); + s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof (Pos)); + s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof (Pos)); + + s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ + + overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof (ush)+2); + s->pending_buf = (uchf *) overlay; + s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof (ush)+2L); + + if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL || + s->pending_buf == Z_NULL) { + s->status = FINISH_STATE; + strm->msg = (char *)ERR_MSG(Z_MEM_ERROR); + deflateEnd(strm); + return (Z_MEM_ERROR); + } + s->d_buf = overlay + s->lit_bufsize/sizeof (ush); + s->l_buf = s->pending_buf + (1+sizeof (ush))*s->lit_bufsize; + + s->level = level; + s->strategy = strategy; + s->method = (Byte)method; + + return (deflateReset(strm)); } /* ========================================================================= */ -int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength) - z_streamp strm; - const Bytef *dictionary; - uInt dictLength; +int ZEXPORT +deflateSetDictionary( + z_streamp strm, + const Bytef *dictionary, + uInt dictLength) { - deflate_state *s; - uInt length = dictLength; - uInt n; - IPos hash_head = 0; - - if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL || - strm->state->wrap == 2 || - (strm->state->wrap == 1 && strm->state->status != INIT_STATE)) - return Z_STREAM_ERROR; - - s = strm->state; - if (s->wrap) - strm->adler = adler32(strm->adler, dictionary, dictLength); - - if (length < MIN_MATCH) return Z_OK; - if (length > MAX_DIST(s)) { - length = MAX_DIST(s); - dictionary += dictLength - length; /* use the tail of the dictionary */ - } - zmemcpy(s->window, dictionary, length); - s->strstart = length; - s->block_start = (long)length; - - /* Insert all strings in the hash table (except for the last two bytes). - * s->lookahead stays null, so s->ins_h will be recomputed at the next - * call of fill_window. - */ - s->ins_h = s->window[0]; - UPDATE_HASH(s, s->ins_h, s->window[1]); - for (n = 0; n <= length - MIN_MATCH; n++) { - INSERT_STRING(s, n, hash_head); - } - if (hash_head) hash_head = 0; /* to make compiler happy */ - return Z_OK; + deflate_state *s; + uInt length = dictLength; + uInt n; + IPos hash_head = 0; + + if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL || + strm->state->wrap == 2 || + (strm->state->wrap == 1 && strm->state->status != INIT_STATE)) + return (Z_STREAM_ERROR); + + s = strm->state; + if (s->wrap) + strm->adler = adler32(strm->adler, dictionary, dictLength); + + if (length < MIN_MATCH) + return (Z_OK); + if (length > MAX_DIST(s)) { + length = MAX_DIST(s); + /* use the tail of the dictionary */ + dictionary += dictLength - length; + } + zmemcpy(s->window, dictionary, length); + s->strstart = length; + s->block_start = (long)length; + + /* + * Insert all strings in the hash table (except for the last two bytes). + * s->lookahead stays null, so s->ins_h will be recomputed at the next + * call of fill_window. + */ + s->ins_h = s->window[0]; + UPDATE_HASH(s, s->ins_h, s->window[1]); + for (n = 0; n <= length - MIN_MATCH; n++) { + INSERT_STRING(s, n, hash_head); + } + if (hash_head) hash_head = 0; /* to make compiler happy */ + return (Z_OK); } /* ========================================================================= */ -int ZEXPORT deflateReset (strm) - z_streamp strm; +int ZEXPORT +deflateReset( + z_streamp strm) { - deflate_state *s; - - if (strm == Z_NULL || strm->state == Z_NULL || - strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) { - return Z_STREAM_ERROR; - } - - strm->total_in = strm->total_out = 0; - strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */ - strm->data_type = Z_UNKNOWN; - - s = (deflate_state *)strm->state; - s->pending = 0; - s->pending_out = s->pending_buf; - - if (s->wrap < 0) { - s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */ - } - s->status = s->wrap ? INIT_STATE : BUSY_STATE; - strm->adler = + deflate_state *s; + + if (strm == Z_NULL || strm->state == Z_NULL || + strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) { + return (Z_STREAM_ERROR); + } + + strm->total_in = strm->total_out = 0; + strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */ + strm->data_type = Z_UNKNOWN; + + s = (deflate_state *)strm->state; + s->pending = 0; + s->pending_out = s->pending_buf; + + if (s->wrap < 0) { + /* was made negative by deflate(..., Z_FINISH); */ + s->wrap = -s->wrap; + } + s->status = s->wrap ? INIT_STATE : BUSY_STATE; + strm->adler = #ifdef GZIP - s->wrap == 2 ? crc32(0L, Z_NULL, 0) : + s->wrap == 2 ? crc32(0L, Z_NULL, 0) : #endif - adler32(0L, Z_NULL, 0); - s->last_flush = Z_NO_FLUSH; + adler32(0L, Z_NULL, 0); + s->last_flush = Z_NO_FLUSH; - _tr_init(s); - lm_init(s); + _tr_init(s); + lm_init(s); - return Z_OK; + return (Z_OK); } /* ========================================================================= */ -int ZEXPORT deflateSetHeader (strm, head) - z_streamp strm; - gz_headerp head; +int ZEXPORT deflateSetHeader( + z_streamp strm, + gz_headerp head) { - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - if (strm->state->wrap != 2) return Z_STREAM_ERROR; - strm->state->gzhead = head; - return Z_OK; + if (strm == Z_NULL || strm->state == Z_NULL) + return (Z_STREAM_ERROR); + if (strm->state->wrap != 2) + return (Z_STREAM_ERROR); + strm->state->gzhead = head; + return (Z_OK); } /* ========================================================================= */ -int ZEXPORT deflatePrime (strm, bits, value) - z_streamp strm; - int bits; - int value; +int ZEXPORT +deflatePrime( + z_streamp strm, + int bits, + int value) { - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - strm->state->bi_valid = bits; - strm->state->bi_buf = (ush)(value & ((1 << bits) - 1)); - return Z_OK; + if (strm == Z_NULL || strm->state == Z_NULL) + return (Z_STREAM_ERROR); + strm->state->bi_valid = bits; + strm->state->bi_buf = (ush)(value & ((1 << bits) - 1)); + return (Z_OK); } /* ========================================================================= */ -int ZEXPORT deflateParams(strm, level, strategy) - z_streamp strm; - int level; - int strategy; +int ZEXPORT +deflateParams( + z_streamp strm, + int level, + int strategy) { - deflate_state *s; - compress_func func; - int err = Z_OK; + deflate_state *s; + compress_func func; + int err = Z_OK; - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - s = strm->state; + if (strm == Z_NULL || strm->state == Z_NULL) + return (Z_STREAM_ERROR); + s = strm->state; #ifdef FASTEST - if (level != 0) level = 1; + if (level != 0) level = 1; #else - if (level == Z_DEFAULT_COMPRESSION) level = 6; + if (level == Z_DEFAULT_COMPRESSION) level = 6; #endif - if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { - return Z_STREAM_ERROR; - } - func = configuration_table[s->level].func; - - if (func != configuration_table[level].func && strm->total_in != 0) { - /* Flush the last buffer: */ - err = deflate(strm, Z_PARTIAL_FLUSH); - } - if (s->level != level) { - s->level = level; - s->max_lazy_match = configuration_table[level].max_lazy; - s->good_match = configuration_table[level].good_length; - s->nice_match = configuration_table[level].nice_length; - s->max_chain_length = configuration_table[level].max_chain; - } - s->strategy = strategy; - return err; + if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { + return (Z_STREAM_ERROR); + } + func = configuration_table[s->level].func; + + if (func != configuration_table[level].func && strm->total_in != 0) { + /* Flush the last buffer: */ + err = deflate(strm, Z_PARTIAL_FLUSH); + } + if (s->level != level) { + s->level = level; + s->max_lazy_match = configuration_table[level].max_lazy; + s->good_match = configuration_table[level].good_length; + s->nice_match = configuration_table[level].nice_length; + s->max_chain_length = configuration_table[level].max_chain; + } + s->strategy = strategy; + return (err); } /* ========================================================================= */ -int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain) - z_streamp strm; - int good_length; - int max_lazy; - int nice_length; - int max_chain; +int ZEXPORT deflateTune( + z_streamp strm, + int good_length, + int max_lazy, + int nice_length, + int max_chain) { - deflate_state *s; - - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - s = strm->state; - s->good_match = good_length; - s->max_lazy_match = max_lazy; - s->nice_match = nice_length; - s->max_chain_length = max_chain; - return Z_OK; + deflate_state *s; + + if (strm == Z_NULL || strm->state == Z_NULL) + return (Z_STREAM_ERROR); + s = strm->state; + s->good_match = good_length; + s->max_lazy_match = max_lazy; + s->nice_match = nice_length; + s->max_chain_length = max_chain; + return (Z_OK); } -/* ========================================================================= +/* * For the default windowBits of 15 and memLevel of 8, this function returns * a close to exact, as well as small, upper bound on the compressed size. * They are coded as constants here for a reason--if the #define's are @@ -486,532 +509,556 @@ int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain) * But even the conservative upper bound of about 14% expansion does not * seem onerous for output buffer allocation. */ -uLong ZEXPORT deflateBound(strm, sourceLen) - z_streamp strm; - uLong sourceLen; +uLong ZEXPORT deflateBound( + z_streamp strm, + uLong sourceLen) { - deflate_state *s; - uLong destLen; + deflate_state *s; + uLong destLen; - /* conservative upper bound */ - destLen = sourceLen + - ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11; + /* conservative upper bound */ + destLen = sourceLen + + ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11; - /* if can't get parameters, return conservative bound */ - if (strm == Z_NULL || strm->state == Z_NULL) - return destLen; + /* if can't get parameters, return conservative bound */ + if (strm == Z_NULL || strm->state == Z_NULL) + return (destLen); - /* if not default parameters, return conservative bound */ - s = strm->state; - if (s->w_bits != 15 || s->hash_bits != 8 + 7) - return destLen; + /* if not default parameters, return conservative bound */ + s = strm->state; + if (s->w_bits != 15 || s->hash_bits != 8 + 7) + return (destLen); - /* default settings: return tight bound for that case */ - return compressBound(sourceLen); + /* default settings: return tight bound for that case */ + return (compressBound(sourceLen)); } -/* ========================================================================= +/* * Put a short in the pending buffer. The 16-bit value is put in MSB order. * IN assertion: the stream state is correct and there is enough room in * pending_buf. */ -local void putShortMSB (s, b) - deflate_state *s; - uInt b; +local void putShortMSB( + deflate_state *s, + uInt b) { - put_byte(s, (Byte)(b >> 8)); - put_byte(s, (Byte)(b & 0xff)); + put_byte(s, (Byte)(b >> 8)); + put_byte(s, (Byte)(b & 0xff)); } -/* ========================================================================= +/* * Flush as much pending output as possible. All deflate() output goes * through this function so some applications may wish to modify it * to avoid allocating a large strm->next_out buffer and copying into it. * (See also read_buf()). */ -local void flush_pending(strm) - z_streamp strm; +local void flush_pending( + z_streamp strm) { - unsigned len = strm->state->pending; - - if (len > strm->avail_out) len = strm->avail_out; - if (len == 0) return; - - zmemcpy(strm->next_out, strm->state->pending_out, len); - strm->next_out += len; - strm->state->pending_out += len; - strm->total_out += len; - strm->avail_out -= len; - strm->state->pending -= len; - if (strm->state->pending == 0) { - strm->state->pending_out = strm->state->pending_buf; - } + unsigned len = strm->state->pending; + + if (len > strm->avail_out) len = strm->avail_out; + if (len == 0) + return; + + zmemcpy(strm->next_out, strm->state->pending_out, len); + strm->next_out += len; + strm->state->pending_out += len; + strm->total_out += len; + strm->avail_out -= len; + strm->state->pending -= len; + if (strm->state->pending == 0) { + strm->state->pending_out = strm->state->pending_buf; + } } /* ========================================================================= */ -int ZEXPORT deflate (strm, flush) - z_streamp strm; - int flush; +int ZEXPORT deflate( + z_streamp strm, + int flush) { - int old_flush; /* value of flush param for previous deflate call */ - deflate_state *s; - - if (strm == Z_NULL || strm->state == Z_NULL || - flush > Z_FINISH || flush < 0) { - return Z_STREAM_ERROR; - } - s = strm->state; - - if (strm->next_out == Z_NULL || - (strm->next_in == Z_NULL && strm->avail_in != 0) || - (s->status == FINISH_STATE && flush != Z_FINISH)) { - ERR_RETURN(strm, Z_STREAM_ERROR); - } - if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR); - - s->strm = strm; /* just in case */ - old_flush = s->last_flush; - s->last_flush = flush; - - /* Write the header */ - if (s->status == INIT_STATE) { + int old_flush; /* value of flush param for previous deflate call */ + deflate_state *s; + + if (strm == Z_NULL || strm->state == Z_NULL || + flush > Z_FINISH || flush < 0) { + return (Z_STREAM_ERROR); + } + s = strm->state; + + if (strm->next_out == Z_NULL || + (strm->next_in == Z_NULL && strm->avail_in != 0) || + (s->status == FINISH_STATE && flush != Z_FINISH)) { + ERR_RETURN(strm, Z_STREAM_ERROR); + } + if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR); + + s->strm = strm; /* just in case */ + old_flush = s->last_flush; + s->last_flush = flush; + + /* Write the header */ + if (s->status == INIT_STATE) { #ifdef GZIP - if (s->wrap == 2) { - strm->adler = crc32(0L, Z_NULL, 0); - put_byte(s, 31); - put_byte(s, 139); - put_byte(s, 8); - if (s->gzhead == NULL) { - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, s->level == 9 ? 2 : - (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? - 4 : 0)); - put_byte(s, OS_CODE); - s->status = BUSY_STATE; - } - else { - put_byte(s, (s->gzhead->text ? 1 : 0) + - (s->gzhead->hcrc ? 2 : 0) + - (s->gzhead->extra == Z_NULL ? 0 : 4) + - (s->gzhead->name == Z_NULL ? 0 : 8) + - (s->gzhead->comment == Z_NULL ? 0 : 16) - ); - put_byte(s, (Byte)(s->gzhead->time & 0xff)); - put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff)); - put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff)); - put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff)); - put_byte(s, s->level == 9 ? 2 : - (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? - 4 : 0)); - put_byte(s, s->gzhead->os & 0xff); - if (s->gzhead->extra != NULL) { - put_byte(s, s->gzhead->extra_len & 0xff); - put_byte(s, (s->gzhead->extra_len >> 8) & 0xff); - } - if (s->gzhead->hcrc) - strm->adler = crc32(strm->adler, s->pending_buf, - s->pending); - s->gzindex = 0; - s->status = EXTRA_STATE; - } - } - else + if (s->wrap == 2) { + strm->adler = crc32(0L, Z_NULL, 0); + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (s->gzhead == NULL) { + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s->level == 9 ? 2 : + (s->strategy >= + Z_HUFFMAN_ONLY || s->level < 2 ? + 4 : 0)); + put_byte(s, OS_CODE); + s->status = BUSY_STATE; + } else { + put_byte(s, (s->gzhead->text ? 1 : 0) + + (s->gzhead->hcrc ? 2 : 0) + + (s->gzhead->extra == Z_NULL ? 0 : 4) + + (s->gzhead->name == Z_NULL ? 0 : 8) + + (s->gzhead->comment == Z_NULL ? 0 : 16)); + put_byte(s, (Byte)(s->gzhead->time & 0xff)); + put_byte(s, + (Byte)((s->gzhead->time >> 8) & 0xff)); + put_byte(s, + (Byte)((s->gzhead->time >> 16) & 0xff)); + put_byte(s, + (Byte)((s->gzhead->time >> 24) & 0xff)); + put_byte(s, s->level == 9 ? 2 : + (s->strategy >= Z_HUFFMAN_ONLY || + s->level < 2 ? + 4 : 0)); + put_byte(s, s->gzhead->os & 0xff); + if (s->gzhead->extra != NULL) { + put_byte(s, + s->gzhead->extra_len & 0xff); + put_byte(s, + (s->gzhead->extra_len >> 8) & 0xff); + } + if (s->gzhead->hcrc) + strm->adler = crc32(strm->adler, + s->pending_buf, + s->pending); + s->gzindex = 0; + s->status = EXTRA_STATE; + } + } else #endif - { - uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8; - uInt level_flags; - - if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2) - level_flags = 0; - else if (s->level < 6) - level_flags = 1; - else if (s->level == 6) - level_flags = 2; - else - level_flags = 3; - header |= (level_flags << 6); - if (s->strstart != 0) header |= PRESET_DICT; - header += 31 - (header % 31); - - s->status = BUSY_STATE; - putShortMSB(s, header); - - /* Save the adler32 of the preset dictionary: */ - if (s->strstart != 0) { - putShortMSB(s, (uInt)(strm->adler >> 16)); - putShortMSB(s, (uInt)(strm->adler & 0xffff)); - } - strm->adler = adler32(0L, Z_NULL, 0); - } - } + { + uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8; + uInt level_flags; + + if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2) + level_flags = 0; + else if (s->level < 6) + level_flags = 1; + else if (s->level == 6) + level_flags = 2; + else + level_flags = 3; + header |= (level_flags << 6); + if (s->strstart != 0) header |= PRESET_DICT; + header += 31 - (header % 31); + + s->status = BUSY_STATE; + putShortMSB(s, header); + + /* Save the adler32 of the preset dictionary: */ + if (s->strstart != 0) { + putShortMSB(s, (uInt)(strm->adler >> 16)); + putShortMSB(s, (uInt)(strm->adler & 0xffff)); + } + strm->adler = adler32(0L, Z_NULL, 0); + } + } #ifdef GZIP - if (s->status == EXTRA_STATE) { - if (s->gzhead->extra != NULL) { - uInt beg = s->pending; /* start of bytes to update crc */ - - while (s->gzindex < (s->gzhead->extra_len & 0xffff)) { - if (s->pending == s->pending_buf_size) { - if (s->gzhead->hcrc && s->pending > beg) - strm->adler = crc32(strm->adler, s->pending_buf + beg, - s->pending - beg); - flush_pending(strm); - beg = s->pending; - if (s->pending == s->pending_buf_size) - break; - } - put_byte(s, s->gzhead->extra[s->gzindex]); - s->gzindex++; - } - if (s->gzhead->hcrc && s->pending > beg) - strm->adler = crc32(strm->adler, s->pending_buf + beg, - s->pending - beg); - if (s->gzindex == s->gzhead->extra_len) { - s->gzindex = 0; - s->status = NAME_STATE; - } - } - else - s->status = NAME_STATE; - } - if (s->status == NAME_STATE) { - if (s->gzhead->name != NULL) { - uInt beg = s->pending; /* start of bytes to update crc */ - int val; - - do { - if (s->pending == s->pending_buf_size) { - if (s->gzhead->hcrc && s->pending > beg) - strm->adler = crc32(strm->adler, s->pending_buf + beg, - s->pending - beg); - flush_pending(strm); - beg = s->pending; - if (s->pending == s->pending_buf_size) { - val = 1; - break; - } - } - val = s->gzhead->name[s->gzindex++]; - put_byte(s, val); - } while (val != 0); - if (s->gzhead->hcrc && s->pending > beg) - strm->adler = crc32(strm->adler, s->pending_buf + beg, - s->pending - beg); - if (val == 0) { - s->gzindex = 0; - s->status = COMMENT_STATE; - } - } - else - s->status = COMMENT_STATE; - } - if (s->status == COMMENT_STATE) { - if (s->gzhead->comment != NULL) { - uInt beg = s->pending; /* start of bytes to update crc */ - int val; - - do { - if (s->pending == s->pending_buf_size) { - if (s->gzhead->hcrc && s->pending > beg) - strm->adler = crc32(strm->adler, s->pending_buf + beg, - s->pending - beg); - flush_pending(strm); - beg = s->pending; - if (s->pending == s->pending_buf_size) { - val = 1; - break; - } - } - val = s->gzhead->comment[s->gzindex++]; - put_byte(s, val); - } while (val != 0); - if (s->gzhead->hcrc && s->pending > beg) - strm->adler = crc32(strm->adler, s->pending_buf + beg, - s->pending - beg); - if (val == 0) - s->status = HCRC_STATE; - } - else - s->status = HCRC_STATE; - } - if (s->status == HCRC_STATE) { - if (s->gzhead->hcrc) { - if (s->pending + 2 > s->pending_buf_size) - flush_pending(strm); - if (s->pending + 2 <= s->pending_buf_size) { - put_byte(s, (Byte)(strm->adler & 0xff)); - put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); - strm->adler = crc32(0L, Z_NULL, 0); - s->status = BUSY_STATE; - } - } - else - s->status = BUSY_STATE; - } + if (s->status == EXTRA_STATE) { + if (s->gzhead->extra != NULL) { + /* start of bytes to update crc */ + uInt beg = s->pending; + + while (s->gzindex < (s->gzhead->extra_len & 0xffff)) { + if (s->pending == s->pending_buf_size) { + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, + s->pending_buf + beg, + s->pending - beg); + flush_pending(strm); + beg = s->pending; + if (s->pending == s->pending_buf_size) + break; + } + put_byte(s, s->gzhead->extra[s->gzindex]); + s->gzindex++; + } + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, + s->pending_buf + beg, + s->pending - beg); + if (s->gzindex == s->gzhead->extra_len) { + s->gzindex = 0; + s->status = NAME_STATE; + } + } else + s->status = NAME_STATE; + } + if (s->status == NAME_STATE) { + if (s->gzhead->name != NULL) { + /* start of bytes to update crc */ + uInt beg = s->pending; + int val; + + do { + if (s->pending == s->pending_buf_size) { + if (s->gzhead->hcrc && + s->pending > beg) + strm->adler = crc32(strm->adler, + s->pending_buf + beg, + s->pending - beg); + flush_pending(strm); + beg = s->pending; + if (s->pending == s->pending_buf_size) { + val = 1; + break; + } + } + val = s->gzhead->name[s->gzindex++]; + put_byte(s, val); + } while (val != 0); + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, + s->pending_buf + beg, + s->pending - beg); + if (val == 0) { + s->gzindex = 0; + s->status = COMMENT_STATE; + } + } else + s->status = COMMENT_STATE; + } + if (s->status == COMMENT_STATE) { + if (s->gzhead->comment != NULL) { + /* start of bytes to update crc */ + uInt beg = s->pending; + int val; + + do { + if (s->pending == s->pending_buf_size) { + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, + s->pending_buf + beg, + s->pending - beg); + flush_pending(strm); + beg = s->pending; + if (s->pending == s->pending_buf_size) { + val = 1; + break; + } + } + val = s->gzhead->comment[s->gzindex++]; + put_byte(s, val); + } while (val != 0); + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, + s->pending_buf + beg, + s->pending - beg); + if (val == 0) + s->status = HCRC_STATE; + } else + s->status = HCRC_STATE; + } + if (s->status == HCRC_STATE) { + if (s->gzhead->hcrc) { + if (s->pending + 2 > s->pending_buf_size) + flush_pending(strm); + if (s->pending + 2 <= s->pending_buf_size) { + put_byte(s, (Byte)(strm->adler & 0xff)); + put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); + strm->adler = crc32(0L, Z_NULL, 0); + s->status = BUSY_STATE; + } + } else + s->status = BUSY_STATE; + } #endif - /* Flush as much pending output as possible */ - if (s->pending != 0) { - flush_pending(strm); - if (strm->avail_out == 0) { - /* Since avail_out is 0, deflate will be called again with - * more output space, but possibly with both pending and - * avail_in equal to zero. There won't be anything to do, - * but this is not an error situation so make sure we - * return OK instead of BUF_ERROR at next call of deflate: - */ - s->last_flush = -1; - return Z_OK; - } - - /* Make sure there is something to do and avoid duplicate consecutive - * flushes. For repeated and useless calls with Z_FINISH, we keep - * returning Z_STREAM_END instead of Z_BUF_ERROR. - */ - } else if (strm->avail_in == 0 && flush <= old_flush && - flush != Z_FINISH) { - ERR_RETURN(strm, Z_BUF_ERROR); - } - - /* User must not provide more input after the first FINISH: */ - if (s->status == FINISH_STATE && strm->avail_in != 0) { - ERR_RETURN(strm, Z_BUF_ERROR); - } - - /* Start a new block or continue the current one. - */ - if (strm->avail_in != 0 || s->lookahead != 0 || - (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) { - block_state bstate; - - bstate = (*(configuration_table[s->level].func))(s, flush); - - if (bstate == finish_started || bstate == finish_done) { - s->status = FINISH_STATE; - } - if (bstate == need_more || bstate == finish_started) { - if (strm->avail_out == 0) { - s->last_flush = -1; /* avoid BUF_ERROR next call, see above */ - } - return Z_OK; - /* If flush != Z_NO_FLUSH && avail_out == 0, the next call - * of deflate should use the same flush parameter to make sure - * that the flush is complete. So we don't have to output an - * empty block here, this will be done at next call. This also - * ensures that for a very small output buffer, we emit at most - * one empty block. - */ - } - if (bstate == block_done) { - if (flush == Z_PARTIAL_FLUSH) { - _tr_align(s); - } else { /* FULL_FLUSH or SYNC_FLUSH */ - _tr_stored_block(s, (char*)0, 0L, 0); - /* For a full flush, this empty block will be recognized - * as a special marker by inflate_sync(). - */ - if (flush == Z_FULL_FLUSH) { - CLEAR_HASH(s); /* forget history */ - } - } - flush_pending(strm); - if (strm->avail_out == 0) { - s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */ - return Z_OK; - } - } - } - Assert(strm->avail_out > 0, "bug2"); - - if (flush != Z_FINISH) return Z_OK; - if (s->wrap <= 0) return Z_STREAM_END; - - /* Write the trailer */ + /* Flush as much pending output as possible */ + if (s->pending != 0) { + flush_pending(strm); + if (strm->avail_out == 0) { + /* + * Since avail_out is 0, deflate will be called again with + * more output space, but possibly with both pending and + * avail_in equal to zero. There won't be anything to do, + * but this is not an error situation so make sure we + * return OK instead of BUF_ERROR at next call of deflate: + */ + s->last_flush = -1; + return (Z_OK); + } + + /* + * Make sure there is something to do and avoid duplicate consecutive + * flushes. For repeated and useless calls with Z_FINISH, we keep + * returning Z_STREAM_END instead of Z_BUF_ERROR. + */ + } else if (strm->avail_in == 0 && flush <= old_flush && + flush != Z_FINISH) { + ERR_RETURN(strm, Z_BUF_ERROR); + } + + /* User must not provide more input after the first FINISH: */ + if (s->status == FINISH_STATE && strm->avail_in != 0) { + ERR_RETURN(strm, Z_BUF_ERROR); + } + + /* + * Start a new block or continue the current one. + */ + if (strm->avail_in != 0 || s->lookahead != 0 || + (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) { + block_state bstate; + + bstate = (*(configuration_table[s->level].func))(s, flush); + + if (bstate == finish_started || bstate == finish_done) { + s->status = FINISH_STATE; + } + if (bstate == need_more || bstate == finish_started) { + if (strm->avail_out == 0) { + /* avoid BUF_ERROR next call, see above */ + s->last_flush = -1; + } + return (Z_OK); + /* + * If flush != Z_NO_FLUSH && avail_out == 0, the next call + * of deflate should use the same flush parameter to make sure + * that the flush is complete. So we don't have to output an + * empty block here, this will be done at next call. This also + * ensures that for a very small output buffer, we emit at most + * one empty block. + */ + } + if (bstate == block_done) { + if (flush == Z_PARTIAL_FLUSH) { + _tr_align(s); + } else { /* FULL_FLUSH or SYNC_FLUSH */ + _tr_stored_block(s, (char *)0, 0L, 0); + /* + * For a full flush, this empty block will be recognized + * as a special marker by inflate_sync(). + */ + if (flush == Z_FULL_FLUSH) { + CLEAR_HASH(s); /* forget history */ + } + } + flush_pending(strm); + if (strm->avail_out == 0) { + /* avoid BUF_ERROR at next call, see above */ + s->last_flush = -1; + return (Z_OK); + } + } + } + Assert(strm->avail_out > 0, "bug2"); + + if (flush != Z_FINISH) + return (Z_OK); + if (s->wrap <= 0) + return (Z_STREAM_END); + + /* Write the trailer */ #ifdef GZIP - if (s->wrap == 2) { - put_byte(s, (Byte)(strm->adler & 0xff)); - put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); - put_byte(s, (Byte)((strm->adler >> 16) & 0xff)); - put_byte(s, (Byte)((strm->adler >> 24) & 0xff)); - put_byte(s, (Byte)(strm->total_in & 0xff)); - put_byte(s, (Byte)((strm->total_in >> 8) & 0xff)); - put_byte(s, (Byte)((strm->total_in >> 16) & 0xff)); - put_byte(s, (Byte)((strm->total_in >> 24) & 0xff)); - } - else + if (s->wrap == 2) { + put_byte(s, (Byte)(strm->adler & 0xff)); + put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); + put_byte(s, (Byte)((strm->adler >> 16) & 0xff)); + put_byte(s, (Byte)((strm->adler >> 24) & 0xff)); + put_byte(s, (Byte)(strm->total_in & 0xff)); + put_byte(s, (Byte)((strm->total_in >> 8) & 0xff)); + put_byte(s, (Byte)((strm->total_in >> 16) & 0xff)); + put_byte(s, (Byte)((strm->total_in >> 24) & 0xff)); + } else #endif - { - putShortMSB(s, (uInt)(strm->adler >> 16)); - putShortMSB(s, (uInt)(strm->adler & 0xffff)); - } - flush_pending(strm); - /* If avail_out is zero, the application will call deflate again - * to flush the rest. - */ - if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */ - return s->pending != 0 ? Z_OK : Z_STREAM_END; + { + putShortMSB(s, (uInt)(strm->adler >> 16)); + putShortMSB(s, (uInt)(strm->adler & 0xffff)); + } + flush_pending(strm); + /* + * If avail_out is zero, the application will call deflate again + * to flush the rest. + */ + if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */ + return (s->pending != 0 ? Z_OK : Z_STREAM_END); } /* ========================================================================= */ -int ZEXPORT deflateEnd (strm) - z_streamp strm; +int ZEXPORT +deflateEnd(z_streamp strm) { - int status; - - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - - status = strm->state->status; - if (status != INIT_STATE && - status != EXTRA_STATE && - status != NAME_STATE && - status != COMMENT_STATE && - status != HCRC_STATE && - status != BUSY_STATE && - status != FINISH_STATE) { - return Z_STREAM_ERROR; - } - - /* Deallocate in reverse order of allocations: */ - TRY_FREE(strm, strm->state->pending_buf); - TRY_FREE(strm, strm->state->head); - TRY_FREE(strm, strm->state->prev); - TRY_FREE(strm, strm->state->window); - - ZFREE(strm, strm->state); - strm->state = Z_NULL; - - return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK; + int status; + + if (strm == Z_NULL || strm->state == Z_NULL) + return (Z_STREAM_ERROR); + + status = strm->state->status; + if (status != INIT_STATE && + status != EXTRA_STATE && + status != NAME_STATE && + status != COMMENT_STATE && + status != HCRC_STATE && + status != BUSY_STATE && + status != FINISH_STATE) { + return (Z_STREAM_ERROR); + } + + /* Deallocate in reverse order of allocations: */ + TRY_FREE(strm, strm->state->pending_buf); + TRY_FREE(strm, strm->state->head); + TRY_FREE(strm, strm->state->prev); + TRY_FREE(strm, strm->state->window); + + ZFREE(strm, strm->state); + strm->state = Z_NULL; + + return (status == BUSY_STATE ? Z_DATA_ERROR : Z_OK); } -/* ========================================================================= +/* * Copy the source state to the destination state. * To simplify the source, this is not supported for 16-bit MSDOS (which * doesn't have enough memory anyway to duplicate compression states). */ -int ZEXPORT deflateCopy (dest, source) - z_streamp dest; - z_streamp source; +int ZEXPORT deflateCopy( + z_streamp dest, + z_streamp source) { #ifdef MAXSEG_64K - return Z_STREAM_ERROR; + return (Z_STREAM_ERROR); #else - deflate_state *ds; - deflate_state *ss; - ushf *overlay; - - - if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) { - return Z_STREAM_ERROR; - } - - ss = source->state; - - zmemcpy(dest, source, sizeof(z_stream)); - - ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state)); - if (ds == Z_NULL) return Z_MEM_ERROR; - dest->state = (struct internal_state FAR *) ds; - zmemcpy(ds, ss, sizeof(deflate_state)); - ds->strm = dest; - - ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte)); - ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos)); - ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos)); - overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2); - ds->pending_buf = (uchf *) overlay; - - if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL || - ds->pending_buf == Z_NULL) { - deflateEnd (dest); - return Z_MEM_ERROR; - } - /* following zmemcpy do not work for 16-bit MSDOS */ - zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte)); - zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos)); - zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos)); - zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size); - - ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf); - ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush); - ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize; - - ds->l_desc.dyn_tree = ds->dyn_ltree; - ds->d_desc.dyn_tree = ds->dyn_dtree; - ds->bl_desc.dyn_tree = ds->bl_tree; - - return Z_OK; + deflate_state *ds; + deflate_state *ss; + ushf *overlay; + + if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) { + return (Z_STREAM_ERROR); + } + + ss = source->state; + + zmemcpy(dest, source, sizeof (z_stream)); + + ds = (deflate_state *) ZALLOC(dest, 1, sizeof (deflate_state)); + if (ds == Z_NULL) + return (Z_MEM_ERROR); + dest->state = (struct internal_state FAR *) ds; + zmemcpy(ds, ss, sizeof (deflate_state)); + ds->strm = dest; + + ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof (Byte)); + ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof (Pos)); + ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof (Pos)); + overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof (ush)+2); + ds->pending_buf = (uchf *) overlay; + + if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL || + ds->pending_buf == Z_NULL) { + deflateEnd(dest); + return (Z_MEM_ERROR); + } + /* following zmemcpy do not work for 16-bit MSDOS */ + zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof (Byte)); + zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof (Pos)); + zmemcpy(ds->head, ss->head, ds->hash_size * sizeof (Pos)); + zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size); + + ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf); + ds->d_buf = overlay + ds->lit_bufsize/sizeof (ush); + ds->l_buf = ds->pending_buf + (1+sizeof (ush))*ds->lit_bufsize; + + ds->l_desc.dyn_tree = ds->dyn_ltree; + ds->d_desc.dyn_tree = ds->dyn_dtree; + ds->bl_desc.dyn_tree = ds->bl_tree; + + return (Z_OK); #endif /* MAXSEG_64K */ } -/* =========================================================================== +/* * Read a new buffer from the current input stream, update the adler32 * and total number of bytes read. All deflate() input goes through * this function so some applications may wish to modify it to avoid * allocating a large strm->next_in buffer and copying from it. * (See also flush_pending()). */ -local int read_buf(strm, buf, size) - z_streamp strm; - Bytef *buf; - unsigned size; +local int read_buf( + z_streamp strm, + Bytef *buf, + unsigned size) { - unsigned len = strm->avail_in; + unsigned len = strm->avail_in; - if (len > size) len = size; - if (len == 0) return 0; + if (len > size) len = size; + if (len == 0) + return (0); - strm->avail_in -= len; + strm->avail_in -= len; - if (strm->state->wrap == 1) { - strm->adler = adler32(strm->adler, strm->next_in, len); - } + if (strm->state->wrap == 1) { + strm->adler = adler32(strm->adler, strm->next_in, len); + } #ifdef GZIP - else if (strm->state->wrap == 2) { - strm->adler = crc32(strm->adler, strm->next_in, len); - } + else if (strm->state->wrap == 2) { + strm->adler = crc32(strm->adler, strm->next_in, len); + } #endif - zmemcpy(buf, strm->next_in, len); - strm->next_in += len; - strm->total_in += len; + zmemcpy(buf, strm->next_in, len); + strm->next_in += len; + strm->total_in += len; - return (int)len; + return ((int)len); } -/* =========================================================================== +/* * Initialize the "longest match" routines for a new zlib stream */ -local void lm_init (s) - deflate_state *s; +local void lm_init( + deflate_state *s) { - s->window_size = (ulg)2L*s->w_size; - - CLEAR_HASH(s); - - /* Set the default configuration parameters: - */ - s->max_lazy_match = configuration_table[s->level].max_lazy; - s->good_match = configuration_table[s->level].good_length; - s->nice_match = configuration_table[s->level].nice_length; - s->max_chain_length = configuration_table[s->level].max_chain; - - s->strstart = 0; - s->block_start = 0L; - s->lookahead = 0; - s->match_length = s->prev_length = MIN_MATCH-1; - s->match_available = 0; - s->ins_h = 0; + s->window_size = (ulg)2L*s->w_size; + + CLEAR_HASH(s); + + /* + * Set the default configuration parameters: + */ + s->max_lazy_match = configuration_table[s->level].max_lazy; + s->good_match = configuration_table[s->level].good_length; + s->nice_match = configuration_table[s->level].nice_length; + s->max_chain_length = configuration_table[s->level].max_chain; + + s->strstart = 0; + s->block_start = 0L; + s->lookahead = 0; + s->match_length = s->prev_length = MIN_MATCH-1; + s->match_available = 0; + s->ins_h = 0; #ifndef FASTEST #ifdef ASMV - match_init(); /* initialize the asm code */ + match_init(); /* initialize the asm code */ #endif #endif } #ifndef FASTEST -/* =========================================================================== +/* * Set match_start to the longest match starting at the given string and * return its length. Matches shorter or equal to prev_length are discarded, * in which case the result is equal to prev_length and match_start is @@ -1021,239 +1068,268 @@ local void lm_init (s) * OUT assertion: the match length is not greater than s->lookahead. */ #ifndef ASMV -/* For 80x86 and 680x0, an optimized version will be provided in match.asm or +/* + * For 80x86 and 680x0, an optimized version will be provided in match.asm or * match.S. The code will be functionally equivalent. */ -local uInt longest_match(s, cur_match) - deflate_state *s; - IPos cur_match; /* current match */ +local uInt longest_match( + deflate_state *s, + IPos cur_match) { - unsigned chain_length = s->max_chain_length;/* max hash chain length */ - register Bytef *scan = s->window + s->strstart; /* current string */ - register Bytef *match; /* matched string */ - register int len; /* length of current match */ - int best_len = s->prev_length; /* best match length so far */ - int nice_match = s->nice_match; /* stop if match long enough */ - IPos limit = s->strstart > (IPos)MAX_DIST(s) ? - s->strstart - (IPos)MAX_DIST(s) : NIL; - /* Stop when cur_match becomes <= limit. To simplify the code, - * we prevent matches with the string of window index 0. - */ - Posf *prev = s->prev; - uInt wmask = s->w_mask; + /* max hash chain length */ + unsigned chain_length = s->max_chain_length; + /* current string */ + register Bytef *scan = s->window + s->strstart; + register Bytef *match; /* matched string */ + register int len; /* length of current match */ + int best_len = s->prev_length; /* best match length so far */ + int nice_match = s->nice_match; /* stop if match long enough */ + IPos limit = s->strstart > (IPos)MAX_DIST(s) ? + s->strstart - (IPos)MAX_DIST(s) : NIL; + /* + * Stop when cur_match becomes <= limit. To simplify the code, + * we prevent matches with the string of window index 0. + */ + Posf *prev = s->prev; + uInt wmask = s->w_mask; #ifdef UNALIGNED_OK - /* Compare two bytes at a time. Note: this is not always beneficial. - * Try with and without -DUNALIGNED_OK to check. - */ - register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1; - register ush scan_start = *(ushf*)scan; - register ush scan_end = *(ushf*)(scan+best_len-1); + /* + * Compare two bytes at a time. Note: this is not always beneficial. + * Try with and without -DUNALIGNED_OK to check. + */ + register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1; + register ush scan_start = *(ushf*)scan; + register ush scan_end = *(ushf*)(scan+best_len-1); #else - register Bytef *strend = s->window + s->strstart + MAX_MATCH; - register Byte scan_end1 = scan[best_len-1]; - register Byte scan_end = scan[best_len]; + register Bytef *strend = s->window + s->strstart + MAX_MATCH; + register Byte scan_end1 = scan[best_len-1]; + register Byte scan_end = scan[best_len]; #endif - /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. - * It is easy to get rid of this optimization if necessary. - */ - Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); - - /* Do not waste too much time if we already have a good match: */ - if (s->prev_length >= s->good_match) { - chain_length >>= 2; - } - /* Do not look for matches beyond the end of the input. This is necessary - * to make deflate deterministic. - */ - if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; - - Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); - - do { - Assert(cur_match < s->strstart, "no future"); - match = s->window + cur_match; - - /* Skip to next match if the match length cannot increase - * or if the match length is less than 2. Note that the checks below - * for insufficient lookahead only occur occasionally for performance - * reasons. Therefore uninitialized memory will be accessed, and - * conditional jumps will be made that depend on those values. - * However the length of the match is limited to the lookahead, so - * the output of deflate is not affected by the uninitialized values. - */ +/* + * The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + /* Do not waste too much time if we already have a good match: */ + if (s->prev_length >= s->good_match) { + chain_length >>= 2; + } +/* + * Do not look for matches beyond the end of the input. This is necessary + * to make deflate deterministic. + */ + if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; + + Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, + "need lookahead"); + + do { + Assert(cur_match < s->strstart, "no future"); + match = s->window + cur_match; + + /* + * Skip to next match if the match length cannot increase + * or if the match length is less than 2. Note that the checks below + * for insufficient lookahead only occur occasionally for performance + * reasons. Therefore uninitialized memory will be accessed, and + * conditional jumps will be made that depend on those values. + * However the length of the match is limited to the lookahead, so + * the output of deflate is not affected by the uninitialized values. + */ #if (defined(UNALIGNED_OK) && MAX_MATCH == 258) - /* This code assumes sizeof(unsigned short) == 2. Do not use - * UNALIGNED_OK if your compiler uses a different size. - */ - if (*(ushf*)(match+best_len-1) != scan_end || - *(ushf*)match != scan_start) continue; - - /* It is not necessary to compare scan[2] and match[2] since they are - * always equal when the other bytes match, given that the hash keys - * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at - * strstart+3, +5, ... up to strstart+257. We check for insufficient - * lookahead only every 4th comparison; the 128th check will be made - * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is - * necessary to put more guard bytes at the end of the window, or - * to check more often for insufficient lookahead. - */ - Assert(scan[2] == match[2], "scan[2]?"); - scan++, match++; - do { - } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) && - *(ushf*)(scan+=2) == *(ushf*)(match+=2) && - *(ushf*)(scan+=2) == *(ushf*)(match+=2) && - *(ushf*)(scan+=2) == *(ushf*)(match+=2) && - scan < strend); - /* The funny "do {}" generates better code on most compilers */ - - /* Here, scan <= window+strstart+257 */ - Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); - if (*scan == *match) scan++; - - len = (MAX_MATCH - 1) - (int)(strend-scan); - scan = strend - (MAX_MATCH-1); + /* + * This code assumes sizeof (unsigned short) == 2. Do not use + * UNALIGNED_OK if your compiler uses a different size. + */ + if (*(ushf*)(match+best_len-1) != scan_end || + *(ushf*)match != scan_start) + continue; + + /* + * It is not necessary to compare scan[2] and match[2] since they are + * always equal when the other bytes match, given that the hash keys + * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at + * strstart+3, +5, ... up to strstart+257. We check for insufficient + * lookahead only every 4th comparison; the 128th check will be made + * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is + * necessary to put more guard bytes at the end of the window, or + * to check more often for insufficient lookahead. + */ + Assert(scan[2] == match[2], "scan[2]?"); + scan++, match++; + do { + } while (*(ushf*)(scan += 2) == *(ushf*)(match += 2) && + *(ushf*)(scan += 2) == *(ushf*)(match += 2) && + *(ushf*)(scan += 2) == *(ushf*)(match += 2) && + *(ushf*)(scan += 2) == *(ushf*)(match += 2) && + scan < strend); + /* The funny "do {}" generates better code on most compilers */ + + /* Here, scan <= window+strstart+257 */ + Assert(scan <= s->window+(unsigned)(s->window_size-1), + "wild scan"); + if (*scan == *match) scan++; + + len = (MAX_MATCH - 1) - (int)(strend-scan); + scan = strend - (MAX_MATCH-1); #else /* UNALIGNED_OK */ - if (match[best_len] != scan_end || - match[best_len-1] != scan_end1 || - *match != *scan || - *++match != scan[1]) continue; - - /* The check at best_len-1 can be removed because it will be made - * again later. (This heuristic is not always a win.) - * It is not necessary to compare scan[2] and match[2] since they - * are always equal when the other bytes match, given that - * the hash keys are equal and that HASH_BITS >= 8. - */ - scan += 2, match++; - Assert(*scan == *match, "match[2]?"); - - /* We check for insufficient lookahead only every 8th comparison; - * the 256th check will be made at strstart+258. - */ - do { - } while (*++scan == *++match && *++scan == *++match && - *++scan == *++match && *++scan == *++match && - *++scan == *++match && *++scan == *++match && - *++scan == *++match && *++scan == *++match && - scan < strend); - - Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); - - len = MAX_MATCH - (int)(strend - scan); - scan = strend - MAX_MATCH; + if (match[best_len] != scan_end || + match[best_len-1] != scan_end1 || + *match != *scan || + *++match != scan[1]) + continue; + + /* + * The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2, match++; + Assert(*scan == *match, "match[2]?"); + + /* + * We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + } while (*++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + scan < strend); + + Assert(scan <= s->window+(unsigned)(s->window_size-1), + "wild scan"); + + len = MAX_MATCH - (int)(strend - scan); + scan = strend - MAX_MATCH; #endif /* UNALIGNED_OK */ - if (len > best_len) { - s->match_start = cur_match; - best_len = len; - if (len >= nice_match) break; + if (len > best_len) { + s->match_start = cur_match; + best_len = len; + if (len >= nice_match) + break; #ifdef UNALIGNED_OK - scan_end = *(ushf*)(scan+best_len-1); + scan_end = *(ushf*)(scan+best_len-1); #else - scan_end1 = scan[best_len-1]; - scan_end = scan[best_len]; + scan_end1 = scan[best_len-1]; + scan_end = scan[best_len]; #endif - } - } while ((cur_match = prev[cur_match & wmask]) > limit - && --chain_length != 0); + } + } while ((cur_match = prev[cur_match & wmask]) > limit && + --chain_length != 0); - if ((uInt)best_len <= s->lookahead) return (uInt)best_len; - return s->lookahead; + if ((uInt)best_len <= s->lookahead) + return ((uInt)best_len); + return (s->lookahead); } #endif /* ASMV */ #endif /* FASTEST */ -/* --------------------------------------------------------------------------- +/* * Optimized version for level == 1 or strategy == Z_RLE only */ -local uInt longest_match_fast(s, cur_match) - deflate_state *s; - IPos cur_match; /* current match */ +local uInt longest_match_fast( + deflate_state *s, + IPos cur_match) { - register Bytef *scan = s->window + s->strstart; /* current string */ - register Bytef *match; /* matched string */ - register int len; /* length of current match */ - register Bytef *strend = s->window + s->strstart + MAX_MATCH; - - /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. - * It is easy to get rid of this optimization if necessary. - */ - Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + register Bytef *scan = s->window + s->strstart; /* current string */ + register Bytef *match; /* matched string */ + register int len; /* length of current match */ + register Bytef *strend = s->window + s->strstart + MAX_MATCH; - Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); - - Assert(cur_match < s->strstart, "no future"); - - match = s->window + cur_match; - - /* Return failure if the match length is less than 2: - */ - if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1; - - /* The check at best_len-1 can be removed because it will be made - * again later. (This heuristic is not always a win.) - * It is not necessary to compare scan[2] and match[2] since they - * are always equal when the other bytes match, given that - * the hash keys are equal and that HASH_BITS >= 8. - */ - scan += 2, match += 2; - Assert(*scan == *match, "match[2]?"); - - /* We check for insufficient lookahead only every 8th comparison; - * the 256th check will be made at strstart+258. - */ - do { - } while (*++scan == *++match && *++scan == *++match && - *++scan == *++match && *++scan == *++match && - *++scan == *++match && *++scan == *++match && - *++scan == *++match && *++scan == *++match && - scan < strend); - - Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); - - len = MAX_MATCH - (int)(strend - scan); - - if (len < MIN_MATCH) return MIN_MATCH - 1; - - s->match_start = cur_match; - return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead; +/* + * The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, + "need lookahead"); + + Assert(cur_match < s->strstart, "no future"); + + match = s->window + cur_match; + + /* + * Return failure if the match length is less than 2: + */ + if (match[0] != scan[0] || match[1] != scan[1]) + return (MIN_MATCH-1); + + /* + * The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2, match += 2; + Assert(*scan == *match, "match[2]?"); + + /* + * We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + } while (*++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + scan < strend); + + Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (int)(strend - scan); + + if (len < MIN_MATCH) + return (MIN_MATCH - 1); + + s->match_start = cur_match; + return ((uInt)len <= s->lookahead ? (uInt)len : s->lookahead); } #ifdef DEBUG -/* =========================================================================== +/* * Check that the match at match_start is indeed a match. */ -local void check_match(s, start, match, length) - deflate_state *s; - IPos start, match; - int length; +local void check_match( + deflate_state *s, + IPos start, match, + int length) { - /* check that the match is indeed a match */ - if (zmemcmp(s->window + match, - s->window + start, length) != EQUAL) { - fprintf(stderr, " start %u, match %u, length %d\n", - start, match, length); - do { - fprintf(stderr, "%c%c", s->window[match++], s->window[start++]); - } while (--length != 0); - z_error("invalid match"); - } - if (z_verbose > 1) { - fprintf(stderr,"\\[%d,%d]", start-match, length); - do { putc(s->window[start++], stderr); } while (--length != 0); - } + /* check that the match is indeed a match */ + if (zmemcmp(s->window + match, + s->window + start, length) != EQUAL) { + fprintf(stderr, " start %u, match %u, length %d\n", + start, match, length); + do { + fprintf(stderr, "%c%c", s->window[match++], + s->window[start++]); + } while (--length != 0); + z_error("invalid match"); + } + if (z_verbose > 1) { + fprintf(stderr, "\\[%d,%d]", start-match, length); + do { putc(s->window[start++], stderr); } + while (--length != 0) + ; + } } #else -# define check_match(s, start, match, length) +#define check_match(s, start, match, length) #endif /* DEBUG */ -/* =========================================================================== +/* * Fill the window when the lookahead becomes insufficient. * Updates strstart and lookahead. * @@ -1263,122 +1339,134 @@ local void check_match(s, start, match, length) * performed for at least two bytes (required for the zip translate_eol * option -- not supported here). */ -local void fill_window(s) - deflate_state *s; +local void fill_window( + deflate_state *s) { - register unsigned n, m; - register Posf *p; - unsigned more; /* Amount of free space at the end of the window. */ - uInt wsize = s->w_size; - - do { - more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart); - - /* Deal with !@#$% 64K limit: */ - if (sizeof(int) <= 2) { - if (more == 0 && s->strstart == 0 && s->lookahead == 0) { - more = wsize; - - } else if (more == (unsigned)(-1)) { - /* Very unlikely, but possible on 16 bit machine if - * strstart == 0 && lookahead == 1 (input done a byte at time) - */ - more--; - } - } - - /* If the window is almost full and there is insufficient lookahead, - * move the upper half to the lower one to make room in the upper half. - */ - if (s->strstart >= wsize+MAX_DIST(s)) { - - zmemcpy(s->window, s->window+wsize, (unsigned)wsize); - s->match_start -= wsize; - s->strstart -= wsize; /* we now have strstart >= MAX_DIST */ - s->block_start -= (long) wsize; - - /* Slide the hash table (could be avoided with 32 bit values - at the expense of memory usage). We slide even when level == 0 - to keep the hash table consistent if we switch back to level > 0 - later. (Using level 0 permanently is not an optimal usage of - zlib, so we don't care about this pathological case.) - */ - /* %%% avoid this when Z_RLE */ - n = s->hash_size; - p = &s->head[n]; - do { - m = *--p; - *p = (Pos)(m >= wsize ? m-wsize : NIL); - } while (--n); - - n = wsize; + register unsigned n, m; + register Posf *p; + unsigned more; /* Amount of free space at the end of the window. */ + uInt wsize = s->w_size; + + do { + more = (unsigned)(s->window_size -(ulg)s->lookahead + -(ulg)s->strstart); + + /* Deal with !@#$% 64K limit: */ + if (sizeof (int) <= 2) { + if (more == 0 && s->strstart == 0 && + s->lookahead == 0) { + more = wsize; + + } else if (more == (unsigned)(-1)) { + /* + * Very unlikely, but possible on 16 bit machine if + * strstart == 0 && lookahead == 1 (input done a byte at time) + */ + more--; + } + } + + /* + * If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (s->strstart >= wsize+MAX_DIST(s)) { + + zmemcpy(s->window, s->window+wsize, (unsigned)wsize); + s->match_start -= wsize; + /* we now have strstart >= MAX_DIST */ + s->strstart -= wsize; + s->block_start -= (long)wsize; + + /* + * Slide the hash table (could be avoided with 32 bit values + * at the expense of memory usage). We slide even when level == 0 + * to keep the hash table consistent if we switch back to level > 0 + * later. (Using level 0 permanently is not an optimal usage of + * zlib, so we don't care about this pathological case.) + */ + /* %%% avoid this when Z_RLE */ + n = s->hash_size; + p = &s->head[n]; + do { + m = *--p; + *p = (Pos)(m >= wsize ? m-wsize : NIL); + } while (--n); + + n = wsize; #ifndef FASTEST - p = &s->prev[n]; - do { - m = *--p; - *p = (Pos)(m >= wsize ? m-wsize : NIL); - /* If n is not on any hash chain, prev[n] is garbage but - * its value will never be used. - */ - } while (--n); + p = &s->prev[n]; + do { + m = *--p; + *p = (Pos)(m >= wsize ? m-wsize : NIL); + /* + * If n is not on any hash chain, prev[n] is garbage but + * its value will never be used. + */ + } while (--n); #endif - more += wsize; - } - if (s->strm->avail_in == 0) return; - - /* If there was no sliding: - * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && - * more == window_size - lookahead - strstart - * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) - * => more >= window_size - 2*WSIZE + 2 - * In the BIG_MEM or MMAP case (not yet supported), - * window_size == input_size + MIN_LOOKAHEAD && - * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. - * Otherwise, window_size == 2*WSIZE so more >= 2. - * If there was sliding, more >= WSIZE. So in all cases, more >= 2. - */ - Assert(more >= 2, "more < 2"); - - n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more); - s->lookahead += n; - - /* Initialize the hash value now that we have some input: */ - if (s->lookahead >= MIN_MATCH) { - s->ins_h = s->window[s->strstart]; - UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); + more += wsize; + } + if (s->strm->avail_in == 0) + return; + +/* + * If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the BIG_MEM or MMAP case (not yet supported), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. + */ + Assert(more >= 2, "more < 2"); + + n = read_buf(s->strm, s->window + s->strstart + s->lookahead, + more); + s->lookahead += n; + + /* Initialize the hash value now that we have some input: */ + if (s->lookahead >= MIN_MATCH) { + s->ins_h = s->window[s->strstart]; + UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); #if MIN_MATCH != 3 - Call UPDATE_HASH() MIN_MATCH-3 more times + // Call UPDATE_HASH() MIN_MATCH-3 more times #endif - } - /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, - * but this is not important since only literal bytes will be emitted. - */ + } + /* + * If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + * but this is not important since only literal bytes will be emitted. + */ - } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0); + } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0); } -/* =========================================================================== +/* * Flush the current block, with given end-of-file flag. * IN assertion: strstart is set to the end of the current match. */ -#define FLUSH_BLOCK_ONLY(s, eof) { \ - _tr_flush_block(s, (s->block_start >= 0L ? \ - (charf *)&s->window[(unsigned)s->block_start] : \ - (charf *)Z_NULL), \ - (ulg)((long)s->strstart - s->block_start), \ - (eof)); \ - s->block_start = s->strstart; \ - flush_pending(s->strm); \ - Tracev((stderr,"[FLUSH]")); \ +#define FLUSH_BLOCK_ONLY(s, eof) { \ + _tr_flush_block(s, (s->block_start >= 0L ? \ + (charf *)&s->window[(unsigned)s->block_start] : \ + (charf *)Z_NULL), \ + (ulg)((long)s->strstart - s->block_start), \ + (eof)); \ + s->block_start = s->strstart; \ + flush_pending(s->strm); \ + Tracev((stderr, "[FLUSH]")); \ } /* Same but force premature exit if necessary. */ -#define FLUSH_BLOCK(s, eof) { \ - FLUSH_BLOCK_ONLY(s, eof); \ - if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \ +#define FLUSH_BLOCK(s, eof) { \ + FLUSH_BLOCK_ONLY(s, eof); \ + if (s->strm->avail_out == 0) \ + return ((eof) ? finish_started : need_more); \ } -/* =========================================================================== +/* * Copy without compression as much as possible from the input stream, return * the current block state. * This function does not insert new strings in the dictionary since @@ -1387,350 +1475,404 @@ local void fill_window(s) * NOTE: this function should be optimized to avoid extra copying from * window to pending_buf. */ -local block_state deflate_stored(s, flush) - deflate_state *s; - int flush; +local block_state deflate_stored( + deflate_state *s, + int flush) { - /* Stored blocks are limited to 0xffff bytes, pending_buf is limited - * to pending_buf_size, and each stored block has a 5 byte header: - */ - ulg max_block_size = 0xffff; - ulg max_start; - - if (max_block_size > s->pending_buf_size - 5) { - max_block_size = s->pending_buf_size - 5; - } - - /* Copy as much as possible from input to output: */ - for (;;) { - /* Fill the window as much as possible: */ - if (s->lookahead <= 1) { - - Assert(s->strstart < s->w_size+MAX_DIST(s) || - s->block_start >= (long)s->w_size, "slide too late"); - - fill_window(s); - if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more; - - if (s->lookahead == 0) break; /* flush the current block */ - } - Assert(s->block_start >= 0L, "block gone"); - - s->strstart += s->lookahead; - s->lookahead = 0; - - /* Emit a stored block if pending_buf will be full: */ - max_start = s->block_start + max_block_size; - if (s->strstart == 0 || (ulg)s->strstart >= max_start) { - /* strstart == 0 is possible when wraparound on 16-bit machine */ - s->lookahead = (uInt)(s->strstart - max_start); - s->strstart = (uInt)max_start; - FLUSH_BLOCK(s, 0); - } - /* Flush if we may have to slide, otherwise block_start may become - * negative and the data will be gone: - */ - if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) { - FLUSH_BLOCK(s, 0); - } - } - FLUSH_BLOCK(s, flush == Z_FINISH); - return flush == Z_FINISH ? finish_done : block_done; + /* + * Stored blocks are limited to 0xffff bytes, pending_buf is limited + * to pending_buf_size, and each stored block has a 5 byte header: + */ + ulg max_block_size = 0xffff; + ulg max_start; + + if (max_block_size > s->pending_buf_size - 5) { + max_block_size = s->pending_buf_size - 5; + } + + /* Copy as much as possible from input to output: */ + for (;;) { + /* Fill the window as much as possible: */ + if (s->lookahead <= 1) { + + Assert(s->strstart < s->w_size+MAX_DIST(s) || + s->block_start >= (long)s->w_size, + "slide too late"); + + fill_window(s); + if (s->lookahead == 0 && flush == Z_NO_FLUSH) + return (need_more); + + if (s->lookahead == 0) + break; /* flush the current block */ + } + Assert(s->block_start >= 0L, "block gone"); + + s->strstart += s->lookahead; + s->lookahead = 0; + + /* Emit a stored block if pending_buf will be full: */ + max_start = s->block_start + max_block_size; + if (s->strstart == 0 || + (ulg)s->strstart >= max_start) { + /* strstart == 0 is possible when wraparound on 16-bit machine */ + s->lookahead = (uInt)(s->strstart - max_start); + s->strstart = (uInt)max_start; + FLUSH_BLOCK(s, 0); + } + /* + * Flush if we may have to slide, otherwise block_start may become + * negative and the data will be gone: + */ + if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) { + FLUSH_BLOCK(s, 0); + } + } + FLUSH_BLOCK(s, flush == Z_FINISH); + return (flush == Z_FINISH ? finish_done : block_done); } -/* =========================================================================== +/* * Compress as much as possible from the input stream, return the current * block state. * This function does not perform lazy evaluation of matches and inserts * new strings in the dictionary only for unmatched strings or for short * matches. It is used only for the fast compression options. */ -local block_state deflate_fast(s, flush) - deflate_state *s; - int flush; +local block_state +deflate_fast( + deflate_state *s, + int flush) { - IPos hash_head = NIL; /* head of the hash chain */ - int bflush; /* set if current block must be flushed */ - - for (;;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the next match, plus MIN_MATCH bytes to insert the - * string following the next match. - */ - if (s->lookahead < MIN_LOOKAHEAD) { - fill_window(s); - if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { - return need_more; - } - if (s->lookahead == 0) break; /* flush the current block */ - } - - /* Insert the string window[strstart .. strstart+2] in the - * dictionary, and set hash_head to the head of the hash chain: - */ - if (s->lookahead >= MIN_MATCH) { - INSERT_STRING(s, s->strstart, hash_head); - } - - /* Find the longest match, discarding those <= prev_length. - * At this point we have always match_length < MIN_MATCH - */ - if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) { - /* To simplify the code, we prevent matches with the string - * of window index 0 (in particular we have to avoid a match - * of the string with itself at the start of the input file). - */ + IPos hash_head = NIL; /* head of the hash chain */ + int bflush; /* set if current block must be flushed */ + + for (;;) { + /* + * Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s->lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s->lookahead < MIN_LOOKAHEAD && + flush == Z_NO_FLUSH) { + return (need_more); + } + if (s->lookahead == 0) + break; /* flush the current block */ + } + + /* + * Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + if (s->lookahead >= MIN_MATCH) { + INSERT_STRING(s, s->strstart, hash_head); + } + + /* + * Find the longest match, discarding those <= prev_length. + * At this point we have always match_length < MIN_MATCH + */ + if (hash_head != NIL && s->strstart - hash_head <= + MAX_DIST(s)) { + /* + * To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ #ifdef FASTEST - if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) || - (s->strategy == Z_RLE && s->strstart - hash_head == 1)) { - s->match_length = longest_match_fast (s, hash_head); - } + if ((s->strategy != Z_HUFFMAN_ONLY && + s->strategy != Z_RLE) || + (s->strategy == Z_RLE && + s->strstart - hash_head == 1)) { + s->match_length = + longest_match_fast(s, hash_head); + } #else - if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) { - s->match_length = longest_match (s, hash_head); - } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) { - s->match_length = longest_match_fast (s, hash_head); - } + if (s->strategy != Z_HUFFMAN_ONLY && + s->strategy != Z_RLE) { + s->match_length = longest_match(s, hash_head); + } else if (s->strategy == Z_RLE && + s->strstart - hash_head == 1) { + s->match_length = + longest_match_fast(s, hash_head); + } #endif - /* longest_match() or longest_match_fast() sets match_start */ - } - if (s->match_length >= MIN_MATCH) { - check_match(s, s->strstart, s->match_start, s->match_length); + /* longest_match() or longest_match_fast() sets match_start */ + } + if (s->match_length >= MIN_MATCH) { + check_match(s, s->strstart, s->match_start, + s->match_length); - _tr_tally_dist(s, s->strstart - s->match_start, - s->match_length - MIN_MATCH, bflush); + _tr_tally_dist(s, s->strstart - s->match_start, + s->match_length - MIN_MATCH, bflush); - s->lookahead -= s->match_length; + s->lookahead -= s->match_length; - /* Insert new strings in the hash table only if the match length - * is not too large. This saves time but degrades compression. - */ + /* + * Insert new strings in the hash table only if the match length + * is not too large. This saves time but degrades compression. + */ #ifndef FASTEST - if (s->match_length <= s->max_insert_length && - s->lookahead >= MIN_MATCH) { - s->match_length--; /* string at strstart already in table */ - do { - s->strstart++; - INSERT_STRING(s, s->strstart, hash_head); - /* strstart never exceeds WSIZE-MAX_MATCH, so there are - * always MIN_MATCH bytes ahead. - */ - } while (--s->match_length != 0); - s->strstart++; - } else + if (s->match_length <= s->max_insert_length && + s->lookahead >= MIN_MATCH) { + /* string at strstart already in table */ + s->match_length--; + do { + s->strstart++; + INSERT_STRING(s, s->strstart, + hash_head); + /* + * strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ + } while (--s->match_length != 0); + s->strstart++; + } else #endif - { - s->strstart += s->match_length; - s->match_length = 0; - s->ins_h = s->window[s->strstart]; - UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); + { + s->strstart += s->match_length; + s->match_length = 0; + s->ins_h = s->window[s->strstart]; + UPDATE_HASH(s, s->ins_h, + s->window[s->strstart+1]); #if MIN_MATCH != 3 - Call UPDATE_HASH() MIN_MATCH-3 more times + // Call UPDATE_HASH() MIN_MATCH-3 more times #endif - /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not - * matter since it will be recomputed at next deflate call. - */ - } - } else { - /* No match, output a literal byte */ - Tracevv((stderr,"%c", s->window[s->strstart])); - _tr_tally_lit (s, s->window[s->strstart], bflush); - s->lookahead--; - s->strstart++; - } - if (bflush) FLUSH_BLOCK(s, 0); - } - FLUSH_BLOCK(s, flush == Z_FINISH); - return flush == Z_FINISH ? finish_done : block_done; + /* + * If lookahead < MIN_MATCH, ins_h is garbage, but it does not + * matter since it will be recomputed at next deflate call. + */ + } + } else { + /* No match, output a literal byte */ + Tracevv((stderr, "%c", s->window[s->strstart])); + _tr_tally_lit(s, s->window[s->strstart], bflush); + s->lookahead--; + s->strstart++; + } + if (bflush) FLUSH_BLOCK(s, 0); + } + FLUSH_BLOCK(s, flush == Z_FINISH); + return (flush == Z_FINISH ? finish_done : block_done); } #ifndef FASTEST -/* =========================================================================== +/* * Same as above, but achieves better compression. We use a lazy * evaluation for matches: a match is finally adopted only if there is * no better match at the next window position. */ -local block_state deflate_slow(s, flush) - deflate_state *s; - int flush; +local block_state +deflate_slow( + deflate_state *s, + int flush) { - IPos hash_head = NIL; /* head of hash chain */ - int bflush; /* set if current block must be flushed */ - - /* Process the input block. */ - for (;;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the next match, plus MIN_MATCH bytes to insert the - * string following the next match. - */ - if (s->lookahead < MIN_LOOKAHEAD) { - fill_window(s); - if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { - return need_more; - } - if (s->lookahead == 0) break; /* flush the current block */ - } - - /* Insert the string window[strstart .. strstart+2] in the - * dictionary, and set hash_head to the head of the hash chain: - */ - if (s->lookahead >= MIN_MATCH) { - INSERT_STRING(s, s->strstart, hash_head); - } - - /* Find the longest match, discarding those <= prev_length. - */ - s->prev_length = s->match_length, s->prev_match = s->match_start; - s->match_length = MIN_MATCH-1; - - if (hash_head != NIL && s->prev_length < s->max_lazy_match && - s->strstart - hash_head <= MAX_DIST(s)) { - /* To simplify the code, we prevent matches with the string - * of window index 0 (in particular we have to avoid a match - * of the string with itself at the start of the input file). - */ - if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) { - s->match_length = longest_match (s, hash_head); - } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) { - s->match_length = longest_match_fast (s, hash_head); - } - /* longest_match() or longest_match_fast() sets match_start */ - - if (s->match_length <= 5 && (s->strategy == Z_FILTERED + IPos hash_head = NIL; /* head of hash chain */ + int bflush; /* set if current block must be flushed */ + + /* Process the input block. */ + for (;;) { + /* + * Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s->lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s->lookahead < MIN_LOOKAHEAD && + flush == Z_NO_FLUSH) { + return (need_more); + } + if (s->lookahead == 0) + break; /* flush the current block */ + } + + /* + * Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + if (s->lookahead >= MIN_MATCH) { + INSERT_STRING(s, s->strstart, hash_head); + } + + /* + * Find the longest match, discarding those <= prev_length. + */ + s->prev_length = s->match_length, + s->prev_match = s->match_start; + s->match_length = MIN_MATCH-1; + + if (hash_head != NIL && s->prev_length < s->max_lazy_match && + s->strstart - hash_head <= MAX_DIST(s)) { + /* + * To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + if (s->strategy != Z_HUFFMAN_ONLY && + s->strategy != Z_RLE) { + s->match_length = longest_match(s, hash_head); + } else if (s->strategy == Z_RLE && + s->strstart - hash_head == 1) { + s->match_length = + longest_match_fast(s, hash_head); + } + /* longest_match() or longest_match_fast() sets match_start */ + + if (s->match_length <= 5 && + (s->strategy == Z_FILTERED || #if TOO_FAR <= 32767 - || (s->match_length == MIN_MATCH && - s->strstart - s->match_start > TOO_FAR) + (s->match_length == MIN_MATCH && + s->strstart - s->match_start > TOO_FAR) || #endif - )) { - - /* If prev_match is also MIN_MATCH, match_start is garbage - * but we will ignore the current match anyway. - */ - s->match_length = MIN_MATCH-1; - } - } - /* If there was a match at the previous step and the current - * match is not better, output the previous match: - */ - if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) { - uInt max_insert = s->strstart + s->lookahead - MIN_MATCH; - /* Do not insert strings in hash table beyond this. */ - - check_match(s, s->strstart-1, s->prev_match, s->prev_length); - - _tr_tally_dist(s, s->strstart -1 - s->prev_match, - s->prev_length - MIN_MATCH, bflush); - - /* Insert in hash table all strings up to the end of the match. - * strstart-1 and strstart are already inserted. If there is not - * enough lookahead, the last two strings are not inserted in - * the hash table. - */ - s->lookahead -= s->prev_length-1; - s->prev_length -= 2; - do { - if (++s->strstart <= max_insert) { - INSERT_STRING(s, s->strstart, hash_head); - } - } while (--s->prev_length != 0); - s->match_available = 0; - s->match_length = MIN_MATCH-1; - s->strstart++; - - if (bflush) FLUSH_BLOCK(s, 0); - - } else if (s->match_available) { - /* If there was no match at the previous position, output a - * single literal. If there was a match but the current match - * is longer, truncate the previous match to a single literal. - */ - Tracevv((stderr,"%c", s->window[s->strstart-1])); - _tr_tally_lit(s, s->window[s->strstart-1], bflush); - if (bflush) { - FLUSH_BLOCK_ONLY(s, 0); - } - s->strstart++; - s->lookahead--; - if (s->strm->avail_out == 0) return need_more; - } else { - /* There is no previous match to compare with, wait for - * the next step to decide. - */ - s->match_available = 1; - s->strstart++; - s->lookahead--; - } - } - Assert (flush != Z_NO_FLUSH, "no flush?"); - if (s->match_available) { - Tracevv((stderr,"%c", s->window[s->strstart-1])); - _tr_tally_lit(s, s->window[s->strstart-1], bflush); - s->match_available = 0; - } - FLUSH_BLOCK(s, flush == Z_FINISH); - return flush == Z_FINISH ? finish_done : block_done; + 0)) { + + /* + * If prev_match is also MIN_MATCH, match_start is garbage + * but we will ignore the current match anyway. + */ + s->match_length = MIN_MATCH-1; + } + } + /* + * If there was a match at the previous step and the current + * match is not better, output the previous match: + */ + if (s->prev_length >= MIN_MATCH && + s->match_length <= s->prev_length) { + uInt max_insert = + s->strstart + s->lookahead - MIN_MATCH; + /* Do not insert strings in hash table beyond this. */ + + check_match(s, s->strstart-1, s->prev_match, + s->prev_length); + + _tr_tally_dist(s, s->strstart -1 - s->prev_match, + s->prev_length - MIN_MATCH, bflush); + + /* + * Insert in hash table all strings up to the end of the match. + * strstart-1 and strstart are already inserted. If there is not + * enough lookahead, the last two strings are not inserted in + * the hash table. + */ + s->lookahead -= s->prev_length-1; + s->prev_length -= 2; + do { + if (++s->strstart <= max_insert) { + INSERT_STRING(s, s->strstart, + hash_head); + } + } while (--s->prev_length != 0); + s->match_available = 0; + s->match_length = MIN_MATCH-1; + s->strstart++; + + if (bflush) FLUSH_BLOCK(s, 0); + + } else if (s->match_available) { + /* + * If there was no match at the previous position, output a + * single literal. If there was a match but the current match + * is longer, truncate the previous match to a single literal. + */ + Tracevv((stderr, "%c", s->window[s->strstart-1])); + _tr_tally_lit(s, s->window[s->strstart-1], bflush); + if (bflush) { + FLUSH_BLOCK_ONLY(s, 0); + } + s->strstart++; + s->lookahead--; + if (s->strm->avail_out == 0) + return (need_more); + } else { + /* + * There is no previous match to compare with, wait for + * the next step to decide. + */ + s->match_available = 1; + s->strstart++; + s->lookahead--; + } + } + Assert(flush != Z_NO_FLUSH, "no flush?"); + if (s->match_available) { + Tracevv((stderr, "%c", s->window[s->strstart-1])); + _tr_tally_lit(s, s->window[s->strstart-1], bflush); + s->match_available = 0; + } + FLUSH_BLOCK(s, flush == Z_FINISH); + return (flush == Z_FINISH ? finish_done : block_done); } #endif /* FASTEST */ #if 0 -/* =========================================================================== +/* * For Z_RLE, simply look for runs of bytes, generate matches only of distance * one. Do not maintain a hash table. (It will be regenerated if this run of * deflate switches away from Z_RLE.) */ -local block_state deflate_rle(s, flush) - deflate_state *s; - int flush; +local block_state +deflate_rle( + deflate_state *s, + int flush) { - int bflush; /* set if current block must be flushed */ - uInt run; /* length of run */ - uInt max; /* maximum length of run */ - uInt prev; /* byte at distance one to match */ - Bytef *scan; /* scan for end of run */ - - for (;;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the longest encodable run. - */ - if (s->lookahead < MAX_MATCH) { - fill_window(s); - if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) { - return need_more; - } - if (s->lookahead == 0) break; /* flush the current block */ - } - - /* See how many times the previous byte repeats */ - run = 0; - if (s->strstart > 0) { /* if there is a previous byte, that is */ - max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH; - scan = s->window + s->strstart - 1; - prev = *scan++; - do { - if (*scan++ != prev) - break; - } while (++run < max); - } - - /* Emit match if have run of MIN_MATCH or longer, else emit literal */ - if (run >= MIN_MATCH) { - check_match(s, s->strstart, s->strstart - 1, run); - _tr_tally_dist(s, 1, run - MIN_MATCH, bflush); - s->lookahead -= run; - s->strstart += run; - } else { - /* No match, output a literal byte */ - Tracevv((stderr,"%c", s->window[s->strstart])); - _tr_tally_lit (s, s->window[s->strstart], bflush); - s->lookahead--; - s->strstart++; - } - if (bflush) FLUSH_BLOCK(s, 0); - } - FLUSH_BLOCK(s, flush == Z_FINISH); - return flush == Z_FINISH ? finish_done : block_done; + int bflush; /* set if current block must be flushed */ + uInt run; /* length of run */ + uInt max; /* maximum length of run */ + uInt prev; /* byte at distance one to match */ + Bytef *scan; /* scan for end of run */ + + for (;;) { + /* + * Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the longest encodable run. + */ + if (s->lookahead < MAX_MATCH) { + fill_window(s); + if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) { + return (need_more); + } + if (s->lookahead == 0) + break; /* flush the current block */ + } + + /* See how many times the previous byte repeats */ + run = 0; + /* if there is a previous byte, that is */ + if (s->strstart > 0) { + max = s->lookahead < MAX_MATCH ? + s->lookahead : MAX_MATCH; + scan = s->window + s->strstart - 1; + prev = *scan++; + do { + if (*scan++ != prev) + break; + } while (++run < max); + } + +/* Emit match if have run of MIN_MATCH or longer, else emit literal */ + if (run >= MIN_MATCH) { + check_match(s, s->strstart, s->strstart - 1, run); + _tr_tally_dist(s, 1, run - MIN_MATCH, bflush); + s->lookahead -= run; + s->strstart += run; + } else { + /* No match, output a literal byte */ + Tracevv((stderr, "%c", s->window[s->strstart])); + _tr_tally_lit(s, s->window[s->strstart], bflush); + s->lookahead--; + s->strstart++; + } + if (bflush) FLUSH_BLOCK(s, 0); + } + FLUSH_BLOCK(s, flush == Z_FINISH); + return (flush == Z_FINISH ? finish_done : block_done); } #endif diff --git a/lib/os/windows/zlib-1.2.3/deflate.h b/lib/os/windows/zlib-1.2.3/deflate.h index 4a340558f49..64251069c38 100644 --- a/lib/os/windows/zlib-1.2.3/deflate.h +++ b/lib/os/windows/zlib-1.2.3/deflate.h @@ -1,295 +1,323 @@ -/* deflate.h -- internal compression state +/* + * deflate.h -- internal compression state * Copyright (C) 1995-2004 Jean-loup Gailly * For conditions of distribution and use, see copyright notice in zlib.h */ -/* WARNING: this file should *not* be used by applications. It is - part of the implementation of the compression library and is - subject to change. Applications should only use zlib.h. +/* + * WARNING: this file should *not* be used by applications. It is + * part of the implementation of the compression library and is + * subject to change. Applications should only use zlib.h. */ /* @(#) $Id$ */ #ifndef DEFLATE_H -#define DEFLATE_H +#define DEFLATE_H #include "zutil.h" -/* define NO_GZIP when compiling if you want to disable gzip header and - trailer creation by deflate(). NO_GZIP would be used to avoid linking in - the crc code when it is not needed. For shared libraries, gzip encoding - should be left enabled. */ +/* + * define NO_GZIP when compiling if you want to disable gzip header and + * trailer creation by deflate(). NO_GZIP would be used to avoid linking in + * the crc code when it is not needed. For shared libraries, gzip encoding + * should be left enabled. + */ #ifndef NO_GZIP -# define GZIP +#define GZIP #endif -/* =========================================================================== +/* * Internal compression state. */ -#define LENGTH_CODES 29 +#define LENGTH_CODES 29 /* number of length codes, not counting the special END_BLOCK code */ -#define LITERALS 256 +#define LITERALS 256 /* number of literal bytes 0..255 */ -#define L_CODES (LITERALS+1+LENGTH_CODES) +#define L_CODES (LITERALS+1+LENGTH_CODES) /* number of Literal or Length codes, including the END_BLOCK code */ -#define D_CODES 30 +#define D_CODES 30 /* number of distance codes */ -#define BL_CODES 19 +#define BL_CODES 19 /* number of codes used to transfer the bit lengths */ -#define HEAP_SIZE (2*L_CODES+1) +#define HEAP_SIZE (2*L_CODES+1) /* maximum heap size */ -#define MAX_BITS 15 +#define MAX_BITS 15 /* All codes must not exceed MAX_BITS bits */ -#define INIT_STATE 42 -#define EXTRA_STATE 69 -#define NAME_STATE 73 -#define COMMENT_STATE 91 -#define HCRC_STATE 103 -#define BUSY_STATE 113 -#define FINISH_STATE 666 +#define INIT_STATE 42 +#define EXTRA_STATE 69 +#define NAME_STATE 73 +#define COMMENT_STATE 91 +#define HCRC_STATE 103 +#define BUSY_STATE 113 +#define FINISH_STATE 666 /* Stream status */ /* Data structure describing a single value and its code string. */ typedef struct ct_data_s { - union { - ush freq; /* frequency count */ - ush code; /* bit string */ - } fc; - union { - ush dad; /* father node in Huffman tree */ - ush len; /* length of bit string */ - } dl; + union { + ush freq; /* frequency count */ + ush code; /* bit string */ + } fc; + union { + ush dad; /* father node in Huffman tree */ + ush len; /* length of bit string */ + } dl; } FAR ct_data; -#define Freq fc.freq -#define Code fc.code -#define Dad dl.dad -#define Len dl.len +#define Freq fc.freq +#define Code fc.code +#define Dad dl.dad +#define Len dl.len typedef struct static_tree_desc_s static_tree_desc; typedef struct tree_desc_s { - ct_data *dyn_tree; /* the dynamic tree */ - int max_code; /* largest code with non zero frequency */ - static_tree_desc *stat_desc; /* the corresponding static tree */ + ct_data *dyn_tree; /* the dynamic tree */ + int max_code; /* largest code with non zero frequency */ + static_tree_desc *stat_desc; /* the corresponding static tree */ } FAR tree_desc; typedef ush Pos; typedef Pos FAR Posf; typedef unsigned IPos; -/* A Pos is an index in the character window. We use short instead of int to +/* + * A Pos is an index in the character window. We use short instead of int to * save space in the various tables. IPos is used only for parameter passing. */ typedef struct internal_state { - z_streamp strm; /* pointer back to this zlib stream */ - int status; /* as the name implies */ - Bytef *pending_buf; /* output still pending */ - ulg pending_buf_size; /* size of pending_buf */ - Bytef *pending_out; /* next pending byte to output to the stream */ - uInt pending; /* nb of bytes in the pending buffer */ - int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ - gz_headerp gzhead; /* gzip header information to write */ - uInt gzindex; /* where in extra, name, or comment */ - Byte method; /* STORED (for zip only) or DEFLATED */ - int last_flush; /* value of flush param for previous deflate call */ - - /* used by deflate.c: */ - - uInt w_size; /* LZ77 window size (32K by default) */ - uInt w_bits; /* log2(w_size) (8..16) */ - uInt w_mask; /* w_size - 1 */ - - Bytef *window; - /* Sliding window. Input bytes are read into the second half of the window, - * and move to the first half later to keep a dictionary of at least wSize - * bytes. With this organization, matches are limited to a distance of - * wSize-MAX_MATCH bytes, but this ensures that IO is always - * performed with a length multiple of the block size. Also, it limits - * the window size to 64K, which is quite useful on MSDOS. - * To do: use the user input buffer as sliding window. - */ - - ulg window_size; - /* Actual size of window: 2*wSize, except when the user input buffer - * is directly used as sliding window. - */ - - Posf *prev; - /* Link to older string with same hash index. To limit the size of this - * array to 64K, this link is maintained only for the last 32K strings. - * An index in this array is thus a window index modulo 32K. - */ - - Posf *head; /* Heads of the hash chains or NIL. */ - - uInt ins_h; /* hash index of string to be inserted */ - uInt hash_size; /* number of elements in hash table */ - uInt hash_bits; /* log2(hash_size) */ - uInt hash_mask; /* hash_size-1 */ - - uInt hash_shift; - /* Number of bits by which ins_h must be shifted at each input - * step. It must be such that after MIN_MATCH steps, the oldest - * byte no longer takes part in the hash key, that is: - * hash_shift * MIN_MATCH >= hash_bits - */ - - long block_start; - /* Window position at the beginning of the current output block. Gets - * negative when the window is moved backwards. - */ - - uInt match_length; /* length of best match */ - IPos prev_match; /* previous match */ - int match_available; /* set if previous match exists */ - uInt strstart; /* start of string to insert */ - uInt match_start; /* start of matching string */ - uInt lookahead; /* number of valid bytes ahead in window */ - - uInt prev_length; - /* Length of the best match at previous step. Matches not greater than this - * are discarded. This is used in the lazy match evaluation. - */ - - uInt max_chain_length; - /* To speed up deflation, hash chains are never searched beyond this - * length. A higher limit improves compression ratio but degrades the - * speed. - */ - - uInt max_lazy_match; - /* Attempt to find a better match only when the current match is strictly - * smaller than this value. This mechanism is used only for compression - * levels >= 4. - */ -# define max_insert_length max_lazy_match - /* Insert new strings in the hash table only if the match length is not - * greater than this length. This saves time but degrades compression. - * max_insert_length is used only for compression levels <= 3. - */ - - int level; /* compression level (1..9) */ - int strategy; /* favor or force Huffman coding*/ - - uInt good_match; - /* Use a faster search when the previous match is longer than this */ - - int nice_match; /* Stop searching when current match exceeds this */ - - /* used by trees.c: */ - /* Didn't use ct_data typedef below to supress compiler warning */ - struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ - struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ - struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ - - struct tree_desc_s l_desc; /* desc. for literal tree */ - struct tree_desc_s d_desc; /* desc. for distance tree */ - struct tree_desc_s bl_desc; /* desc. for bit length tree */ - - ush bl_count[MAX_BITS+1]; - /* number of codes at each bit length for an optimal tree */ - - int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ - int heap_len; /* number of elements in the heap */ - int heap_max; /* element of largest frequency */ - /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. - * The same heap array is used to build all trees. - */ - - uch depth[2*L_CODES+1]; - /* Depth of each subtree used as tie breaker for trees of equal frequency - */ - - uchf *l_buf; /* buffer for literals or lengths */ - - uInt lit_bufsize; - /* Size of match buffer for literals/lengths. There are 4 reasons for - * limiting lit_bufsize to 64K: - * - frequencies can be kept in 16 bit counters - * - if compression is not successful for the first block, all input - * data is still in the window so we can still emit a stored block even - * when input comes from standard input. (This can also be done for - * all blocks if lit_bufsize is not greater than 32K.) - * - if compression is not successful for a file smaller than 64K, we can - * even emit a stored file instead of a stored block (saving 5 bytes). - * This is applicable only for zip (not gzip or zlib). - * - creating new Huffman trees less frequently may not provide fast - * adaptation to changes in the input data statistics. (Take for - * example a binary file with poorly compressible code followed by - * a highly compressible string table.) Smaller buffer sizes give - * fast adaptation but have of course the overhead of transmitting - * trees more frequently. - * - I can't count above 4 - */ - - uInt last_lit; /* running index in l_buf */ - - ushf *d_buf; - /* Buffer for distances. To simplify the code, d_buf and l_buf have - * the same number of elements. To use different lengths, an extra flag - * array would be necessary. - */ - - ulg opt_len; /* bit length of current block with optimal trees */ - ulg static_len; /* bit length of current block with static trees */ - uInt matches; /* number of string matches in current block */ - int last_eob_len; /* bit length of EOB code for last block */ + z_streamp strm; /* pointer back to this zlib stream */ + int status; /* as the name implies */ + Bytef *pending_buf; /* output still pending */ + ulg pending_buf_size; /* size of pending_buf */ + Bytef *pending_out; /* next pending byte to output to the stream */ + uInt pending; /* nb of bytes in the pending buffer */ + int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ + gz_headerp gzhead; /* gzip header information to write */ + uInt gzindex; /* where in extra, name, or comment */ + Byte method; /* STORED (for zip only) or DEFLATED */ + int last_flush; /* value of flush param for previous deflate call */ + + /* used by deflate.c: */ + + uInt w_size; /* LZ77 window size (32K by default) */ + uInt w_bits; /* log2(w_size) (8..16) */ + uInt w_mask; /* w_size - 1 */ + + Bytef *window; + /* + * Sliding window. Input bytes are read into the second half of the + * window, and move to the first half later to keep a dictionary + * of at least wSize bytes. With this organization, matches + * are limited to a distance of + * wSize-MAX_MATCH bytes, but this ensures that IO is always + * performed with a length multiple of the block size. Also, it limits + * the window size to 64K, which is quite useful on MSDOS. + * To do: use the user input buffer as sliding window. + */ + + ulg window_size; + /* + * Actual size of window: 2*wSize, except when the user input buffer + * is directly used as sliding window. + */ + + Posf *prev; + /* + * Link to older string with same hash index. To limit the size of this + * array to 64K, this link is maintained only for the last 32K strings. + * An index in this array is thus a window index modulo 32K. + */ + + Posf *head; /* Heads of the hash chains or NIL. */ + + uInt ins_h; /* hash index of string to be inserted */ + uInt hash_size; /* number of elements in hash table */ + uInt hash_bits; /* log2(hash_size) */ + uInt hash_mask; /* hash_size-1 */ + + uInt hash_shift; + /* + * Number of bits by which ins_h must be shifted at each input + * step. It must be such that after MIN_MATCH steps, the oldest + * byte no longer takes part in the hash key, that is: + * hash_shift * MIN_MATCH >= hash_bits + */ + + long block_start; + /* + * Window position at the beginning of the current output block. Gets + * negative when the window is moved backwards. + */ + + uInt match_length; /* length of best match */ + IPos prev_match; /* previous match */ + int match_available; /* set if previous match exists */ + uInt strstart; /* start of string to insert */ + uInt match_start; /* start of matching string */ + uInt lookahead; /* number of valid bytes ahead in window */ + + uInt prev_length; + /* + * Length of the best match at previous step. Matches not greater than + * this are discarded. This is used in the lazy match evaluation. + */ + + uInt max_chain_length; + /* + * To speed up deflation, hash chains are never searched beyond this + * length. A higher limit improves compression ratio but degrades the + * speed. + */ + + uInt max_lazy_match; + /* + * Attempt to find a better match only when the current match is + * strictly smaller than this value. This mechanism is used only + * for compression + * levels >= 4. + */ +#define max_insert_length max_lazy_match + /* + * Insert new strings in the hash table only if the match length is not + * greater than this length. This saves time but degrades compression. + * max_insert_length is used only for compression levels <= 3. + */ + + int level; /* compression level (1..9) */ + int strategy; /* favor or force Huffman coding */ + + uInt good_match; + /* Use a faster search when the previous match is longer than this */ + + int nice_match; /* Stop searching when current match exceeds this */ + + /* used by trees.c: */ + /* Didn't use ct_data typedef below to supress compiler warning */ + struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ + struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ + struct ct_data_s bl_tree[2*BL_CODES+1]; + + struct tree_desc_s l_desc; /* desc. for literal tree */ + struct tree_desc_s d_desc; /* desc. for distance tree */ + struct tree_desc_s bl_desc; /* desc. for bit length tree */ + + ush bl_count[MAX_BITS+1]; + /* number of codes at each bit length for an optimal tree */ + + int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ + int heap_len; /* number of elements in the heap */ + int heap_max; /* element of largest frequency */ + /* + * The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is + * not used. + * The same heap array is used to build all trees. + */ + + uch depth[2*L_CODES+1]; + /* + * Depth of each subtree used as tie breaker for trees of equal + * frequency + */ + + uchf *l_buf; /* buffer for literals or lengths */ + + uInt lit_bufsize; + /* + * Size of match buffer for literals/lengths. There are 4 reasons for + * limiting lit_bufsize to 64K: + * - frequencies can be kept in 16 bit counters + * - if compression is not successful for the first block, all input + * data is still in the window so we can still emit a stored block even + * when input comes from standard input. (This can also be done for + * all blocks if lit_bufsize is not greater than 32K.) + * if compression is not successful for a file smaller than 64K, we can + * even emit a stored file instead of a stored block (saving 5 bytes). + * This is applicable only for zip (not gzip or zlib). + * - creating new Huffman trees less frequently may not provide fast + * adaptation to changes in the input data statistics. (Take for + * example a binary file with poorly compressible code followed by + * a highly compressible string table.) Smaller buffer sizes give + * fast adaptation but have of course the overhead of transmitting + * trees more frequently. + * - I can't count above 4 + */ + + uInt last_lit; /* running index in l_buf */ + + ushf *d_buf; + /* + * Buffer for distances. To simplify the code, d_buf and l_buf have + * the same number of elements. To use different lengths, an extra flag + * array would be necessary. + */ + + ulg opt_len; /* bit length of current block with optimal trees */ + ulg static_len; /* bit length of current block with static trees */ + uInt matches; /* number of string matches in current block */ + int last_eob_len; /* bit length of EOB code for last block */ #ifdef DEBUG - ulg compressed_len; /* total bit length of compressed file mod 2^32 */ - ulg bits_sent; /* bit length of compressed data sent mod 2^32 */ + ulg compressed_len; /* total bit length of compressed file mod 2^32 */ + ulg bits_sent; /* bit length of compressed data sent mod 2^32 */ #endif - ush bi_buf; - /* Output buffer. bits are inserted starting at the bottom (least - * significant bits). - */ - int bi_valid; - /* Number of valid bits in bi_buf. All bits above the last valid bit - * are always zero. - */ + ush bi_buf; + /* + * Output buffer. bits are inserted starting at the bottom (least + * significant bits). + */ + int bi_valid; + /* + * Number of valid bits in bi_buf. All bits above the last valid bit + * are always zero. + */ } FAR deflate_state; -/* Output a byte on the stream. +/* + * Output a byte on the stream. * IN assertion: there is enough room in pending_buf. */ -#define put_byte(s, c) {s->pending_buf[s->pending++] = (Byte) (c);} +#define put_byte(s, c) {s->pending_buf[s->pending++] = (Byte) (c); } -#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) -/* Minimum amount of lookahead, except at the end of the input file. +#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) +/* + * Minimum amount of lookahead, except at the end of the input file. * See deflate.c for comments about the MIN_MATCH+1. */ -#define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD) -/* In order to simplify the code, particularly on 16 bit machines, match +#define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD) +/* + * In order to simplify the code, particularly on 16 bit machines, match * distances are limited to MAX_DIST instead of WSIZE. */ - /* in trees.c */ -void _tr_init OF((deflate_state *s)); -int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc)); -void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len, - int eof)); -void _tr_align OF((deflate_state *s)); +/* in trees.c */ +void _tr_init OF((deflate_state *s)); +int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc)); +void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len, + int eof)); +void _tr_align OF((deflate_state *s)); void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len, - int eof)); + int eof)); -#define d_code(dist) \ - ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)]) -/* Mapping from a distance to a distance code. dist is the distance - 1 and +#define d_code(dist) \ + ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)]) +/* + * Mapping from a distance to a distance code. dist is the distance - 1 and * must not have side effects. _dist_code[256] and _dist_code[257] are never * used. */ @@ -298,34 +326,34 @@ void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len, /* Inline versions of _tr_tally for speed: */ #if defined(GEN_TREES_H) || !defined(STDC) - extern uch _length_code[]; - extern uch _dist_code[]; +extern uch _length_code[]; +extern uch _dist_code[]; #else - extern const uch _length_code[]; - extern const uch _dist_code[]; +extern const uch _length_code[]; +extern const uch _dist_code[]; #endif -# define _tr_tally_lit(s, c, flush) \ - { uch cc = (c); \ - s->d_buf[s->last_lit] = 0; \ - s->l_buf[s->last_lit++] = cc; \ - s->dyn_ltree[cc].Freq++; \ - flush = (s->last_lit == s->lit_bufsize-1); \ - } -# define _tr_tally_dist(s, distance, length, flush) \ - { uch len = (length); \ - ush dist = (distance); \ - s->d_buf[s->last_lit] = dist; \ - s->l_buf[s->last_lit++] = len; \ - dist--; \ - s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \ - s->dyn_dtree[d_code(dist)].Freq++; \ - flush = (s->last_lit == s->lit_bufsize-1); \ - } +#define _tr_tally_lit(s, c, flush) \ + { uch cc = (c); \ + s->d_buf[s->last_lit] = 0; \ + s->l_buf[s->last_lit++] = cc; \ + s->dyn_ltree[cc].Freq++; \ + flush = (s->last_lit == s->lit_bufsize-1); \ + } +#define _tr_tally_dist(s, distance, length, flush) \ + { uch len = (length); \ + ush dist = (distance); \ + s->d_buf[s->last_lit] = dist; \ + s->l_buf[s->last_lit++] = len; \ + dist--; \ + s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \ + s->dyn_dtree[d_code(dist)].Freq++; \ + flush = (s->last_lit == s->lit_bufsize-1); \ + } #else -# define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c) -# define _tr_tally_dist(s, distance, length, flush) \ - flush = _tr_tally(s, distance, length) +#define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c) +#define _tr_tally_dist(s, distance, length, flush) \ + flush = _tr_tally(s, distance, length) #endif #endif /* DEFLATE_H */ diff --git a/lib/os/windows/zlib-1.2.3/example.c b/lib/os/windows/zlib-1.2.3/example.c deleted file mode 100644 index 6c8a0ee7633..00000000000 --- a/lib/os/windows/zlib-1.2.3/example.c +++ /dev/null @@ -1,565 +0,0 @@ -/* example.c -- usage example of the zlib compression library - * Copyright (C) 1995-2004 Jean-loup Gailly. - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* @(#) $Id$ */ - -#include -#include "zlib.h" - -#ifdef STDC -# include -# include -#endif - -#if defined(VMS) || defined(RISCOS) -# define TESTFILE "foo-gz" -#else -# define TESTFILE "foo.gz" -#endif - -#define CHECK_ERR(err, msg) { \ - if (err != Z_OK) { \ - fprintf(stderr, "%s error: %d\n", msg, err); \ - exit(1); \ - } \ -} - -const char hello[] = "hello, hello!"; -/* "hello world" would be more standard, but the repeated "hello" - * stresses the compression code better, sorry... - */ - -const char dictionary[] = "hello"; -uLong dictId; /* Adler32 value of the dictionary */ - -void test_compress OF((Byte *compr, uLong comprLen, - Byte *uncompr, uLong uncomprLen)); -void test_gzio OF((const char *fname, - Byte *uncompr, uLong uncomprLen)); -void test_deflate OF((Byte *compr, uLong comprLen)); -void test_inflate OF((Byte *compr, uLong comprLen, - Byte *uncompr, uLong uncomprLen)); -void test_large_deflate OF((Byte *compr, uLong comprLen, - Byte *uncompr, uLong uncomprLen)); -void test_large_inflate OF((Byte *compr, uLong comprLen, - Byte *uncompr, uLong uncomprLen)); -void test_flush OF((Byte *compr, uLong *comprLen)); -void test_sync OF((Byte *compr, uLong comprLen, - Byte *uncompr, uLong uncomprLen)); -void test_dict_deflate OF((Byte *compr, uLong comprLen)); -void test_dict_inflate OF((Byte *compr, uLong comprLen, - Byte *uncompr, uLong uncomprLen)); -int main OF((int argc, char *argv[])); - -/* =========================================================================== - * Test compress() and uncompress() - */ -void test_compress(compr, comprLen, uncompr, uncomprLen) - Byte *compr, *uncompr; - uLong comprLen, uncomprLen; -{ - int err; - uLong len = (uLong)strlen(hello)+1; - - err = compress(compr, &comprLen, (const Bytef*)hello, len); - CHECK_ERR(err, "compress"); - - strcpy((char*)uncompr, "garbage"); - - err = uncompress(uncompr, &uncomprLen, compr, comprLen); - CHECK_ERR(err, "uncompress"); - - if (strcmp((char*)uncompr, hello)) { - fprintf(stderr, "bad uncompress\n"); - exit(1); - } else { - printf("uncompress(): %s\n", (char *)uncompr); - } -} - -/* =========================================================================== - * Test read/write of .gz files - */ -void test_gzio(fname, uncompr, uncomprLen) - const char *fname; /* compressed file name */ - Byte *uncompr; - uLong uncomprLen; -{ -#ifdef NO_GZCOMPRESS - fprintf(stderr, "NO_GZCOMPRESS -- gz* functions cannot compress\n"); -#else - int err; - int len = (int)strlen(hello)+1; - gzFile file; - z_off_t pos; - - file = gzopen(fname, "wb"); - if (file == NULL) { - fprintf(stderr, "gzopen error\n"); - exit(1); - } - gzputc(file, 'h'); - if (gzputs(file, "ello") != 4) { - fprintf(stderr, "gzputs err: %s\n", gzerror(file, &err)); - exit(1); - } - if (gzprintf(file, ", %s!", "hello") != 8) { - fprintf(stderr, "gzprintf err: %s\n", gzerror(file, &err)); - exit(1); - } - gzseek(file, 1L, SEEK_CUR); /* add one zero byte */ - gzclose(file); - - file = gzopen(fname, "rb"); - if (file == NULL) { - fprintf(stderr, "gzopen error\n"); - exit(1); - } - strcpy((char*)uncompr, "garbage"); - - if (gzread(file, uncompr, (unsigned)uncomprLen) != len) { - fprintf(stderr, "gzread err: %s\n", gzerror(file, &err)); - exit(1); - } - if (strcmp((char*)uncompr, hello)) { - fprintf(stderr, "bad gzread: %s\n", (char*)uncompr); - exit(1); - } else { - printf("gzread(): %s\n", (char*)uncompr); - } - - pos = gzseek(file, -8L, SEEK_CUR); - if (pos != 6 || gztell(file) != pos) { - fprintf(stderr, "gzseek error, pos=%ld, gztell=%ld\n", - (long)pos, (long)gztell(file)); - exit(1); - } - - if (gzgetc(file) != ' ') { - fprintf(stderr, "gzgetc error\n"); - exit(1); - } - - if (gzungetc(' ', file) != ' ') { - fprintf(stderr, "gzungetc error\n"); - exit(1); - } - - gzgets(file, (char*)uncompr, (int)uncomprLen); - if (strlen((char*)uncompr) != 7) { /* " hello!" */ - fprintf(stderr, "gzgets err after gzseek: %s\n", gzerror(file, &err)); - exit(1); - } - if (strcmp((char*)uncompr, hello + 6)) { - fprintf(stderr, "bad gzgets after gzseek\n"); - exit(1); - } else { - printf("gzgets() after gzseek: %s\n", (char*)uncompr); - } - - gzclose(file); -#endif -} - -/* =========================================================================== - * Test deflate() with small buffers - */ -void test_deflate(compr, comprLen) - Byte *compr; - uLong comprLen; -{ - z_stream c_stream; /* compression stream */ - int err; - uLong len = (uLong)strlen(hello)+1; - - c_stream.zalloc = (alloc_func)0; - c_stream.zfree = (free_func)0; - c_stream.opaque = (voidpf)0; - - err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION); - CHECK_ERR(err, "deflateInit"); - - c_stream.next_in = (Bytef*)hello; - c_stream.next_out = compr; - - while (c_stream.total_in != len && c_stream.total_out < comprLen) { - c_stream.avail_in = c_stream.avail_out = 1; /* force small buffers */ - err = deflate(&c_stream, Z_NO_FLUSH); - CHECK_ERR(err, "deflate"); - } - /* Finish the stream, still forcing small buffers: */ - for (;;) { - c_stream.avail_out = 1; - err = deflate(&c_stream, Z_FINISH); - if (err == Z_STREAM_END) break; - CHECK_ERR(err, "deflate"); - } - - err = deflateEnd(&c_stream); - CHECK_ERR(err, "deflateEnd"); -} - -/* =========================================================================== - * Test inflate() with small buffers - */ -void test_inflate(compr, comprLen, uncompr, uncomprLen) - Byte *compr, *uncompr; - uLong comprLen, uncomprLen; -{ - int err; - z_stream d_stream; /* decompression stream */ - - strcpy((char*)uncompr, "garbage"); - - d_stream.zalloc = (alloc_func)0; - d_stream.zfree = (free_func)0; - d_stream.opaque = (voidpf)0; - - d_stream.next_in = compr; - d_stream.avail_in = 0; - d_stream.next_out = uncompr; - - err = inflateInit(&d_stream); - CHECK_ERR(err, "inflateInit"); - - while (d_stream.total_out < uncomprLen && d_stream.total_in < comprLen) { - d_stream.avail_in = d_stream.avail_out = 1; /* force small buffers */ - err = inflate(&d_stream, Z_NO_FLUSH); - if (err == Z_STREAM_END) break; - CHECK_ERR(err, "inflate"); - } - - err = inflateEnd(&d_stream); - CHECK_ERR(err, "inflateEnd"); - - if (strcmp((char*)uncompr, hello)) { - fprintf(stderr, "bad inflate\n"); - exit(1); - } else { - printf("inflate(): %s\n", (char *)uncompr); - } -} - -/* =========================================================================== - * Test deflate() with large buffers and dynamic change of compression level - */ -void test_large_deflate(compr, comprLen, uncompr, uncomprLen) - Byte *compr, *uncompr; - uLong comprLen, uncomprLen; -{ - z_stream c_stream; /* compression stream */ - int err; - - c_stream.zalloc = (alloc_func)0; - c_stream.zfree = (free_func)0; - c_stream.opaque = (voidpf)0; - - err = deflateInit(&c_stream, Z_BEST_SPEED); - CHECK_ERR(err, "deflateInit"); - - c_stream.next_out = compr; - c_stream.avail_out = (uInt)comprLen; - - /* At this point, uncompr is still mostly zeroes, so it should compress - * very well: - */ - c_stream.next_in = uncompr; - c_stream.avail_in = (uInt)uncomprLen; - err = deflate(&c_stream, Z_NO_FLUSH); - CHECK_ERR(err, "deflate"); - if (c_stream.avail_in != 0) { - fprintf(stderr, "deflate not greedy\n"); - exit(1); - } - - /* Feed in already compressed data and switch to no compression: */ - deflateParams(&c_stream, Z_NO_COMPRESSION, Z_DEFAULT_STRATEGY); - c_stream.next_in = compr; - c_stream.avail_in = (uInt)comprLen/2; - err = deflate(&c_stream, Z_NO_FLUSH); - CHECK_ERR(err, "deflate"); - - /* Switch back to compressing mode: */ - deflateParams(&c_stream, Z_BEST_COMPRESSION, Z_FILTERED); - c_stream.next_in = uncompr; - c_stream.avail_in = (uInt)uncomprLen; - err = deflate(&c_stream, Z_NO_FLUSH); - CHECK_ERR(err, "deflate"); - - err = deflate(&c_stream, Z_FINISH); - if (err != Z_STREAM_END) { - fprintf(stderr, "deflate should report Z_STREAM_END\n"); - exit(1); - } - err = deflateEnd(&c_stream); - CHECK_ERR(err, "deflateEnd"); -} - -/* =========================================================================== - * Test inflate() with large buffers - */ -void test_large_inflate(compr, comprLen, uncompr, uncomprLen) - Byte *compr, *uncompr; - uLong comprLen, uncomprLen; -{ - int err; - z_stream d_stream; /* decompression stream */ - - strcpy((char*)uncompr, "garbage"); - - d_stream.zalloc = (alloc_func)0; - d_stream.zfree = (free_func)0; - d_stream.opaque = (voidpf)0; - - d_stream.next_in = compr; - d_stream.avail_in = (uInt)comprLen; - - err = inflateInit(&d_stream); - CHECK_ERR(err, "inflateInit"); - - for (;;) { - d_stream.next_out = uncompr; /* discard the output */ - d_stream.avail_out = (uInt)uncomprLen; - err = inflate(&d_stream, Z_NO_FLUSH); - if (err == Z_STREAM_END) break; - CHECK_ERR(err, "large inflate"); - } - - err = inflateEnd(&d_stream); - CHECK_ERR(err, "inflateEnd"); - - if (d_stream.total_out != 2*uncomprLen + comprLen/2) { - fprintf(stderr, "bad large inflate: %ld\n", d_stream.total_out); - exit(1); - } else { - printf("large_inflate(): OK\n"); - } -} - -/* =========================================================================== - * Test deflate() with full flush - */ -void test_flush(compr, comprLen) - Byte *compr; - uLong *comprLen; -{ - z_stream c_stream; /* compression stream */ - int err; - uInt len = (uInt)strlen(hello)+1; - - c_stream.zalloc = (alloc_func)0; - c_stream.zfree = (free_func)0; - c_stream.opaque = (voidpf)0; - - err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION); - CHECK_ERR(err, "deflateInit"); - - c_stream.next_in = (Bytef*)hello; - c_stream.next_out = compr; - c_stream.avail_in = 3; - c_stream.avail_out = (uInt)*comprLen; - err = deflate(&c_stream, Z_FULL_FLUSH); - CHECK_ERR(err, "deflate"); - - compr[3]++; /* force an error in first compressed block */ - c_stream.avail_in = len - 3; - - err = deflate(&c_stream, Z_FINISH); - if (err != Z_STREAM_END) { - CHECK_ERR(err, "deflate"); - } - err = deflateEnd(&c_stream); - CHECK_ERR(err, "deflateEnd"); - - *comprLen = c_stream.total_out; -} - -/* =========================================================================== - * Test inflateSync() - */ -void test_sync(compr, comprLen, uncompr, uncomprLen) - Byte *compr, *uncompr; - uLong comprLen, uncomprLen; -{ - int err; - z_stream d_stream; /* decompression stream */ - - strcpy((char*)uncompr, "garbage"); - - d_stream.zalloc = (alloc_func)0; - d_stream.zfree = (free_func)0; - d_stream.opaque = (voidpf)0; - - d_stream.next_in = compr; - d_stream.avail_in = 2; /* just read the zlib header */ - - err = inflateInit(&d_stream); - CHECK_ERR(err, "inflateInit"); - - d_stream.next_out = uncompr; - d_stream.avail_out = (uInt)uncomprLen; - - inflate(&d_stream, Z_NO_FLUSH); - CHECK_ERR(err, "inflate"); - - d_stream.avail_in = (uInt)comprLen-2; /* read all compressed data */ - err = inflateSync(&d_stream); /* but skip the damaged part */ - CHECK_ERR(err, "inflateSync"); - - err = inflate(&d_stream, Z_FINISH); - if (err != Z_DATA_ERROR) { - fprintf(stderr, "inflate should report DATA_ERROR\n"); - /* Because of incorrect adler32 */ - exit(1); - } - err = inflateEnd(&d_stream); - CHECK_ERR(err, "inflateEnd"); - - printf("after inflateSync(): hel%s\n", (char *)uncompr); -} - -/* =========================================================================== - * Test deflate() with preset dictionary - */ -void test_dict_deflate(compr, comprLen) - Byte *compr; - uLong comprLen; -{ - z_stream c_stream; /* compression stream */ - int err; - - c_stream.zalloc = (alloc_func)0; - c_stream.zfree = (free_func)0; - c_stream.opaque = (voidpf)0; - - err = deflateInit(&c_stream, Z_BEST_COMPRESSION); - CHECK_ERR(err, "deflateInit"); - - err = deflateSetDictionary(&c_stream, - (const Bytef*)dictionary, sizeof(dictionary)); - CHECK_ERR(err, "deflateSetDictionary"); - - dictId = c_stream.adler; - c_stream.next_out = compr; - c_stream.avail_out = (uInt)comprLen; - - c_stream.next_in = (Bytef*)hello; - c_stream.avail_in = (uInt)strlen(hello)+1; - - err = deflate(&c_stream, Z_FINISH); - if (err != Z_STREAM_END) { - fprintf(stderr, "deflate should report Z_STREAM_END\n"); - exit(1); - } - err = deflateEnd(&c_stream); - CHECK_ERR(err, "deflateEnd"); -} - -/* =========================================================================== - * Test inflate() with a preset dictionary - */ -void test_dict_inflate(compr, comprLen, uncompr, uncomprLen) - Byte *compr, *uncompr; - uLong comprLen, uncomprLen; -{ - int err; - z_stream d_stream; /* decompression stream */ - - strcpy((char*)uncompr, "garbage"); - - d_stream.zalloc = (alloc_func)0; - d_stream.zfree = (free_func)0; - d_stream.opaque = (voidpf)0; - - d_stream.next_in = compr; - d_stream.avail_in = (uInt)comprLen; - - err = inflateInit(&d_stream); - CHECK_ERR(err, "inflateInit"); - - d_stream.next_out = uncompr; - d_stream.avail_out = (uInt)uncomprLen; - - for (;;) { - err = inflate(&d_stream, Z_NO_FLUSH); - if (err == Z_STREAM_END) break; - if (err == Z_NEED_DICT) { - if (d_stream.adler != dictId) { - fprintf(stderr, "unexpected dictionary"); - exit(1); - } - err = inflateSetDictionary(&d_stream, (const Bytef*)dictionary, - sizeof(dictionary)); - } - CHECK_ERR(err, "inflate with dict"); - } - - err = inflateEnd(&d_stream); - CHECK_ERR(err, "inflateEnd"); - - if (strcmp((char*)uncompr, hello)) { - fprintf(stderr, "bad inflate with dict\n"); - exit(1); - } else { - printf("inflate with dictionary: %s\n", (char *)uncompr); - } -} - -/* =========================================================================== - * Usage: example [output.gz [input.gz]] - */ - -int main(argc, argv) - int argc; - char *argv[]; -{ - Byte *compr, *uncompr; - uLong comprLen = 10000*sizeof(int); /* don't overflow on MSDOS */ - uLong uncomprLen = comprLen; - static const char* myVersion = ZLIB_VERSION; - - if (zlibVersion()[0] != myVersion[0]) { - fprintf(stderr, "incompatible zlib version\n"); - exit(1); - - } else if (strcmp(zlibVersion(), ZLIB_VERSION) != 0) { - fprintf(stderr, "warning: different zlib version\n"); - } - - printf("zlib version %s = 0x%04x, compile flags = 0x%lx\n", - ZLIB_VERSION, ZLIB_VERNUM, zlibCompileFlags()); - - compr = (Byte*)calloc((uInt)comprLen, 1); - uncompr = (Byte*)calloc((uInt)uncomprLen, 1); - /* compr and uncompr are cleared to avoid reading uninitialized - * data and to ensure that uncompr compresses well. - */ - if (compr == Z_NULL || uncompr == Z_NULL) { - printf("out of memory\n"); - exit(1); - } - test_compress(compr, comprLen, uncompr, uncomprLen); - - test_gzio((argc > 1 ? argv[1] : TESTFILE), - uncompr, uncomprLen); - - test_deflate(compr, comprLen); - test_inflate(compr, comprLen, uncompr, uncomprLen); - - test_large_deflate(compr, comprLen, uncompr, uncomprLen); - test_large_inflate(compr, comprLen, uncompr, uncomprLen); - - test_flush(compr, &comprLen); - test_sync(compr, comprLen, uncompr, uncomprLen); - comprLen = uncomprLen; - - test_dict_deflate(compr, comprLen); - test_dict_inflate(compr, comprLen, uncompr, uncomprLen); - - free(compr); - free(uncompr); - - return 0; -} diff --git a/lib/os/windows/zlib-1.2.3/gzio.c b/lib/os/windows/zlib-1.2.3/gzio.c index cb018313d8a..8a8181c80b3 100644 --- a/lib/os/windows/zlib-1.2.3/gzio.c +++ b/lib/os/windows/zlib-1.2.3/gzio.c @@ -1,4 +1,5 @@ -/* gzio.c -- IO on .gz files +/* + * gzio.c -- IO on .gz files * Copyright (C) 1995-2005 Jean-loup Gailly. * For conditions of distribution and use, see copyright notice in zlib.h * @@ -11,28 +12,28 @@ #include "zutil.h" -#ifdef NO_DEFLATE /* for compatibility with old definition */ -# define NO_GZCOMPRESS +#ifdef NO_DEFLATE /* for compatibility with old definition */ +#define NO_GZCOMPRESS #endif #ifndef NO_DUMMY_DECL -struct internal_state {int dummy;}; /* for buggy compilers */ +struct internal_state { int dummy; }; /* for buggy compilers */ #endif #ifndef Z_BUFSIZE -# ifdef MAXSEG_64K -# define Z_BUFSIZE 4096 /* minimize memory usage for 16-bit DOS */ -# else -# define Z_BUFSIZE 16384 -# endif +#ifdef MAXSEG_64K +#define Z_BUFSIZE 4096 /* minimize memory usage for 16-bit DOS */ +#else +#define Z_BUFSIZE 16384 +#endif #endif #ifndef Z_PRINTF_BUFSIZE -# define Z_PRINTF_BUFSIZE 4096 +#define Z_PRINTF_BUFSIZE 4096 #endif #ifdef __MVS__ -# pragma map (fdopen , "\174\174FDOPEN") - FILE *fdopen(int, const char *); +#pragma map(fdopen, "\174\174FDOPEN") +FILE *fdopen(int, const char *); #endif #ifndef STDC @@ -40,987 +41,1076 @@ extern voidp malloc OF((uInt size)); extern void free OF((voidpf ptr)); #endif -#define ALLOC(size) malloc(size) -#define TRYFREE(p) {if (p) free(p);} +#define ALLOC(size) malloc(size) +#define TRYFREE(p) {if (p) free(p); } static int const gz_magic[2] = {0x1f, 0x8b}; /* gzip magic header */ /* gzip flag byte */ -#define ASCII_FLAG 0x01 /* bit 0 set: file probably ascii text */ -#define HEAD_CRC 0x02 /* bit 1 set: header CRC present */ -#define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */ -#define ORIG_NAME 0x08 /* bit 3 set: original file name present */ -#define COMMENT 0x10 /* bit 4 set: file comment present */ -#define RESERVED 0xE0 /* bits 5..7: reserved */ +#define ASCII_FLAG 0x01 /* bit 0 set: file probably ascii text */ +#define HEAD_CRC 0x02 /* bit 1 set: header CRC present */ +#define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */ +#define ORIG_NAME 0x08 /* bit 3 set: original file name present */ +#define COMMENT 0x10 /* bit 4 set: file comment present */ +#define RESERVED 0xE0 /* bits 5..7: reserved */ typedef struct gz_stream { - z_stream stream; - int z_err; /* error code for last stream operation */ - int z_eof; /* set if end of input file */ - FILE *file; /* .gz file */ - Byte *inbuf; /* input buffer */ - Byte *outbuf; /* output buffer */ - uLong crc; /* crc32 of uncompressed data */ - char *msg; /* error message */ - char *path; /* path name for debugging only */ - int transparent; /* 1 if input file is not a .gz file */ - char mode; /* 'w' or 'r' */ - z_off_t start; /* start of compressed data in file (header skipped) */ - z_off_t in; /* bytes into deflate or inflate */ - z_off_t out; /* bytes out of deflate or inflate */ - int back; /* one character push-back */ - int last; /* true if push-back is last character */ + z_stream stream; + int z_err; /* error code for last stream operation */ + int z_eof; /* set if end of input file */ + FILE *file; /* .gz file */ + Byte *inbuf; /* input buffer */ + Byte *outbuf; /* output buffer */ + uLong crc; /* crc32 of uncompressed data */ + char *msg; /* error message */ + char *path; /* path name for debugging only */ + int transparent; /* 1 if input file is not a .gz file */ + char mode; /* 'w' or 'r' */ + z_off_t start; /* start of compressed data in file (header skipped) */ + z_off_t in; /* bytes into deflate or inflate */ + z_off_t out; /* bytes out of deflate or inflate */ + int back; /* one character push-back */ + int last; /* true if push-back is last character */ } gz_stream; -local gzFile gz_open OF((const char *path, const char *mode, int fd)); -local int do_flush OF((gzFile file, int flush)); -local int get_byte OF((gz_stream *s)); +local gzFile gz_open OF((const char *path, const char *mode, int fd)); +local int do_flush OF((gzFile file, int flush)); +local int get_byte OF((gz_stream *s)); local void check_header OF((gz_stream *s)); -local int destroy OF((gz_stream *s)); -local void putLong OF((FILE *file, uLong x)); -local uLong getLong OF((gz_stream *s)); - -/* =========================================================================== - Opens a gzip (.gz) file for reading or writing. The mode parameter - is as in fopen ("rb" or "wb"). The file is given either by file descriptor - or path name (if fd == -1). - gz_open returns NULL if the file could not be opened or if there was - insufficient memory to allocate the (de)compression state; errno - can be checked to distinguish the two cases (if errno is zero, the - zlib error is Z_MEM_ERROR). -*/ -local gzFile gz_open (path, mode, fd) - const char *path; - const char *mode; - int fd; +local int destroy OF((gz_stream *s)); +local void putLong OF((FILE *file, uLong x)); +local uLong getLong OF((gz_stream *s)); + +/* + * Opens a gzip (.gz) file for reading or writing. The mode parameter + * is as in fopen ("rb" or "wb"). The file is given either by file descriptor + * or path name (if fd == -1). + * gz_open returns NULL if the file could not be opened or if there was + * insufficient memory to allocate the (de)compression state; errno + * can be checked to distinguish the two cases (if errno is zero, the + * zlib error is Z_MEM_ERROR). + */ +local gzFile +gz_open( + const char *path, + const char *mode, + int fd) { - int err; - int level = Z_DEFAULT_COMPRESSION; /* compression level */ - int strategy = Z_DEFAULT_STRATEGY; /* compression strategy */ - char *p = (char*)mode; - gz_stream *s; - char fmode[80]; /* copy of mode, without the compression level */ - char *m = fmode; - - if (!path || !mode) return Z_NULL; - - s = (gz_stream *)ALLOC(sizeof(gz_stream)); - if (!s) return Z_NULL; - - s->stream.zalloc = (alloc_func)0; - s->stream.zfree = (free_func)0; - s->stream.opaque = (voidpf)0; - s->stream.next_in = s->inbuf = Z_NULL; - s->stream.next_out = s->outbuf = Z_NULL; - s->stream.avail_in = s->stream.avail_out = 0; - s->file = NULL; - s->z_err = Z_OK; - s->z_eof = 0; - s->in = 0; - s->out = 0; - s->back = EOF; - s->crc = crc32(0L, Z_NULL, 0); - s->msg = NULL; - s->transparent = 0; - - s->path = (char*)ALLOC(strlen(path)+1); - if (s->path == NULL) { - return destroy(s), (gzFile)Z_NULL; - } - strcpy(s->path, path); /* do this early for debugging */ - - s->mode = '\0'; - do { - if (*p == 'r') s->mode = 'r'; - if (*p == 'w' || *p == 'a') s->mode = 'w'; - if (*p >= '0' && *p <= '9') { - level = *p - '0'; - } else if (*p == 'f') { - strategy = Z_FILTERED; - } else if (*p == 'h') { - strategy = Z_HUFFMAN_ONLY; - } else if (*p == 'R') { - strategy = Z_RLE; - } else { - *m++ = *p; /* copy the mode */ - } - } while (*p++ && m != fmode + sizeof(fmode)); - if (s->mode == '\0') return destroy(s), (gzFile)Z_NULL; - - if (s->mode == 'w') { + int err; + int level = Z_DEFAULT_COMPRESSION; /* compression level */ + int strategy = Z_DEFAULT_STRATEGY; /* compression strategy */ + char *p = (char *)mode; + gz_stream *s; + char fmode[80]; /* copy of mode, without the compression level */ + char *m = fmode; + + if (!path || !mode) + return (Z_NULL); + + s = (gz_stream *)ALLOC(sizeof (gz_stream)); + if (!s) + return (Z_NULL); + + s->stream.zalloc = (alloc_func)0; + s->stream.zfree = (free_func)0; + s->stream.opaque = (voidpf)0; + s->stream.next_in = s->inbuf = Z_NULL; + s->stream.next_out = s->outbuf = Z_NULL; + s->stream.avail_in = s->stream.avail_out = 0; + s->file = NULL; + s->z_err = Z_OK; + s->z_eof = 0; + s->in = 0; + s->out = 0; + s->back = EOF; + s->crc = crc32(0L, Z_NULL, 0); + s->msg = NULL; + s->transparent = 0; + + s->path = (char *)ALLOC(strlen(path)+1); + if (s->path == NULL) { + return (destroy(s), (gzFile)Z_NULL); + } + strcpy(s->path, path); /* do this early for debugging */ + + s->mode = '\0'; + do { + if (*p == 'r') s->mode = 'r'; + if (*p == 'w' || *p == 'a') s->mode = 'w'; + if (*p >= '0' && *p <= '9') { + level = *p - '0'; + } else if (*p == 'f') { + strategy = Z_FILTERED; + } else if (*p == 'h') { + strategy = Z_HUFFMAN_ONLY; + } else if (*p == 'R') { + strategy = Z_RLE; + } else { + *m++ = *p; /* copy the mode */ + } + } while (*p++ && m != fmode + sizeof (fmode)); + if (s->mode == '\0') + return (destroy(s), (gzFile)Z_NULL); + + if (s->mode == 'w') { #ifdef NO_GZCOMPRESS - err = Z_STREAM_ERROR; + err = Z_STREAM_ERROR; #else - err = deflateInit2(&(s->stream), level, - Z_DEFLATED, -MAX_WBITS, DEF_MEM_LEVEL, strategy); - /* windowBits is passed < 0 to suppress zlib header */ + err = deflateInit2(&(s->stream), level, + Z_DEFLATED, -MAX_WBITS, DEF_MEM_LEVEL, strategy); + /* windowBits is passed < 0 to suppress zlib header */ - s->stream.next_out = s->outbuf = (Byte*)ALLOC(Z_BUFSIZE); + s->stream.next_out = s->outbuf = (Byte*)ALLOC(Z_BUFSIZE); #endif - if (err != Z_OK || s->outbuf == Z_NULL) { - return destroy(s), (gzFile)Z_NULL; - } - } else { - s->stream.next_in = s->inbuf = (Byte*)ALLOC(Z_BUFSIZE); - - err = inflateInit2(&(s->stream), -MAX_WBITS); - /* windowBits is passed < 0 to tell that there is no zlib header. - * Note that in this case inflate *requires* an extra "dummy" byte - * after the compressed stream in order to complete decompression and - * return Z_STREAM_END. Here the gzip CRC32 ensures that 4 bytes are - * present after the compressed stream. - */ - if (err != Z_OK || s->inbuf == Z_NULL) { - return destroy(s), (gzFile)Z_NULL; - } - } - s->stream.avail_out = Z_BUFSIZE; - - errno = 0; - s->file = fd < 0 ? F_OPEN(path, fmode) : (FILE*)fdopen(fd, fmode); - - if (s->file == NULL) { - return destroy(s), (gzFile)Z_NULL; - } - if (s->mode == 'w') { - /* Write a very simple .gz header: - */ - fprintf(s->file, "%c%c%c%c%c%c%c%c%c%c", gz_magic[0], gz_magic[1], - Z_DEFLATED, 0 /*flags*/, 0,0,0,0 /*time*/, 0 /*xflags*/, OS_CODE); - s->start = 10L; - /* We use 10L instead of ftell(s->file) to because ftell causes an - * fflush on some systems. This version of the library doesn't use - * start anyway in write mode, so this initialization is not - * necessary. - */ - } else { - check_header(s); /* skip the .gz header */ - s->start = ftell(s->file) - s->stream.avail_in; - } - - return (gzFile)s; + if (err != Z_OK || s->outbuf == Z_NULL) { + return (destroy(s), (gzFile)Z_NULL); + } + } else { + s->stream.next_in = s->inbuf = (Byte*)ALLOC(Z_BUFSIZE); + + err = inflateInit2(&(s->stream), -MAX_WBITS); + /* + * windowBits is passed < 0 to tell that there is no zlib header. + * Note that in this case inflate *requires* an extra "dummy" byte + * after the compressed stream in order to complete decompression and + * return Z_STREAM_END. Here the gzip CRC32 ensures that 4 bytes are + * present after the compressed stream. + */ + if (err != Z_OK || s->inbuf == Z_NULL) { + return (destroy(s), (gzFile)Z_NULL); + } + } + s->stream.avail_out = Z_BUFSIZE; + + errno = 0; + s->file = fd < 0 ? F_OPEN(path, fmode) : (FILE *)fdopen(fd, fmode); + + if (s->file == NULL) { + return (destroy(s), (gzFile)Z_NULL); + } + if (s->mode == 'w') { + /* Write a very simple .gz header: */ + fprintf(s->file, "%c%c%c%c%c%c%c%c%c%c", gz_magic[0], + gz_magic[1], + Z_DEFLATED, 0 /* flags */, 0, 0, 0, 0 /* time */, + 0 /* xflags */, OS_CODE); + s->start = 10L; + /* + * We use 10L instead of ftell(s->file) to because ftell causes an + * fflush on some systems. This version of the library doesn't use + * start anyway in write mode, so this initialization is not + * necessary. + */ + } else { + check_header(s); /* skip the .gz header */ + s->start = ftell(s->file) - s->stream.avail_in; + } + + return ((gzFile)s); } -/* =========================================================================== - Opens a gzip (.gz) file for reading or writing. -*/ -gzFile ZEXPORT gzopen (path, mode) - const char *path; - const char *mode; +/* + * Opens a gzip (.gz) file for reading or writing. + */ +gzFile ZEXPORT +gzopen( + const char *path, + const char *mode) { - return gz_open (path, mode, -1); + return (gz_open(path, mode, -1)); } -/* =========================================================================== - Associate a gzFile with the file descriptor fd. fd is not dup'ed here - to mimic the behavio(u)r of fdopen. -*/ -gzFile ZEXPORT gzdopen (fd, mode) - int fd; - const char *mode; +/* + * Associate a gzFile with the file descriptor fd. fd is not dup'ed here + * to mimic the behavio(u)r of fdopen. + */ +gzFile ZEXPORT +gzdopen( + int fd, + const char *mode) { - char name[46]; /* allow for up to 128-bit integers */ + char name[46]; /* allow for up to 128-bit integers */ - if (fd < 0) return (gzFile)Z_NULL; - sprintf(name, "", fd); /* for debugging */ + if (fd < 0) + return ((gzFile)Z_NULL); + sprintf(name, "", fd); /* for debugging */ - return gz_open (name, mode, fd); + return (gz_open(name, mode, fd)); } -/* =========================================================================== +/* * Update the compression level and strategy */ -int ZEXPORT gzsetparams (file, level, strategy) - gzFile file; - int level; - int strategy; +int ZEXPORT +gzsetparams( + gzFile file, + int level, + int strategy) { - gz_stream *s = (gz_stream*)file; + gz_stream *s = (gz_stream*)file; - if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR; + if (s == NULL || s->mode != 'w') + return (Z_STREAM_ERROR); - /* Make room to allow flushing */ - if (s->stream.avail_out == 0) { + /* Make room to allow flushing */ + if (s->stream.avail_out == 0) { - s->stream.next_out = s->outbuf; - if (fwrite(s->outbuf, 1, Z_BUFSIZE, s->file) != Z_BUFSIZE) { - s->z_err = Z_ERRNO; - } - s->stream.avail_out = Z_BUFSIZE; - } + s->stream.next_out = s->outbuf; + if (fwrite(s->outbuf, 1, Z_BUFSIZE, s->file) != Z_BUFSIZE) { + s->z_err = Z_ERRNO; + } + s->stream.avail_out = Z_BUFSIZE; + } - return deflateParams (&(s->stream), level, strategy); + return (deflateParams(&(s->stream), level, strategy)); } -/* =========================================================================== - Read a byte from a gz_stream; update next_in and avail_in. Return EOF - for end of file. - IN assertion: the stream s has been sucessfully opened for reading. -*/ -local int get_byte(s) - gz_stream *s; +/* + * Read a byte from a gz_stream; update next_in and avail_in. Return EOF + * for end of file. + * IN assertion: the stream s has been sucessfully opened for reading. + */ +local int +get_byte(gz_stream *s) { - if (s->z_eof) return EOF; - if (s->stream.avail_in == 0) { - errno = 0; - s->stream.avail_in = (uInt)fread(s->inbuf, 1, Z_BUFSIZE, s->file); - if (s->stream.avail_in == 0) { - s->z_eof = 1; - if (ferror(s->file)) s->z_err = Z_ERRNO; - return EOF; - } - s->stream.next_in = s->inbuf; - } - s->stream.avail_in--; - return *(s->stream.next_in)++; + if (s->z_eof) + return (EOF); + if (s->stream.avail_in == 0) { + errno = 0; + s->stream.avail_in = (uInt)fread(s->inbuf, 1, Z_BUFSIZE, + s->file); + if (s->stream.avail_in == 0) { + s->z_eof = 1; + if (ferror(s->file)) s->z_err = Z_ERRNO; + return (EOF); + } + s->stream.next_in = s->inbuf; + } + s->stream.avail_in--; + return (*(s->stream.next_in)++); } -/* =========================================================================== - Check the gzip header of a gz_stream opened for reading. Set the stream - mode to transparent if the gzip magic header is not present; set s->err - to Z_DATA_ERROR if the magic header is present but the rest of the header - is incorrect. - IN assertion: the stream s has already been created sucessfully; - s->stream.avail_in is zero for the first time, but may be non-zero - for concatenated .gz files. -*/ -local void check_header(s) - gz_stream *s; +/* + * Check the gzip header of a gz_stream opened for reading. Set the stream + * mode to transparent if the gzip magic header is not present; set s->err + * to Z_DATA_ERROR if the magic header is present but the rest of the header + * is incorrect. + * IN assertion: the stream s has already been created sucessfully; + * s->stream.avail_in is zero for the first time, but may be non-zero + * for concatenated .gz files. + */ +local void +check_header(gz_stream *s) { - int method; /* method byte */ - int flags; /* flags byte */ - uInt len; - int c; - - /* Assure two bytes in the buffer so we can peek ahead -- handle case - where first byte of header is at the end of the buffer after the last - gzip segment */ - len = s->stream.avail_in; - if (len < 2) { - if (len) s->inbuf[0] = s->stream.next_in[0]; - errno = 0; - len = (uInt)fread(s->inbuf + len, 1, Z_BUFSIZE >> len, s->file); - if (len == 0 && ferror(s->file)) s->z_err = Z_ERRNO; - s->stream.avail_in += len; - s->stream.next_in = s->inbuf; - if (s->stream.avail_in < 2) { - s->transparent = s->stream.avail_in; - return; - } - } - - /* Peek ahead to check the gzip magic header */ - if (s->stream.next_in[0] != gz_magic[0] || - s->stream.next_in[1] != gz_magic[1]) { - s->transparent = 1; - return; - } - s->stream.avail_in -= 2; - s->stream.next_in += 2; - - /* Check the rest of the gzip header */ - method = get_byte(s); - flags = get_byte(s); - if (method != Z_DEFLATED || (flags & RESERVED) != 0) { - s->z_err = Z_DATA_ERROR; - return; - } - - /* Discard time, xflags and OS code: */ - for (len = 0; len < 6; len++) (void)get_byte(s); - - if ((flags & EXTRA_FIELD) != 0) { /* skip the extra field */ - len = (uInt)get_byte(s); - len += ((uInt)get_byte(s))<<8; - /* len is garbage if EOF but the loop below will quit anyway */ - while (len-- != 0 && get_byte(s) != EOF) ; - } - if ((flags & ORIG_NAME) != 0) { /* skip the original file name */ - while ((c = get_byte(s)) != 0 && c != EOF) ; - } - if ((flags & COMMENT) != 0) { /* skip the .gz file comment */ - while ((c = get_byte(s)) != 0 && c != EOF) ; - } - if ((flags & HEAD_CRC) != 0) { /* skip the header crc */ - for (len = 0; len < 2; len++) (void)get_byte(s); - } - s->z_err = s->z_eof ? Z_DATA_ERROR : Z_OK; + int method; /* method byte */ + int flags; /* flags byte */ + uInt len; + int c; + + /* + * Assure two bytes in the buffer so we can peek ahead -- handle case + * where first byte of header is at the end of the buffer after the last + * gzip segment + */ + len = s->stream.avail_in; + if (len < 2) { + if (len) s->inbuf[0] = s->stream.next_in[0]; + errno = 0; + len = (uInt)fread(s->inbuf + len, 1, Z_BUFSIZE >> len, s->file); + if (len == 0 && ferror(s->file)) s->z_err = Z_ERRNO; + s->stream.avail_in += len; + s->stream.next_in = s->inbuf; + if (s->stream.avail_in < 2) { + s->transparent = s->stream.avail_in; + return; + } + } + + /* Peek ahead to check the gzip magic header */ + if (s->stream.next_in[0] != gz_magic[0] || + s->stream.next_in[1] != gz_magic[1]) { + s->transparent = 1; + return; + } + s->stream.avail_in -= 2; + s->stream.next_in += 2; + + /* Check the rest of the gzip header */ + method = get_byte(s); + flags = get_byte(s); + if (method != Z_DEFLATED || (flags & RESERVED) != 0) { + s->z_err = Z_DATA_ERROR; + return; + } + + /* Discard time, xflags and OS code: */ + for (len = 0; len < 6; len++) (void)get_byte(s); + + if ((flags & EXTRA_FIELD) != 0) { /* skip the extra field */ + len = (uInt)get_byte(s); + len += ((uInt)get_byte(s))<<8; + /* len is garbage if EOF but the loop below will quit anyway */ + while (len-- != 0 && get_byte(s) != EOF) + ; + } + if ((flags & ORIG_NAME) != 0) { /* skip the original file name */ + while ((c = get_byte(s)) != 0 && c != EOF) + ; + } + if ((flags & COMMENT) != 0) { /* skip the .gz file comment */ + while ((c = get_byte(s)) != 0 && c != EOF) + ; + } + if ((flags & HEAD_CRC) != 0) { /* skip the header crc */ + for (len = 0; len < 2; len++) (void)get_byte(s); + } + s->z_err = s->z_eof ? Z_DATA_ERROR : Z_OK; } - /* =========================================================================== +/* * Cleanup then free the given gz_stream. Return a zlib error code. - Try freeing in the reverse order of allocations. + * Try freeing in the reverse order of allocations. */ -local int destroy (s) - gz_stream *s; +local int +destroy(gz_stream *s) { - int err = Z_OK; + int err = Z_OK; - if (!s) return Z_STREAM_ERROR; + if (!s) + return (Z_STREAM_ERROR); - TRYFREE(s->msg); + TRYFREE(s->msg); - if (s->stream.state != NULL) { - if (s->mode == 'w') { + if (s->stream.state != NULL) { + if (s->mode == 'w') { #ifdef NO_GZCOMPRESS - err = Z_STREAM_ERROR; + err = Z_STREAM_ERROR; #else - err = deflateEnd(&(s->stream)); + err = deflateEnd(&(s->stream)); #endif - } else if (s->mode == 'r') { - err = inflateEnd(&(s->stream)); - } - } - if (s->file != NULL && fclose(s->file)) { + } else if (s->mode == 'r') { + err = inflateEnd(&(s->stream)); + } + } + if (s->file != NULL && fclose(s->file)) { #ifdef ESPIPE - if (errno != ESPIPE) /* fclose is broken for pipes in HP/UX */ + if (errno != ESPIPE) /* fclose is broken for pipes in HP/UX */ #endif - err = Z_ERRNO; - } - if (s->z_err < 0) err = s->z_err; - - TRYFREE(s->inbuf); - TRYFREE(s->outbuf); - TRYFREE(s->path); - TRYFREE(s); - return err; + err = Z_ERRNO; + } + if (s->z_err < 0) err = s->z_err; + + TRYFREE(s->inbuf); + TRYFREE(s->outbuf); + TRYFREE(s->path); + TRYFREE(s); + return (err); } -/* =========================================================================== - Reads the given number of uncompressed bytes from the compressed file. - gzread returns the number of bytes actually read (0 for end of file). -*/ -int ZEXPORT gzread (file, buf, len) - gzFile file; - voidp buf; - unsigned len; +/* + * Reads the given number of uncompressed bytes from the compressed file. + * gzread returns the number of bytes actually read (0 for end of file). + */ +int ZEXPORT +gzread( + gzFile file, + voidp buf, + unsigned len) { - gz_stream *s = (gz_stream*)file; - Bytef *start = (Bytef*)buf; /* starting point for crc computation */ - Byte *next_out; /* == stream.next_out but not forced far (for MSDOS) */ - - if (s == NULL || s->mode != 'r') return Z_STREAM_ERROR; - - if (s->z_err == Z_DATA_ERROR || s->z_err == Z_ERRNO) return -1; - if (s->z_err == Z_STREAM_END) return 0; /* EOF */ - - next_out = (Byte*)buf; - s->stream.next_out = (Bytef*)buf; - s->stream.avail_out = len; - - if (s->stream.avail_out && s->back != EOF) { - *next_out++ = s->back; - s->stream.next_out++; - s->stream.avail_out--; - s->back = EOF; - s->out++; - start++; - if (s->last) { - s->z_err = Z_STREAM_END; - return 1; - } - } - - while (s->stream.avail_out != 0) { - - if (s->transparent) { - /* Copy first the lookahead bytes: */ - uInt n = s->stream.avail_in; - if (n > s->stream.avail_out) n = s->stream.avail_out; - if (n > 0) { - zmemcpy(s->stream.next_out, s->stream.next_in, n); - next_out += n; - s->stream.next_out = next_out; - s->stream.next_in += n; - s->stream.avail_out -= n; - s->stream.avail_in -= n; - } - if (s->stream.avail_out > 0) { - s->stream.avail_out -= - (uInt)fread(next_out, 1, s->stream.avail_out, s->file); - } - len -= s->stream.avail_out; - s->in += len; - s->out += len; - if (len == 0) s->z_eof = 1; - return (int)len; - } - if (s->stream.avail_in == 0 && !s->z_eof) { - - errno = 0; - s->stream.avail_in = (uInt)fread(s->inbuf, 1, Z_BUFSIZE, s->file); - if (s->stream.avail_in == 0) { - s->z_eof = 1; - if (ferror(s->file)) { - s->z_err = Z_ERRNO; - break; - } - } - s->stream.next_in = s->inbuf; - } - s->in += s->stream.avail_in; - s->out += s->stream.avail_out; - s->z_err = inflate(&(s->stream), Z_NO_FLUSH); - s->in -= s->stream.avail_in; - s->out -= s->stream.avail_out; - - if (s->z_err == Z_STREAM_END) { - /* Check CRC and original size */ - s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start)); - start = s->stream.next_out; - - if (getLong(s) != s->crc) { - s->z_err = Z_DATA_ERROR; - } else { - (void)getLong(s); - /* The uncompressed length returned by above getlong() may be - * different from s->out in case of concatenated .gz files. - * Check for such files: - */ - check_header(s); - if (s->z_err == Z_OK) { - inflateReset(&(s->stream)); - s->crc = crc32(0L, Z_NULL, 0); - } - } - } - if (s->z_err != Z_OK || s->z_eof) break; - } - s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start)); - - if (len == s->stream.avail_out && - (s->z_err == Z_DATA_ERROR || s->z_err == Z_ERRNO)) - return -1; - return (int)(len - s->stream.avail_out); + gz_stream *s = (gz_stream*)file; + Bytef *start = (Bytef*)buf; /* starting point for crc computation */ + Byte *next_out; /* == stream.next_out but not forced far (for MSDOS) */ + + if (s == NULL || s->mode != 'r') + return (Z_STREAM_ERROR); + + if (s->z_err == Z_DATA_ERROR || s->z_err == Z_ERRNO) + return (-1); + if (s->z_err == Z_STREAM_END) + return (0); /* EOF */ + + next_out = (Byte*)buf; + s->stream.next_out = (Bytef*)buf; + s->stream.avail_out = len; + + if (s->stream.avail_out && s->back != EOF) { + *next_out++ = s->back; + s->stream.next_out++; + s->stream.avail_out--; + s->back = EOF; + s->out++; + start++; + if (s->last) { + s->z_err = Z_STREAM_END; + return (1); + } + } + + while (s->stream.avail_out != 0) { + + if (s->transparent) { + /* Copy first the lookahead bytes: */ + uInt n = s->stream.avail_in; + if (n > s->stream.avail_out) n = s->stream.avail_out; + if (n > 0) { + zmemcpy(s->stream.next_out, s->stream.next_in, + n); + next_out += n; + s->stream.next_out = next_out; + s->stream.next_in += n; + s->stream.avail_out -= n; + s->stream.avail_in -= n; + } + if (s->stream.avail_out > 0) { + s->stream.avail_out -= + (uInt)fread(next_out, 1, s->stream. + avail_out, s->file); + } + len -= s->stream. avail_out; + s->in += len; + s->out += len; + if (len == 0) s->z_eof = 1; + return ((int)len); + } + if (s->stream.avail_in == 0 && !s->z_eof) { + + errno = 0; + s->stream.avail_in = (uInt)fread(s->inbuf, 1, Z_BUFSIZE, + s->file); + if (s->stream.avail_in == 0) { + s->z_eof = 1; + if (ferror(s->file)) { + s->z_err = Z_ERRNO; + break; + } + } + s->stream.next_in = s->inbuf; + } + s->in += s->stream.avail_in; + s->out += s->stream.avail_out; + s->z_err = inflate(&(s->stream), Z_NO_FLUSH); + s->in -= s->stream.avail_in; + s->out -= s->stream.avail_out; + + if (s->z_err == Z_STREAM_END) { + /* Check CRC and original size */ + s->crc = crc32(s->crc, start, + (uInt)(s->stream.next_out - start)); + start = s->stream.next_out; + + if (getLong(s) != s->crc) { + s->z_err = Z_DATA_ERROR; + } else { + (void) getLong(s); + /* + * The uncompressed length returned by above getlong() may be + * different from s->out in case of concatenated .gz files. + * Check for such files: + */ + check_header(s); + if (s->z_err == Z_OK) { + inflateReset(&(s->stream)); + s->crc = crc32(0L, Z_NULL, 0); + } + } + } + if (s->z_err != Z_OK || s->z_eof) + break; + } + s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start)); + + if (len == s->stream.avail_out && + (s->z_err == Z_DATA_ERROR || s->z_err == Z_ERRNO)) + return (-1); + return (int)(len - s->stream.avail_out); } -/* =========================================================================== - Reads one byte from the compressed file. gzgetc returns this byte - or -1 in case of end of file or error. -*/ -int ZEXPORT gzgetc(file) - gzFile file; +/* + * Reads one byte from the compressed file. gzgetc returns this byte + * or -1 in case of end of file or error. + */ +int ZEXPORT +gzgetc(gzFile file) { - unsigned char c; + unsigned char c; - return gzread(file, &c, 1) == 1 ? c : -1; + return (gzread(file, &c, 1) == 1 ? c : -1); } -/* =========================================================================== - Push one byte back onto the stream. -*/ -int ZEXPORT gzungetc(c, file) - int c; - gzFile file; +/* + * Push one byte back onto the stream. + */ +int ZEXPORT +gzungetc( + int c, + gzFile file) { - gz_stream *s = (gz_stream*)file; - - if (s == NULL || s->mode != 'r' || c == EOF || s->back != EOF) return EOF; - s->back = c; - s->out--; - s->last = (s->z_err == Z_STREAM_END); - if (s->last) s->z_err = Z_OK; - s->z_eof = 0; - return c; + gz_stream *s = (gz_stream*)file; + + if (s == NULL || s->mode != 'r' || c == EOF || s->back != EOF) + return (EOF); + s->back = c; + s->out--; + s->last = (s->z_err == Z_STREAM_END); + if (s->last) s->z_err = Z_OK; + s->z_eof = 0; + return (c); } -/* =========================================================================== - Reads bytes from the compressed file until len-1 characters are - read, or a newline character is read and transferred to buf, or an - end-of-file condition is encountered. The string is then terminated - with a null character. - gzgets returns buf, or Z_NULL in case of error. - - The current implementation is not optimized at all. -*/ -char * ZEXPORT gzgets(file, buf, len) - gzFile file; - char *buf; - int len; +/* + * Reads bytes from the compressed file until len-1 characters are + * read, or a newline character is read and transferred to buf, or an + * end-of-file condition is encountered. The string is then terminated + * with a null character. + * gzgets returns buf, or Z_NULL in case of error. + * + * The current implementation is not optimized at all. + */ +char *ZEXPORT +gzgets( + gzFile file, + char *buf, + int len) { - char *b = buf; - if (buf == Z_NULL || len <= 0) return Z_NULL; - - while (--len > 0 && gzread(file, buf, 1) == 1 && *buf++ != '\n') ; - *buf = '\0'; - return b == buf && len > 0 ? Z_NULL : b; + char *b = buf; + if (buf == Z_NULL || len <= 0) + return (Z_NULL); + + while (--len > 0 && gzread(file, buf, 1) == 1 && + *buf++ != '\n') + ; + *buf = '\0'; + return (b == buf && len > 0 ? Z_NULL : b); } #ifndef NO_GZCOMPRESS -/* =========================================================================== - Writes the given number of uncompressed bytes into the compressed file. - gzwrite returns the number of bytes actually written (0 in case of error). -*/ -int ZEXPORT gzwrite (file, buf, len) - gzFile file; - voidpc buf; - unsigned len; +/* + * Writes the given number of uncompressed bytes into the compressed file. + * gzwrite returns the number of bytes actually written (0 in case of error). + */ +int ZEXPORT +gzwrite( + gzFile file, + voidpc buf, + unsigned len) { - gz_stream *s = (gz_stream*)file; - - if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR; - - s->stream.next_in = (Bytef*)buf; - s->stream.avail_in = len; - - while (s->stream.avail_in != 0) { - - if (s->stream.avail_out == 0) { - - s->stream.next_out = s->outbuf; - if (fwrite(s->outbuf, 1, Z_BUFSIZE, s->file) != Z_BUFSIZE) { - s->z_err = Z_ERRNO; - break; - } - s->stream.avail_out = Z_BUFSIZE; - } - s->in += s->stream.avail_in; - s->out += s->stream.avail_out; - s->z_err = deflate(&(s->stream), Z_NO_FLUSH); - s->in -= s->stream.avail_in; - s->out -= s->stream.avail_out; - if (s->z_err != Z_OK) break; - } - s->crc = crc32(s->crc, (const Bytef *)buf, len); - - return (int)(len - s->stream.avail_in); + gz_stream *s = (gz_stream*)file; + + if (s == NULL || s->mode != 'w') + return (Z_STREAM_ERROR); + + s->stream.next_in = (Bytef*)buf; + s->stream.avail_in = len; + + while (s->stream.avail_in != 0) { + + if (s->stream.avail_out == 0) { + + s->stream.next_out = s->outbuf; + if (fwrite(s->outbuf, 1, Z_BUFSIZE, s->file) != + Z_BUFSIZE) { + s->z_err = Z_ERRNO; + break; + } + s->stream.avail_out = Z_BUFSIZE; + } + s->in += s->stream.avail_in; + s->out += s->stream.avail_out; + s->z_err = deflate(&(s->stream), Z_NO_FLUSH); + s->in -= s->stream.avail_in; + s->out -= s->stream.avail_out; + if (s->z_err != Z_OK) + break; + } + s->crc = crc32(s->crc, (const Bytef *)buf, len); + + return ((int)(len - s->stream.avail_in)); } -/* =========================================================================== - Converts, formats, and writes the args to the compressed file under - control of the format string, as in fprintf. gzprintf returns the number of - uncompressed bytes actually written (0 in case of error). -*/ +/* + * Converts, formats, and writes the args to the compressed file under + * control of the format string, as in fprintf. gzprintf returns the number of + * uncompressed bytes actually written (0 in case of error). + */ #ifdef STDC #include -int ZEXPORTVA gzprintf (gzFile file, const char *format, /* args */ ...) +int ZEXPORTVA +gzprintf(gzFile file, const char *format, /* args */ ...) { - char buf[Z_PRINTF_BUFSIZE]; - va_list va; - int len; + char buf[Z_PRINTF_BUFSIZE]; + va_list va; + int len; - buf[sizeof(buf) - 1] = 0; - va_start(va, format); + buf[sizeof (buf) - 1] = 0; + va_start(va, format); #ifdef NO_vsnprintf -# ifdef HAS_vsprintf_void - (void)vsprintf(buf, format, va); - va_end(va); - for (len = 0; len < sizeof(buf); len++) - if (buf[len] == 0) break; -# else - len = vsprintf(buf, format, va); - va_end(va); -# endif +#ifdef HAS_vsprintf_void + (void) vsprintf(buf, format, va); + va_end(va); + for (len = 0; len < sizeof (buf); len++) + if (buf[len] == 0) break; +#else + len = vsprintf(buf, format, va); + va_end(va); +#endif +#else +#ifdef HAS_vsnprintf_void + (void) vsnprintf(buf, sizeof (buf), format, va); + va_end(va); + len = strlen(buf); #else -# ifdef HAS_vsnprintf_void - (void)vsnprintf(buf, sizeof(buf), format, va); - va_end(va); - len = strlen(buf); -# else - len = vsnprintf(buf, sizeof(buf), format, va); - va_end(va); -# endif + len = vsnprintf(buf, sizeof (buf), format, va); + va_end(va); #endif - if (len <= 0 || len >= (int)sizeof(buf) || buf[sizeof(buf) - 1] != 0) - return 0; - return gzwrite(file, buf, (unsigned)len); +#endif + if (len <= 0 || len >= (int)sizeof (buf) || buf[sizeof (buf) - 1] != 0) + return (0); + return (gzwrite(file, buf, (unsigned)len)); } #else /* not ANSI C */ -int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, - a11, a12, a13, a14, a15, a16, a17, a18, a19, a20) - gzFile file; - const char *format; - int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, - a11, a12, a13, a14, a15, a16, a17, a18, a19, a20; +int ZEXPORTVA +gzprintf( + gzFile file, + const char *format, + int a1, + int a2, + int a3, + int a4, + int a5, + int a6, + int a7, + int a8, + int a9, + int a10, + int a11, + int a12, + int a13, + int a14, + int a15, + int a16, + int a17, + int a18, + int a19, + int a20) { - char buf[Z_PRINTF_BUFSIZE]; - int len; + char buf[Z_PRINTF_BUFSIZE]; + int len; - buf[sizeof(buf) - 1] = 0; + buf[sizeof (buf) - 1] = 0; #ifdef NO_snprintf -# ifdef HAS_sprintf_void - sprintf(buf, format, a1, a2, a3, a4, a5, a6, a7, a8, - a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); - for (len = 0; len < sizeof(buf); len++) - if (buf[len] == 0) break; -# else - len = sprintf(buf, format, a1, a2, a3, a4, a5, a6, a7, a8, - a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); -# endif +#ifdef HAS_sprintf_void + sprintf(buf, format, a1, a2, a3, a4, a5, a6, a7, a8, + a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); + for (len = 0; len < sizeof (buf); len++) + if (buf[len] == 0) + break; +#else + len = sprintf(buf, format, a1, a2, a3, a4, a5, a6, a7, a8, + a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); +#endif #else -# ifdef HAS_snprintf_void - snprintf(buf, sizeof(buf), format, a1, a2, a3, a4, a5, a6, a7, a8, - a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); - len = strlen(buf); -# else - len = snprintf(buf, sizeof(buf), format, a1, a2, a3, a4, a5, a6, a7, a8, - a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); -# endif +#ifdef HAS_snprintf_void + snprintf(buf, sizeof (buf), format, a1, a2, a3, a4, a5, a6, a7, a8, + a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); + len = strlen(buf); +#else + len = snprintf(buf, sizeof (buf), format, a1, a2, a3, a4, a5, a6, a7, + a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); +#endif #endif - if (len <= 0 || len >= sizeof(buf) || buf[sizeof(buf) - 1] != 0) - return 0; - return gzwrite(file, buf, len); + if (len <= 0 || len >= sizeof (buf) || buf[sizeof (buf) - 1] != 0) + return (0); + return (gzwrite(file, buf, len)); } #endif -/* =========================================================================== - Writes c, converted to an unsigned char, into the compressed file. - gzputc returns the value that was written, or -1 in case of error. -*/ -int ZEXPORT gzputc(file, c) - gzFile file; - int c; +/* + * Writes c, converted to an unsigned char, into the compressed file. + * gzputc returns the value that was written, or -1 in case of error. + */ +int ZEXPORT +gzputc( + gzFile file, + int c) { - unsigned char cc = (unsigned char) c; /* required for big endian systems */ + /* required for big endian systems */ + unsigned char cc = (unsigned char)c; - return gzwrite(file, &cc, 1) == 1 ? (int)cc : -1; + return (gzwrite(file, &cc, 1) == 1 ? (int)cc : -1); } -/* =========================================================================== - Writes the given null-terminated string to the compressed file, excluding - the terminating null character. - gzputs returns the number of characters written, or -1 in case of error. -*/ -int ZEXPORT gzputs(file, s) - gzFile file; - const char *s; +/* + * Writes the given null-terminated string to the compressed file, excluding + * the terminating null character. + * gzputs returns the number of characters written, or -1 in case of error. + */ +int ZEXPORT +gzputs( + gzFile file, + const char *s) { - return gzwrite(file, (char*)s, (unsigned)strlen(s)); + return (gzwrite(file, (char *)s, (unsigned)strlen(s))); } -/* =========================================================================== - Flushes all pending output into the compressed file. The parameter - flush is as in the deflate() function. -*/ -local int do_flush (file, flush) - gzFile file; - int flush; +/* + * Flushes all pending output into the compressed file. The parameter + * flush is as in the deflate() function. + */ +local int +do_flush( + gzFile file, + int flush) { - uInt len; - int done = 0; - gz_stream *s = (gz_stream*)file; - - if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR; - - s->stream.avail_in = 0; /* should be zero already anyway */ - - for (;;) { - len = Z_BUFSIZE - s->stream.avail_out; - - if (len != 0) { - if ((uInt)fwrite(s->outbuf, 1, len, s->file) != len) { - s->z_err = Z_ERRNO; - return Z_ERRNO; - } - s->stream.next_out = s->outbuf; - s->stream.avail_out = Z_BUFSIZE; - } - if (done) break; - s->out += s->stream.avail_out; - s->z_err = deflate(&(s->stream), flush); - s->out -= s->stream.avail_out; - - /* Ignore the second of two consecutive flushes: */ - if (len == 0 && s->z_err == Z_BUF_ERROR) s->z_err = Z_OK; - - /* deflate has finished flushing only when it hasn't used up - * all the available space in the output buffer: - */ - done = (s->stream.avail_out != 0 || s->z_err == Z_STREAM_END); - - if (s->z_err != Z_OK && s->z_err != Z_STREAM_END) break; - } - return s->z_err == Z_STREAM_END ? Z_OK : s->z_err; + uInt len; + int done = 0; + gz_stream *s = (gz_stream*)file; + + if (s == NULL || s->mode != 'w') + return (Z_STREAM_ERROR); + + s->stream.avail_in = 0; /* should be zero already anyway */ + + for (;;) { + len = Z_BUFSIZE - s->stream.avail_out; + + if (len != 0) { + if ((uInt)fwrite(s->outbuf, 1, len, s->file) != len) { + s->z_err = Z_ERRNO; + return (Z_ERRNO); + } + s->stream.next_out = s->outbuf; + s->stream.avail_out = Z_BUFSIZE; + } + if (done) + break; + s->out += s->stream.avail_out; + s->z_err = deflate(&(s->stream), flush); + s->out -= s->stream.avail_out; + + /* Ignore the second of two consecutive flushes: */ + if (len == 0 && s->z_err == Z_BUF_ERROR) s->z_err = Z_OK; + + /* + * deflate has finished flushing only when it hasn't used up + * all the available space in the output buffer: + */ + done = (s->stream.avail_out != 0 || s->z_err == Z_STREAM_END); + + if (s->z_err != Z_OK && s->z_err != Z_STREAM_END) + break; + } + return (s->z_err == Z_STREAM_END ? Z_OK : s->z_err); } -int ZEXPORT gzflush (file, flush) - gzFile file; - int flush; +int ZEXPORT +gzflush( + gzFile file, + int flush) { - gz_stream *s = (gz_stream*)file; - int err = do_flush (file, flush); + gz_stream *s = (gz_stream*)file; + int err = do_flush(file, flush); - if (err) return err; - fflush(s->file); - return s->z_err == Z_STREAM_END ? Z_OK : s->z_err; + if (err) + return (err); + fflush(s->file); + return (s->z_err == Z_STREAM_END ? Z_OK : s->z_err); } #endif /* NO_GZCOMPRESS */ -/* =========================================================================== - Sets the starting position for the next gzread or gzwrite on the given - compressed file. The offset represents a number of bytes in the - gzseek returns the resulting offset location as measured in bytes from - the beginning of the uncompressed stream, or -1 in case of error. - SEEK_END is not implemented, returns error. - In this version of the library, gzseek can be extremely slow. -*/ -z_off_t ZEXPORT gzseek (file, offset, whence) - gzFile file; - z_off_t offset; - int whence; +/* + * Sets the starting position for the next gzread or gzwrite on the given + * compressed file. The offset represents a number of bytes in the + * gzseek returns the resulting offset location as measured in bytes from + * the beginning of the uncompressed stream, or -1 in case of error. + * SEEK_END is not implemented, returns error. + * In this version of the library, gzseek can be extremely slow. + */ +z_off_t ZEXPORT +gzseek( + gzFile file, + z_off_t offset, + int whence) { - gz_stream *s = (gz_stream*)file; + gz_stream *s = (gz_stream*)file; - if (s == NULL || whence == SEEK_END || - s->z_err == Z_ERRNO || s->z_err == Z_DATA_ERROR) { - return -1L; - } + if (s == NULL || whence == SEEK_END || + s->z_err == Z_ERRNO || s->z_err == Z_DATA_ERROR) { + return (-1L); + } - if (s->mode == 'w') { + if (s->mode == 'w') { #ifdef NO_GZCOMPRESS - return -1L; + return (-1L); #else - if (whence == SEEK_SET) { - offset -= s->in; - } - if (offset < 0) return -1L; - - /* At this point, offset is the number of zero bytes to write. */ - if (s->inbuf == Z_NULL) { - s->inbuf = (Byte*)ALLOC(Z_BUFSIZE); /* for seeking */ - if (s->inbuf == Z_NULL) return -1L; - zmemzero(s->inbuf, Z_BUFSIZE); - } - while (offset > 0) { - uInt size = Z_BUFSIZE; - if (offset < Z_BUFSIZE) size = (uInt)offset; - - size = gzwrite(file, s->inbuf, size); - if (size == 0) return -1L; - - offset -= size; - } - return s->in; + if (whence == SEEK_SET) { + offset -= s->in; + } + if (offset < 0) + return (-1L); + + /* At this point, offset is the number of zero bytes to write. */ + if (s->inbuf == Z_NULL) { + s->inbuf = (Byte*)ALLOC(Z_BUFSIZE); /* for seeking */ + if (s->inbuf == Z_NULL) + return (-1L); + zmemzero(s->inbuf, Z_BUFSIZE); + } + while (offset > 0) { + uInt size = Z_BUFSIZE; + if (offset < Z_BUFSIZE) size = (uInt)offset; + + size = gzwrite(file, s->inbuf, size); + if (size == 0) + return (-1L); + + offset -= size; + } + return (s->in); #endif - } - /* Rest of function is for reading only */ - - /* compute absolute position */ - if (whence == SEEK_CUR) { - offset += s->out; - } - if (offset < 0) return -1L; - - if (s->transparent) { - /* map to fseek */ - s->back = EOF; - s->stream.avail_in = 0; - s->stream.next_in = s->inbuf; - if (fseek(s->file, offset, SEEK_SET) < 0) return -1L; - - s->in = s->out = offset; - return offset; - } - - /* For a negative seek, rewind and use positive seek */ - if (offset >= s->out) { - offset -= s->out; - } else if (gzrewind(file) < 0) { - return -1L; - } - /* offset is now the number of bytes to skip. */ - - if (offset != 0 && s->outbuf == Z_NULL) { - s->outbuf = (Byte*)ALLOC(Z_BUFSIZE); - if (s->outbuf == Z_NULL) return -1L; - } - if (offset && s->back != EOF) { - s->back = EOF; - s->out++; - offset--; - if (s->last) s->z_err = Z_STREAM_END; - } - while (offset > 0) { - int size = Z_BUFSIZE; - if (offset < Z_BUFSIZE) size = (int)offset; - - size = gzread(file, s->outbuf, (uInt)size); - if (size <= 0) return -1L; - offset -= size; - } - return s->out; + } + /* Rest of function is for reading only */ + + /* compute absolute position */ + if (whence == SEEK_CUR) { + offset += s->out; + } + if (offset < 0) + return (-1L); + + if (s->transparent) { + /* map to fseek */ + s->back = EOF; + s->stream.avail_in = 0; + s->stream.next_in = s->inbuf; + if (fseek(s->file, offset, SEEK_SET) < 0) + return (-1L); + + s->in = s->out = offset; + return (offset); + } + + /* For a negative seek, rewind and use positive seek */ + if (offset >= s->out) { + offset -= s->out; + } else if (gzrewind(file) < 0) { + return (-1L); + } + /* offset is now the number of bytes to skip. */ + + if (offset != 0 && s->outbuf == Z_NULL) { + s->outbuf = (Byte*)ALLOC(Z_BUFSIZE); + if (s->outbuf == Z_NULL) + return (-1L); + } + if (offset && s->back != EOF) { + s->back = EOF; + s->out++; + offset--; + if (s->last) s->z_err = Z_STREAM_END; + } + while (offset > 0) { + int size = Z_BUFSIZE; + if (offset < Z_BUFSIZE) size = (int)offset; + + size = gzread(file, s->outbuf, (uInt)size); + if (size <= 0) + return (-1L); + offset -= size; + } + return (s->out); } -/* =========================================================================== - Rewinds input file. -*/ -int ZEXPORT gzrewind (file) - gzFile file; +/* + * Rewinds input file. + */ +int ZEXPORT +gzrewind(gzFile file) { - gz_stream *s = (gz_stream*)file; - - if (s == NULL || s->mode != 'r') return -1; - - s->z_err = Z_OK; - s->z_eof = 0; - s->back = EOF; - s->stream.avail_in = 0; - s->stream.next_in = s->inbuf; - s->crc = crc32(0L, Z_NULL, 0); - if (!s->transparent) (void)inflateReset(&s->stream); - s->in = 0; - s->out = 0; - return fseek(s->file, s->start, SEEK_SET); + gz_stream *s = (gz_stream*)file; + + if (s == NULL || s->mode != 'r') + return (-1); + + s->z_err = Z_OK; + s->z_eof = 0; + s->back = EOF; + s->stream.avail_in = 0; + s->stream.next_in = s->inbuf; + s->crc = crc32(0L, Z_NULL, 0); + if (!s->transparent) (void)inflateReset(&s->stream); + s->in = 0; + s->out = 0; + return (fseek(s->file, s->start, SEEK_SET)); } -/* =========================================================================== - Returns the starting position for the next gzread or gzwrite on the - given compressed file. This position represents a number of bytes in the - uncompressed data stream. -*/ -z_off_t ZEXPORT gztell (file) - gzFile file; +/* + * Returns the starting position for the next gzread or gzwrite on the + * given compressed file. This position represents a number of bytes in the + * uncompressed data stream. + */ +z_off_t ZEXPORT +gztell(gzFile file) { - return gzseek(file, 0LL, SEEK_CUR); + return (gzseek(file, 0LL, SEEK_CUR)); } -/* =========================================================================== - Returns 1 when EOF has previously been detected reading the given - input stream, otherwise zero. -*/ -int ZEXPORT gzeof (file) - gzFile file; +/* + * Returns 1 when EOF has previously been detected reading the given + * input stream, otherwise zero. + */ +int ZEXPORT +gzeof(gzFile file) { - gz_stream *s = (gz_stream*)file; - - /* With concatenated compressed files that can have embedded - * crc trailers, z_eof is no longer the only/best indicator of EOF - * on a gz_stream. Handle end-of-stream error explicitly here. - */ - if (s == NULL || s->mode != 'r') return 0; - if (s->z_eof) return 1; - return s->z_err == Z_STREAM_END; + gz_stream *s = (gz_stream*)file; + + /* + * With concatenated compressed files that can have embedded + * crc trailers, z_eof is no longer the only/best indicator of EOF + * on a gz_stream. Handle end-of-stream error explicitly here. + */ + if (s == NULL || s->mode != 'r') + return (0); + if (s->z_eof) + return (1); + return (s->z_err == Z_STREAM_END); } -/* =========================================================================== - Returns 1 if reading and doing so transparently, otherwise zero. -*/ -int ZEXPORT gzdirect (file) - gzFile file; +/* + * Returns 1 if reading and doing so transparently, otherwise zero. + */ +int ZEXPORT +gzdirect(gzFile file) { - gz_stream *s = (gz_stream*)file; + gz_stream *s = (gz_stream*)file; - if (s == NULL || s->mode != 'r') return 0; - return s->transparent; + if (s == NULL || s->mode != 'r') + return (0); + return (s->transparent); } -/* =========================================================================== - Outputs a long in LSB order to the given file -*/ -local void putLong (file, x) - FILE *file; - uLong x; +/* + * Outputs a long in LSB order to the given file + */ +local void +putLong( + FILE *file, + uLong x) { - int n; - for (n = 0; n < 4; n++) { - fputc((int)(x & 0xff), file); - x >>= 8; - } + int n; + for (n = 0; n < 4; n++) { + fputc((int)(x & 0xff), file); + x >>= 8; + } } -/* =========================================================================== - Reads a long in LSB order from the given gz_stream. Sets z_err in case - of error. -*/ -local uLong getLong (s) - gz_stream *s; +/* + * Reads a long in LSB order from the given gz_stream. Sets z_err in case + * of error. + */ +local uLong +getLong(gz_stream *s) { - uLong x = (uLong)get_byte(s); - int c; - - x += ((uLong)get_byte(s))<<8; - x += ((uLong)get_byte(s))<<16; - c = get_byte(s); - if (c == EOF) s->z_err = Z_DATA_ERROR; - x += ((uLong)c)<<24; - return x; + uLong x = (uLong)get_byte(s); + int c; + + x += ((uLong)get_byte(s))<<8; + x += ((uLong)get_byte(s))<<16; + c = get_byte(s); + if (c == EOF) s->z_err = Z_DATA_ERROR; + x += ((uLong)c)<<24; + return (x); } -/* =========================================================================== - Flushes all pending output if necessary, closes the compressed file - and deallocates all the (de)compression state. -*/ -int ZEXPORT gzclose (file) - gzFile file; +/* + * Flushes all pending output if necessary, closes the compressed file + * and deallocates all the (de)compression state. + */ +int ZEXPORT +gzclose(gzFile file) { - gz_stream *s = (gz_stream*)file; + gz_stream *s = (gz_stream*)file; - if (s == NULL) return Z_STREAM_ERROR; + if (s == NULL) + return (Z_STREAM_ERROR); - if (s->mode == 'w') { + if (s->mode == 'w') { #ifdef NO_GZCOMPRESS - return Z_STREAM_ERROR; + return (Z_STREAM_ERROR); #else - if (do_flush (file, Z_FINISH) != Z_OK) - return destroy((gz_stream*)file); + if (do_flush(file, Z_FINISH) != Z_OK) + return (destroy((gz_stream*)file)); - putLong (s->file, s->crc); - putLong (s->file, (uLong)(s->in & 0xffffffff)); + putLong(s->file, s->crc); + putLong(s->file, (uLong)(s->in & 0xffffffff)); #endif - } - return destroy((gz_stream*)file); + } + return (destroy((gz_stream*)file)); } #ifdef STDC -# define zstrerror(errnum) strerror(errnum) +#define zstrerror(errnum) strerror(errnum) #else -# define zstrerror(errnum) "" +#define zstrerror(errnum) "" #endif -/* =========================================================================== - Returns the error message for the last error which occurred on the - given compressed file. errnum is set to zlib error number. If an - error occurred in the file system and not in the compression library, - errnum is set to Z_ERRNO and the application may consult errno - to get the exact error code. -*/ -const char * ZEXPORT gzerror (file, errnum) - gzFile file; - int *errnum; +/* + * Returns the error message for the last error which occurred on the + * given compressed file. errnum is set to zlib error number. If an + * error occurred in the file system and not in the compression library, + * errnum is set to Z_ERRNO and the application may consult errno + * to get the exact error code. + */ +const char *ZEXPORT +gzerror( + gzFile file, + int *errnum) { - char *m; - gz_stream *s = (gz_stream*)file; - - if (s == NULL) { - *errnum = Z_STREAM_ERROR; - return (const char*)ERR_MSG(Z_STREAM_ERROR); - } - *errnum = s->z_err; - if (*errnum == Z_OK) return (const char*)""; - - m = (char*)(*errnum == Z_ERRNO ? zstrerror(errno) : s->stream.msg); - - if (m == NULL || *m == '\0') m = (char*)ERR_MSG(s->z_err); - - TRYFREE(s->msg); - s->msg = (char*)ALLOC(strlen(s->path) + strlen(m) + 3); - if (s->msg == Z_NULL) return (const char*)ERR_MSG(Z_MEM_ERROR); - strcpy(s->msg, s->path); - strcat(s->msg, ": "); - strcat(s->msg, m); - return (const char*)s->msg; + char *m; + gz_stream *s = (gz_stream*)file; + + if (s == NULL) { + *errnum = Z_STREAM_ERROR; + return ((const char *)ERR_MSG(Z_STREAM_ERROR)); + } + *errnum = s->z_err; + if (*errnum == Z_OK) + return ((const char *)""); + + m = (char *)(*errnum == Z_ERRNO ? zstrerror(errno) : s->stream.msg); + + if (m == NULL || *m == '\0') m = (char *)ERR_MSG(s->z_err); + + TRYFREE(s->msg); + s->msg = (char *)ALLOC(strlen(s->path) + strlen(m) + 3); + if (s->msg == Z_NULL) + return ((const char *)ERR_MSG(Z_MEM_ERROR)); + strcpy(s->msg, s->path); + strcat(s->msg, ": "); + strcat(s->msg, m); + return ((const char *)s->msg); } -/* =========================================================================== - Clear the error and end-of-file flags, and do the same for the real file. -*/ -void ZEXPORT gzclearerr (file) - gzFile file; +/* + * Clear the error and end-of-file flags, and do the same for the real file. + */ +void ZEXPORT +gzclearerr(gzFile file) { - gz_stream *s = (gz_stream*)file; + gz_stream *s = (gz_stream*)file; - if (s == NULL) return; - if (s->z_err != Z_STREAM_END) s->z_err = Z_OK; - s->z_eof = 0; - clearerr(s->file); + if (s == NULL) + return; + if (s->z_err != Z_STREAM_END) s->z_err = Z_OK; + s->z_eof = 0; + clearerr(s->file); } diff --git a/lib/os/windows/zlib-1.2.3/infback.c b/lib/os/windows/zlib-1.2.3/infback.c index 455dbc9ee84..970192df405 100644 --- a/lib/os/windows/zlib-1.2.3/infback.c +++ b/lib/os/windows/zlib-1.2.3/infback.c @@ -1,13 +1,14 @@ -/* infback.c -- inflate using a call-back interface +/* + * infback.c -- inflate using a call-back interface * Copyright (C) 1995-2005 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* - This code is largely copied from inflate.c. Normally either infback.o or - inflate.o would be linked into an application--not both. The interface - with inffast.c is retained so that optimized assembler-coded versions of - inflate_fast() can be used with either inflate.c or infback.c. + * This code is largely copied from inflate.c. Normally either infback.o or + * inflate.o would be linked into an application--not both. The interface + * with inffast.c is retained so that optimized assembler-coded versions of + * inflate_fast() can be used with either inflate.c or infback.c. */ #include "zutil.h" @@ -19,605 +20,651 @@ local void fixedtables OF((struct inflate_state FAR *state)); /* - strm provides memory allocation functions in zalloc and zfree, or - Z_NULL to use the library memory allocation functions. - - windowBits is in the range 8..15, and window is a user-supplied - window and output buffer that is 2**windowBits bytes. + * strm provides memory allocation functions in zalloc and zfree, or + * Z_NULL to use the library memory allocation functions. + * + * windowBits is in the range 8..15, and window is a user-supplied + * window and output buffer that is 2**windowBits bytes. */ -int ZEXPORT inflateBackInit_(strm, windowBits, window, version, stream_size) -z_streamp strm; -int windowBits; -unsigned char FAR *window; -const char *version; -int stream_size; +int ZEXPORT +inflateBackInit_( + z_streamp strm, + int windowBits, + unsigned char FAR *window, + const char *version, + int stream_size) { - struct inflate_state FAR *state; - - if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || - stream_size != (int)(sizeof(z_stream))) - return Z_VERSION_ERROR; - if (strm == Z_NULL || window == Z_NULL || - windowBits < 8 || windowBits > 15) - return Z_STREAM_ERROR; - strm->msg = Z_NULL; /* in case we return an error */ - if (strm->zalloc == (alloc_func)0) { - strm->zalloc = zcalloc; - strm->opaque = (voidpf)0; - } - if (strm->zfree == (free_func)0) strm->zfree = zcfree; - state = (struct inflate_state FAR *)ZALLOC(strm, 1, - sizeof(struct inflate_state)); - if (state == Z_NULL) return Z_MEM_ERROR; - Tracev((stderr, "inflate: allocated\n")); - strm->state = (struct internal_state FAR *)state; - state->dmax = 32768U; - state->wbits = windowBits; - state->wsize = 1U << windowBits; - state->window = window; - state->write = 0; - state->whave = 0; - return Z_OK; + struct inflate_state FAR *state; + + if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || + stream_size != (int)(sizeof (z_stream))) + return (Z_VERSION_ERROR); + if (strm == Z_NULL || window == Z_NULL || + windowBits < 8 || windowBits > 15) + return (Z_STREAM_ERROR); + strm->msg = Z_NULL; /* in case we return an error */ + if (strm->zalloc == (alloc_func)0) { + strm->zalloc = zcalloc; + strm->opaque = (voidpf)0; + } + if (strm->zfree == (free_func)0) strm->zfree = zcfree; + state = (struct inflate_state FAR *)ZALLOC(strm, 1, + sizeof (struct inflate_state)); + if (state == Z_NULL) + return (Z_MEM_ERROR); + Tracev((stderr, "inflate: allocated\n")); + strm->state = (struct internal_state FAR *)state; + state->dmax = 32768U; + state->wbits = windowBits; + state->wsize = 1U << windowBits; + state->window = window; + state->write = 0; + state->whave = 0; + return (Z_OK); } /* - Return state with length and distance decoding tables and index sizes set to - fixed code decoding. Normally this returns fixed tables from inffixed.h. - If BUILDFIXED is defined, then instead this routine builds the tables the - first time it's called, and returns those tables the first time and - thereafter. This reduces the size of the code by about 2K bytes, in - exchange for a little execution time. However, BUILDFIXED should not be - used for threaded applications, since the rewriting of the tables and virgin - may not be thread-safe. + * Return state with length and distance decoding tables and index sizes set to + * fixed code decoding. Normally this returns fixed tables from inffixed.h. + * If BUILDFIXED is defined, then instead this routine builds the tables the + * first time it's called, and returns those tables the first time and + * thereafter. This reduces the size of the code by about 2K bytes, in + * exchange for a little execution time. However, BUILDFIXED should not be + * used for threaded applications, since the rewriting of the tables and virgin + * may not be thread-safe. */ -local void fixedtables(state) -struct inflate_state FAR *state; +local void +fixedtables(struct inflate_state FAR *state) { #ifdef BUILDFIXED - static int virgin = 1; - static code *lenfix, *distfix; - static code fixed[544]; - - /* build fixed huffman tables if first call (may not be thread safe) */ - if (virgin) { - unsigned sym, bits; - static code *next; - - /* literal/length table */ - sym = 0; - while (sym < 144) state->lens[sym++] = 8; - while (sym < 256) state->lens[sym++] = 9; - while (sym < 280) state->lens[sym++] = 7; - while (sym < 288) state->lens[sym++] = 8; - next = fixed; - lenfix = next; - bits = 9; - inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work); - - /* distance table */ - sym = 0; - while (sym < 32) state->lens[sym++] = 5; - distfix = next; - bits = 5; - inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work); - - /* do this just once */ - virgin = 0; - } + static int virgin = 1; + static code *lenfix, *distfix; + static code fixed[544]; + + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + unsigned sym, bits; + static code *next; + + /* literal/length table */ + sym = 0; + while (sym < 144) state->lens[sym++] = 8; + while (sym < 256) state->lens[sym++] = 9; + while (sym < 280) state->lens[sym++] = 7; + while (sym < 288) state->lens[sym++] = 8; + next = fixed; + lenfix = next; + bits = 9; + inflate_table(LENS, state->lens, 288, &(next), &(bits), + state->work); + + /* distance table */ + sym = 0; + while (sym < 32) state->lens[sym++] = 5; + distfix = next; + bits = 5; + inflate_table(DISTS, state->lens, 32, &(next), &(bits), + state->work); + + /* do this just once */ + virgin = 0; + } #else /* !BUILDFIXED */ -# include "inffixed.h" +#include "inffixed.h" #endif /* BUILDFIXED */ - state->lencode = lenfix; - state->lenbits = 9; - state->distcode = distfix; - state->distbits = 5; + state->lencode = lenfix; + state->lenbits = 9; + state->distcode = distfix; + state->distbits = 5; } /* Macros for inflateBack(): */ /* Load returned state from inflate_fast() */ -#define LOAD() \ +#define LOAD() \ do { \ - put = strm->next_out; \ - left = strm->avail_out; \ - next = strm->next_in; \ - have = strm->avail_in; \ - hold = state->hold; \ - bits = state->bits; \ - } while (0) + put = strm->next_out; \ + left = strm->avail_out; \ + next = strm->next_in; \ + have = strm->avail_in; \ + hold = state->hold; \ + bits = state->bits; \ + } while (0) /* Set state from registers for inflate_fast() */ -#define RESTORE() \ +#define RESTORE() \ do { \ - strm->next_out = put; \ - strm->avail_out = left; \ - strm->next_in = next; \ - strm->avail_in = have; \ - state->hold = hold; \ - state->bits = bits; \ - } while (0) + strm->next_out = put; \ + strm->avail_out = left; \ + strm->next_in = next; \ + strm->avail_in = have; \ + state->hold = hold; \ + state->bits = bits; \ + } while (0) /* Clear the input bit accumulator */ -#define INITBITS() \ +#define INITBITS() \ do { \ - hold = 0; \ - bits = 0; \ - } while (0) + hold = 0; \ + bits = 0; \ + } while (0) -/* Assure that some input is available. If input is requested, but denied, - then return a Z_BUF_ERROR from inflateBack(). */ -#define PULL() \ +/* + * Assure that some input is available. If input is requested, but denied, + * then return a Z_BUF_ERROR from inflateBack(). + */ +#define PULL() \ do { \ - if (have == 0) { \ - have = in(in_desc, &next); \ - if (have == 0) { \ - next = Z_NULL; \ - ret = Z_BUF_ERROR; \ - goto inf_leave; \ - } \ - } \ - } while (0) - -/* Get a byte of input into the bit accumulator, or return from inflateBack() - with an error if there is no input available. */ -#define PULLBYTE() \ + if (have == 0) { \ + have = in(in_desc, &next); \ + if (have == 0) { \ + next = Z_NULL; \ + ret = Z_BUF_ERROR; \ + goto inf_leave; \ + } \ + } \ + } while (0) + +/* + * Get a byte of input into the bit accumulator, or return from inflateBack() + * with an error if there is no input available. + */ +#define PULLBYTE() \ do { \ - PULL(); \ - have--; \ - hold += (unsigned long)(*next++) << bits; \ - bits += 8; \ - } while (0) - -/* Assure that there are at least n bits in the bit accumulator. If there is - not enough available input to do that, then return from inflateBack() with - an error. */ -#define NEEDBITS(n) \ + PULL(); \ + have--; \ + hold += (unsigned long)(*next++) << bits; \ + bits += 8; \ + } while (0) + +/* + * Assure that there are at least n bits in the bit accumulator. If there is + * not enough available input to do that, then return from inflateBack() with + * an error. + */ +#define NEEDBITS(n) \ do { \ - while (bits < (unsigned)(n)) \ - PULLBYTE(); \ - } while (0) + while (bits < (unsigned)(n)) \ + PULLBYTE(); \ + } while (0) /* Return the low n bits of the bit accumulator (n < 16) */ -#define BITS(n) \ - ((unsigned)hold & ((1U << (n)) - 1)) +#define BITS(n) \ + ((unsigned)hold & ((1U << (n)) - 1)) /* Remove n bits from the bit accumulator */ -#define DROPBITS(n) \ +#define DROPBITS(n) \ do { \ - hold >>= (n); \ - bits -= (unsigned)(n); \ - } while (0) + hold >>= (n); \ + bits -= (unsigned)(n); \ + } while (0) /* Remove zero to seven bits as needed to go to a byte boundary */ -#define BYTEBITS() \ +#define BYTEBITS() \ do { \ - hold >>= bits & 7; \ - bits -= bits & 7; \ - } while (0) - -/* Assure that some output space is available, by writing out the window - if it's full. If the write fails, return from inflateBack() with a - Z_BUF_ERROR. */ -#define ROOM() \ + hold >>= bits & 7; \ + bits -= bits & 7; \ + } while (0) + +/* + * Assure that some output space is available, by writing out the window + * if it's full. If the write fails, return from inflateBack() with a + * Z_BUF_ERROR. + */ +#define ROOM() \ do { \ - if (left == 0) { \ - put = state->window; \ - left = state->wsize; \ - state->whave = left; \ - if (out(out_desc, put, left)) { \ - ret = Z_BUF_ERROR; \ - goto inf_leave; \ - } \ - } \ - } while (0) + if (left == 0) { \ + put = state->window; \ + left = state->wsize; \ + state->whave = left; \ + if (out(out_desc, put, left)) { \ + ret = Z_BUF_ERROR; \ + goto inf_leave; \ + } \ + } \ + } while (0) /* - strm provides the memory allocation functions and window buffer on input, - and provides information on the unused input on return. For Z_DATA_ERROR - returns, strm will also provide an error message. - - in() and out() are the call-back input and output functions. When - inflateBack() needs more input, it calls in(). When inflateBack() has - filled the window with output, or when it completes with data in the - window, it calls out() to write out the data. The application must not - change the provided input until in() is called again or inflateBack() - returns. The application must not change the window/output buffer until - inflateBack() returns. - - in() and out() are called with a descriptor parameter provided in the - inflateBack() call. This parameter can be a structure that provides the - information required to do the read or write, as well as accumulated - information on the input and output such as totals and check values. - - in() should return zero on failure. out() should return non-zero on - failure. If either in() or out() fails, than inflateBack() returns a - Z_BUF_ERROR. strm->next_in can be checked for Z_NULL to see whether it - was in() or out() that caused in the error. Otherwise, inflateBack() - returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format - error, or Z_MEM_ERROR if it could not allocate memory for the state. - inflateBack() can also return Z_STREAM_ERROR if the input parameters - are not correct, i.e. strm is Z_NULL or the state was not initialized. + * strm provides the memory allocation functions and window buffer on input, + * and provides information on the unused input on return. For Z_DATA_ERROR + * returns, strm will also provide an error message. + * + * in() and out() are the call-back input and output functions. When + * inflateBack() needs more input, it calls in(). When inflateBack() has + * filled the window with output, or when it completes with data in the + * window, it calls out() to write out the data. The application must not + * change the provided input until in() is called again or inflateBack() + * returns. The application must not change the window/output buffer until + * inflateBack() returns. + * + * in() and out() are called with a descriptor parameter provided in the + * inflateBack() call. This parameter can be a structure that provides the + * information required to do the read or write, as well as accumulated + * information on the input and output such as totals and check values. + * + * in() should return zero on failure. out() should return non-zero on + * failure. If either in() or out() fails, than inflateBack() returns a + * Z_BUF_ERROR. strm->next_in can be checked for Z_NULL to see whether it + * was in() or out() that caused in the error. Otherwise, inflateBack() + * returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format + * error, or Z_MEM_ERROR if it could not allocate memory for the state. + * inflateBack() can also return Z_STREAM_ERROR if the input parameters + * are not correct, i.e. strm is Z_NULL or the state was not initialized. */ -int ZEXPORT inflateBack(strm, in, in_desc, out, out_desc) -z_streamp strm; -in_func in; -void FAR *in_desc; -out_func out; -void FAR *out_desc; +int ZEXPORT +inflateBack( + z_streamp strm, + in_func in, + void FAR *in_desc, + out_func out, + void FAR *out_desc) { - struct inflate_state FAR *state; - unsigned char FAR *next; /* next input */ - unsigned char FAR *put; /* next output */ - unsigned have, left; /* available input and output */ - unsigned long hold; /* bit buffer */ - unsigned bits; /* bits in bit buffer */ - unsigned copy; /* number of stored or match bytes to copy */ - unsigned char FAR *from; /* where to copy match bytes from */ - code this; /* current decoding table entry */ - code last; /* parent table entry */ - unsigned len; /* length to copy for repeats, bits to drop */ - int ret; /* return code */ - static const unsigned short order[19] = /* permutation of code lengths */ - {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; - - /* Check that the strm exists and that the state was initialized */ - if (strm == Z_NULL || strm->state == Z_NULL) - return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - - /* Reset the state */ - strm->msg = Z_NULL; - state->mode = TYPE; - state->last = 0; - state->whave = 0; - next = strm->next_in; - have = next != Z_NULL ? strm->avail_in : 0; - hold = 0; - bits = 0; - put = state->window; - left = state->wsize; - - /* Inflate until end of block marked as last */ - for (;;) - switch (state->mode) { - case TYPE: - /* determine and dispatch block type */ - if (state->last) { - BYTEBITS(); - state->mode = DONE; - break; - } - NEEDBITS(3); - state->last = BITS(1); - DROPBITS(1); - switch (BITS(2)) { - case 0: /* stored block */ - Tracev((stderr, "inflate: stored block%s\n", - state->last ? " (last)" : "")); - state->mode = STORED; - break; - case 1: /* fixed block */ - fixedtables(state); - Tracev((stderr, "inflate: fixed codes block%s\n", - state->last ? " (last)" : "")); - state->mode = LEN; /* decode codes */ - break; - case 2: /* dynamic block */ - Tracev((stderr, "inflate: dynamic codes block%s\n", - state->last ? " (last)" : "")); - state->mode = TABLE; - break; - case 3: - strm->msg = (char *)"invalid block type"; - state->mode = BAD; - } - DROPBITS(2); - break; - - case STORED: - /* get and verify stored block length */ - BYTEBITS(); /* go to byte boundary */ - NEEDBITS(32); - if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { - strm->msg = (char *)"invalid stored block lengths"; - state->mode = BAD; - break; - } - state->length = (unsigned)hold & 0xffff; - Tracev((stderr, "inflate: stored length %u\n", - state->length)); - INITBITS(); - - /* copy stored block from input to output */ - while (state->length != 0) { - copy = state->length; - PULL(); - ROOM(); - if (copy > have) copy = have; - if (copy > left) copy = left; - zmemcpy(put, next, copy); - have -= copy; - next += copy; - left -= copy; - put += copy; - state->length -= copy; - } - Tracev((stderr, "inflate: stored end\n")); - state->mode = TYPE; - break; - - case TABLE: - /* get dynamic table entries descriptor */ - NEEDBITS(14); - state->nlen = BITS(5) + 257; - DROPBITS(5); - state->ndist = BITS(5) + 1; - DROPBITS(5); - state->ncode = BITS(4) + 4; - DROPBITS(4); + struct inflate_state FAR *state; + unsigned char FAR *next; /* next input */ + unsigned char FAR *put; /* next output */ + unsigned have, left; /* available input and output */ + unsigned long hold; /* bit buffer */ + unsigned bits; /* bits in bit buffer */ + unsigned copy; /* number of stored or match bytes to copy */ + unsigned char FAR *from; /* where to copy match bytes from */ + code this; /* current decoding table entry */ + code last; /* parent table entry */ + unsigned len; /* length to copy for repeats, bits to drop */ + int ret; /* return code */ + static const unsigned short order[19] = + {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; + + /* Check that the strm exists and that the state was initialized */ + if (strm == Z_NULL || strm->state == Z_NULL) + return (Z_STREAM_ERROR); + state = (struct inflate_state FAR *)strm->state; + + /* Reset the state */ + strm->msg = Z_NULL; + state->mode = TYPE; + state->last = 0; + state->whave = 0; + next = strm->next_in; + have = next != Z_NULL ? strm->avail_in : 0; + hold = 0; + bits = 0; + put = state->window; + left = state->wsize; + + /* Inflate until end of block marked as last */ + for (;;) + switch (state->mode) { + case TYPE: + /* determine and dispatch block type */ + if (state->last) { + BYTEBITS(); + state->mode = DONE; + break; + } + NEEDBITS(3); + state->last = BITS(1); + DROPBITS(1); + switch (BITS(2)) { + case 0: /* stored block */ + Tracev((stderr, "inflate: stored block%s\n", + state->last ? " (last)" : "")); + state->mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + Tracev((stderr, + "inflate: fixed codes block%s\n", + state->last ? " (last)" : "")); + state->mode = LEN; /* decode codes */ + break; + case 2: /* dynamic block */ + Tracev((stderr, + "inflate: dynamic codes block%s\n", + state->last ? " (last)" : "")); + state->mode = TABLE; + break; + case 3: + strm->msg = (char *)"invalid block type"; + state->mode = BAD; + } + DROPBITS(2); + break; + + case STORED: + /* get and verify stored block length */ + BYTEBITS(); /* go to byte boundary */ + NEEDBITS(32); + if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { + strm->msg = + (char *)"invalid stored block lengths"; + state->mode = BAD; + break; + } + state->length = (unsigned)hold & 0xffff; + Tracev((stderr, "inflate: stored length %u\n", + state->length)); + INITBITS(); + + /* copy stored block from input to output */ + while (state->length != 0) { + copy = state->length; + PULL(); + ROOM(); + if (copy > have) copy = have; + if (copy > left) copy = left; + zmemcpy(put, next, copy); + have -= copy; + next += copy; + left -= copy; + put += copy; + state->length -= copy; + } + Tracev((stderr, "inflate: stored end\n")); + state->mode = TYPE; + break; + + case TABLE: + /* get dynamic table entries descriptor */ + NEEDBITS(14); + state->nlen = BITS(5) + 257; + DROPBITS(5); + state->ndist = BITS(5) + 1; + DROPBITS(5); + state->ncode = BITS(4) + 4; + DROPBITS(4); #ifndef PKZIP_BUG_WORKAROUND - if (state->nlen > 286 || state->ndist > 30) { - strm->msg = (char *)"too many length or distance symbols"; - state->mode = BAD; - break; - } + if (state->nlen > 286 || state->ndist > 30) { + strm->msg = (char *) + "too many length or distance symbols"; + state->mode = BAD; + break; + } #endif - Tracev((stderr, "inflate: table sizes ok\n")); - - /* get code length code lengths (not a typo) */ - state->have = 0; - while (state->have < state->ncode) { - NEEDBITS(3); - state->lens[order[state->have++]] = (unsigned short)BITS(3); - DROPBITS(3); - } - while (state->have < 19) - state->lens[order[state->have++]] = 0; - state->next = state->codes; - state->lencode = (code const FAR *)(state->next); - state->lenbits = 7; - ret = inflate_table(CODES, state->lens, 19, &(state->next), - &(state->lenbits), state->work); - if (ret) { - strm->msg = (char *)"invalid code lengths set"; - state->mode = BAD; - break; - } - Tracev((stderr, "inflate: code lengths ok\n")); - - /* get length and distance code code lengths */ - state->have = 0; - while (state->have < state->nlen + state->ndist) { - for (;;) { - this = state->lencode[BITS(state->lenbits)]; - if ((unsigned)(this.bits) <= bits) break; - PULLBYTE(); - } - if (this.val < 16) { - NEEDBITS(this.bits); - DROPBITS(this.bits); - state->lens[state->have++] = this.val; - } - else { - if (this.val == 16) { - NEEDBITS(this.bits + 2); - DROPBITS(this.bits); - if (state->have == 0) { - strm->msg = (char *)"invalid bit length repeat"; - state->mode = BAD; - break; - } - len = (unsigned)(state->lens[state->have - 1]); - copy = 3 + BITS(2); - DROPBITS(2); - } - else if (this.val == 17) { - NEEDBITS(this.bits + 3); - DROPBITS(this.bits); - len = 0; - copy = 3 + BITS(3); - DROPBITS(3); - } - else { - NEEDBITS(this.bits + 7); - DROPBITS(this.bits); - len = 0; - copy = 11 + BITS(7); - DROPBITS(7); - } - if (state->have + copy > state->nlen + state->ndist) { - strm->msg = (char *)"invalid bit length repeat"; - state->mode = BAD; - break; - } - while (copy--) - state->lens[state->have++] = (unsigned short)len; - } - } - - /* handle error breaks in while */ - if (state->mode == BAD) break; - - /* build code tables */ - state->next = state->codes; - state->lencode = (code const FAR *)(state->next); - state->lenbits = 9; - ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), - &(state->lenbits), state->work); - if (ret) { - strm->msg = (char *)"invalid literal/lengths set"; - state->mode = BAD; - break; - } - state->distcode = (code const FAR *)(state->next); - state->distbits = 6; - ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, - &(state->next), &(state->distbits), state->work); - if (ret) { - strm->msg = (char *)"invalid distances set"; - state->mode = BAD; - break; - } - Tracev((stderr, "inflate: codes ok\n")); - state->mode = LEN; - - case LEN: - /* use inflate_fast() if we have enough input and output */ - if (have >= 6 && left >= 258) { - RESTORE(); - if (state->whave < state->wsize) - state->whave = state->wsize - left; - inflate_fast(strm, state->wsize); - LOAD(); - break; - } - - /* get a literal, length, or end-of-block code */ - for (;;) { - this = state->lencode[BITS(state->lenbits)]; - if ((unsigned)(this.bits) <= bits) break; - PULLBYTE(); - } - if (this.op && (this.op & 0xf0) == 0) { - last = this; - for (;;) { - this = state->lencode[last.val + - (BITS(last.bits + last.op) >> last.bits)]; - if ((unsigned)(last.bits + this.bits) <= bits) break; - PULLBYTE(); - } - DROPBITS(last.bits); - } - DROPBITS(this.bits); - state->length = (unsigned)this.val; - - /* process literal */ - if (this.op == 0) { - Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ? - "inflate: literal '%c'\n" : - "inflate: literal 0x%02x\n", this.val)); - ROOM(); - *put++ = (unsigned char)(state->length); - left--; - state->mode = LEN; - break; - } - - /* process end of block */ - if (this.op & 32) { - Tracevv((stderr, "inflate: end of block\n")); - state->mode = TYPE; - break; - } - - /* invalid code */ - if (this.op & 64) { - strm->msg = (char *)"invalid literal/length code"; - state->mode = BAD; - break; - } - - /* length code -- get extra bits, if any */ - state->extra = (unsigned)(this.op) & 15; - if (state->extra != 0) { - NEEDBITS(state->extra); - state->length += BITS(state->extra); - DROPBITS(state->extra); - } - Tracevv((stderr, "inflate: length %u\n", state->length)); - - /* get distance code */ - for (;;) { - this = state->distcode[BITS(state->distbits)]; - if ((unsigned)(this.bits) <= bits) break; - PULLBYTE(); - } - if ((this.op & 0xf0) == 0) { - last = this; - for (;;) { - this = state->distcode[last.val + - (BITS(last.bits + last.op) >> last.bits)]; - if ((unsigned)(last.bits + this.bits) <= bits) break; - PULLBYTE(); - } - DROPBITS(last.bits); - } - DROPBITS(this.bits); - if (this.op & 64) { - strm->msg = (char *)"invalid distance code"; - state->mode = BAD; - break; - } - state->offset = (unsigned)this.val; - - /* get distance extra bits, if any */ - state->extra = (unsigned)(this.op) & 15; - if (state->extra != 0) { - NEEDBITS(state->extra); - state->offset += BITS(state->extra); - DROPBITS(state->extra); - } - if (state->offset > state->wsize - (state->whave < state->wsize ? - left : 0)) { - strm->msg = (char *)"invalid distance too far back"; - state->mode = BAD; - break; - } - Tracevv((stderr, "inflate: distance %u\n", state->offset)); - - /* copy match from window to output */ - do { - ROOM(); - copy = state->wsize - state->offset; - if (copy < left) { - from = put + copy; - copy = left - copy; - } - else { - from = put - state->offset; - copy = left; - } - if (copy > state->length) copy = state->length; - state->length -= copy; - left -= copy; - do { - *put++ = *from++; - } while (--copy); - } while (state->length != 0); - break; - - case DONE: - /* inflate stream terminated properly -- write leftover output */ - ret = Z_STREAM_END; - if (left < state->wsize) { - if (out(out_desc, state->window, state->wsize - left)) - ret = Z_BUF_ERROR; - } - goto inf_leave; - - case BAD: - ret = Z_DATA_ERROR; - goto inf_leave; - - default: /* can't happen, but makes compilers happy */ - ret = Z_STREAM_ERROR; - goto inf_leave; - } - - /* Return unused input */ - inf_leave: - strm->next_in = next; - strm->avail_in = have; - return ret; + Tracev((stderr, "inflate: table sizes ok\n")); + + /* get code length code lengths (not a typo) */ + state->have = 0; + while (state->have < state->ncode) { + NEEDBITS(3); + state->lens[order[state->have++]] = + (unsigned short)BITS(3); + DROPBITS(3); + } + while (state->have < 19) + state->lens[order[state->have++]] = 0; + state->next = state->codes; + state->lencode = (code const FAR *)(state->next); + state->lenbits = 7; + ret = inflate_table(CODES, state->lens, 19, + &(state->next), &(state->lenbits), + state->work); + if (ret) { + strm->msg = (char *)"invalid code lengths set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: code lengths ok\n")); + + /* get length and distance code code lengths */ + state->have = 0; + while (state->have < state->nlen + state->ndist) { + for (;;) { + this = state->lencode[ + BITS(state->lenbits)]; + if ((unsigned)(this.bits) <= bits) + break; + PULLBYTE(); + } + if (this.val < 16) { + NEEDBITS(this.bits); + DROPBITS(this.bits); + state->lens[state->have++] = this.val; + } else { + if (this.val == 16) { + NEEDBITS(this.bits + 2); + DROPBITS(this.bits); + if (state->have == 0) { + strm->msg = (char *) + "invalid bit " + "length repeat"; + state->mode = BAD; + break; + } + len = (unsigned) + (state->lens[ + state->have - 1]); + copy = 3 + BITS(2); + DROPBITS(2); + } else if (this.val == 17) { + NEEDBITS(this.bits + 3); + DROPBITS(this.bits); + len = 0; + copy = 3 + BITS(3); + DROPBITS(3); + } else { + NEEDBITS(this.bits + 7); + DROPBITS(this.bits); + len = 0; + copy = 11 + BITS(7); + DROPBITS(7); + } + if (state->have + copy > + state->nlen + state->ndist) { + strm->msg = (char *) + "invalid bit length repeat"; + state->mode = BAD; + break; + } + while (copy--) + state->lens[state->have++] = + (unsigned short)len; + } + } + + /* handle error breaks in while */ + if (state->mode == BAD) + break; + + /* build code tables */ + state->next = state->codes; + state->lencode = (code const FAR *)(state->next); + state->lenbits = 9; + ret = inflate_table(LENS, state->lens, + state->nlen, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *) + "invalid literal/lengths set"; + state->mode = BAD; + break; + } + state->distcode = (code const FAR *)(state->next); + state->distbits = 6; + ret = inflate_table(DISTS, state->lens + state->nlen, + state->ndist, &(state->next), &(state->distbits), + state->work); + if (ret) { + strm->msg = (char *)"invalid distances set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: codes ok\n")); + state->mode = LEN; + + case LEN: + /* use inflate_fast() if we have enough input and output */ + if (have >= 6 && left >= 258) { + RESTORE(); + if (state->whave < state->wsize) + state->whave = state->wsize - left; + inflate_fast(strm, state->wsize); + LOAD(); + break; + } + + /* get a literal, length, or end-of-block code */ + for (;;) { + this = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(this.bits) <= bits) + break; + PULLBYTE(); + } + if (this.op && (this.op & 0xf0) == 0) { + last = this; + for (;;) { + this = state->lencode[last.val + + (BITS(last.bits + last.op) >> + last.bits)]; + if ((unsigned)(last.bits + this.bits) <= + bits) + break; + PULLBYTE(); + } + DROPBITS(last.bits); + } + DROPBITS(this.bits); + state->length = (unsigned)this.val; + + /* process literal */ + if (this.op == 0) { + Tracevv((stderr, this.val >= 0x20 && + this.val < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", + this.val)); + ROOM(); + *put++ = (unsigned char)(state->length); + left--; + state->mode = LEN; + break; + } + + /* process end of block */ + if (this.op & 32) { + Tracevv((stderr, + "inflate: end of block\n")); + state->mode = TYPE; + break; + } + + /* invalid code */ + if (this.op & 64) { + strm->msg = (char *) + "invalid literal/length code"; + state->mode = BAD; + break; + } + + /* length code -- get extra bits, if any */ + state->extra = (unsigned)(this.op) & 15; + if (state->extra != 0) { + NEEDBITS(state->extra); + state->length += BITS(state->extra); + DROPBITS(state->extra); + } + Tracevv((stderr, "inflate: length %u\n", + state->length)); + + /* get distance code */ + for (;;) { + this = state->distcode[BITS(state->distbits)]; + if ((unsigned)(this.bits) <= bits) + break; + PULLBYTE(); + } + if ((this.op & 0xf0) == 0) { + last = this; + for (;;) { + this = state->distcode[last.val + + (BITS(last.bits + last.op) >> + last.bits)]; + if ((unsigned)(last.bits + this.bits) <= + bits) + break; + PULLBYTE(); + } + DROPBITS(last.bits); + } + DROPBITS(this.bits); + if (this.op & 64) { + strm->msg = (char *)"invalid distance code"; + state->mode = BAD; + break; + } + state->offset = (unsigned)this.val; + + /* get distance extra bits, if any */ + state->extra = (unsigned)(this.op) & 15; + if (state->extra != 0) { + NEEDBITS(state->extra); + state->offset += BITS(state->extra); + DROPBITS(state->extra); + } + if (state->offset > state->wsize - + (state->whave < state->wsize ? + left : 0)) { + strm->msg = (char *) + "invalid distance too far back"; + state->mode = BAD; + break; + } + Tracevv((stderr, "inflate: distance %u\n", + state->offset)); + + /* copy match from window to output */ + do { + ROOM(); + copy = state->wsize - state->offset; + if (copy < left) { + from = put + copy; + copy = left - copy; + } else { + from = put - state->offset; + copy = left; + } + if (copy > state->length) copy = state->length; + state->length -= copy; + left -= copy; + do { + *put++ = *from++; + } while (--copy); + } while (state->length != 0); + break; + + case DONE: + /* inflate stream terminated properly -- write leftover output */ + ret = Z_STREAM_END; + if (left < state->wsize) { + if (out(out_desc, state->window, + state->wsize - left)) + ret = Z_BUF_ERROR; + } + goto inf_leave; + + case BAD: + ret = Z_DATA_ERROR; + goto inf_leave; + + default: /* can't happen, but makes compilers happy */ + ret = Z_STREAM_ERROR; + goto inf_leave; + } + + /* Return unused input */ +inf_leave: + strm->next_in = next; + strm->avail_in = have; + return (ret); } -int ZEXPORT inflateBackEnd(strm) -z_streamp strm; +int ZEXPORT +inflateBackEnd(z_streamp strm) { - if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0) - return Z_STREAM_ERROR; - ZFREE(strm, strm->state); - strm->state = Z_NULL; - Tracev((stderr, "inflate: end\n")); - return Z_OK; + if (strm == Z_NULL || strm->state == Z_NULL || + strm->zfree == (free_func)0) + return (Z_STREAM_ERROR); + ZFREE(strm, strm->state); + strm->state = Z_NULL; + Tracev((stderr, "inflate: end\n")); + return (Z_OK); } diff --git a/lib/os/windows/zlib-1.2.3/inffast.c b/lib/os/windows/zlib-1.2.3/inffast.c index bbee92ed1e6..9248f7f523c 100644 --- a/lib/os/windows/zlib-1.2.3/inffast.c +++ b/lib/os/windows/zlib-1.2.3/inffast.c @@ -1,4 +1,5 @@ -/* inffast.c -- fast decoding +/* + * inffast.c -- fast decoding * Copyright (C) 1995-2004 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ @@ -10,309 +11,327 @@ #ifndef ASMINF -/* Allow machine dependent optimization for post-increment or pre-increment. - Based on testing to date, - Pre-increment preferred for: - - PowerPC G3 (Adler) - - MIPS R5000 (Randers-Pehrson) - Post-increment preferred for: - - none - No measurable difference: - - Pentium III (Anderson) - - M68060 (Nikl) +/* + * Allow machine dependent optimization for post-increment or pre-increment. + * Based on testing to date, + * Pre-increment preferred for: + * - PowerPC G3 (Adler) + * - MIPS R5000 (Randers-Pehrson) + * Post-increment preferred for: + * - none + * No measurable difference: + * - Pentium III (Anderson) + * - M68060 (Nikl) */ #ifdef POSTINC -# define OFF 0 -# define PUP(a) *(a)++ +#define OFF 0 +#define PUP(a) *(a)++ #else -# define OFF 1 -# define PUP(a) *++(a) +#define OFF 1 +#define PUP(a) *++(a) #endif /* - Decode literal, length, and distance codes and write out the resulting - literal and match bytes until either not enough input or output is - available, an end-of-block is encountered, or a data error is encountered. - When large enough input and output buffers are supplied to inflate(), for - example, a 16K input buffer and a 64K output buffer, more than 95% of the - inflate execution time is spent in this routine. - - Entry assumptions: - - state->mode == LEN - strm->avail_in >= 6 - strm->avail_out >= 258 - start >= strm->avail_out - state->bits < 8 - - On return, state->mode is one of: - - LEN -- ran out of enough output space or enough available input - TYPE -- reached end of block code, inflate() to interpret next block - BAD -- error in block data - - Notes: - - - The maximum input bits used by a length/distance pair is 15 bits for the - length code, 5 bits for the length extra, 15 bits for the distance code, - and 13 bits for the distance extra. This totals 48 bits, or six bytes. - Therefore if strm->avail_in >= 6, then there is enough input to avoid - checking for available input while decoding. - - - The maximum bytes that a single length/distance pair can output is 258 - bytes, which is the maximum length that can be coded. inflate_fast() - requires strm->avail_out >= 258 for each loop to avoid checking for - output space. + * Decode literal, length, and distance codes and write out the resulting + * literal and match bytes until either not enough input or output is + * available, an end-of-block is encountered, or a data error is encountered. + * When large enough input and output buffers are supplied to inflate(), for + * example, a 16K input buffer and a 64K output buffer, more than 95% of the + * inflate execution time is spent in this routine. + * + * Entry assumptions: + * + * state->mode == LEN + * strm->avail_in >= 6 + * strm->avail_out >= 258 + * start >= strm->avail_out + * state->bits < 8 + * + * On return, state->mode is one of: + * + * LEN -- ran out of enough output space or enough available input + * TYPE -- reached end of block code, inflate() to interpret next block + * BAD -- error in block data + * + * Notes: + * + * - The maximum input bits used by a length/distance pair is 15 bits for the + * length code, 5 bits for the length extra, 15 bits for the distance code, + * and 13 bits for the distance extra. This totals 48 bits, or six bytes. + * Therefore if strm->avail_in >= 6, then there is enough input to avoid + * checking for available input while decoding. + * + * - The maximum bytes that a single length/distance pair can output is 258 + * bytes, which is the maximum length that can be coded. inflate_fast() + * requires strm->avail_out >= 258 for each loop to avoid checking for + * output space. */ -void inflate_fast(strm, start) -z_streamp strm; -unsigned start; /* inflate()'s starting value for strm->avail_out */ +void +inflate_fast( + z_streamp strm, + unsigned start) /* inflate()'s starting value for strm->avail_out */ { - struct inflate_state FAR *state; - unsigned char FAR *in; /* local strm->next_in */ - unsigned char FAR *last; /* while in < last, enough input available */ - unsigned char FAR *out; /* local strm->next_out */ - unsigned char FAR *beg; /* inflate()'s initial strm->next_out */ - unsigned char FAR *end; /* while out < end, enough space available */ + struct inflate_state FAR *state; + unsigned char FAR *in; /* local strm->next_in */ + unsigned char FAR *last; /* while in < last, enough input available */ + unsigned char FAR *out; /* local strm->next_out */ + unsigned char FAR *beg; /* inflate()'s initial strm->next_out */ + unsigned char FAR *end; /* while out < end, enough space available */ #ifdef INFLATE_STRICT - unsigned dmax; /* maximum distance from zlib header */ + unsigned dmax; /* maximum distance from zlib header */ #endif - unsigned wsize; /* window size or zero if not using window */ - unsigned whave; /* valid bytes in the window */ - unsigned write; /* window write index */ - unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */ - unsigned long hold; /* local strm->hold */ - unsigned bits; /* local strm->bits */ - code const FAR *lcode; /* local strm->lencode */ - code const FAR *dcode; /* local strm->distcode */ - unsigned lmask; /* mask for first level of length codes */ - unsigned dmask; /* mask for first level of distance codes */ - code this; /* retrieved table entry */ - unsigned op; /* code bits, operation, extra bits, or */ - /* window position, window bytes to copy */ - unsigned len; /* match length, unused bytes */ - unsigned dist; /* match distance */ - unsigned char FAR *from; /* where to copy match from */ + unsigned wsize; /* window size or zero if not using window */ + unsigned whave; /* valid bytes in the window */ + unsigned write; /* window write index */ + unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */ + unsigned long hold; /* local strm->hold */ + unsigned bits; /* local strm->bits */ + code const FAR *lcode; /* local strm->lencode */ + code const FAR *dcode; /* local strm->distcode */ + unsigned lmask; /* mask for first level of length codes */ + unsigned dmask; /* mask for first level of distance codes */ + code this; /* retrieved table entry */ + unsigned op; /* code bits, operation, extra bits, or */ + /* window position, window bytes to copy */ + unsigned len; /* match length, unused bytes */ + unsigned dist; /* match distance */ + unsigned char FAR *from; /* where to copy match from */ - /* copy state to local variables */ - state = (struct inflate_state FAR *)strm->state; - in = strm->next_in - OFF; - last = in + (strm->avail_in - 5); - out = strm->next_out - OFF; - beg = out - (start - strm->avail_out); - end = out + (strm->avail_out - 257); + /* copy state to local variables */ + state = (struct inflate_state FAR *)strm->state; + in = strm->next_in - OFF; + last = in + (strm->avail_in - 5); + out = strm->next_out - OFF; + beg = out - (start - strm->avail_out); + end = out + (strm->avail_out - 257); #ifdef INFLATE_STRICT - dmax = state->dmax; + dmax = state->dmax; #endif - wsize = state->wsize; - whave = state->whave; - write = state->write; - window = state->window; - hold = state->hold; - bits = state->bits; - lcode = state->lencode; - dcode = state->distcode; - lmask = (1U << state->lenbits) - 1; - dmask = (1U << state->distbits) - 1; + wsize = state->wsize; + whave = state->whave; + write = state->write; + window = state->window; + hold = state->hold; + bits = state->bits; + lcode = state->lencode; + dcode = state->distcode; + lmask = (1U << state->lenbits) - 1; + dmask = (1U << state->distbits) - 1; - /* decode literals and length/distances until end-of-block or not enough - input data or output space */ - do { - if (bits < 15) { - hold += (unsigned long)(PUP(in)) << bits; - bits += 8; - hold += (unsigned long)(PUP(in)) << bits; - bits += 8; - } - this = lcode[hold & lmask]; - dolen: - op = (unsigned)(this.bits); - hold >>= op; - bits -= op; - op = (unsigned)(this.op); - if (op == 0) { /* literal */ - Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ? - "inflate: literal '%c'\n" : - "inflate: literal 0x%02x\n", this.val)); - PUP(out) = (unsigned char)(this.val); - } - else if (op & 16) { /* length base */ - len = (unsigned)(this.val); - op &= 15; /* number of extra bits */ - if (op) { - if (bits < op) { - hold += (unsigned long)(PUP(in)) << bits; - bits += 8; - } - len += (unsigned)hold & ((1U << op) - 1); - hold >>= op; - bits -= op; - } - Tracevv((stderr, "inflate: length %u\n", len)); - if (bits < 15) { - hold += (unsigned long)(PUP(in)) << bits; - bits += 8; - hold += (unsigned long)(PUP(in)) << bits; - bits += 8; - } - this = dcode[hold & dmask]; - dodist: - op = (unsigned)(this.bits); - hold >>= op; - bits -= op; - op = (unsigned)(this.op); - if (op & 16) { /* distance base */ - dist = (unsigned)(this.val); - op &= 15; /* number of extra bits */ - if (bits < op) { - hold += (unsigned long)(PUP(in)) << bits; - bits += 8; - if (bits < op) { - hold += (unsigned long)(PUP(in)) << bits; - bits += 8; - } - } - dist += (unsigned)hold & ((1U << op) - 1); + /* + * decode literals and length/distances until end-of-block or not enough + * input data or output space + */ + do { + if (bits < 15) { + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + } + this = lcode[hold & lmask]; +dolen: + op = (unsigned)(this.bits); + hold >>= op; + bits -= op; + op = (unsigned)(this.op); + if (op == 0) { /* literal */ + Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", this.val)); + PUP(out) = (unsigned char)(this.val); + } else if (op & 16) { /* length base */ + len = (unsigned)(this.val); + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { + hold += + (unsigned long)(PUP(in)) << bits; + bits += 8; + } + len += (unsigned)hold & ((1U << op) - 1); + hold >>= op; + bits -= op; + } + Tracevv((stderr, "inflate: length %u\n", len)); + if (bits < 15) { + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + } + this = dcode[hold & dmask]; +dodist: + op = (unsigned)(this.bits); + hold >>= op; + bits -= op; + op = (unsigned)(this.op); + if (op & 16) { /* distance base */ + dist = (unsigned)(this.val); + op &= 15; /* number of extra bits */ + if (bits < op) { + hold += + (unsigned long)(PUP(in)) << bits; + bits += 8; + if (bits < op) { + hold += (unsigned long)(PUP(in)) + << bits; + bits += 8; + } + } + dist += (unsigned)hold & ((1U << op) - 1); #ifdef INFLATE_STRICT - if (dist > dmax) { - strm->msg = (char *)"invalid distance too far back"; - state->mode = BAD; - break; - } + if (dist > dmax) { + strm->msg = (char *) + "invalid distance too far back"; + state->mode = BAD; + break; + } #endif - hold >>= op; - bits -= op; - Tracevv((stderr, "inflate: distance %u\n", dist)); - op = (unsigned)(out - beg); /* max distance in output */ - if (dist > op) { /* see if copy from window */ - op = dist - op; /* distance back in window */ - if (op > whave) { - strm->msg = (char *)"invalid distance too far back"; - state->mode = BAD; - break; - } - from = window - OFF; - if (write == 0) { /* very common case */ - from += wsize - op; - if (op < len) { /* some from window */ - len -= op; - do { - PUP(out) = PUP(from); - } while (--op); - from = out - dist; /* rest from output */ - } - } - else if (write < op) { /* wrap around window */ - from += wsize + write - op; - op -= write; - if (op < len) { /* some from end of window */ - len -= op; - do { - PUP(out) = PUP(from); - } while (--op); - from = window - OFF; - if (write < len) { /* some from start of window */ - op = write; - len -= op; - do { - PUP(out) = PUP(from); - } while (--op); - from = out - dist; /* rest from output */ - } - } - } - else { /* contiguous in window */ - from += write - op; - if (op < len) { /* some from window */ - len -= op; - do { - PUP(out) = PUP(from); - } while (--op); - from = out - dist; /* rest from output */ - } - } - while (len > 2) { - PUP(out) = PUP(from); - PUP(out) = PUP(from); - PUP(out) = PUP(from); - len -= 3; - } - if (len) { - PUP(out) = PUP(from); - if (len > 1) - PUP(out) = PUP(from); - } - } - else { - from = out - dist; /* copy direct from output */ - do { /* minimum length is three */ - PUP(out) = PUP(from); - PUP(out) = PUP(from); - PUP(out) = PUP(from); - len -= 3; - } while (len > 2); - if (len) { - PUP(out) = PUP(from); - if (len > 1) - PUP(out) = PUP(from); - } - } - } - else if ((op & 64) == 0) { /* 2nd level distance code */ - this = dcode[this.val + (hold & ((1U << op) - 1))]; - goto dodist; - } - else { - strm->msg = (char *)"invalid distance code"; - state->mode = BAD; - break; - } - } - else if ((op & 64) == 0) { /* 2nd level length code */ - this = lcode[this.val + (hold & ((1U << op) - 1))]; - goto dolen; - } - else if (op & 32) { /* end-of-block */ - Tracevv((stderr, "inflate: end of block\n")); - state->mode = TYPE; - break; - } - else { - strm->msg = (char *)"invalid literal/length code"; - state->mode = BAD; - break; - } - } while (in < last && out < end); + hold >>= op; + bits -= op; + Tracevv((stderr, + "inflate: distance %u\n", dist)); + /* max distance in output */ + op = (unsigned)(out - beg); + if (dist > op) { /* see if copy from window */ + /* distance back in window */ + op = dist - op; + if (op > whave) { + strm->msg = (char *) + "invalid distance " + "too far back"; + state->mode = BAD; + break; + } + from = window - OFF; + /* very common case */ + if (write == 0) { + from += wsize - op; + /* some from window */ + if (op < len) { + len -= op; + do { + PUP(out) = + PUP(from); + } while (--op); + /* rest from output */ + from = out - dist; + } + /* wrap around window */ + /* Indentation gets a bit deep here */ + } else if (write < op) { + from += wsize + write - op; + op -= write; + /* some from end of window */ + if (op < len) { + len -= op; + do { + PUP(out) = PUP(from); + } while (--op); + from = window - OFF; + /* some from start of window */ + if (write < len) { + op = write; + len -= op; + do { + PUP(out) = PUP(from); + } while (--op); + /* rest from output */ + from = out - dist; + } + } + } else { + /* contiguous in window */ + from += write - op; + if (op < len) { /* some from window */ + len -= op; + do { + PUP(out) = PUP(from); + } while (--op); + from = out - dist; + /* rest from output */ + } + } while (len > 2) { + PUP(out) = PUP(from); + PUP(out) = PUP(from); + PUP(out) = PUP(from); + len -= 3; + } + if (len) { + PUP(out) = PUP(from); + if (len > 1) + PUP(out) = PUP(from); + } + } else { + from = out - dist; /* copy direct from output */ + do { /* minimum length is three */ + PUP(out) = PUP(from); + PUP(out) = PUP(from); + PUP(out) = PUP(from); + len -= 3; + } while (len > 2); + if (len) { + PUP(out) = PUP(from); + if (len > 1) + PUP(out) = PUP(from); + } + } + } else if ((op & 64) == 0) { + /* 2nd level distance code */ + this = dcode[this.val + + (hold & ((1U << op) - 1))]; + goto dodist; + } else { + strm->msg = (char *)"invalid distance code"; + state->mode = BAD; + break; + } + } else if ((op & 64) == 0) { + /* 2nd level length code */ + this = lcode[this.val + (hold & ((1U << op) - 1))]; + goto dolen; + } else if (op & 32) { + /* end-of-block */ + Tracevv((stderr, "inflate: end of block\n")); + state->mode = TYPE; + break; + } else { + strm->msg = (char *)"invalid literal/length code"; + state->mode = BAD; + break; + } + } while (in < last && out < end); - /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ - len = bits >> 3; - in -= len; - bits -= len << 3; - hold &= (1U << bits) - 1; +/* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + len = bits >> 3; + in -= len; + bits -= len << 3; + hold &= (1U << bits) - 1; - /* update state and return */ - strm->next_in = in + OFF; - strm->next_out = out + OFF; - strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last)); - strm->avail_out = (unsigned)(out < end ? - 257 + (end - out) : 257 - (out - end)); - state->hold = hold; - state->bits = bits; - return; + /* update state and return */ + strm->next_in = in + OFF; + strm->next_out = out + OFF; + strm->avail_in = + (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last)); + strm->avail_out = (unsigned)(out < end ? + 257 + (end - out) : 257 - (out - end)); + state->hold = hold; + state->bits = bits; } /* - inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe): - - Using bit fields for code structure - - Different op definition to avoid & for extra bits (do & for table bits) - - Three separate decoding do-loops for direct, window, and write == 0 - - Special case for distance > 1 copies to do overlapped load and store copy - - Explicit branch predictions (based on measured branch probabilities) - - Deferring match copy and interspersed it with decoding subsequent codes - - Swapping literal/length else - - Swapping window/direct else - - Larger unrolled copy loops (three is about right) - - Moving len -= 3 statement into middle of loop + * inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe): + * - Using bit fields for code structure + * - Different op definition to avoid & for extra bits (do & for table bits) + * - Three separate decoding do-loops for direct, window, and write == 0 + * - Special case for distance > 1 copies to do overlapped load and store copy + * - Explicit branch predictions (based on measured branch probabilities) + * - Deferring match copy and interspersed it with decoding subsequent codes + * - Swapping literal/length else + * - Swapping window/direct else + * - Larger unrolled copy loops (three is about right) + * - Moving len -= 3 statement into middle of loop */ #endif /* !ASMINF */ diff --git a/lib/os/windows/zlib-1.2.3/inffast.h b/lib/os/windows/zlib-1.2.3/inffast.h index 1e88d2d97b5..b20b8066526 100644 --- a/lib/os/windows/zlib-1.2.3/inffast.h +++ b/lib/os/windows/zlib-1.2.3/inffast.h @@ -1,11 +1,13 @@ -/* inffast.h -- header to use inffast.c +/* + * inffast.h -- header to use inffast.c * Copyright (C) 1995-2003 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ -/* WARNING: this file should *not* be used by applications. It is - part of the implementation of the compression library and is - subject to change. Applications should only use zlib.h. +/* + * WARNING: this file should *not* be used by applications. It is + * part of the implementation of the compression library and is + * subject to change. Applications should only use zlib.h. */ void inflate_fast OF((z_streamp strm, unsigned start)); diff --git a/lib/os/windows/zlib-1.2.3/inffixed.h b/lib/os/windows/zlib-1.2.3/inffixed.h index 75ed4b5978d..af5b0de034a 100644 --- a/lib/os/windows/zlib-1.2.3/inffixed.h +++ b/lib/os/windows/zlib-1.2.3/inffixed.h @@ -1,94 +1,174 @@ - /* inffixed.h -- table for decoding fixed codes - * Generated automatically by makefixed(). - */ +/* + * inffixed.h -- table for decoding fixed codes + * Generated automatically by makefixed(). + */ - /* WARNING: this file should *not* be used by applications. It - is part of the implementation of the compression library and - is subject to change. Applications should only use zlib.h. - */ +/* + * WARNING: this file should *not* be used by applications. It + * is part of the implementation of the compression library and + * is subject to change. Applications should only use zlib.h. + */ - static const code lenfix[512] = { - {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48}, - {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128}, - {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59}, - {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176}, - {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20}, - {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100}, - {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8}, - {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216}, - {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76}, - {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114}, - {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2}, - {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148}, - {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42}, - {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86}, - {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15}, - {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236}, - {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62}, - {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142}, - {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31}, - {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162}, - {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25}, - {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105}, - {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4}, - {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202}, - {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69}, - {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125}, - {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13}, - {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195}, - {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35}, - {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91}, - {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19}, - {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246}, - {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55}, - {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135}, - {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99}, - {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190}, - {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16}, - {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96}, - {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6}, - {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209}, - {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72}, - {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116}, - {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4}, - {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153}, - {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44}, - {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82}, - {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11}, - {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229}, - {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58}, - {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138}, - {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51}, - {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173}, - {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30}, - {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110}, - {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0}, - {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195}, - {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65}, - {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121}, - {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9}, - {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258}, - {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37}, - {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93}, - {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23}, - {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251}, - {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51}, - {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131}, - {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67}, - {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183}, - {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23}, - {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103}, - {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9}, - {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223}, - {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79}, - {0,9,255} - }; +static const code lenfix[512] = { + {96, 7, 0}, {0, 8, 80}, {0, 8, 16}, {20, 8, 115}, {18, 7, 31}, + {0, 8, 112}, {0, 8, 48}, + {0, 9, 192}, {16, 7, 10}, {0, 8, 96}, {0, 8, 32}, {0, 9, 160}, + {0, 8, 0}, {0, 8, 128}, + {0, 8, 64}, {0, 9, 224}, {16, 7, 6}, {0, 8, 88}, {0, 8, 24}, + {0, 9, 144}, {19, 7, 59}, + {0, 8, 120}, {0, 8, 56}, {0, 9, 208}, {17, 7, 17}, {0, 8, 104}, + {0, 8, 40}, {0, 9, 176}, + {0, 8, 8}, {0, 8, 136}, {0, 8, 72}, {0, 9, 240}, {16, 7, 4}, + {0, 8, 84}, {0, 8, 20}, + {21, 8, 227}, {19, 7, 43}, {0, 8, 116}, {0, 8, 52}, {0, 9, 200}, + {17, 7, 13}, {0, 8, 100}, + {0, 8, 36}, {0, 9, 168}, {0, 8, 4}, {0, 8, 132}, {0, 8, 68}, + {0, 9, 232}, {16, 7, 8}, + {0, 8, 92}, {0, 8, 28}, {0, 9, 152}, {20, 7, 83}, {0, 8, 124}, + {0, 8, 60}, {0, 9, 216}, + {18, 7, 23}, {0, 8, 108}, {0, 8, 44}, {0, 9, 184}, {0, 8, 12}, + {0, 8, 140}, {0, 8, 76}, + {0, 9, 248}, {16, 7, 3}, {0, 8, 82}, {0, 8, 18}, {21, 8, 163}, + {19, 7, 35}, {0, 8, 114}, + {0, 8, 50}, {0, 9, 196}, {17, 7, 11}, {0, 8, 98}, {0, 8, 34}, + {0, 9, 164}, {0, 8, 2}, + {0, 8, 130}, {0, 8, 66}, {0, 9, 228}, {16, 7, 7}, {0, 8, 90}, + {0, 8, 26}, {0, 9, 148}, + {20, 7, 67}, {0, 8, 122}, {0, 8, 58}, {0, 9, 212}, {18, 7, 19}, + {0, 8, 106}, {0, 8, 42}, + {0, 9, 180}, {0, 8, 10}, {0, 8, 138}, {0, 8, 74}, {0, 9, 244}, + {16, 7, 5}, {0, 8, 86}, + {0, 8, 22}, {64, 8, 0}, {19, 7, 51}, {0, 8, 118}, {0, 8, 54}, + {0, 9, 204}, {17, 7, 15}, + {0, 8, 102}, {0, 8, 38}, {0, 9, 172}, {0, 8, 6}, {0, 8, 134}, + {0, 8, 70}, {0, 9, 236}, + {16, 7, 9}, {0, 8, 94}, {0, 8, 30}, {0, 9, 156}, {20, 7, 99}, + {0, 8, 126}, {0, 8, 62}, + {0, 9, 220}, {18, 7, 27}, {0, 8, 110}, {0, 8, 46}, {0, 9, 188}, + {0, 8, 14}, {0, 8, 142}, + {0, 8, 78}, {0, 9, 252}, {96, 7, 0}, {0, 8, 81}, {0, 8, 17}, + {21, 8, 131}, {18, 7, 31}, + {0, 8, 113}, {0, 8, 49}, {0, 9, 194}, {16, 7, 10}, {0, 8, 97}, + {0, 8, 33}, {0, 9, 162}, + {0, 8, 1}, {0, 8, 129}, {0, 8, 65}, {0, 9, 226}, {16, 7, 6}, + {0, 8, 89}, {0, 8, 25}, + {0, 9, 146}, {19, 7, 59}, {0, 8, 121}, {0, 8, 57}, {0, 9, 210}, + {17, 7, 17}, {0, 8, 105}, + {0, 8, 41}, {0, 9, 178}, {0, 8, 9}, {0, 8, 137}, {0, 8, 73}, + {0, 9, 242}, {16, 7, 4}, + {0, 8, 85}, {0, 8, 21}, {16, 8, 258}, {19, 7, 43}, {0, 8, 117}, + {0, 8, 53}, {0, 9, 202}, + {17, 7, 13}, {0, 8, 101}, {0, 8, 37}, {0, 9, 170}, {0, 8, 5}, + {0, 8, 133}, {0, 8, 69}, + {0, 9, 234}, {16, 7, 8}, {0, 8, 93}, {0, 8, 29}, {0, 9, 154}, + {20, 7, 83}, {0, 8, 125}, + {0, 8, 61}, {0, 9, 218}, {18, 7, 23}, {0, 8, 109}, {0, 8, 45}, + {0, 9, 186}, {0, 8, 13}, + {0, 8, 141}, {0, 8, 77}, {0, 9, 250}, {16, 7, 3}, {0, 8, 83}, + {0, 8, 19}, {21, 8, 195}, + {19, 7, 35}, {0, 8, 115}, {0, 8, 51}, {0, 9, 198}, {17, 7, 11}, + {0, 8, 99}, {0, 8, 35}, + {0, 9, 166}, {0, 8, 3}, {0, 8, 131}, {0, 8, 67}, {0, 9, 230}, + {16, 7, 7}, {0, 8, 91}, + {0, 8, 27}, {0, 9, 150}, {20, 7, 67}, {0, 8, 123}, {0, 8, 59}, + {0, 9, 214}, {18, 7, 19}, + {0, 8, 107}, {0, 8, 43}, {0, 9, 182}, {0, 8, 11}, {0, 8, 139}, + {0, 8, 75}, {0, 9, 246}, + {16, 7, 5}, {0, 8, 87}, {0, 8, 23}, {64, 8, 0}, {19, 7, 51}, + {0, 8, 119}, {0, 8, 55}, + {0, 9, 206}, {17, 7, 15}, {0, 8, 103}, {0, 8, 39}, {0, 9, 174}, + {0, 8, 7}, {0, 8, 135}, + {0, 8, 71}, {0, 9, 238}, {16, 7, 9}, {0, 8, 95}, {0, 8, 31}, + {0, 9, 158}, {20, 7, 99}, + {0, 8, 127}, {0, 8, 63}, {0, 9, 222}, {18, 7, 27}, {0, 8, 111}, + {0, 8, 47}, {0, 9, 190}, + {0, 8, 15}, {0, 8, 143}, {0, 8, 79}, {0, 9, 254}, {96, 7, 0}, + {0, 8, 80}, {0, 8, 16}, + {20, 8, 115}, {18, 7, 31}, {0, 8, 112}, {0, 8, 48}, {0, 9, 193}, + {16, 7, 10}, {0, 8, 96}, + {0, 8, 32}, {0, 9, 161}, {0, 8, 0}, {0, 8, 128}, {0, 8, 64}, + {0, 9, 225}, {16, 7, 6}, + {0, 8, 88}, {0, 8, 24}, {0, 9, 145}, {19, 7, 59}, {0, 8, 120}, + {0, 8, 56}, {0, 9, 209}, + {17, 7, 17}, {0, 8, 104}, {0, 8, 40}, {0, 9, 177}, {0, 8, 8}, + {0, 8, 136}, {0, 8, 72}, + {0, 9, 241}, {16, 7, 4}, {0, 8, 84}, {0, 8, 20}, {21, 8, 227}, + {19, 7, 43}, {0, 8, 116}, + {0, 8, 52}, {0, 9, 201}, {17, 7, 13}, {0, 8, 100}, {0, 8, 36}, + {0, 9, 169}, {0, 8, 4}, + {0, 8, 132}, {0, 8, 68}, {0, 9, 233}, {16, 7, 8}, {0, 8, 92}, + {0, 8, 28}, {0, 9, 153}, + {20, 7, 83}, {0, 8, 124}, {0, 8, 60}, {0, 9, 217}, {18, 7, 23}, + {0, 8, 108}, {0, 8, 44}, + {0, 9, 185}, {0, 8, 12}, {0, 8, 140}, {0, 8, 76}, {0, 9, 249}, + {16, 7, 3}, {0, 8, 82}, + {0, 8, 18}, {21, 8, 163}, {19, 7, 35}, {0, 8, 114}, {0, 8, 50}, + {0, 9, 197}, {17, 7, 11}, + {0, 8, 98}, {0, 8, 34}, {0, 9, 165}, {0, 8, 2}, {0, 8, 130}, + {0, 8, 66}, {0, 9, 229}, + {16, 7, 7}, {0, 8, 90}, {0, 8, 26}, {0, 9, 149}, {20, 7, 67}, + {0, 8, 122}, {0, 8, 58}, + {0, 9, 213}, {18, 7, 19}, {0, 8, 106}, {0, 8, 42}, {0, 9, 181}, + {0, 8, 10}, {0, 8, 138}, + {0, 8, 74}, {0, 9, 245}, {16, 7, 5}, {0, 8, 86}, {0, 8, 22}, + {64, 8, 0}, {19, 7, 51}, + {0, 8, 118}, {0, 8, 54}, {0, 9, 205}, {17, 7, 15}, {0, 8, 102}, + {0, 8, 38}, {0, 9, 173}, + {0, 8, 6}, {0, 8, 134}, {0, 8, 70}, {0, 9, 237}, {16, 7, 9}, + {0, 8, 94}, {0, 8, 30}, + {0, 9, 157}, {20, 7, 99}, {0, 8, 126}, {0, 8, 62}, {0, 9, 221}, + {18, 7, 27}, {0, 8, 110}, + {0, 8, 46}, {0, 9, 189}, {0, 8, 14}, {0, 8, 142}, {0, 8, 78}, + {0, 9, 253}, {96, 7, 0}, + {0, 8, 81}, {0, 8, 17}, {21, 8, 131}, {18, 7, 31}, {0, 8, 113}, + {0, 8, 49}, {0, 9, 195}, + {16, 7, 10}, {0, 8, 97}, {0, 8, 33}, {0, 9, 163}, {0, 8, 1}, + {0, 8, 129}, {0, 8, 65}, + {0, 9, 227}, {16, 7, 6}, {0, 8, 89}, {0, 8, 25}, {0, 9, 147}, + {19, 7, 59}, {0, 8, 121}, + {0, 8, 57}, {0, 9, 211}, {17, 7, 17}, {0, 8, 105}, {0, 8, 41}, + {0, 9, 179}, {0, 8, 9}, + {0, 8, 137}, {0, 8, 73}, {0, 9, 243}, {16, 7, 4}, {0, 8, 85}, + {0, 8, 21}, {16, 8, 258}, + {19, 7, 43}, {0, 8, 117}, {0, 8, 53}, {0, 9, 203}, {17, 7, 13}, + {0, 8, 101}, {0, 8, 37}, + {0, 9, 171}, {0, 8, 5}, {0, 8, 133}, {0, 8, 69}, {0, 9, 235}, + {16, 7, 8}, {0, 8, 93}, + {0, 8, 29}, {0, 9, 155}, {20, 7, 83}, {0, 8, 125}, {0, 8, 61}, + {0, 9, 219}, {18, 7, 23}, + {0, 8, 109}, {0, 8, 45}, {0, 9, 187}, {0, 8, 13}, {0, 8, 141}, + {0, 8, 77}, {0, 9, 251}, + {16, 7, 3}, {0, 8, 83}, {0, 8, 19}, {21, 8, 195}, {19, 7, 35}, + {0, 8, 115}, {0, 8, 51}, + {0, 9, 199}, {17, 7, 11}, {0, 8, 99}, {0, 8, 35}, {0, 9, 167}, + {0, 8, 3}, {0, 8, 131}, + {0, 8, 67}, {0, 9, 231}, {16, 7, 7}, {0, 8, 91}, {0, 8, 27}, + {0, 9, 151}, {20, 7, 67}, + {0, 8, 123}, {0, 8, 59}, {0, 9, 215}, {18, 7, 19}, {0, 8, 107}, + {0, 8, 43}, {0, 9, 183}, + {0, 8, 11}, {0, 8, 139}, {0, 8, 75}, {0, 9, 247}, {16, 7, 5}, + {0, 8, 87}, {0, 8, 23}, + {64, 8, 0}, {19, 7, 51}, {0, 8, 119}, {0, 8, 55}, {0, 9, 207}, + {17, 7, 15}, {0, 8, 103}, + {0, 8, 39}, {0, 9, 175}, {0, 8, 7}, {0, 8, 135}, {0, 8, 71}, + {0, 9, 239}, {16, 7, 9}, + {0, 8, 95}, {0, 8, 31}, {0, 9, 159}, {20, 7, 99}, {0, 8, 127}, + {0, 8, 63}, {0, 9, 223}, + {18, 7, 27}, {0, 8, 111}, {0, 8, 47}, {0, 9, 191}, {0, 8, 15}, + {0, 8, 143}, {0, 8, 79}, + {0, 9, 255} +}; - static const code distfix[32] = { - {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025}, - {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193}, - {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385}, - {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577}, - {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073}, - {22,5,193},{64,5,0} - }; +static const code distfix[32] = { + {16, 5, 1}, {23, 5, 257}, {19, 5, 17}, {27, 5, 4097}, {17, 5, 5}, + {25, 5, 1025}, + {21, 5, 65}, {29, 5, 16385}, {16, 5, 3}, {24, 5, 513}, {20, 5, 33}, + {28, 5, 8193}, + {18, 5, 9}, {26, 5, 2049}, {22, 5, 129}, {64, 5, 0}, {16, 5, 2}, + {23, 5, 385}, + {19, 5, 25}, {27, 5, 6145}, {17, 5, 7}, {25, 5, 1537}, {21, 5, 97}, + {29, 5, 24577}, + {16, 5, 4}, {24, 5, 769}, {20, 5, 49}, {28, 5, 12289}, {18, 5, 13}, + {26, 5, 3073}, + {22, 5, 193}, {64, 5, 0} +}; diff --git a/lib/os/windows/zlib-1.2.3/inflate.c b/lib/os/windows/zlib-1.2.3/inflate.c index 1e858289a23..f0ba207b2b7 100644 --- a/lib/os/windows/zlib-1.2.3/inflate.c +++ b/lib/os/windows/zlib-1.2.3/inflate.c @@ -1,4 +1,5 @@ -/* inflate.c -- zlib decompression +/* + * inflate.c -- zlib decompression * Copyright (C) 1995-2005 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ @@ -86,1283 +87,1379 @@ #include "inffast.h" #ifdef MAKEFIXED -# ifndef BUILDFIXED -# define BUILDFIXED -# endif +#ifndef BUILDFIXED +#define BUILDFIXED +#endif #endif /* function prototypes */ local void fixedtables OF((struct inflate_state FAR *state)); local int updatewindow OF((z_streamp strm, unsigned out)); #ifdef BUILDFIXED - void makefixed OF((void)); +void makefixed OF((void)); #endif local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf, - unsigned len)); + unsigned len)); -int ZEXPORT inflateReset(strm) -z_streamp strm; +int ZEXPORT +inflateReset( + z_streamp strm) { - struct inflate_state FAR *state; - - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - strm->total_in = strm->total_out = state->total = 0; - strm->msg = Z_NULL; - strm->adler = 1; /* to support ill-conceived Java test suite */ - state->mode = HEAD; - state->last = 0; - state->havedict = 0; - state->dmax = 32768U; - state->head = Z_NULL; - state->wsize = 0; - state->whave = 0; - state->write = 0; - state->hold = 0; - state->bits = 0; - state->lencode = state->distcode = state->next = state->codes; - Tracev((stderr, "inflate: reset\n")); - return Z_OK; + struct inflate_state FAR *state; + + if (strm == Z_NULL || strm->state == Z_NULL) + return (Z_STREAM_ERROR); + state = (struct inflate_state FAR *)strm->state; + strm->total_in = strm->total_out = state->total = 0; + strm->msg = Z_NULL; + strm->adler = 1; /* to support ill-conceived Java test suite */ + state->mode = HEAD; + state->last = 0; + state->havedict = 0; + state->dmax = 32768U; + state->head = Z_NULL; + state->wsize = 0; + state->whave = 0; + state->write = 0; + state->hold = 0; + state->bits = 0; + state->lencode = state->distcode = state->next = state->codes; + Tracev((stderr, "inflate: reset\n")); + return (Z_OK); } -int ZEXPORT inflatePrime(strm, bits, value) -z_streamp strm; -int bits; -int value; +int ZEXPORT +inflatePrime(z_streamp strm, + int bits, + int value) { - struct inflate_state FAR *state; - - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR; - value &= (1L << bits) - 1; - state->hold += value << state->bits; - state->bits += bits; - return Z_OK; + struct inflate_state FAR *state; + + if (strm == Z_NULL || strm->state == Z_NULL) + return (Z_STREAM_ERROR); + state = (struct inflate_state FAR *)strm->state; + if (bits > 16 || state->bits + bits > 32) + return (Z_STREAM_ERROR); + value &= (1L << bits) - 1; + state->hold += value << state->bits; + state->bits += bits; + return (Z_OK); } -int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size) -z_streamp strm; -int windowBits; -const char *version; -int stream_size; +int ZEXPORT +inflateInit2_( + z_streamp strm, + int windowBits, + const char *version, + int stream_size) { - struct inflate_state FAR *state; - - if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || - stream_size != (int)(sizeof(z_stream))) - return Z_VERSION_ERROR; - if (strm == Z_NULL) return Z_STREAM_ERROR; - strm->msg = Z_NULL; /* in case we return an error */ - if (strm->zalloc == (alloc_func)0) { - strm->zalloc = zcalloc; - strm->opaque = (voidpf)0; - } - if (strm->zfree == (free_func)0) strm->zfree = zcfree; - state = (struct inflate_state FAR *) - ZALLOC(strm, 1, sizeof(struct inflate_state)); - if (state == Z_NULL) return Z_MEM_ERROR; - Tracev((stderr, "inflate: allocated\n")); - strm->state = (struct internal_state FAR *)state; - if (windowBits < 0) { - state->wrap = 0; - windowBits = -windowBits; - } - else { - state->wrap = (windowBits >> 4) + 1; + struct inflate_state FAR *state; + + if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || + stream_size != (int)(sizeof (z_stream))) + return (Z_VERSION_ERROR); + if (strm == Z_NULL) + return (Z_STREAM_ERROR); + strm->msg = Z_NULL; /* in case we return an error */ + if (strm->zalloc == (alloc_func)0) { + strm->zalloc = zcalloc; + strm->opaque = (voidpf)0; + } + if (strm->zfree == (free_func)0) strm->zfree = zcfree; + state = (struct inflate_state FAR *) + ZALLOC(strm, 1, sizeof (struct inflate_state)); + if (state == Z_NULL) + return (Z_MEM_ERROR); + Tracev((stderr, "inflate: allocated\n")); + strm->state = (struct internal_state FAR *)state; + if (windowBits < 0) { + state->wrap = 0; + windowBits = -windowBits; + } else { + state->wrap = (windowBits >> 4) + 1; #ifdef GUNZIP - if (windowBits < 48) windowBits &= 15; + if (windowBits < 48) windowBits &= 15; #endif - } - if (windowBits < 8 || windowBits > 15) { - ZFREE(strm, state); - strm->state = Z_NULL; - return Z_STREAM_ERROR; - } - state->wbits = (unsigned)windowBits; - state->window = Z_NULL; - return inflateReset(strm); + } + if (windowBits < 8 || windowBits > 15) { + ZFREE(strm, state); + strm->state = Z_NULL; + return (Z_STREAM_ERROR); + } + state->wbits = (unsigned)windowBits; + state->window = Z_NULL; + return (inflateReset(strm)); } -int ZEXPORT inflateInit_(strm, version, stream_size) -z_streamp strm; -const char *version; -int stream_size; +int ZEXPORT +inflateInit_( + z_streamp strm, + const char *version, + int stream_size) { - return inflateInit2_(strm, DEF_WBITS, version, stream_size); + return (inflateInit2_(strm, DEF_WBITS, version, stream_size)); } /* - Return state with length and distance decoding tables and index sizes set to - fixed code decoding. Normally this returns fixed tables from inffixed.h. - If BUILDFIXED is defined, then instead this routine builds the tables the - first time it's called, and returns those tables the first time and - thereafter. This reduces the size of the code by about 2K bytes, in - exchange for a little execution time. However, BUILDFIXED should not be - used for threaded applications, since the rewriting of the tables and virgin - may not be thread-safe. + * Return state with length and distance decoding tables and index sizes set to + * fixed code decoding. Normally this returns fixed tables from inffixed.h. + * If BUILDFIXED is defined, then instead this routine builds the tables the + * first time it's called, and returns those tables the first time and + * thereafter. This reduces the size of the code by about 2K bytes, in + * exchange for a little execution time. However, BUILDFIXED should not be + * used for threaded applications, since the rewriting of the tables and virgin + * may not be thread-safe. */ -local void fixedtables(state) -struct inflate_state FAR *state; +local void +fixedtables( + struct inflate_state FAR *state) { #ifdef BUILDFIXED - static int virgin = 1; - static code *lenfix, *distfix; - static code fixed[544]; - - /* build fixed huffman tables if first call (may not be thread safe) */ - if (virgin) { - unsigned sym, bits; - static code *next; - - /* literal/length table */ - sym = 0; - while (sym < 144) state->lens[sym++] = 8; - while (sym < 256) state->lens[sym++] = 9; - while (sym < 280) state->lens[sym++] = 7; - while (sym < 288) state->lens[sym++] = 8; - next = fixed; - lenfix = next; - bits = 9; - inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work); - - /* distance table */ - sym = 0; - while (sym < 32) state->lens[sym++] = 5; - distfix = next; - bits = 5; - inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work); - - /* do this just once */ - virgin = 0; - } + static int virgin = 1; + static code *lenfix, *distfix; + static code fixed[544]; + + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + unsigned sym, bits; + static code *next; + + /* literal/length table */ + sym = 0; + while (sym < 144) state->lens[sym++] = 8; + while (sym < 256) state->lens[sym++] = 9; + while (sym < 280) state->lens[sym++] = 7; + while (sym < 288) state->lens[sym++] = 8; + next = fixed; + lenfix = next; + bits = 9; + inflate_table(LENS, state->lens, 288, &(next), &(bits), + state->work); + + /* distance table */ + sym = 0; + while (sym < 32) state->lens[sym++] = 5; + distfix = next; + bits = 5; + inflate_table(DISTS, state->lens, 32, &(next), &(bits), + state->work); + + /* do this just once */ + virgin = 0; + } #else /* !BUILDFIXED */ -# include "inffixed.h" +#include "inffixed.h" #endif /* BUILDFIXED */ - state->lencode = lenfix; - state->lenbits = 9; - state->distcode = distfix; - state->distbits = 5; + state->lencode = lenfix; + state->lenbits = 9; + state->distcode = distfix; + state->distbits = 5; } #ifdef MAKEFIXED #include /* - Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also - defines BUILDFIXED, so the tables are built on the fly. makefixed() writes - those tables to stdout, which would be piped to inffixed.h. A small program - can simply call makefixed to do this: - - void makefixed(void); - - int main(void) - { - makefixed(); - return 0; - } - - Then that can be linked with zlib built with MAKEFIXED defined and run: - - a.out > inffixed.h + * Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also + * defines BUILDFIXED, so the tables are built on the fly. makefixed() writes + * those tables to stdout, which would be piped to inffixed.h. A small program + * can simply call makefixed to do this: + * + * void makefixed(void); + * + * int main(void) + * { + * makefixed(); + * return 0; + * } + * + * Then that can be linked with zlib built with MAKEFIXED defined and run: + * + * a.out > inffixed.h */ -void makefixed() +void +makefixed() { - unsigned low, size; - struct inflate_state state; - - fixedtables(&state); - puts(" /* inffixed.h -- table for decoding fixed codes"); - puts(" * Generated automatically by makefixed()."); - puts(" */"); - puts(""); - puts(" /* WARNING: this file should *not* be used by applications."); - puts(" It is part of the implementation of this library and is"); - puts(" subject to change. Applications should only use zlib.h."); - puts(" */"); - puts(""); - size = 1U << 9; - printf(" static const code lenfix[%u] = {", size); - low = 0; - for (;;) { - if ((low % 7) == 0) printf("\n "); - printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits, - state.lencode[low].val); - if (++low == size) break; - putchar(','); - } - puts("\n };"); - size = 1U << 5; - printf("\n static const code distfix[%u] = {", size); - low = 0; - for (;;) { - if ((low % 6) == 0) printf("\n "); - printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits, - state.distcode[low].val); - if (++low == size) break; - putchar(','); - } - puts("\n };"); + unsigned low, size; + struct inflate_state state; + + fixedtables(&state); + puts(" /* inffixed.h -- table for decoding fixed codes"); + puts(" * Generated automatically by makefixed()."); + puts(" */"); + puts(""); + puts(" /* WARNING: this file should *not* be used by applications."); + puts(" It is part of the implementation of this library and is"); + puts(" subject to change. Applications should only use zlib.h."); + puts(" */"); + puts(""); + size = 1U << 9; + printf(" static const code lenfix[%u] = {", size); + low = 0; + for (;;) { + if ((low % 7) == 0) printf("\n "); + printf("{%u,%u,%d}", state.lencode[low].op, + state.lencode[low].bits, + state.lencode[low].val); + if (++low == size) + break; + putchar(','); + } + puts("\n };"); + size = 1U << 5; + printf("\n static const code distfix[%u] = {", size); + low = 0; + for (;;) { + if ((low % 6) == 0) printf("\n "); + printf("{%u,%u,%d}", state.distcode[low].op, + state.distcode[low].bits, + state.distcode[low].val); + if (++low == size) + break; + putchar(','); + } + puts("\n };"); } #endif /* MAKEFIXED */ /* - Update the window with the last wsize (normally 32K) bytes written before - returning. If window does not exist yet, create it. This is only called - when a window is already in use, or when output has been written during this - inflate call, but the end of the deflate stream has not been reached yet. - It is also called to create a window for dictionary data when a dictionary - is loaded. - - Providing output buffers larger than 32K to inflate() should provide a speed - advantage, since only the last 32K of output is copied to the sliding window - upon return from inflate(), and since all distances after the first 32K of - output will fall in the output data, making match copies simpler and faster. - The advantage may be dependent on the size of the processor's data caches. + * Update the window with the last wsize (normally 32K) bytes written before + * returning. If window does not exist yet, create it. This is only called + * when a window is already in use, or when output has been written during this + * inflate call, but the end of the deflate stream has not been reached yet. + * It is also called to create a window for dictionary data when a dictionary + * is loaded. + * + * Providing output buffers larger than 32K to inflate() should provide a speed + * advantage, since only the last 32K of output is copied to the sliding window + * upon return from inflate(), and since all distances after the first 32K of + * output will fall in the output data, making match copies simpler and faster. + * The advantage may be dependent on the size of the processor's data caches. */ -local int updatewindow(strm, out) -z_streamp strm; -unsigned out; +local int +updatewindow( + z_streamp strm, + unsigned out) { - struct inflate_state FAR *state; - unsigned copy, dist; - - state = (struct inflate_state FAR *)strm->state; - - /* if it hasn't been done already, allocate space for the window */ - if (state->window == Z_NULL) { - state->window = (unsigned char FAR *) - ZALLOC(strm, 1U << state->wbits, - sizeof(unsigned char)); - if (state->window == Z_NULL) return 1; - } - - /* if window not in use yet, initialize */ - if (state->wsize == 0) { - state->wsize = 1U << state->wbits; - state->write = 0; - state->whave = 0; - } - - /* copy state->wsize or less output bytes into the circular window */ - copy = out - strm->avail_out; - if (copy >= state->wsize) { - zmemcpy(state->window, strm->next_out - state->wsize, state->wsize); - state->write = 0; - state->whave = state->wsize; - } - else { - dist = state->wsize - state->write; - if (dist > copy) dist = copy; - zmemcpy(state->window + state->write, strm->next_out - copy, dist); - copy -= dist; - if (copy) { - zmemcpy(state->window, strm->next_out - copy, copy); - state->write = copy; - state->whave = state->wsize; - } - else { - state->write += dist; - if (state->write == state->wsize) state->write = 0; - if (state->whave < state->wsize) state->whave += dist; - } - } - return 0; + struct inflate_state FAR *state; + unsigned copy, dist; + + state = (struct inflate_state FAR *)strm->state; + + /* if it hasn't been done already, allocate space for the window */ + if (state->window == Z_NULL) { + state->window = (unsigned char FAR *) + ZALLOC(strm, 1U << state->wbits, + sizeof (unsigned char)); + if (state->window == Z_NULL) + return (1); + } + + /* if window not in use yet, initialize */ + if (state->wsize == 0) { + state->wsize = 1U << state->wbits; + state->write = 0; + state->whave = 0; + } + + /* copy state->wsize or less output bytes into the circular window */ + copy = out - strm->avail_out; + if (copy >= state->wsize) { + zmemcpy(state->window, strm->next_out - state->wsize, + state->wsize); + state->write = 0; + state->whave = state->wsize; + } else { + dist = state->wsize - state->write; + if (dist > copy) dist = copy; + zmemcpy(state->window + state->write, strm->next_out - copy, + dist); + copy -= dist; + if (copy) { + zmemcpy(state->window, strm->next_out - copy, copy); + state->write = copy; + state->whave = state->wsize; + } else { + state->write += dist; + if (state->write == state->wsize) state->write = 0; + if (state->whave < state->wsize) state->whave += dist; + } + } + return (0); } /* Macros for inflate(): */ /* check function to use adler32() for zlib or crc32() for gzip */ #ifdef GUNZIP -# define UPDATE(check, buf, len) \ - (state->flags ? crc32(check, buf, len) : adler32(check, buf, len)) +#define UPDATE(check, buf, len) \ + (state->flags ? crc32(check, buf, len) : adler32(check, buf, len)) #else -# define UPDATE(check, buf, len) adler32(check, buf, len) +#define UPDATE(check, buf, len) adler32(check, buf, len) #endif /* check macros for header crc */ #ifdef GUNZIP -# define CRC2(check, word) \ +#define CRC2(check, word) \ do { \ - hbuf[0] = (unsigned char)(word); \ - hbuf[1] = (unsigned char)((word) >> 8); \ - check = crc32(check, hbuf, 2); \ - } while (0) + hbuf[0] = (unsigned char)(word); \ + hbuf[1] = (unsigned char)((word) >> 8); \ + check = crc32(check, hbuf, 2); \ + } while (0) -# define CRC4(check, word) \ +#define CRC4(check, word) \ do { \ - hbuf[0] = (unsigned char)(word); \ - hbuf[1] = (unsigned char)((word) >> 8); \ - hbuf[2] = (unsigned char)((word) >> 16); \ - hbuf[3] = (unsigned char)((word) >> 24); \ - check = crc32(check, hbuf, 4); \ - } while (0) + hbuf[0] = (unsigned char)(word); \ + hbuf[1] = (unsigned char)((word) >> 8); \ + hbuf[2] = (unsigned char)((word) >> 16); \ + hbuf[3] = (unsigned char)((word) >> 24); \ + check = crc32(check, hbuf, 4); \ + } while (0) #endif /* Load registers with state in inflate() for speed */ -#define LOAD() \ - do { \ - put = strm->next_out; \ - left = strm->avail_out; \ - next = strm->next_in; \ - have = strm->avail_in; \ - hold = state->hold; \ - bits = state->bits; \ - } while (0) +#define LOAD() \ + do { \ + put = strm->next_out; \ + left = strm->avail_out; \ + next = strm->next_in; \ + have = strm->avail_in; \ + hold = state->hold; \ + bits = state->bits; \ + } while (0) /* Restore state from registers in inflate() */ -#define RESTORE() \ - do { \ - strm->next_out = put; \ - strm->avail_out = left; \ - strm->next_in = next; \ - strm->avail_in = have; \ - state->hold = hold; \ - state->bits = bits; \ - } while (0) +#define RESTORE() \ + do { \ + strm->next_out = put; \ + strm->avail_out = left; \ + strm->next_in = next; \ + strm->avail_in = have; \ + state->hold = hold; \ + state->bits = bits; \ + } while (0) /* Clear the input bit accumulator */ -#define INITBITS() \ - do { \ - hold = 0; \ - bits = 0; \ - } while (0) +#define INITBITS() \ + do { \ + hold = 0; \ + bits = 0; \ + } while (0) -/* Get a byte of input into the bit accumulator, or return from inflate() - if there is no input available. */ -#define PULLBYTE() \ - do { \ - if (have == 0) goto inf_leave; \ - have--; \ - hold += (unsigned long)(*next++) << bits; \ - bits += 8; \ - } while (0) - -/* Assure that there are at least n bits in the bit accumulator. If there is - not enough available input to do that, then return from inflate(). */ -#define NEEDBITS(n) \ - do { \ - while (bits < (unsigned)(n)) \ - PULLBYTE(); \ - } while (0) +/* + * Get a byte of input into the bit accumulator, or return from inflate() + * if there is no input available. + */ +#define PULLBYTE() \ + do { \ + if (have == 0) goto inf_leave; \ + have--; \ + hold += (unsigned long)(*next++) << bits; \ + bits += 8; \ + } while (0) + +/* + * Assure that there are at least n bits in the bit accumulator. If there is + * not enough available input to do that, then return from inflate(). + */ +#define NEEDBITS(n) \ + do { \ + while (bits < (unsigned)(n)) \ + PULLBYTE(); \ + } while (0) /* Return the low n bits of the bit accumulator (n < 16) */ -#define BITS(n) \ - ((unsigned)hold & ((1U << (n)) - 1)) +#define BITS(n) \ + ((unsigned)hold & ((1U << (n)) - 1)) /* Remove n bits from the bit accumulator */ -#define DROPBITS(n) \ - do { \ - hold >>= (n); \ - bits -= (unsigned)(n); \ - } while (0) +#define DROPBITS(n) \ + do { \ + hold >>= (n); \ + bits -= (unsigned)(n); \ + } while (0) /* Remove zero to seven bits as needed to go to a byte boundary */ -#define BYTEBITS() \ - do { \ - hold >>= bits & 7; \ - bits -= bits & 7; \ - } while (0) +#define BYTEBITS() \ + do { \ + hold >>= bits & 7; \ + bits -= bits & 7; \ + } while (0) /* Reverse the bytes in a 32-bit value */ -#define REVERSE(q) \ - ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \ - (((q) & 0xff00) << 8) + (((q) & 0xff) << 24)) +#define REVERSE(q) \ + ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \ + (((q) & 0xff00) << 8) + (((q) & 0xff) << 24)) /* - inflate() uses a state machine to process as much input data and generate as - much output data as possible before returning. The state machine is - structured roughly as follows: - - for (;;) switch (state) { - ... - case STATEn: - if (not enough input data or output space to make progress) - return; - ... make progress ... - state = STATEm; - break; - ... - } - - so when inflate() is called again, the same case is attempted again, and - if the appropriate resources are provided, the machine proceeds to the - next state. The NEEDBITS() macro is usually the way the state evaluates - whether it can proceed or should return. NEEDBITS() does the return if - the requested bits are not available. The typical use of the BITS macros - is: - - NEEDBITS(n); - ... do something with BITS(n) ... - DROPBITS(n); - - where NEEDBITS(n) either returns from inflate() if there isn't enough - input left to load n bits into the accumulator, or it continues. BITS(n) - gives the low n bits in the accumulator. When done, DROPBITS(n) drops - the low n bits off the accumulator. INITBITS() clears the accumulator - and sets the number of available bits to zero. BYTEBITS() discards just - enough bits to put the accumulator on a byte boundary. After BYTEBITS() - and a NEEDBITS(8), then BITS(8) would return the next byte in the stream. - - NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return - if there is no input available. The decoding of variable length codes uses - PULLBYTE() directly in order to pull just enough bytes to decode the next - code, and no more. - - Some states loop until they get enough input, making sure that enough - state information is maintained to continue the loop where it left off - if NEEDBITS() returns in the loop. For example, want, need, and keep - would all have to actually be part of the saved state in case NEEDBITS() - returns: - - case STATEw: - while (want < need) { - NEEDBITS(n); - keep[want++] = BITS(n); - DROPBITS(n); - } - state = STATEx; - case STATEx: - - As shown above, if the next state is also the next case, then the break - is omitted. - - A state may also return if there is not enough output space available to - complete that state. Those states are copying stored data, writing a - literal byte, and copying a matching string. - - When returning, a "goto inf_leave" is used to update the total counters, - update the check value, and determine whether any progress has been made - during that inflate() call in order to return the proper return code. - Progress is defined as a change in either strm->avail_in or strm->avail_out. - When there is a window, goto inf_leave will update the window with the last - output written. If a goto inf_leave occurs in the middle of decompression - and there is no window currently, goto inf_leave will create one and copy - output to the window for the next call of inflate(). - - In this implementation, the flush parameter of inflate() only affects the - return code (per zlib.h). inflate() always writes as much as possible to - strm->next_out, given the space available and the provided input--the effect - documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers - the allocation of and copying into a sliding window until necessary, which - provides the effect documented in zlib.h for Z_FINISH when the entire input - stream available. So the only thing the flush parameter actually does is: - when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it - will return Z_BUF_ERROR if it has not reached the end of the stream. + * inflate() uses a state machine to process as much input data and generate as + * much output data as possible before returning. The state machine is + * structured roughly as follows: + * + * for (;;) switch (state) { + * ... + * case STATEn: + * if (not enough input data or output space to make progress) + * return; + * ... make progress ... + * state = STATEm; + * break; + * ... + * } + * + * so when inflate() is called again, the same case is attempted again, and + * if the appropriate resources are provided, the machine proceeds to the + * next state. The NEEDBITS() macro is usually the way the state evaluates + * whether it can proceed or should return. NEEDBITS() does the return if + * the requested bits are not available. The typical use of the BITS macros + * is: + * + * NEEDBITS(n); + * ... do something with BITS(n) ... + * DROPBITS(n); + * + * where NEEDBITS(n) either returns from inflate() if there isn't enough + * input left to load n bits into the accumulator, or it continues. BITS(n) + * gives the low n bits in the accumulator. When done, DROPBITS(n) drops + * the low n bits off the accumulator. INITBITS() clears the accumulator + * and sets the number of available bits to zero. BYTEBITS() discards just + * enough bits to put the accumulator on a byte boundary. After BYTEBITS() + * and a NEEDBITS(8), then BITS(8) would return the next byte in the stream. + * + * NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return + * if there is no input available. The decoding of variable length codes uses + * PULLBYTE() directly in order to pull just enough bytes to decode the next + * code, and no more. + * + * Some states loop until they get enough input, making sure that enough + * state information is maintained to continue the loop where it left off + * if NEEDBITS() returns in the loop. For example, want, need, and keep + * would all have to actually be part of the saved state in case NEEDBITS() + * returns: + * + * case STATEw: + * while (want < need) { + * NEEDBITS(n); + * keep[want++] = BITS(n); + * DROPBITS(n); + * } + * state = STATEx; + * case STATEx: + * + * As shown above, if the next state is also the next case, then the break + * is omitted. + * + * A state may also return if there is not enough output space available to + * complete that state. Those states are copying stored data, writing a + * literal byte, and copying a matching string. + * + * When returning, a "goto inf_leave" is used to update the total counters, + * update the check value, and determine whether any progress has been made + * during that inflate() call in order to return the proper return code. + * Progress is defined as a change in either strm->avail_in or strm->avail_out. + * When there is a window, goto inf_leave will update the window with the last + * output written. If a goto inf_leave occurs in the middle of decompression + * and there is no window currently, goto inf_leave will create one and copy + * output to the window for the next call of inflate(). + * + * In this implementation, the flush parameter of inflate() only affects the + * return code (per zlib.h). inflate() always writes as much as possible to + * strm->next_out, given the space available and the provided input--the effect + * documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers + * the allocation of and copying into a sliding window until necessary, which + * provides the effect documented in zlib.h for Z_FINISH when the entire input + * stream available. So the only thing the flush parameter actually does is: + * when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it + * will return Z_BUF_ERROR if it has not reached the end of the stream. */ -int ZEXPORT inflate(strm, flush) -z_streamp strm; -int flush; +int ZEXPORT +inflate( + z_streamp strm, + int flush) { - struct inflate_state FAR *state; - unsigned char FAR *next; /* next input */ - unsigned char FAR *put; /* next output */ - unsigned have, left; /* available input and output */ - unsigned long hold; /* bit buffer */ - unsigned bits; /* bits in bit buffer */ - unsigned in, out; /* save starting available input and output */ - unsigned copy; /* number of stored or match bytes to copy */ - unsigned char FAR *from; /* where to copy match bytes from */ - code this; /* current decoding table entry */ - code last; /* parent table entry */ - unsigned len; /* length to copy for repeats, bits to drop */ - int ret; /* return code */ + struct inflate_state FAR *state; + unsigned char FAR *next; /* next input */ + unsigned char FAR *put; /* next output */ + unsigned have, left; /* available input and output */ + unsigned long hold; /* bit buffer */ + unsigned bits; /* bits in bit buffer */ + unsigned in, out; /* save starting available input and output */ + unsigned copy; /* number of stored or match bytes to copy */ + unsigned char FAR *from; /* where to copy match bytes from */ + code this; /* current decoding table entry */ + code last; /* parent table entry */ + unsigned len; /* length to copy for repeats, bits to drop */ + int ret; /* return code */ #ifdef GUNZIP - unsigned char hbuf[4]; /* buffer for gzip header crc calculation */ + unsigned char hbuf[4]; /* buffer for gzip header crc calculation */ #endif - static const unsigned short order[19] = /* permutation of code lengths */ - {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; - - if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL || - (strm->next_in == Z_NULL && strm->avail_in != 0)) - return Z_STREAM_ERROR; - - state = (struct inflate_state FAR *)strm->state; - if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */ - LOAD(); - in = have; - out = left; - ret = Z_OK; - for (;;) - switch (state->mode) { - case HEAD: - if (state->wrap == 0) { - state->mode = TYPEDO; - break; - } - NEEDBITS(16); + /* permutation of code lengths */ + static const unsigned short order[19] = + {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; + + if (strm == Z_NULL || strm->state == Z_NULL || + strm->next_out == Z_NULL || + (strm->next_in == Z_NULL && strm->avail_in != 0)) + return (Z_STREAM_ERROR); + + state = (struct inflate_state FAR *)strm->state; + if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */ + LOAD(); + in = have; + out = left; + ret = Z_OK; + for (;;) + switch (state->mode) { + case HEAD: + if (state->wrap == 0) { + state->mode = TYPEDO; + break; + } + NEEDBITS(16); #ifdef GUNZIP - if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */ - state->check = crc32(0L, Z_NULL, 0); - CRC2(state->check, hold); - INITBITS(); - state->mode = FLAGS; - break; - } - state->flags = 0; /* expect zlib header */ - if (state->head != Z_NULL) - state->head->done = -1; - if (!(state->wrap & 1) || /* check if zlib header allowed */ + /* gzip header */ + if ((state->wrap & 2) && hold == 0x8b1f) { + state->check = crc32(0L, Z_NULL, 0); + CRC2(state->check, hold); + INITBITS(); + state->mode = FLAGS; + break; + } + state->flags = 0; /* expect zlib header */ + if (state->head != Z_NULL) + state->head->done = -1; + /* check if zlib header allowed */ + if (!(state->wrap & 1) || + ((BITS(8) << 8) + (hold >> 8)) % 31) { + strm->msg = (char *)"incorrect header check"; + state->mode = BAD; + break; + } #else - if ( + if (((BITS(8) << 8) + (hold >> 8)) % 31) { + strm->msg = (char *)"incorrect header check"; + state->mode = BAD; + break; + } + #endif - ((BITS(8) << 8) + (hold >> 8)) % 31) { - strm->msg = (char *)"incorrect header check"; - state->mode = BAD; - break; - } - if (BITS(4) != Z_DEFLATED) { - strm->msg = (char *)"unknown compression method"; - state->mode = BAD; - break; - } - DROPBITS(4); - len = BITS(4) + 8; - if (len > state->wbits) { - strm->msg = (char *)"invalid window size"; - state->mode = BAD; - break; - } - state->dmax = 1U << len; - Tracev((stderr, "inflate: zlib header ok\n")); - strm->adler = state->check = adler32(0L, Z_NULL, 0); - state->mode = hold & 0x200 ? DICTID : TYPE; - INITBITS(); - break; + if (BITS(4) != Z_DEFLATED) { + strm->msg = + (char *)"unknown compression method"; + state->mode = BAD; + break; + } + DROPBITS(4); + len = BITS(4) + 8; + if (len > state->wbits) { + strm->msg = (char *)"invalid window size"; + state->mode = BAD; + break; + } + state->dmax = 1U << len; + Tracev((stderr, "inflate: zlib header ok\n")); + strm->adler = state->check = adler32(0L, Z_NULL, 0); + state->mode = hold & 0x200 ? DICTID : TYPE; + INITBITS(); + break; #ifdef GUNZIP - case FLAGS: - NEEDBITS(16); - state->flags = (int)(hold); - if ((state->flags & 0xff) != Z_DEFLATED) { - strm->msg = (char *)"unknown compression method"; - state->mode = BAD; - break; - } - if (state->flags & 0xe000) { - strm->msg = (char *)"unknown header flags set"; - state->mode = BAD; - break; - } - if (state->head != Z_NULL) - state->head->text = (int)((hold >> 8) & 1); - if (state->flags & 0x0200) CRC2(state->check, hold); - INITBITS(); - state->mode = TIME; - case TIME: - NEEDBITS(32); - if (state->head != Z_NULL) - state->head->time = hold; - if (state->flags & 0x0200) CRC4(state->check, hold); - INITBITS(); - state->mode = OS; - case OS: - NEEDBITS(16); - if (state->head != Z_NULL) { - state->head->xflags = (int)(hold & 0xff); - state->head->os = (int)(hold >> 8); - } - if (state->flags & 0x0200) CRC2(state->check, hold); - INITBITS(); - state->mode = EXLEN; - case EXLEN: - if (state->flags & 0x0400) { - NEEDBITS(16); - state->length = (unsigned)(hold); - if (state->head != Z_NULL) - state->head->extra_len = (unsigned)hold; - if (state->flags & 0x0200) CRC2(state->check, hold); - INITBITS(); - } - else if (state->head != Z_NULL) - state->head->extra = Z_NULL; - state->mode = EXTRA; - case EXTRA: - if (state->flags & 0x0400) { - copy = state->length; - if (copy > have) copy = have; - if (copy) { - if (state->head != Z_NULL && - state->head->extra != Z_NULL) { - len = state->head->extra_len - state->length; - zmemcpy(state->head->extra + len, next, - len + copy > state->head->extra_max ? - state->head->extra_max - len : copy); - } - if (state->flags & 0x0200) - state->check = crc32(state->check, next, copy); - have -= copy; - next += copy; - state->length -= copy; - } - if (state->length) goto inf_leave; - } - state->length = 0; - state->mode = NAME; - case NAME: - if (state->flags & 0x0800) { - if (have == 0) goto inf_leave; - copy = 0; - do { - len = (unsigned)(next[copy++]); - if (state->head != Z_NULL && - state->head->name != Z_NULL && - state->length < state->head->name_max) - state->head->name[state->length++] = (Byte)len; - } while (len && copy < have); - if (state->flags & 0x0200) - state->check = crc32(state->check, next, copy); - have -= copy; - next += copy; - if (len) goto inf_leave; - } - else if (state->head != Z_NULL) - state->head->name = Z_NULL; - state->length = 0; - state->mode = COMMENT; - case COMMENT: - if (state->flags & 0x1000) { - if (have == 0) goto inf_leave; - copy = 0; - do { - len = (unsigned)(next[copy++]); - if (state->head != Z_NULL && - state->head->comment != Z_NULL && - state->length < state->head->comm_max) - state->head->comment[state->length++] = (Byte)len; - } while (len && copy < have); - if (state->flags & 0x0200) - state->check = crc32(state->check, next, copy); - have -= copy; - next += copy; - if (len) goto inf_leave; - } - else if (state->head != Z_NULL) - state->head->comment = Z_NULL; - state->mode = HCRC; - case HCRC: - if (state->flags & 0x0200) { - NEEDBITS(16); - if (hold != (state->check & 0xffff)) { - strm->msg = (char *)"header crc mismatch"; - state->mode = BAD; - break; - } - INITBITS(); - } - if (state->head != Z_NULL) { - state->head->hcrc = (int)((state->flags >> 9) & 1); - state->head->done = 1; - } - strm->adler = state->check = crc32(0L, Z_NULL, 0); - state->mode = TYPE; - break; + case FLAGS: + NEEDBITS(16); + state->flags = (int)(hold); + if ((state->flags & 0xff) != Z_DEFLATED) { + strm->msg = (char *) + "unknown compression method"; + state->mode = BAD; + break; + } + if (state->flags & 0xe000) { + strm->msg = (char *)"unknown header flags set"; + state->mode = BAD; + break; + } + if (state->head != Z_NULL) + state->head->text = (int)((hold >> 8) & 1); + if (state->flags & 0x0200) CRC2(state->check, hold); + INITBITS(); + state->mode = TIME; + case TIME: + NEEDBITS(32); + if (state->head != Z_NULL) + state->head->time = hold; + if (state->flags & 0x0200) CRC4(state->check, hold); + INITBITS(); + state->mode = OS; + case OS: + NEEDBITS(16); + if (state->head != Z_NULL) { + state->head->xflags = (int)(hold & 0xff); + state->head->os = (int)(hold >> 8); + } + if (state->flags & 0x0200) CRC2(state->check, hold); + INITBITS(); + state->mode = EXLEN; + case EXLEN: + if (state->flags & 0x0400) { + NEEDBITS(16); + state->length = (unsigned)(hold); + if (state->head != Z_NULL) + state->head->extra_len = (unsigned)hold; + if (state->flags & 0x0200) + CRC2(state->check, hold); + INITBITS(); + } else if (state->head != Z_NULL) + state->head->extra = Z_NULL; + state->mode = EXTRA; + case EXTRA: + if (state->flags & 0x0400) { + copy = state->length; + if (copy > have) copy = have; + if (copy) { + if (state->head != Z_NULL && + state->head->extra != Z_NULL) { + len = state->head->extra_len - + state->length; + zmemcpy( + state->head->extra + len, + next, + len + copy > + state->head->extra_max ? + state->head->extra_max - + len : + copy); + } + if (state->flags & 0x0200) + state->check = + crc32(state->check, + next, copy); + have -= copy; + next += copy; + state->length -= copy; + } + if (state->length) goto inf_leave; + } + state->length = 0; + state->mode = NAME; + case NAME: + if (state->flags & 0x0800) { + if (have == 0) goto inf_leave; + copy = 0; + do { + len = (unsigned)(next[copy++]); + if (state->head != Z_NULL && + state->head->name != Z_NULL && + state->length < + state->head->name_max) + state->head->name[ + state->length++] = + (Byte)len; + } while (len && copy < have); + if (state->flags & 0x0200) + state->check = crc32(state->check, + next, copy); + have -= copy; + next += copy; + if (len) goto inf_leave; + } else if (state->head != Z_NULL) + state->head->name = Z_NULL; + state->length = 0; + state->mode = COMMENT; + case COMMENT: + if (state->flags & 0x1000) { + if (have == 0) goto inf_leave; + copy = 0; + do { + len = (unsigned)(next[copy++]); + if (state->head != Z_NULL && + state->head->comment != Z_NULL && + state->length < + state->head->comm_max) + state->head->comment[ + state->length++] = + (Byte)len; + } while (len && copy < have); + if (state->flags & 0x0200) + state->check = crc32(state->check, + next, copy); + have -= copy; + next += copy; + if (len) goto inf_leave; + } else if (state->head != Z_NULL) + state->head->comment = Z_NULL; + state->mode = HCRC; + case HCRC: + if (state->flags & 0x0200) { + NEEDBITS(16); + if (hold != (state->check & 0xffff)) { + strm->msg = + (char *)"header crc mismatch"; + state->mode = BAD; + break; + } + INITBITS(); + } + if (state->head != Z_NULL) { + state->head->hcrc = + (int)((state->flags >> 9) & 1); + state->head->done = 1; + } + strm->adler = state->check = + crc32(0L, Z_NULL, 0); + state->mode = TYPE; + break; #endif - case DICTID: - NEEDBITS(32); - strm->adler = state->check = REVERSE(hold); - INITBITS(); - state->mode = DICT; - case DICT: - if (state->havedict == 0) { - RESTORE(); - return Z_NEED_DICT; - } - strm->adler = state->check = adler32(0L, Z_NULL, 0); - state->mode = TYPE; - case TYPE: - if (flush == Z_BLOCK) goto inf_leave; - case TYPEDO: - if (state->last) { - BYTEBITS(); - state->mode = CHECK; - break; - } - NEEDBITS(3); - state->last = BITS(1); - DROPBITS(1); - switch (BITS(2)) { - case 0: /* stored block */ - Tracev((stderr, "inflate: stored block%s\n", - state->last ? " (last)" : "")); - state->mode = STORED; - break; - case 1: /* fixed block */ - fixedtables(state); - Tracev((stderr, "inflate: fixed codes block%s\n", - state->last ? " (last)" : "")); - state->mode = LEN; /* decode codes */ - break; - case 2: /* dynamic block */ - Tracev((stderr, "inflate: dynamic codes block%s\n", - state->last ? " (last)" : "")); - state->mode = TABLE; - break; - case 3: - strm->msg = (char *)"invalid block type"; - state->mode = BAD; - } - DROPBITS(2); - break; - case STORED: - BYTEBITS(); /* go to byte boundary */ - NEEDBITS(32); - if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { - strm->msg = (char *)"invalid stored block lengths"; - state->mode = BAD; - break; - } - state->length = (unsigned)hold & 0xffff; - Tracev((stderr, "inflate: stored length %u\n", - state->length)); - INITBITS(); - state->mode = COPY; - case COPY: - copy = state->length; - if (copy) { - if (copy > have) copy = have; - if (copy > left) copy = left; - if (copy == 0) goto inf_leave; - zmemcpy(put, next, copy); - have -= copy; - next += copy; - left -= copy; - put += copy; - state->length -= copy; - break; - } - Tracev((stderr, "inflate: stored end\n")); - state->mode = TYPE; - break; - case TABLE: - NEEDBITS(14); - state->nlen = BITS(5) + 257; - DROPBITS(5); - state->ndist = BITS(5) + 1; - DROPBITS(5); - state->ncode = BITS(4) + 4; - DROPBITS(4); + case DICTID: + NEEDBITS(32); + strm->adler = state->check = REVERSE(hold); + INITBITS(); + state->mode = DICT; + case DICT: + if (state->havedict == 0) { + RESTORE(); + return (Z_NEED_DICT); + } + strm->adler = state->check = adler32(0L, Z_NULL, 0); + state->mode = TYPE; + case TYPE: + if (flush == Z_BLOCK) goto inf_leave; + case TYPEDO: + if (state->last) { + BYTEBITS(); + state->mode = CHECK; + break; + } + NEEDBITS(3); + state->last = BITS(1); + DROPBITS(1); + switch (BITS(2)) { + case 0: /* stored block */ + Tracev((stderr, "inflate: stored block%s\n", + state->last ? " (last)" : "")); + state->mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + Tracev((stderr, + "inflate: fixed codes block%s\n", + state->last ? " (last)" : "")); + state->mode = LEN; /* decode codes */ + break; + case 2: /* dynamic block */ + Tracev((stderr, + "inflate: dynamic codes block%s\n", + state->last ? " (last)" : "")); + state->mode = TABLE; + break; + case 3: + strm->msg = (char *)"invalid block type"; + state->mode = BAD; + } + DROPBITS(2); + break; + case STORED: + BYTEBITS(); /* go to byte boundary */ + NEEDBITS(32); + if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { + strm->msg = + (char *)"invalid stored block lengths"; + state->mode = BAD; + break; + } + state->length = (unsigned)hold & 0xffff; + Tracev((stderr, + "inflate: stored length %u\n", + state->length)); + INITBITS(); + state->mode = COPY; + case COPY: + copy = state->length; + if (copy) { + if (copy > have) copy = have; + if (copy > left) copy = left; + if (copy == 0) goto inf_leave; + zmemcpy(put, next, copy); + have -= copy; + next += copy; + left -= copy; + put += copy; + state->length -= copy; + break; + } + Tracev((stderr, "inflate: stored end\n")); + state->mode = TYPE; + break; + case TABLE: + NEEDBITS(14); + state->nlen = BITS(5) + 257; + DROPBITS(5); + state->ndist = BITS(5) + 1; + DROPBITS(5); + state->ncode = BITS(4) + 4; + DROPBITS(4); #ifndef PKZIP_BUG_WORKAROUND - if (state->nlen > 286 || state->ndist > 30) { - strm->msg = (char *)"too many length or distance symbols"; - state->mode = BAD; - break; - } + if (state->nlen > 286 || state->ndist > 30) { + strm->msg = (char *) + "too many length or distance symbols"; + state->mode = BAD; + break; + } #endif - Tracev((stderr, "inflate: table sizes ok\n")); - state->have = 0; - state->mode = LENLENS; - case LENLENS: - while (state->have < state->ncode) { - NEEDBITS(3); - state->lens[order[state->have++]] = (unsigned short)BITS(3); - DROPBITS(3); - } - while (state->have < 19) - state->lens[order[state->have++]] = 0; - state->next = state->codes; - state->lencode = (code const FAR *)(state->next); - state->lenbits = 7; - ret = inflate_table(CODES, state->lens, 19, &(state->next), - &(state->lenbits), state->work); - if (ret) { - strm->msg = (char *)"invalid code lengths set"; - state->mode = BAD; - break; - } - Tracev((stderr, "inflate: code lengths ok\n")); - state->have = 0; - state->mode = CODELENS; - case CODELENS: - while (state->have < state->nlen + state->ndist) { - for (;;) { - this = state->lencode[BITS(state->lenbits)]; - if ((unsigned)(this.bits) <= bits) break; - PULLBYTE(); - } - if (this.val < 16) { - NEEDBITS(this.bits); - DROPBITS(this.bits); - state->lens[state->have++] = this.val; - } - else { - if (this.val == 16) { - NEEDBITS(this.bits + 2); - DROPBITS(this.bits); - if (state->have == 0) { - strm->msg = (char *)"invalid bit length repeat"; - state->mode = BAD; - break; - } - len = state->lens[state->have - 1]; - copy = 3 + BITS(2); - DROPBITS(2); - } - else if (this.val == 17) { - NEEDBITS(this.bits + 3); - DROPBITS(this.bits); - len = 0; - copy = 3 + BITS(3); - DROPBITS(3); - } - else { - NEEDBITS(this.bits + 7); - DROPBITS(this.bits); - len = 0; - copy = 11 + BITS(7); - DROPBITS(7); - } - if (state->have + copy > state->nlen + state->ndist) { - strm->msg = (char *)"invalid bit length repeat"; - state->mode = BAD; - break; - } - while (copy--) - state->lens[state->have++] = (unsigned short)len; - } - } - - /* handle error breaks in while */ - if (state->mode == BAD) break; - - /* build code tables */ - state->next = state->codes; - state->lencode = (code const FAR *)(state->next); - state->lenbits = 9; - ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), - &(state->lenbits), state->work); - if (ret) { - strm->msg = (char *)"invalid literal/lengths set"; - state->mode = BAD; - break; - } - state->distcode = (code const FAR *)(state->next); - state->distbits = 6; - ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, - &(state->next), &(state->distbits), state->work); - if (ret) { - strm->msg = (char *)"invalid distances set"; - state->mode = BAD; - break; - } - Tracev((stderr, "inflate: codes ok\n")); - state->mode = LEN; - case LEN: - if (have >= 6 && left >= 258) { - RESTORE(); - inflate_fast(strm, out); - LOAD(); - break; - } - for (;;) { - this = state->lencode[BITS(state->lenbits)]; - if ((unsigned)(this.bits) <= bits) break; - PULLBYTE(); - } - if (this.op && (this.op & 0xf0) == 0) { - last = this; - for (;;) { - this = state->lencode[last.val + - (BITS(last.bits + last.op) >> last.bits)]; - if ((unsigned)(last.bits + this.bits) <= bits) break; - PULLBYTE(); - } - DROPBITS(last.bits); - } - DROPBITS(this.bits); - state->length = (unsigned)this.val; - if ((int)(this.op) == 0) { - Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ? - "inflate: literal '%c'\n" : - "inflate: literal 0x%02x\n", this.val)); - state->mode = LIT; - break; - } - if (this.op & 32) { - Tracevv((stderr, "inflate: end of block\n")); - state->mode = TYPE; - break; - } - if (this.op & 64) { - strm->msg = (char *)"invalid literal/length code"; - state->mode = BAD; - break; - } - state->extra = (unsigned)(this.op) & 15; - state->mode = LENEXT; - case LENEXT: - if (state->extra) { - NEEDBITS(state->extra); - state->length += BITS(state->extra); - DROPBITS(state->extra); - } - Tracevv((stderr, "inflate: length %u\n", state->length)); - state->mode = DIST; - case DIST: - for (;;) { - this = state->distcode[BITS(state->distbits)]; - if ((unsigned)(this.bits) <= bits) break; - PULLBYTE(); - } - if ((this.op & 0xf0) == 0) { - last = this; - for (;;) { - this = state->distcode[last.val + - (BITS(last.bits + last.op) >> last.bits)]; - if ((unsigned)(last.bits + this.bits) <= bits) break; - PULLBYTE(); - } - DROPBITS(last.bits); - } - DROPBITS(this.bits); - if (this.op & 64) { - strm->msg = (char *)"invalid distance code"; - state->mode = BAD; - break; - } - state->offset = (unsigned)this.val; - state->extra = (unsigned)(this.op) & 15; - state->mode = DISTEXT; - case DISTEXT: - if (state->extra) { - NEEDBITS(state->extra); - state->offset += BITS(state->extra); - DROPBITS(state->extra); - } + Tracev((stderr, "inflate: table sizes ok\n")); + state->have = 0; + state->mode = LENLENS; + case LENLENS: + while (state->have < state->ncode) { + NEEDBITS(3); + state->lens[order[state->have++]] = + (unsigned short)BITS(3); + DROPBITS(3); + } + while (state->have < 19) + state->lens[order[state->have++]] = 0; + state->next = state->codes; + state->lencode = (code const FAR *)(state->next); + state->lenbits = 7; + ret = inflate_table(CODES, state->lens, 19, + &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid code lengths set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: code lengths ok\n")); + state->have = 0; + state->mode = CODELENS; + case CODELENS: + while (state->have < state->nlen + state->ndist) { + for (;;) { + this = state->lencode[ + BITS(state->lenbits)]; + if ((unsigned)(this.bits) <= bits) + break; + PULLBYTE(); + } + if (this.val < 16) { + NEEDBITS(this.bits); + DROPBITS(this.bits); + state->lens[state->have++] = this.val; + } else { + if (this.val == 16) { + NEEDBITS(this.bits + 2); + DROPBITS(this.bits); + if (state->have == 0) { + strm->msg = (char *) + "invalid bit " + "length repeat"; + state->mode = BAD; + break; + } + len = state->lens[ + state->have - 1]; + copy = 3 + BITS(2); + DROPBITS(2); + } else if (this.val == 17) { + NEEDBITS(this.bits + 3); + DROPBITS(this.bits); + len = 0; + copy = 3 + BITS(3); + DROPBITS(3); + } else { + NEEDBITS(this.bits + 7); + DROPBITS(this.bits); + len = 0; + copy = 11 + BITS(7); + DROPBITS(7); + } + if (state->have + copy > state->nlen + + state->ndist) { + strm->msg = (char *) + "invalid bit length repeat"; + state->mode = BAD; + break; + } + while (copy--) + state->lens[state->have++] = + (unsigned short)len; + } + } + + /* handle error breaks in while */ + if (state->mode == BAD) + break; + + /* build code tables */ + state->next = state->codes; + state->lencode = (code const FAR *)(state->next); + state->lenbits = 9; + ret = inflate_table(LENS, state->lens, state->nlen, + &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *) + "invalid literal/lengths set"; + state->mode = BAD; + break; + } + state->distcode = (code const FAR *)(state->next); + state->distbits = 6; + ret = inflate_table(DISTS, state->lens + state->nlen, + state->ndist, + &(state->next), &(state->distbits), state->work); + if (ret) { + strm->msg = (char *)"invalid distances set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: codes ok\n")); + state->mode = LEN; + case LEN: + if (have >= 6 && left >= 258) { + RESTORE(); + inflate_fast(strm, out); + LOAD(); + break; + } + for (;;) { + this = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(this.bits) <= bits) + break; + PULLBYTE(); + } + if (this.op && (this.op & 0xf0) == 0) { + last = this; + for (;;) { + this = state->lencode[last.val + + (BITS(last.bits + last.op) >> + last.bits)]; + if ((unsigned)(last.bits + this.bits) + <= bits) + break; + PULLBYTE(); + } + DROPBITS(last.bits); + } + DROPBITS(this.bits); + state->length = (unsigned)this.val; + if ((int)(this.op) == 0) { + Tracevv((stderr, this.val >= 0x20 && + this.val < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", + this.val)); + state->mode = LIT; + break; + } + if (this.op & 32) { + Tracevv((stderr, + "inflate: end of block\n")); + state->mode = TYPE; + break; + } + if (this.op & 64) { + strm->msg = (char *) + "invalid literal/length code"; + state->mode = BAD; + break; + } + state->extra = (unsigned)(this.op) & 15; + state->mode = LENEXT; + case LENEXT: + if (state->extra) { + NEEDBITS(state->extra); + state->length += BITS(state->extra); + DROPBITS(state->extra); + } + Tracevv((stderr, + "inflate: length %u\n", state->length)); + state->mode = DIST; + case DIST: + for (;;) { + this = state->distcode[BITS(state->distbits)]; + if ((unsigned)(this.bits) <= bits) + break; + PULLBYTE(); + } + if ((this.op & 0xf0) == 0) { + last = this; + for (;;) { + this = state->distcode[last.val + + (BITS(last.bits + last.op) >> + last.bits)]; + if ((unsigned)(last.bits + this.bits) <= + bits) + break; + PULLBYTE(); + } + DROPBITS(last.bits); + } + DROPBITS(this.bits); + if (this.op & 64) { + strm->msg = (char *)"invalid distance code"; + state->mode = BAD; + break; + } + state->offset = (unsigned)this.val; + state->extra = (unsigned)(this.op) & 15; + state->mode = DISTEXT; + case DISTEXT: + if (state->extra) { + NEEDBITS(state->extra); + state->offset += BITS(state->extra); + DROPBITS(state->extra); + } #ifdef INFLATE_STRICT - if (state->offset > state->dmax) { - strm->msg = (char *)"invalid distance too far back"; - state->mode = BAD; - break; - } + if (state->offset > state->dmax) { + strm->msg = (char *) + "invalid distance too far back"; + state->mode = BAD; + break; + } #endif - if (state->offset > state->whave + out - left) { - strm->msg = (char *)"invalid distance too far back"; - state->mode = BAD; - break; - } - Tracevv((stderr, "inflate: distance %u\n", state->offset)); - state->mode = MATCH; - case MATCH: - if (left == 0) goto inf_leave; - copy = out - left; - if (state->offset > copy) { /* copy from window */ - copy = state->offset - copy; - if (copy > state->write) { - copy -= state->write; - from = state->window + (state->wsize - copy); - } - else - from = state->window + (state->write - copy); - if (copy > state->length) copy = state->length; - } - else { /* copy from output */ - from = put - state->offset; - copy = state->length; - } - if (copy > left) copy = left; - left -= copy; - state->length -= copy; - do { - *put++ = *from++; - } while (--copy); - if (state->length == 0) state->mode = LEN; - break; - case LIT: - if (left == 0) goto inf_leave; - *put++ = (unsigned char)(state->length); - left--; - state->mode = LEN; - break; - case CHECK: - if (state->wrap) { - NEEDBITS(32); - out -= left; - strm->total_out += out; - state->total += out; - if (out) - strm->adler = state->check = - UPDATE(state->check, put - out, out); - out = left; - if (( + if (state->offset > state->whave + out - left) { + strm->msg = (char *) + "invalid distance too far back"; + state->mode = BAD; + break; + } + Tracevv((stderr, + "inflate: distance %u\n", state->offset)); + state->mode = MATCH; + case MATCH: + if (left == 0) goto inf_leave; + copy = out - left; + if (state->offset > copy) { /* copy from window */ + copy = state->offset - copy; + if (copy > state->write) { + copy -= state->write; + from = state->window + + (state->wsize - copy); + } else + from = state->window + + (state->write - copy); + if (copy > state->length) + copy = state->length; + } else { /* copy from output */ + from = put - state->offset; + copy = state->length; + } + if (copy > left) copy = left; + left -= copy; + state->length -= copy; + do { + *put++ = *from++; + } while (--copy); + if (state->length == 0) state->mode = LEN; + break; + case LIT: + if (left == 0) goto inf_leave; + *put++ = (unsigned char)(state->length); + left--; + state->mode = LEN; + break; + case CHECK: + if (state->wrap) { + NEEDBITS(32); + out -= left; + strm->total_out += out; + state->total += out; + if (out) + strm->adler = state->check = + UPDATE(state->check, put - out, + out); + out = left; + if (( #ifdef GUNZIP - state->flags ? hold : + state->flags ? hold : #endif - REVERSE(hold)) != state->check) { - strm->msg = (char *)"incorrect data check"; - state->mode = BAD; - break; - } - INITBITS(); - Tracev((stderr, "inflate: check matches trailer\n")); - } + REVERSE(hold)) != state->check) { + strm->msg = (char *) + "incorrect data check"; + state->mode = BAD; + break; + } + INITBITS(); + Tracev((stderr, + "inflate: check matches trailer\n")); + } #ifdef GUNZIP - state->mode = LENGTH; - case LENGTH: - if (state->wrap && state->flags) { - NEEDBITS(32); - if (hold != (state->total & 0xffffffffUL)) { - strm->msg = (char *)"incorrect length check"; - state->mode = BAD; - break; - } - INITBITS(); - Tracev((stderr, "inflate: length matches trailer\n")); - } + state->mode = LENGTH; + case LENGTH: + if (state->wrap && state->flags) { + NEEDBITS(32); + if (hold != (state->total & 0xffffffffUL)) { + strm->msg = (char *) + "incorrect length check"; + state->mode = BAD; + break; + } + INITBITS(); + Tracev((stderr, + "inflate: length matches trailer\n")); + } #endif - state->mode = DONE; - case DONE: - ret = Z_STREAM_END; - goto inf_leave; - case BAD: - ret = Z_DATA_ERROR; - goto inf_leave; - case MEM: - return Z_MEM_ERROR; - case SYNC: - default: - return Z_STREAM_ERROR; - } - - /* - Return from inflate(), updating the total counts and the check value. - If there was no progress during the inflate() call, return a buffer - error. Call updatewindow() to create and/or update the window state. - Note: a memory error from inflate() is non-recoverable. - */ - inf_leave: - RESTORE(); - if (state->wsize || (state->mode < CHECK && out != strm->avail_out)) - if (updatewindow(strm, out)) { - state->mode = MEM; - return Z_MEM_ERROR; - } - in -= strm->avail_in; - out -= strm->avail_out; - strm->total_in += in; - strm->total_out += out; - state->total += out; - if (state->wrap && out) - strm->adler = state->check = - UPDATE(state->check, strm->next_out - out, out); - strm->data_type = state->bits + (state->last ? 64 : 0) + - (state->mode == TYPE ? 128 : 0); - if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK) - ret = Z_BUF_ERROR; - return ret; + state->mode = DONE; + case DONE: + ret = Z_STREAM_END; + goto inf_leave; + case BAD: + ret = Z_DATA_ERROR; + goto inf_leave; + case MEM: + return (Z_MEM_ERROR); + case SYNC: + default: + return (Z_STREAM_ERROR); + } + + /* + * Return from inflate(), updating the total counts and the check value. + * If there was no progress during the inflate() call, return a buffer + * error. Call updatewindow() to create and/or update the window state. + * Note: a memory error from inflate() is non-recoverable. + */ +inf_leave: + RESTORE(); + if (state->wsize || (state->mode < CHECK && out != strm->avail_out)) + if (updatewindow(strm, out)) { + state->mode = MEM; + return (Z_MEM_ERROR); + } + in -= strm->avail_in; + out -= strm->avail_out; + strm->total_in += in; + strm->total_out += out; + state->total += out; + if (state->wrap && out) + strm->adler = state->check = + UPDATE(state->check, strm->next_out - out, out); + strm->data_type = state->bits + (state->last ? 64 : 0) + + (state->mode == TYPE ? 128 : 0); + if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK) + ret = Z_BUF_ERROR; + return (ret); } -int ZEXPORT inflateEnd(strm) -z_streamp strm; +int ZEXPORT +inflateEnd(z_streamp strm) { - struct inflate_state FAR *state; - if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0) - return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - if (state->window != Z_NULL) ZFREE(strm, state->window); - ZFREE(strm, strm->state); - strm->state = Z_NULL; - Tracev((stderr, "inflate: end\n")); - return Z_OK; + struct inflate_state FAR *state; + if (strm == Z_NULL || strm->state == Z_NULL || + strm->zfree == (free_func)0) + return (Z_STREAM_ERROR); + state = (struct inflate_state FAR *)strm->state; + if (state->window != Z_NULL) ZFREE(strm, state->window); + ZFREE(strm, strm->state); + strm->state = Z_NULL; + Tracev((stderr, "inflate: end\n")); + return (Z_OK); } -int ZEXPORT inflateSetDictionary(strm, dictionary, dictLength) -z_streamp strm; -const Bytef *dictionary; -uInt dictLength; +int ZEXPORT +inflateSetDictionary( + z_streamp strm, + const Bytef *dictionary, + uInt dictLength) { - struct inflate_state FAR *state; - unsigned long id; - - /* check state */ - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - if (state->wrap != 0 && state->mode != DICT) - return Z_STREAM_ERROR; - - /* check for correct dictionary id */ - if (state->mode == DICT) { - id = adler32(0L, Z_NULL, 0); - id = adler32(id, dictionary, dictLength); - if (id != state->check) - return Z_DATA_ERROR; - } - - /* copy dictionary to window */ - if (updatewindow(strm, strm->avail_out)) { - state->mode = MEM; - return Z_MEM_ERROR; - } - if (dictLength > state->wsize) { - zmemcpy(state->window, dictionary + dictLength - state->wsize, - state->wsize); - state->whave = state->wsize; - } - else { - zmemcpy(state->window + state->wsize - dictLength, dictionary, - dictLength); - state->whave = dictLength; - } - state->havedict = 1; - Tracev((stderr, "inflate: dictionary set\n")); - return Z_OK; + struct inflate_state FAR *state; + unsigned long id; + + /* check state */ + if (strm == Z_NULL || strm->state == Z_NULL) + return (Z_STREAM_ERROR); + state = (struct inflate_state FAR *)strm->state; + if (state->wrap != 0 && state->mode != DICT) + return (Z_STREAM_ERROR); + + /* check for correct dictionary id */ + if (state->mode == DICT) { + id = adler32(0L, Z_NULL, 0); + id = adler32(id, dictionary, dictLength); + if (id != state->check) + return (Z_DATA_ERROR); + } + + /* copy dictionary to window */ + if (updatewindow(strm, strm->avail_out)) { + state->mode = MEM; + return (Z_MEM_ERROR); + } + if (dictLength > state->wsize) { + zmemcpy(state->window, dictionary + dictLength - state->wsize, + state->wsize); + state->whave = state->wsize; + } else { + zmemcpy(state->window + state->wsize - dictLength, dictionary, + dictLength); + state->whave = dictLength; + } + state->havedict = 1; + Tracev((stderr, "inflate: dictionary set\n")); + return (Z_OK); } -int ZEXPORT inflateGetHeader(strm, head) -z_streamp strm; -gz_headerp head; +int ZEXPORT +inflateGetHeader(z_streamp strm, gz_headerp head) { - struct inflate_state FAR *state; - - /* check state */ - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - if ((state->wrap & 2) == 0) return Z_STREAM_ERROR; - - /* save header structure */ - state->head = head; - head->done = 0; - return Z_OK; + struct inflate_state FAR *state; + + /* check state */ + if (strm == Z_NULL || strm->state == Z_NULL) + return (Z_STREAM_ERROR); + state = (struct inflate_state FAR *)strm->state; + if ((state->wrap & 2) == 0) + return (Z_STREAM_ERROR); + + /* save header structure */ + state->head = head; + head->done = 0; + return (Z_OK); } /* - Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found - or when out of input. When called, *have is the number of pattern bytes - found in order so far, in 0..3. On return *have is updated to the new - state. If on return *have equals four, then the pattern was found and the - return value is how many bytes were read including the last byte of the - pattern. If *have is less than four, then the pattern has not been found - yet and the return value is len. In the latter case, syncsearch() can be - called again with more data and the *have state. *have is initialized to - zero for the first call. + * Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found + * or when out of input. When called, *have is the number of pattern bytes + * found in order so far, in 0..3. On return *have is updated to the new + * state. If on return *have equals four, then the pattern was found and the + * return value is how many bytes were read including the last byte of the + * pattern. If *have is less than four, then the pattern has not been found + * yet and the return value is len. In the latter case, syncsearch() can be + * called again with more data and the *have state. *have is initialized to + * zero for the first call. */ -local unsigned syncsearch(have, buf, len) -unsigned FAR *have; -unsigned char FAR *buf; -unsigned len; +local unsigned +syncsearch( + unsigned FAR *have, + unsigned char FAR *buf, + unsigned len) { - unsigned got; - unsigned next; - - got = *have; - next = 0; - while (next < len && got < 4) { - if ((int)(buf[next]) == (got < 2 ? 0 : 0xff)) - got++; - else if (buf[next]) - got = 0; - else - got = 4 - got; - next++; - } - *have = got; - return next; + unsigned got; + unsigned next; + + got = *have; + next = 0; + while (next < len && got < 4) { + if ((int)(buf[next]) == (got < 2 ? 0 : 0xff)) + got++; + else if (buf[next]) + got = 0; + else + got = 4 - got; + next++; + } + *have = got; + return (next); } -int ZEXPORT inflateSync(strm) -z_streamp strm; +int ZEXPORT +inflateSync(z_streamp strm) { - unsigned len; /* number of bytes to look at or looked at */ - unsigned long in, out; /* temporary to save total_in and total_out */ - unsigned char buf[4]; /* to restore bit buffer to byte string */ - struct inflate_state FAR *state; - - /* check parameters */ - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR; - - /* if first time, start search in bit buffer */ - if (state->mode != SYNC) { - state->mode = SYNC; - state->hold <<= state->bits & 7; - state->bits -= state->bits & 7; - len = 0; - while (state->bits >= 8) { - buf[len++] = (unsigned char)(state->hold); - state->hold >>= 8; - state->bits -= 8; - } - state->have = 0; - syncsearch(&(state->have), buf, len); - } - - /* search available input */ - len = syncsearch(&(state->have), strm->next_in, strm->avail_in); - strm->avail_in -= len; - strm->next_in += len; - strm->total_in += len; - - /* return no joy or set up to restart inflate() on a new block */ - if (state->have != 4) return Z_DATA_ERROR; - in = strm->total_in; out = strm->total_out; - inflateReset(strm); - strm->total_in = in; strm->total_out = out; - state->mode = TYPE; - return Z_OK; + unsigned len; /* number of bytes to look at or looked at */ + unsigned long in, out; /* temporary to save total_in and total_out */ + unsigned char buf[4]; /* to restore bit buffer to byte string */ + struct inflate_state FAR *state; + + /* check parameters */ + if (strm == Z_NULL || strm->state == Z_NULL) + return (Z_STREAM_ERROR); + state = (struct inflate_state FAR *)strm->state; + if (strm->avail_in == 0 && state->bits < 8) + return (Z_BUF_ERROR); + + /* if first time, start search in bit buffer */ + if (state->mode != SYNC) { + state->mode = SYNC; + state->hold <<= state->bits & 7; + state->bits -= state->bits & 7; + len = 0; + while (state->bits >= 8) { + buf[len++] = (unsigned char)(state->hold); + state->hold >>= 8; + state->bits -= 8; + } + state->have = 0; + syncsearch(&(state->have), buf, len); + } + + /* search available input */ + len = syncsearch(&(state->have), strm->next_in, strm->avail_in); + strm->avail_in -= len; + strm->next_in += len; + strm->total_in += len; + + /* return no joy or set up to restart inflate() on a new block */ + if (state->have != 4) + return (Z_DATA_ERROR); + in = strm->total_in; out = strm->total_out; + inflateReset(strm); + strm->total_in = in; strm->total_out = out; + state->mode = TYPE; + return (Z_OK); } /* - Returns true if inflate is currently at the end of a block generated by - Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP - implementation to provide an additional safety check. PPP uses - Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored - block. When decompressing, PPP checks that at the end of input packet, - inflate is waiting for these length bytes. + * Returns true if inflate is currently at the end of a block generated by + * Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP + * implementation to provide an additional safety check. PPP uses + * Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored + * block. When decompressing, PPP checks that at the end of input packet, + * inflate is waiting for these length bytes. */ -int ZEXPORT inflateSyncPoint(strm) -z_streamp strm; +int ZEXPORT +inflateSyncPoint(z_streamp strm) { - struct inflate_state FAR *state; + struct inflate_state FAR *state; - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - return state->mode == STORED && state->bits == 0; + if (strm == Z_NULL || strm->state == Z_NULL) + return (Z_STREAM_ERROR); + state = (struct inflate_state FAR *)strm->state; + return (state->mode == STORED && state->bits == 0); } -int ZEXPORT inflateCopy(dest, source) -z_streamp dest; -z_streamp source; +int ZEXPORT +inflateCopy(z_streamp dest, z_streamp source) { - struct inflate_state FAR *state; - struct inflate_state FAR *copy; - unsigned char FAR *window; - unsigned wsize; - - /* check input */ - if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL || - source->zalloc == (alloc_func)0 || source->zfree == (free_func)0) - return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)source->state; - - /* allocate space */ - copy = (struct inflate_state FAR *) - ZALLOC(source, 1, sizeof(struct inflate_state)); - if (copy == Z_NULL) return Z_MEM_ERROR; - window = Z_NULL; - if (state->window != Z_NULL) { - window = (unsigned char FAR *) - ZALLOC(source, 1U << state->wbits, sizeof(unsigned char)); - if (window == Z_NULL) { - ZFREE(source, copy); - return Z_MEM_ERROR; - } - } - - /* copy state */ - zmemcpy(dest, source, sizeof(z_stream)); - zmemcpy(copy, state, sizeof(struct inflate_state)); - if (state->lencode >= state->codes && - state->lencode <= state->codes + ENOUGH - 1) { - copy->lencode = copy->codes + (state->lencode - state->codes); - copy->distcode = copy->codes + (state->distcode - state->codes); - } - copy->next = copy->codes + (state->next - state->codes); - if (window != Z_NULL) { - wsize = 1U << state->wbits; - zmemcpy(window, state->window, wsize); - } - copy->window = window; - dest->state = (struct internal_state FAR *)copy; - return Z_OK; + struct inflate_state FAR *state; + struct inflate_state FAR *copy; + unsigned char FAR *window; + unsigned wsize; + + /* check input */ + if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL || + source->zalloc == (alloc_func)0 || source->zfree == (free_func)0) + return (Z_STREAM_ERROR); + state = (struct inflate_state FAR *)source->state; + + /* allocate space */ + copy = (struct inflate_state FAR *) + ZALLOC(source, 1, sizeof (struct inflate_state)); + if (copy == Z_NULL) + return (Z_MEM_ERROR); + window = Z_NULL; + if (state->window != Z_NULL) { + window = (unsigned char FAR *) + ZALLOC(source, 1U << state->wbits, sizeof (unsigned char)); + if (window == Z_NULL) { + ZFREE(source, copy); + return (Z_MEM_ERROR); + } + } + + /* copy state */ + zmemcpy(dest, source, sizeof (z_stream)); + zmemcpy(copy, state, sizeof (struct inflate_state)); + if (state->lencode >= state->codes && + state->lencode <= state->codes + ENOUGH - 1) { + copy->lencode = copy->codes + (state->lencode - state->codes); + copy->distcode = copy->codes + (state->distcode - state->codes); + } + copy->next = copy->codes + (state->next - state->codes); + if (window != Z_NULL) { + wsize = 1U << state->wbits; + zmemcpy(window, state->window, wsize); + } + copy->window = window; + dest->state = (struct internal_state FAR *)copy; + return (Z_OK); } diff --git a/lib/os/windows/zlib-1.2.3/inflate.h b/lib/os/windows/zlib-1.2.3/inflate.h index 07bd3e78a7c..de9fa253198 100644 --- a/lib/os/windows/zlib-1.2.3/inflate.h +++ b/lib/os/windows/zlib-1.2.3/inflate.h @@ -1,115 +1,119 @@ -/* inflate.h -- internal inflate state definition +/* + * inflate.h -- internal inflate state definition * Copyright (C) 1995-2004 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ -/* WARNING: this file should *not* be used by applications. It is - part of the implementation of the compression library and is - subject to change. Applications should only use zlib.h. +/* + * WARNING: this file should *not* be used by applications. It is + * part of the implementation of the compression library and is + * subject to change. Applications should only use zlib.h. */ -/* define NO_GZIP when compiling if you want to disable gzip header and - trailer decoding by inflate(). NO_GZIP would be used to avoid linking in - the crc code when it is not needed. For shared libraries, gzip decoding - should be left enabled. */ +/* + * define NO_GZIP when compiling if you want to disable gzip header and + * trailer decoding by inflate(). NO_GZIP would be used to avoid linking in + * the crc code when it is not needed. For shared libraries, gzip decoding + * should be left enabled. + */ #ifndef NO_GZIP -# define GUNZIP +#define GUNZIP #endif /* Possible inflate modes between inflate() calls */ typedef enum { - HEAD, /* i: waiting for magic header */ - FLAGS, /* i: waiting for method and flags (gzip) */ - TIME, /* i: waiting for modification time (gzip) */ - OS, /* i: waiting for extra flags and operating system (gzip) */ - EXLEN, /* i: waiting for extra length (gzip) */ - EXTRA, /* i: waiting for extra bytes (gzip) */ - NAME, /* i: waiting for end of file name (gzip) */ - COMMENT, /* i: waiting for end of comment (gzip) */ - HCRC, /* i: waiting for header crc (gzip) */ - DICTID, /* i: waiting for dictionary check value */ - DICT, /* waiting for inflateSetDictionary() call */ - TYPE, /* i: waiting for type bits, including last-flag bit */ - TYPEDO, /* i: same, but skip check to exit inflate on new block */ - STORED, /* i: waiting for stored size (length and complement) */ - COPY, /* i/o: waiting for input or output to copy stored block */ - TABLE, /* i: waiting for dynamic block table lengths */ - LENLENS, /* i: waiting for code length code lengths */ - CODELENS, /* i: waiting for length/lit and distance code lengths */ - LEN, /* i: waiting for length/lit code */ - LENEXT, /* i: waiting for length extra bits */ - DIST, /* i: waiting for distance code */ - DISTEXT, /* i: waiting for distance extra bits */ - MATCH, /* o: waiting for output space to copy string */ - LIT, /* o: waiting for output space to write literal */ - CHECK, /* i: waiting for 32-bit check value */ - LENGTH, /* i: waiting for 32-bit length (gzip) */ - DONE, /* finished check, done -- remain here until reset */ - BAD, /* got a data error -- remain here until reset */ - MEM, /* got an inflate() memory error -- remain here until reset */ - SYNC /* looking for synchronization bytes to restart inflate() */ + HEAD, /* i: waiting for magic header */ + FLAGS, /* i: waiting for method and flags (gzip) */ + TIME, /* i: waiting for modification time (gzip) */ + OS, /* i: waiting for extra flags and operating system (gzip) */ + EXLEN, /* i: waiting for extra length (gzip) */ + EXTRA, /* i: waiting for extra bytes (gzip) */ + NAME, /* i: waiting for end of file name (gzip) */ + COMMENT, /* i: waiting for end of comment (gzip) */ + HCRC, /* i: waiting for header crc (gzip) */ + DICTID, /* i: waiting for dictionary check value */ + DICT, /* waiting for inflateSetDictionary() call */ + TYPE, /* i: waiting for type bits, including last-flag bit */ + TYPEDO, /* i: same, but skip check to exit inflate on new block */ + STORED, /* i: waiting for stored size (length and complement) */ + COPY, /* i/o: waiting for input or output to copy stored block */ + TABLE, /* i: waiting for dynamic block table lengths */ + LENLENS, /* i: waiting for code length code lengths */ + CODELENS, /* i: waiting for length/lit and distance code lengths */ + LEN, /* i: waiting for length/lit code */ + LENEXT, /* i: waiting for length extra bits */ + DIST, /* i: waiting for distance code */ + DISTEXT, /* i: waiting for distance extra bits */ + MATCH, /* o: waiting for output space to copy string */ + LIT, /* o: waiting for output space to write literal */ + CHECK, /* i: waiting for 32-bit check value */ + LENGTH, /* i: waiting for 32-bit length (gzip) */ + DONE, /* finished check, done -- remain here until reset */ + BAD, /* got a data error -- remain here until reset */ + MEM, /* got an inflate() memory error -- remain here until reset */ + SYNC /* looking for synchronization bytes to restart inflate() */ } inflate_mode; /* - State transitions between above modes - - - (most modes can go to the BAD or MEM mode -- not shown for clarity) - - Process header: - HEAD -> (gzip) or (zlib) - (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME - NAME -> COMMENT -> HCRC -> TYPE - (zlib) -> DICTID or TYPE - DICTID -> DICT -> TYPE - Read deflate blocks: - TYPE -> STORED or TABLE or LEN or CHECK - STORED -> COPY -> TYPE - TABLE -> LENLENS -> CODELENS -> LEN - Read deflate codes: - LEN -> LENEXT or LIT or TYPE - LENEXT -> DIST -> DISTEXT -> MATCH -> LEN - LIT -> LEN - Process trailer: - CHECK -> LENGTH -> DONE + * State transitions between above modes - + * + * (most modes can go to the BAD or MEM mode -- not shown for clarity) + * + * Process header: + * HEAD -> (gzip) or (zlib) + * (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME + * NAME -> COMMENT -> HCRC -> TYPE + * (zlib) -> DICTID or TYPE + * DICTID -> DICT -> TYPE + * Read deflate blocks: + * TYPE -> STORED or TABLE or LEN or CHECK + * STORED -> COPY -> TYPE + * TABLE -> LENLENS -> CODELENS -> LEN + * Read deflate codes: + * LEN -> LENEXT or LIT or TYPE + * LENEXT -> DIST -> DISTEXT -> MATCH -> LEN + * LIT -> LEN + * Process trailer: + * CHECK -> LENGTH -> DONE */ /* state maintained between inflate() calls. Approximately 7K bytes. */ struct inflate_state { - inflate_mode mode; /* current inflate mode */ - int last; /* true if processing last block */ - int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ - int havedict; /* true if dictionary provided */ - int flags; /* gzip header method and flags (0 if zlib) */ - unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */ - unsigned long check; /* protected copy of check value */ - unsigned long total; /* protected copy of output count */ - gz_headerp head; /* where to save gzip header information */ - /* sliding window */ - unsigned wbits; /* log base 2 of requested window size */ - unsigned wsize; /* window size or zero if not using window */ - unsigned whave; /* valid bytes in the window */ - unsigned write; /* window write index */ - unsigned char FAR *window; /* allocated sliding window, if needed */ - /* bit accumulator */ - unsigned long hold; /* input bit accumulator */ - unsigned bits; /* number of bits in "in" */ - /* for string and stored block copying */ - unsigned length; /* literal or length of data to copy */ - unsigned offset; /* distance back to copy string from */ - /* for table and code decoding */ - unsigned extra; /* extra bits needed */ - /* fixed and dynamic code tables */ - code const FAR *lencode; /* starting table for length/literal codes */ - code const FAR *distcode; /* starting table for distance codes */ - unsigned lenbits; /* index bits for lencode */ - unsigned distbits; /* index bits for distcode */ - /* dynamic table building */ - unsigned ncode; /* number of code length code lengths */ - unsigned nlen; /* number of length code lengths */ - unsigned ndist; /* number of distance code lengths */ - unsigned have; /* number of code lengths in lens[] */ - code FAR *next; /* next available space in codes[] */ - unsigned short lens[320]; /* temporary storage for code lengths */ - unsigned short work[288]; /* work area for code table building */ - code codes[ENOUGH]; /* space for code tables */ + inflate_mode mode; /* current inflate mode */ + int last; /* true if processing last block */ + int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ + int havedict; /* true if dictionary provided */ + int flags; /* gzip header method and flags (0 if zlib) */ + unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */ + unsigned long check; /* protected copy of check value */ + unsigned long total; /* protected copy of output count */ + gz_headerp head; /* where to save gzip header information */ + /* sliding window */ + unsigned wbits; /* log base 2 of requested window size */ + unsigned wsize; /* window size or zero if not using window */ + unsigned whave; /* valid bytes in the window */ + unsigned write; /* window write index */ + unsigned char FAR *window; /* allocated sliding window, if needed */ + /* bit accumulator */ + unsigned long hold; /* input bit accumulator */ + unsigned bits; /* number of bits in "in" */ + /* for string and stored block copying */ + unsigned length; /* literal or length of data to copy */ + unsigned offset; /* distance back to copy string from */ + /* for table and code decoding */ + unsigned extra; /* extra bits needed */ + /* fixed and dynamic code tables */ + code const FAR *lencode; /* starting table for length/literal codes */ + code const FAR *distcode; /* starting table for distance codes */ + unsigned lenbits; /* index bits for lencode */ + unsigned distbits; /* index bits for distcode */ + /* dynamic table building */ + unsigned ncode; /* number of code length code lengths */ + unsigned nlen; /* number of length code lengths */ + unsigned ndist; /* number of distance code lengths */ + unsigned have; /* number of code lengths in lens[] */ + code FAR *next; /* next available space in codes[] */ + unsigned short lens[320]; /* temporary storage for code lengths */ + unsigned short work[288]; /* work area for code table building */ + code codes[ENOUGH]; /* space for code tables */ }; diff --git a/lib/os/windows/zlib-1.2.3/inftrees.c b/lib/os/windows/zlib-1.2.3/inftrees.c index 8a9c13ff03d..f230eb6dad8 100644 --- a/lib/os/windows/zlib-1.2.3/inftrees.c +++ b/lib/os/windows/zlib-1.2.3/inftrees.c @@ -1,4 +1,5 @@ -/* inftrees.c -- generate Huffman trees for efficient decoding +/* + * inftrees.c -- generate Huffman trees for efficient decoding * Copyright (C) 1995-2005 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ @@ -6,324 +7,331 @@ #include "zutil.h" #include "inftrees.h" -#define MAXBITS 15 +#define MAXBITS 15 const char inflate_copyright[] = - " inflate 1.2.3 Copyright 1995-2005 Mark Adler "; + " inflate 1.2.3 Copyright 1995-2005 Mark Adler "; /* - If you use the zlib library in a product, an acknowledgment is welcome - in the documentation of your product. If for some reason you cannot - include such an acknowledgment, I would appreciate that you keep this - copyright string in the executable of your product. + * If you use the zlib library in a product, an acknowledgment is welcome + * in the documentation of your product. If for some reason you cannot + * include such an acknowledgment, I would appreciate that you keep this + * copyright string in the executable of your product. */ /* - Build a set of tables to decode the provided canonical Huffman code. - The code lengths are lens[0..codes-1]. The result starts at *table, - whose indices are 0..2^bits-1. work is a writable array of at least - lens shorts, which is used as a work area. type is the type of code - to be generated, CODES, LENS, or DISTS. On return, zero is success, - -1 is an invalid code, and +1 means that ENOUGH isn't enough. table - on return points to the next available entry's address. bits is the - requested root table index bits, and on return it is the actual root - table index bits. It will differ if the request is greater than the - longest code or if it is less than the shortest code. + * Build a set of tables to decode the provided canonical Huffman code. + * The code lengths are lens[0..codes-1]. The result starts at *table, + * whose indices are 0..2^bits-1. work is a writable array of at least + * lens shorts, which is used as a work area. type is the type of code + * to be generated, CODES, LENS, or DISTS. On return, zero is success, + * -1 is an invalid code, and +1 means that ENOUGH isn't enough. table + * on return points to the next available entry's address. bits is the + * requested root table index bits, and on return it is the actual root + * table index bits. It will differ if the request is greater than the + * longest code or if it is less than the shortest code. */ -int inflate_table(type, lens, codes, table, bits, work) -codetype type; -unsigned short FAR *lens; -unsigned codes; -code FAR * FAR *table; -unsigned FAR *bits; -unsigned short FAR *work; +int +inflate_table( + codetype type, + unsigned short FAR *lens, + unsigned codes, + code FAR * FAR *table, + unsigned FAR *bits, + unsigned short FAR *work) { - unsigned len; /* a code's length in bits */ - unsigned sym; /* index of code symbols */ - unsigned min, max; /* minimum and maximum code lengths */ - unsigned root; /* number of index bits for root table */ - unsigned curr; /* number of index bits for current table */ - unsigned drop; /* code bits to drop for sub-table */ - int left; /* number of prefix codes available */ - unsigned used; /* code entries in table used */ - unsigned huff; /* Huffman code */ - unsigned incr; /* for incrementing code, index */ - unsigned fill; /* index for replicating entries */ - unsigned low; /* low bits for current root entry */ - unsigned mask; /* mask for low root bits */ - code this; /* table entry for duplication */ - code FAR *next; /* next available space in table */ - const unsigned short FAR *base; /* base value table to use */ - const unsigned short FAR *extra; /* extra bits table to use */ - int end; /* use base and extra for symbol > end */ - unsigned short count[MAXBITS+1]; /* number of codes of each length */ - unsigned short offs[MAXBITS+1]; /* offsets in table for each length */ - static const unsigned short lbase[31] = { /* Length codes 257..285 base */ - 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, - 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; - static const unsigned short lext[31] = { /* Length codes 257..285 extra */ - 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, - 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196}; - static const unsigned short dbase[32] = { /* Distance codes 0..29 base */ - 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, - 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, - 8193, 12289, 16385, 24577, 0, 0}; - static const unsigned short dext[32] = { /* Distance codes 0..29 extra */ - 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, - 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, - 28, 28, 29, 29, 64, 64}; - - /* - Process a set of code lengths to create a canonical Huffman code. The - code lengths are lens[0..codes-1]. Each length corresponds to the - symbols 0..codes-1. The Huffman code is generated by first sorting the - symbols by length from short to long, and retaining the symbol order - for codes with equal lengths. Then the code starts with all zero bits - for the first code of the shortest length, and the codes are integer - increments for the same length, and zeros are appended as the length - increases. For the deflate format, these bits are stored backwards - from their more natural integer increment ordering, and so when the - decoding tables are built in the large loop below, the integer codes - are incremented backwards. - - This routine assumes, but does not check, that all of the entries in - lens[] are in the range 0..MAXBITS. The caller must assure this. - 1..MAXBITS is interpreted as that code length. zero means that that - symbol does not occur in this code. - - The codes are sorted by computing a count of codes for each length, - creating from that a table of starting indices for each length in the - sorted table, and then entering the symbols in order in the sorted - table. The sorted table is work[], with that space being provided by - the caller. - - The length counts are used for other purposes as well, i.e. finding - the minimum and maximum length codes, determining if there are any - codes at all, checking for a valid set of lengths, and looking ahead - at length counts to determine sub-table sizes when building the - decoding tables. - */ - - /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ - for (len = 0; len <= MAXBITS; len++) - count[len] = 0; - for (sym = 0; sym < codes; sym++) - count[lens[sym]]++; - - /* bound code lengths, force root to be within code lengths */ - root = *bits; - for (max = MAXBITS; max >= 1; max--) - if (count[max] != 0) break; - if (root > max) root = max; - if (max == 0) { /* no symbols to code at all */ - this.op = (unsigned char)64; /* invalid code marker */ - this.bits = (unsigned char)1; - this.val = (unsigned short)0; - *(*table)++ = this; /* make a table to force an error */ - *(*table)++ = this; - *bits = 1; - return 0; /* no symbols, but wait for decoding to report error */ - } - for (min = 1; min <= MAXBITS; min++) - if (count[min] != 0) break; - if (root < min) root = min; - - /* check for an over-subscribed or incomplete set of lengths */ - left = 1; - for (len = 1; len <= MAXBITS; len++) { - left <<= 1; - left -= count[len]; - if (left < 0) return -1; /* over-subscribed */ - } - if (left > 0 && (type == CODES || max != 1)) - return -1; /* incomplete set */ - - /* generate offsets into symbol table for each length for sorting */ - offs[1] = 0; - for (len = 1; len < MAXBITS; len++) - offs[len + 1] = offs[len] + count[len]; - - /* sort symbols by length, by symbol order within each length */ - for (sym = 0; sym < codes; sym++) - if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym; - - /* - Create and fill in decoding tables. In this loop, the table being - filled is at next and has curr index bits. The code being used is huff - with length len. That code is converted to an index by dropping drop - bits off of the bottom. For codes where len is less than drop + curr, - those top drop + curr - len bits are incremented through all values to - fill the table with replicated entries. - - root is the number of index bits for the root table. When len exceeds - root, sub-tables are created pointed to by the root entry with an index - of the low root bits of huff. This is saved in low to check for when a - new sub-table should be started. drop is zero when the root table is - being filled, and drop is root when sub-tables are being filled. - - When a new sub-table is needed, it is necessary to look ahead in the - code lengths to determine what size sub-table is needed. The length - counts are used for this, and so count[] is decremented as codes are - entered in the tables. - - used keeps track of how many table entries have been allocated from the - provided *table space. It is checked when a LENS table is being made - against the space in *table, ENOUGH, minus the maximum space needed by - the worst case distance code, MAXD. This should never happen, but the - sufficiency of ENOUGH has not been proven exhaustively, hence the check. - This assumes that when type == LENS, bits == 9. - - sym increments through all symbols, and the loop terminates when - all codes of length max, i.e. all codes, have been processed. This - routine permits incomplete codes, so another loop after this one fills - in the rest of the decoding tables with invalid code markers. - */ - - /* set up for code type */ - switch (type) { - case CODES: - base = extra = work; /* dummy value--not used */ - end = 19; - break; - case LENS: - base = lbase; - base -= 257; - extra = lext; - extra -= 257; - end = 256; - break; - default: /* DISTS */ - base = dbase; - extra = dext; - end = -1; - } + unsigned len; /* a code's length in bits */ + unsigned sym; /* index of code symbols */ + unsigned min, max; /* minimum and maximum code lengths */ + unsigned root; /* number of index bits for root table */ + unsigned curr; /* number of index bits for current table */ + unsigned drop; /* code bits to drop for sub-table */ + int left; /* number of prefix codes available */ + unsigned used; /* code entries in table used */ + unsigned huff; /* Huffman code */ + unsigned incr; /* for incrementing code, index */ + unsigned fill; /* index for replicating entries */ + unsigned low; /* low bits for current root entry */ + unsigned mask; /* mask for low root bits */ + code this; /* table entry for duplication */ + code FAR *next; /* next available space in table */ + const unsigned short FAR *base; /* base value table to use */ + const unsigned short FAR *extra; /* extra bits table to use */ + int end; /* use base and extra for symbol > end */ + unsigned short count[MAXBITS+1]; /* number of codes of each length */ + unsigned short offs[MAXBITS+1]; /* offsets in table for each length */ + /* Length codes 257..285 base */ + static const unsigned short lbase[31] = { + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; + /* Length codes 257..285 extra */ + static const unsigned short lext[31] = { + 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, + 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196}; + /* Distance codes 0..29 base */ + static const unsigned short dbase[32] = { + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577, 0, 0}; + /* Distance codes 0..29 extra */ + static const unsigned short dext[32] = { + 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, + 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, + 28, 28, 29, 29, 64, 64}; - /* initialize state for loop */ - huff = 0; /* starting code */ - sym = 0; /* starting code symbol */ - len = min; /* starting code length */ - next = *table; /* current table to fill in */ - curr = root; /* current table index bits */ - drop = 0; /* current bits to drop from code for index */ - low = (unsigned)(-1); /* trigger new sub-table when len > root */ - used = 1U << root; /* use root table entries */ - mask = used - 1; /* mask for comparing low */ - - /* check available table space */ - if (type == LENS && used >= ENOUGH - MAXD) - return 1; - - /* process all codes and make table entries */ - for (;;) { - /* create table entry */ - this.bits = (unsigned char)(len - drop); - if ((int)(work[sym]) < end) { - this.op = (unsigned char)0; - this.val = work[sym]; - } - else if ((int)(work[sym]) > end) { - this.op = (unsigned char)(extra[work[sym]]); - this.val = base[work[sym]]; - } - else { - this.op = (unsigned char)(32 + 64); /* end of block */ - this.val = 0; - } - - /* replicate for those indices with low len bits equal to huff */ - incr = 1U << (len - drop); - fill = 1U << curr; - min = fill; /* save offset to next table */ - do { - fill -= incr; - next[(huff >> drop) + fill] = this; - } while (fill != 0); - - /* backwards increment the len-bit code huff */ - incr = 1U << (len - 1); - while (huff & incr) - incr >>= 1; - if (incr != 0) { - huff &= incr - 1; - huff += incr; - } - else - huff = 0; - - /* go to next symbol, update count, len */ - sym++; - if (--(count[len]) == 0) { - if (len == max) break; - len = lens[work[sym]]; - } - - /* create new sub-table if needed */ - if (len > root && (huff & mask) != low) { - /* if first time, transition to sub-tables */ - if (drop == 0) - drop = root; - - /* increment past last table */ - next += min; /* here min is 1 << curr */ - - /* determine length of next table */ - curr = len - drop; - left = (int)(1 << curr); - while (curr + drop < max) { - left -= count[curr + drop]; - if (left <= 0) break; - curr++; - left <<= 1; - } - - /* check for enough space */ - used += 1U << curr; - if (type == LENS && used >= ENOUGH - MAXD) - return 1; - - /* point entry in root table to sub-table */ - low = huff & mask; - (*table)[low].op = (unsigned char)curr; - (*table)[low].bits = (unsigned char)root; - (*table)[low].val = (unsigned short)(next - *table); - } - } +/* + * Process a set of code lengths to create a canonical Huffman code. The + * code lengths are lens[0..codes-1]. Each length corresponds to the + * symbols 0..codes-1. The Huffman code is generated by first sorting the + * symbols by length from short to long, and retaining the symbol order + * for codes with equal lengths. Then the code starts with all zero bits + * for the first code of the shortest length, and the codes are integer + * increments for the same length, and zeros are appended as the length + * increases. For the deflate format, these bits are stored backwards + * from their more natural integer increment ordering, and so when the + * decoding tables are built in the large loop below, the integer codes + * are incremented backwards. + * + * This routine assumes, but does not check, that all of the entries in + * lens[] are in the range 0..MAXBITS. The caller must assure this. + * 1..MAXBITS is interpreted as that code length. zero means that that + * symbol does not occur in this code. + * + * The codes are sorted by computing a count of codes for each length, + * creating from that a table of starting indices for each length in the + * sorted table, and then entering the symbols in order in the sorted + * table. The sorted table is work[], with that space being provided by + * the caller. + * + * The length counts are used for other purposes as well, i.e. finding + * the minimum and maximum length codes, determining if there are any + * codes at all, checking for a valid set of lengths, and looking ahead + * at length counts to determine sub-table sizes when building the + * decoding tables. + */ - /* - Fill in rest of table for incomplete codes. This loop is similar to the - loop above in incrementing huff for table indices. It is assumed that - len is equal to curr + drop, so there is no loop needed to increment - through high index bits. When the current sub-table is filled, the loop - drops back to the root table to fill in any remaining entries there. - */ - this.op = (unsigned char)64; /* invalid code marker */ - this.bits = (unsigned char)(len - drop); - this.val = (unsigned short)0; - while (huff != 0) { - /* when done with sub-table, drop back to root table */ - if (drop != 0 && (huff & mask) != low) { - drop = 0; - len = root; - next = *table; - this.bits = (unsigned char)len; - } + /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ + for (len = 0; len <= MAXBITS; len++) + count[len] = 0; + for (sym = 0; sym < codes; sym++) + count[lens[sym]]++; + + /* bound code lengths, force root to be within code lengths */ + root = *bits; + for (max = MAXBITS; max >= 1; max--) + if (count[max] != 0) + break; + if (root > max) root = max; + if (max == 0) { /* no symbols to code at all */ + this.op = (unsigned char)64; /* invalid code marker */ + this.bits = (unsigned char)1; + this.val = (unsigned short)0; + *(*table)++ = this; /* make a table to force an error */ + *(*table)++ = this; + *bits = 1; + return (0); /* no syms, but wait for decoding to report err */ + } + for (min = 1; min <= MAXBITS; min++) + if (count[min] != 0) + break; + if (root < min) root = min; + + /* check for an over-subscribed or incomplete set of lengths */ + left = 1; + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) + return (-1); /* over-subscribed */ + } + if (left > 0 && (type == CODES || max != 1)) + return (-1); /* incomplete set */ + + /* generate offsets into symbol table for each length for sorting */ + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) + offs[len + 1] = offs[len] + count[len]; + + /* sort symbols by length, by symbol order within each length */ + for (sym = 0; sym < codes; sym++) + if (lens[sym] != 0) + work[offs[lens[sym]]++] = (unsigned short)sym; - /* put invalid code marker in table */ - next[huff >> drop] = this; +/* + * Create and fill in decoding tables. In this loop, the table being + * filled is at next and has curr index bits. The code being used is huff + * with length len. That code is converted to an index by dropping drop + * bits off of the bottom. For codes where len is less than drop + curr, + * those top drop + curr - len bits are incremented through all values to + * fill the table with replicated entries. + * + * root is the number of index bits for the root table. When len exceeds + * root, sub-tables are created pointed to by the root entry with an index + * of the low root bits of huff. This is saved in low to check for when a + * new sub-table should be started. drop is zero when the root table is + * being filled, and drop is root when sub-tables are being filled. + * + * When a new sub-table is needed, it is necessary to look ahead in the + * code lengths to determine what size sub-table is needed. The length + * counts are used for this, and so count[] is decremented as codes are + * entered in the tables. + * + * used keeps track of how many table entries have been allocated from the + * provided *table space. It is checked when a LENS table is being made + * against the space in *table, ENOUGH, minus the maximum space needed by + * the worst case distance code, MAXD. This should never happen, but the + * sufficiency of ENOUGH has not been proven exhaustively, hence the check. + * This assumes that when type == LENS, bits == 9. + * + * sym increments through all symbols, and the loop terminates when + * all codes of length max, i.e. all codes, have been processed. This + * routine permits incomplete codes, so another loop after this one fills + * in the rest of the decoding tables with invalid code markers. + */ - /* backwards increment the len-bit code huff */ - incr = 1U << (len - 1); - while (huff & incr) - incr >>= 1; - if (incr != 0) { - huff &= incr - 1; - huff += incr; - } - else - huff = 0; - } + /* set up for code type */ + switch (type) { + case CODES: + base = extra = work; /* dummy value--not used */ + end = 19; + break; + case LENS: + base = lbase; + base -= 257; + extra = lext; + extra -= 257; + end = 256; + break; + default: /* DISTS */ + base = dbase; + extra = dext; + end = -1; + } + + /* initialize state for loop */ + huff = 0; /* starting code */ + sym = 0; /* starting code symbol */ + len = min; /* starting code length */ + next = *table; /* current table to fill in */ + curr = root; /* current table index bits */ + drop = 0; /* current bits to drop from code for index */ + low = (unsigned)(-1); /* trigger new sub-table when len > root */ + used = 1U << root; /* use root table entries */ + mask = used - 1; /* mask for comparing low */ + + /* check available table space */ + if (type == LENS && used >= ENOUGH - MAXD) + return (1); + + /* process all codes and make table entries */ + for (;;) { + /* create table entry */ + this.bits = (unsigned char)(len - drop); + if ((int)(work[sym]) < end) { + this.op = (unsigned char)0; + this.val = work[sym]; + } else if ((int)(work[sym]) > end) { + this.op = (unsigned char)(extra[work[sym]]); + this.val = base[work[sym]]; + } else { + this.op = (unsigned char)(32 + 64); /* end of block */ + this.val = 0; + } + +/* replicate for those indices with low len bits equal to huff */ + incr = 1U << (len - drop); + fill = 1U << curr; + min = fill; /* save offset to next table */ + do { + fill -= incr; + next[(huff >> drop) + fill] = this; + } while (fill != 0); + + /* backwards increment the len-bit code huff */ + incr = 1U << (len - 1); + while (huff & incr) + incr >>= 1; + if (incr != 0) { + huff &= incr - 1; + huff += incr; + } else + huff = 0; + + /* go to next symbol, update count, len */ + sym++; + if (--(count[len]) == 0) { + if (len == max) + break; + len = lens[work[sym]]; + } + + /* create new sub-table if needed */ + if (len > root && (huff & mask) != low) { + /* if first time, transition to sub-tables */ + if (drop == 0) + drop = root; + + /* increment past last table */ + next += min; /* here min is 1 << curr */ + + /* determine length of next table */ + curr = len - drop; + left = (int)(1 << curr); + while (curr + drop < max) { + left -= count[curr + drop]; + if (left <= 0) + break; + curr++; + left <<= 1; + } + + /* check for enough space */ + used += 1U << curr; + if (type == LENS && used >= ENOUGH - MAXD) + return (1); + + /* point entry in root table to sub-table */ + low = huff & mask; + (*table)[low].op = (unsigned char)curr; + (*table)[low].bits = (unsigned char)root; + (*table)[low].val = (unsigned short)(next - *table); + } + } - /* set return parameters */ - *table += used; - *bits = root; - return 0; +/* + * Fill in rest of table for incomplete codes. This loop is similar to the + * loop above in incrementing huff for table indices. It is assumed that + * len is equal to curr + drop, so there is no loop needed to increment + * through high index bits. When the current sub-table is filled, the loop + * drops back to the root table to fill in any remaining entries there. + */ + this.op = (unsigned char)64; /* invalid code marker */ + this.bits = (unsigned char)(len - drop); + this.val = (unsigned short)0; + while (huff != 0) { + /* when done with sub-table, drop back to root table */ + if (drop != 0 && (huff & mask) != low) { + drop = 0; + len = root; + next = *table; + this.bits = (unsigned char)len; + } + + /* put invalid code marker in table */ + next[huff >> drop] = this; + + /* backwards increment the len-bit code huff */ + incr = 1U << (len - 1); + while (huff & incr) + incr >>= 1; + if (incr != 0) { + huff &= incr - 1; + huff += incr; + } else + huff = 0; + } + + /* set return parameters */ + *table += used; + *bits = root; + return (0); } diff --git a/lib/os/windows/zlib-1.2.3/inftrees.h b/lib/os/windows/zlib-1.2.3/inftrees.h index b1104c87e76..7e3203bfa68 100644 --- a/lib/os/windows/zlib-1.2.3/inftrees.h +++ b/lib/os/windows/zlib-1.2.3/inftrees.h @@ -1,55 +1,62 @@ -/* inftrees.h -- header to use inftrees.c +/* + * inftrees.h -- header to use inftrees.c * Copyright (C) 1995-2005 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ -/* WARNING: this file should *not* be used by applications. It is - part of the implementation of the compression library and is - subject to change. Applications should only use zlib.h. +/* + * WARNING: this file should *not* be used by applications. It is + * part of the implementation of the compression library and is + * subject to change. Applications should only use zlib.h. */ -/* Structure for decoding tables. Each entry provides either the - information needed to do the operation requested by the code that - indexed that table entry, or it provides a pointer to another - table that indexes more bits of the code. op indicates whether - the entry is a pointer to another table, a literal, a length or - distance, an end-of-block, or an invalid code. For a table - pointer, the low four bits of op is the number of index bits of - that table. For a length or distance, the low four bits of op - is the number of extra bits to get after the code. bits is - the number of bits in this code or part of the code to drop off - of the bit buffer. val is the actual byte to output in the case - of a literal, the base length or distance, or the offset from - the current table to the next table. Each entry is four bytes. */ +/* + * Structure for decoding tables. Each entry provides either the + * information needed to do the operation requested by the code that + * indexed that table entry, or it provides a pointer to another + * table that indexes more bits of the code. op indicates whether + * the entry is a pointer to another table, a literal, a length or + * distance, an end-of-block, or an invalid code. For a table + * pointer, the low four bits of op is the number of index bits of + * that table. For a length or distance, the low four bits of op + * is the number of extra bits to get after the code. bits is + * the number of bits in this code or part of the code to drop off + * of the bit buffer. val is the actual byte to output in the case + * of a literal, the base length or distance, or the offset from + * the current table to the next table. Each entry is four bytes. + */ typedef struct { - unsigned char op; /* operation, extra bits, table bits */ - unsigned char bits; /* bits in this part of the code */ - unsigned short val; /* offset in table or code value */ + unsigned char op; /* operation, extra bits, table bits */ + unsigned char bits; /* bits in this part of the code */ + unsigned short val; /* offset in table or code value */ } code; -/* op values as set by inflate_table(): - 00000000 - literal - 0000tttt - table link, tttt != 0 is the number of table index bits - 0001eeee - length or distance, eeee is the number of extra bits - 01100000 - end of block - 01000000 - invalid code +/* + * op values as set by inflate_table(): + * 00000000 - literal + * 0000tttt - table link, tttt != 0 is the number of table index bits + * 0001eeee - length or distance, eeee is the number of extra bits + * 01100000 - end of block + * 01000000 - invalid code */ -/* Maximum size of dynamic tree. The maximum found in a long but non- - exhaustive search was 1444 code structures (852 for length/literals - and 592 for distances, the latter actually the result of an - exhaustive search). The true maximum is not known, but the value - below is more than safe. */ -#define ENOUGH 2048 -#define MAXD 592 +/* + * Maximum size of dynamic tree. The maximum found in a long but non- + * exhaustive search was 1444 code structures (852 for length/literals + * and 592 for distances, the latter actually the result of an + * exhaustive search). The true maximum is not known, but the value + * below is more than safe. + */ +#define ENOUGH 2048 +#define MAXD 592 /* Type of code to build for inftable() */ typedef enum { - CODES, - LENS, - DISTS + CODES, + LENS, + DISTS } codetype; extern int inflate_table OF((codetype type, unsigned short FAR *lens, - unsigned codes, code FAR * FAR *table, - unsigned FAR *bits, unsigned short FAR *work)); + unsigned codes, code FAR * FAR *table, + unsigned FAR *bits, unsigned short FAR *work)); diff --git a/lib/os/windows/zlib-1.2.3/minigzip.c b/lib/os/windows/zlib-1.2.3/minigzip.c index 4524b96a1d6..97acd81dcdf 100644 --- a/lib/os/windows/zlib-1.2.3/minigzip.c +++ b/lib/os/windows/zlib-1.2.3/minigzip.c @@ -1,4 +1,5 @@ -/* minigzip.c -- simulate gzip using the zlib compression library +/* + * minigzip.c -- simulate gzip using the zlib compression library * Copyright (C) 1995-2005 Jean-loup Gailly. * For conditions of distribution and use, see copyright notice in zlib.h */ @@ -19,245 +20,256 @@ #include "zlib.h" #ifdef STDC -# include -# include +#include +#include #endif #ifdef USE_MMAP -# include -# include -# include +#include +#include +#include #endif #if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__) -# include -# include -# define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY) +#include +#include +#define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY) #else -# define SET_BINARY_MODE(file) +#define SET_BINARY_MODE(file) #endif #ifdef VMS -# define unlink delete -# define GZ_SUFFIX "-gz" +#define unlink delete +#define GZ_SUFFIX "-gz" #endif #ifdef RISCOS -# define unlink remove -# define GZ_SUFFIX "-gz" -# define fileno(file) file->__file +#define unlink remove +#define GZ_SUFFIX "-gz" +#define fileno(file) file->__file #endif #if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os -# include /* for fileno */ +#include /* for fileno */ #endif #ifndef WIN32 /* unlink already in stdio.h for WIN32 */ - extern int unlink OF((const char *)); +extern int unlink OF((const char *)); #endif #ifndef GZ_SUFFIX -# define GZ_SUFFIX ".gz" +#define GZ_SUFFIX ".gz" #endif -#define SUFFIX_LEN (sizeof(GZ_SUFFIX)-1) +#define SUFFIX_LEN (sizeof (GZ_SUFFIX)-1) -#define BUFLEN 16384 -#define MAX_NAME_LEN 1024 +#define BUFLEN 16384 +#define MAX_NAME_LEN 1024 #ifdef MAXSEG_64K -# define local static - /* Needed for systems with limitation on stack size. */ +#define local static +/* Needed for systems with limitation on stack size. */ #else -# define local +#define local #endif char *prog; -void error OF((const char *msg)); -void gz_compress OF((FILE *in, gzFile out)); +void error OF((const char *msg)); +void gz_compress OF((FILE *in, gzFile out)); #ifdef USE_MMAP int gz_compress_mmap OF((FILE *in, gzFile out)); #endif void gz_uncompress OF((gzFile in, FILE *out)); void file_compress OF((char *file, char *mode)); void file_uncompress OF((char *file)); -int main OF((int argc, char *argv[])); +int main OF((int argc, char *argv[])); -/* =========================================================================== +/* * Display error message and exit */ -void error(msg) - const char *msg; +void +error(const char *msg) { - fprintf(stderr, "%s: %s\n", prog, msg); - exit(1); + fprintf(stderr, "%s: %s\n", prog, msg); + exit(1); } -/* =========================================================================== +/* * Compress input to output then close both files. */ -void gz_compress(in, out) - FILE *in; - gzFile out; +void +gz_compress(FILE *in, gzFile out) { - local char buf[BUFLEN]; - int len; - int err; + local char buf[BUFLEN]; + int len; + int err; #ifdef USE_MMAP - /* Try first compressing with mmap. If mmap fails (minigzip used in a - * pipe), use the normal fread loop. - */ - if (gz_compress_mmap(in, out) == Z_OK) return; + /* + * Try first compressing with mmap. If mmap fails (minigzip used in a + * pipe), use the normal fread loop. + */ + if (gz_compress_mmap(in, out) == Z_OK) + return; #endif - for (;;) { - len = (int)fread(buf, 1, sizeof(buf), in); - if (ferror(in)) { - perror("fread"); - exit(1); - } - if (len == 0) break; - - if (gzwrite(out, buf, (unsigned)len) != len) error(gzerror(out, &err)); - } - fclose(in); - if (gzclose(out) != Z_OK) error("failed gzclose"); + for (;;) { + len = (int)fread(buf, 1, sizeof (buf), in); + if (ferror(in)) { + perror("fread"); + exit(1); + } + if (len == 0) + break; + + if (gzwrite(out, buf, (unsigned)len) != len) + error(gzerror(out, &err)); + } + fclose(in); + if (gzclose(out) != Z_OK) error("failed gzclose"); } #ifdef USE_MMAP /* MMAP version, Miguel Albrecht */ -/* Try compressing the input file at once using mmap. Return Z_OK if +/* + * Try compressing the input file at once using mmap. Return Z_OK if * if success, Z_ERRNO otherwise. */ -int gz_compress_mmap(in, out) - FILE *in; - gzFile out; +int +gz_compress_mmap( + FILE *in, + gzFile out) { - int len; - int err; - int ifd = fileno(in); - caddr_t buf; /* mmap'ed buffer for the entire input file */ - off_t buf_len; /* length of the input file */ - struct stat sb; - - /* Determine the size of the file, needed for mmap: */ - if (fstat(ifd, &sb) < 0) return Z_ERRNO; - buf_len = sb.st_size; - if (buf_len <= 0) return Z_ERRNO; - - /* Now do the actual mmap: */ - buf = mmap((caddr_t) 0, buf_len, PROT_READ, MAP_SHARED, ifd, (off_t)0); - if (buf == (caddr_t)(-1)) return Z_ERRNO; - - /* Compress the whole file at once: */ - len = gzwrite(out, (char *)buf, (unsigned)buf_len); - - if (len != (int)buf_len) error(gzerror(out, &err)); - - munmap(buf, buf_len); - fclose(in); - if (gzclose(out) != Z_OK) error("failed gzclose"); - return Z_OK; + int len; + int err; + int ifd = fileno(in); + caddr_t buf; /* mmap'ed buffer for the entire input file */ + off_t buf_len; /* length of the input file */ + struct stat sb; + + /* Determine the size of the file, needed for mmap: */ + if (fstat(ifd, &sb) < 0) + return (Z_ERRNO); + buf_len = sb.st_size; + if (buf_len <= 0) + return (Z_ERRNO); + + /* Now do the actual mmap: */ + buf = mmap((caddr_t)0, buf_len, PROT_READ, MAP_SHARED, ifd, (off_t)0); + if (buf == (caddr_t)(-1)) + return (Z_ERRNO); + + /* Compress the whole file at once: */ + len = gzwrite(out, (char *)buf, (unsigned)buf_len); + + if (len != (int)buf_len) error(gzerror(out, &err)); + + munmap(buf, buf_len); + fclose(in); + if (gzclose(out) != Z_OK) error("failed gzclose"); + return (Z_OK); } #endif /* USE_MMAP */ -/* =========================================================================== +/* * Uncompress input to output then close both files. */ -void gz_uncompress(in, out) - gzFile in; - FILE *out; +void +gz_uncompress( + gzFile in, + FILE *out) { - local char buf[BUFLEN]; - int len; - int err; - - for (;;) { - len = gzread(in, buf, sizeof(buf)); - if (len < 0) error (gzerror(in, &err)); - if (len == 0) break; - - if ((int)fwrite(buf, 1, (unsigned)len, out) != len) { - error("failed fwrite"); - } - } - if (fclose(out)) error("failed fclose"); - - if (gzclose(in) != Z_OK) error("failed gzclose"); + local char buf[BUFLEN]; + int len; + int err; + + for (;;) { + len = gzread(in, buf, sizeof (buf)); + if (len < 0) error(gzerror(in, &err)); + if (len == 0) + break; + + if ((int)fwrite(buf, 1, (unsigned)len, out) != len) { + error("failed fwrite"); + } + } + if (fclose(out)) error("failed fclose"); + + if (gzclose(in) != Z_OK) error("failed gzclose"); } -/* =========================================================================== +/* * Compress the given file: create a corresponding .gz file and remove the * original. */ -void file_compress(file, mode) - char *file; - char *mode; +void +file_compress( + char *file, + char *mode) { - local char outfile[MAX_NAME_LEN]; - FILE *in; - gzFile out; - - strcpy(outfile, file); - strcat(outfile, GZ_SUFFIX); - - in = fopen(file, "rb"); - if (in == NULL) { - perror(file); - exit(1); - } - out = gzopen(outfile, mode); - if (out == NULL) { - fprintf(stderr, "%s: can't gzopen %s\n", prog, outfile); - exit(1); - } - gz_compress(in, out); - - unlink(file); + local char outfile[MAX_NAME_LEN]; + FILE *in; + gzFile out; + + strcpy(outfile, file); + strcat(outfile, GZ_SUFFIX); + + in = fopen(file, "rb"); + if (in == NULL) { + perror(file); + exit(1); + } + out = gzopen(outfile, mode); + if (out == NULL) { + fprintf(stderr, "%s: can't gzopen %s\n", prog, outfile); + exit(1); + } + gz_compress(in, out); + + unlink(file); } -/* =========================================================================== +/* * Uncompress the given file and remove the original. */ -void file_uncompress(file) - char *file; +void +file_uncompress(char *file) { - local char buf[MAX_NAME_LEN]; - char *infile, *outfile; - FILE *out; - gzFile in; - uInt len = (uInt)strlen(file); - - strcpy(buf, file); - - if (len > SUFFIX_LEN && strcmp(file+len-SUFFIX_LEN, GZ_SUFFIX) == 0) { - infile = file; - outfile = buf; - outfile[len-3] = '\0'; - } else { - outfile = file; - infile = buf; - strcat(infile, GZ_SUFFIX); - } - in = gzopen(infile, "rb"); - if (in == NULL) { - fprintf(stderr, "%s: can't gzopen %s\n", prog, infile); - exit(1); - } - out = fopen(outfile, "wb"); - if (out == NULL) { - perror(file); - exit(1); - } - - gz_uncompress(in, out); - - unlink(infile); + local char buf[MAX_NAME_LEN]; + char *infile, *outfile; + FILE *out; + gzFile in; + uInt len = (uInt)strlen(file); + + strcpy(buf, file); + + if (len > SUFFIX_LEN && strcmp(file+len-SUFFIX_LEN, GZ_SUFFIX) == 0) { + infile = file; + outfile = buf; + outfile[len-3] = '\0'; + } else { + outfile = file; + infile = buf; + strcat(infile, GZ_SUFFIX); + } + in = gzopen(infile, "rb"); + if (in == NULL) { + fprintf(stderr, "%s: can't gzopen %s\n", prog, infile); + exit(1); + } + out = fopen(outfile, "wb"); + if (out == NULL) { + perror(file); + exit(1); + } + + gz_uncompress(in, out); + + unlink(infile); } -/* =========================================================================== +/* * Usage: minigzip [-d] [-f] [-h] [-r] [-1 to -9] [files...] * -d : decompress * -f : compress with Z_FILTERED @@ -266,57 +278,58 @@ void file_uncompress(file) * -1 to -9 : compression level */ -int main(argc, argv) - int argc; - char *argv[]; +int main( + int argc, + char *argv[]) { - int uncompr = 0; - gzFile file; - char outmode[20]; - - strcpy(outmode, "wb6 "); - - prog = argv[0]; - argc--, argv++; - - while (argc > 0) { - if (strcmp(*argv, "-d") == 0) - uncompr = 1; - else if (strcmp(*argv, "-f") == 0) - outmode[3] = 'f'; - else if (strcmp(*argv, "-h") == 0) - outmode[3] = 'h'; - else if (strcmp(*argv, "-r") == 0) - outmode[3] = 'R'; - else if ((*argv)[0] == '-' && (*argv)[1] >= '1' && (*argv)[1] <= '9' && - (*argv)[2] == 0) - outmode[2] = (*argv)[1]; - else - break; - argc--, argv++; - } - if (outmode[3] == ' ') - outmode[3] = 0; - if (argc == 0) { - SET_BINARY_MODE(stdin); - SET_BINARY_MODE(stdout); - if (uncompr) { - file = gzdopen(fileno(stdin), "rb"); - if (file == NULL) error("can't gzdopen stdin"); - gz_uncompress(file, stdout); - } else { - file = gzdopen(fileno(stdout), outmode); - if (file == NULL) error("can't gzdopen stdout"); - gz_compress(stdin, file); - } - } else { - do { - if (uncompr) { - file_uncompress(*argv); - } else { - file_compress(*argv, outmode); - } - } while (argv++, --argc); - } - return 0; + int uncompr = 0; + gzFile file; + char outmode[20]; + + strcpy(outmode, "wb6 "); + + prog = argv[0]; + argc--, argv++; + + while (argc > 0) { + if (strcmp(*argv, "-d") == 0) + uncompr = 1; + else if (strcmp(*argv, "-f") == 0) + outmode[3] = 'f'; + else if (strcmp(*argv, "-h") == 0) + outmode[3] = 'h'; + else if (strcmp(*argv, "-r") == 0) + outmode[3] = 'R'; + else if ((*argv)[0] == '-' && (*argv)[1] >= '1' && + (*argv)[1] <= '9' && + (*argv)[2] == 0) + outmode[2] = (*argv)[1]; + else + break; + argc--, argv++; + } + if (outmode[3] == ' ') + outmode[3] = 0; + if (argc == 0) { + SET_BINARY_MODE(stdin); + SET_BINARY_MODE(stdout); + if (uncompr) { + file = gzdopen(fileno(stdin), "rb"); + if (file == NULL) error("can't gzdopen stdin"); + gz_uncompress(file, stdout); + } else { + file = gzdopen(fileno(stdout), outmode); + if (file == NULL) error("can't gzdopen stdout"); + gz_compress(stdin, file); + } + } else { + do { + if (uncompr) { + file_uncompress(*argv); + } else { + file_compress(*argv, outmode); + } + } while (argv++, --argc); + } + return (0); } diff --git a/lib/os/windows/zlib-1.2.3/trees.c b/lib/os/windows/zlib-1.2.3/trees.c index 5073fcc942c..d482f93b439 100644 --- a/lib/os/windows/zlib-1.2.3/trees.c +++ b/lib/os/windows/zlib-1.2.3/trees.c @@ -1,4 +1,5 @@ -/* trees.c -- output deflated data using Huffman coding +/* + * trees.c -- output deflated data using Huffman coding * Copyright (C) 1995-2005 Jean-loup Gailly * For conditions of distribution and use, see copyright notice in zlib.h */ @@ -31,76 +32,84 @@ /* @(#) $Id$ */ -/* #define GEN_TREES_H */ +/* #define GEN_TREES_H */ #include "deflate.h" #ifdef DEBUG -# include +#include #endif -/* =========================================================================== +/* * Constants */ -#define MAX_BL_BITS 7 +#define MAX_BL_BITS 7 /* Bit length codes must not exceed MAX_BL_BITS bits */ -#define END_BLOCK 256 +#define END_BLOCK 256 /* end of block literal code */ -#define REP_3_6 16 +#define REP_3_6 16 /* repeat previous bit length 3-6 times (2 bits of repeat count) */ -#define REPZ_3_10 17 +#define REPZ_3_10 17 /* repeat a zero length 3-10 times (3 bits of repeat count) */ -#define REPZ_11_138 18 +#define REPZ_11_138 18 /* repeat a zero length 11-138 times (7 bits of repeat count) */ local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */ - = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0}; += {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, + 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0}; local const int extra_dbits[D_CODES] /* extra bits for each distance code */ - = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; += {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, + 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; -local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */ - = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7}; +/* extra bits for each bit length code */ +local const int extra_blbits[BL_CODES] += {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7}; local const uch bl_order[BL_CODES] - = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15}; -/* The lengths of the bit length codes are sent in order of decreasing += {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; +/* + * The lengths of the bit length codes are sent in order of decreasing * probability, to avoid transmitting the lengths for unused bit length codes. */ -#define Buf_size (8 * 2*sizeof(char)) -/* Number of bits used within bi_buf. (bi_buf might be implemented on +#define Buf_size (8 * 2*sizeof (char)) +/* + * Number of bits used within bi_buf. (bi_buf might be implemented on * more than 16 bits on some systems.) */ -/* =========================================================================== +/* * Local data. These are initialized only once. */ -#define DIST_CODE_LEN 512 /* see definition of array dist_code below */ +#define DIST_CODE_LEN 512 /* see definition of array dist_code below */ #if defined(GEN_TREES_H) || !defined(STDC) /* non ANSI compilers may not accept trees.h */ local ct_data static_ltree[L_CODES+2]; -/* The static literal tree. Since the bit lengths are imposed, there is no +/* + * The static literal tree. Since the bit lengths are imposed, there is no * need for the L_CODES extra codes used during heap construction. However * The codes 286 and 287 are needed to build a canonical tree (see _tr_init * below). */ local ct_data static_dtree[D_CODES]; -/* The static distance tree. (Actually a trivial tree since all codes use +/* + * The static distance tree. (Actually a trivial tree since all codes use * 5 bits.) */ uch _dist_code[DIST_CODE_LEN]; -/* Distance codes. The first 256 values correspond to the distances +/* + * Distance codes. The first 256 values correspond to the distances * 3 .. 258, the last 256 values correspond to the top 8 bits of * the 15 bit distances. */ @@ -115,369 +124,378 @@ local int base_dist[D_CODES]; /* First normalized distance for each code (0 = distance of 1) */ #else -# include "trees.h" +#include "trees.h" #endif /* GEN_TREES_H */ struct static_tree_desc_s { - const ct_data *static_tree; /* static tree or NULL */ - const intf *extra_bits; /* extra bits for each code or NULL */ - int extra_base; /* base index for extra_bits */ - int elems; /* max number of elements in the tree */ - int max_length; /* max bit length for the codes */ + const ct_data *static_tree; /* static tree or NULL */ + const intf *extra_bits; /* extra bits for each code or NULL */ + int extra_base; /* base index for extra_bits */ + int elems; /* max number of elements in the tree */ + int max_length; /* max bit length for the codes */ }; local static_tree_desc static_l_desc = {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS}; local static_tree_desc static_d_desc = -{static_dtree, extra_dbits, 0, D_CODES, MAX_BITS}; +{static_dtree, extra_dbits, 0, D_CODES, MAX_BITS}; local static_tree_desc static_bl_desc = {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS}; -/* =========================================================================== +/* * Local (static) routines in this file. */ local void tr_static_init OF((void)); -local void init_block OF((deflate_state *s)); -local void pqdownheap OF((deflate_state *s, ct_data *tree, int k)); -local void gen_bitlen OF((deflate_state *s, tree_desc *desc)); -local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count)); -local void build_tree OF((deflate_state *s, tree_desc *desc)); -local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code)); -local void send_tree OF((deflate_state *s, ct_data *tree, int max_code)); +local void init_block OF((deflate_state *s)); +local void pqdownheap OF((deflate_state *s, ct_data *tree, int k)); +local void gen_bitlen OF((deflate_state *s, tree_desc *desc)); +local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count)); +local void build_tree OF((deflate_state *s, tree_desc *desc)); +local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code)); +local void send_tree OF((deflate_state *s, ct_data *tree, int max_code)); local int build_bl_tree OF((deflate_state *s)); local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes, - int blcodes)); + int blcodes)); local void compress_block OF((deflate_state *s, ct_data *ltree, - ct_data *dtree)); + ct_data *dtree)); local void set_data_type OF((deflate_state *s)); local unsigned bi_reverse OF((unsigned value, int length)); -local void bi_windup OF((deflate_state *s)); -local void bi_flush OF((deflate_state *s)); -local void copy_block OF((deflate_state *s, charf *buf, unsigned len, - int header)); +local void bi_windup OF((deflate_state *s)); +local void bi_flush OF((deflate_state *s)); +local void copy_block OF((deflate_state *s, charf *buf, unsigned len, + int header)); #ifdef GEN_TREES_H local void gen_trees_header OF((void)); #endif #ifndef DEBUG -# define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len) - /* Send a code of the given tree. c and tree must not have side effects */ +#define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len) +/* Send a code of the given tree. c and tree must not have side effects */ #else /* DEBUG */ -# define send_code(s, c, tree) \ - { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \ - send_bits(s, tree[c].Code, tree[c].Len); } +#define send_code(s, c, tree) \ + { if (z_verbose > 2) fprintf(stderr, "\ncd %3d ", (c)); \ + send_bits(s, tree[c].Code, tree[c].Len); } #endif -/* =========================================================================== +/* * Output a short LSB first on the stream. * IN assertion: there is enough room in pendingBuf. */ -#define put_short(s, w) { \ +#define put_short(s, w) { \ put_byte(s, (uch)((w) & 0xff)); \ put_byte(s, (uch)((ush)(w) >> 8)); \ } -/* =========================================================================== +/* * Send a value on a given number of bits. * IN assertion: length <= 16 and value fits in length bits. */ #ifdef DEBUG -local void send_bits OF((deflate_state *s, int value, int length)); +local void send_bits OF((deflate_state *s, int value, int length)); -local void send_bits(s, value, length) - deflate_state *s; - int value; /* value to send */ - int length; /* number of bits */ +local void +send_bits( + deflate_state *s, + int value, /* value to send */ + int length) /* number of bits */ { - Tracevv((stderr," l %2d v %4x ", length, value)); - Assert(length > 0 && length <= 15, "invalid length"); - s->bits_sent += (ulg)length; - - /* If not enough room in bi_buf, use (valid) bits from bi_buf and - * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid)) - * unused bits in value. - */ - if (s->bi_valid > (int)Buf_size - length) { - s->bi_buf |= (value << s->bi_valid); - put_short(s, s->bi_buf); - s->bi_buf = (ush)value >> (Buf_size - s->bi_valid); - s->bi_valid += length - Buf_size; - } else { - s->bi_buf |= value << s->bi_valid; - s->bi_valid += length; - } + Tracevv((stderr, " l %2d v %4x ", length, value)); + Assert(length > 0 && length <= 15, "invalid length"); + s->bits_sent += (ulg)length; + + /* + * If not enough room in bi_buf, use (valid) bits from bi_buf and + * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid)) + * unused bits in value. + */ + if (s->bi_valid > (int)Buf_size - length) { + s->bi_buf |= (value << s->bi_valid); + put_short(s, s->bi_buf); + s->bi_buf = (ush)value >> (Buf_size - s->bi_valid); + s->bi_valid += length - Buf_size; + } else { + s->bi_buf |= value << s->bi_valid; + s->bi_valid += length; + } } #else /* !DEBUG */ -#define send_bits(s, value, length) \ +#define send_bits(s, value, length) \ { int len = length;\ - if (s->bi_valid > (int)Buf_size - len) {\ - int val = value;\ - s->bi_buf |= (val << s->bi_valid);\ - put_short(s, s->bi_buf);\ - s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\ - s->bi_valid += len - Buf_size;\ - } else {\ - s->bi_buf |= (value) << s->bi_valid;\ - s->bi_valid += len;\ - }\ + if (s->bi_valid > (int)Buf_size - len) {\ + int val = value;\ + s->bi_buf |= (val << s->bi_valid);\ + put_short(s, s->bi_buf);\ + s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\ + s->bi_valid += len - Buf_size;\ + } else {\ + s->bi_buf |= (value) << s->bi_valid;\ + s->bi_valid += len;\ + }\ } #endif /* DEBUG */ /* the arguments must not have side effects */ -/* =========================================================================== +/* * Initialize the various 'constant' tables. */ -local void tr_static_init() +local void +tr_static_init() { #if defined(GEN_TREES_H) || !defined(STDC) - static int static_init_done = 0; - int n; /* iterates over tree elements */ - int bits; /* bit counter */ - int length; /* length value */ - int code; /* code value */ - int dist; /* distance index */ - ush bl_count[MAX_BITS+1]; - /* number of codes at each bit length for an optimal tree */ - - if (static_init_done) return; - - /* For some embedded targets, global variables are not initialized: */ - static_l_desc.static_tree = static_ltree; - static_l_desc.extra_bits = extra_lbits; - static_d_desc.static_tree = static_dtree; - static_d_desc.extra_bits = extra_dbits; - static_bl_desc.extra_bits = extra_blbits; - - /* Initialize the mapping length (0..255) -> length code (0..28) */ - length = 0; - for (code = 0; code < LENGTH_CODES-1; code++) { - base_length[code] = length; - for (n = 0; n < (1< dist code (0..29) */ - dist = 0; - for (code = 0 ; code < 16; code++) { - base_dist[code] = dist; - for (n = 0; n < (1<>= 7; /* from now on, all distances are divided by 128 */ - for ( ; code < D_CODES; code++) { - base_dist[code] = dist << 7; - for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { - _dist_code[256 + dist++] = (uch)code; - } - } - Assert (dist == 256, "tr_static_init: 256+dist != 512"); - - /* Construct the codes of the static literal tree */ - for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0; - n = 0; - while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++; - while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++; - while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++; - while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++; - /* Codes 286 and 287 do not exist, but we must include them in the - * tree construction to get a canonical Huffman tree (longest code - * all ones) - */ - gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count); - - /* The static distance tree is trivial: */ - for (n = 0; n < D_CODES; n++) { - static_dtree[n].Len = 5; - static_dtree[n].Code = bi_reverse((unsigned)n, 5); - } - static_init_done = 1; - -# ifdef GEN_TREES_H - gen_trees_header(); -# endif + static int static_init_done = 0; + int n; /* iterates over tree elements */ + int bits; /* bit counter */ + int length; /* length value */ + int code; /* code value */ + int dist; /* distance index */ + ush bl_count[MAX_BITS+1]; + /* number of codes at each bit length for an optimal tree */ + + if (static_init_done) + return; + + /* For some embedded targets, global variables are not initialized: */ + static_l_desc.static_tree = static_ltree; + static_l_desc.extra_bits = extra_lbits; + static_d_desc.static_tree = static_dtree; + static_d_desc.extra_bits = extra_dbits; + static_bl_desc.extra_bits = extra_blbits; + + /* Initialize the mapping length (0..255) -> length code (0..28) */ + length = 0; + for (code = 0; code < LENGTH_CODES-1; code++) { + base_length[code] = length; + for (n = 0; n < (1< dist code (0..29) */ + dist = 0; + for (code = 0; code < 16; code++) { + base_dist[code] = dist; + for (n = 0; n < (1<>= 7; /* from now on, all distances are divided by 128 */ + for (; code < D_CODES; code++) { + base_dist[code] = dist << 7; + for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { + _dist_code[256 + dist++] = (uch)code; + } + } + Assert(dist == 256, "tr_static_init: 256+dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0; + n = 0; + while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++; + while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++; + while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++; + while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++; + /* + * Codes 286 and 287 do not exist, but we must include them in the + * tree construction to get a canonical Huffman tree (longest code + * all ones) + */ + gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count); + + /* The static distance tree is trivial: */ + for (n = 0; n < D_CODES; n++) { + static_dtree[n].Len = 5; + static_dtree[n].Code = bi_reverse((unsigned)n, 5); + } + static_init_done = 1; + +#ifdef GEN_TREES_H + gen_trees_header(); +#endif #endif /* defined(GEN_TREES_H) || !defined(STDC) */ } -/* =========================================================================== +/* * Genererate the file trees.h describing the static trees. */ #ifdef GEN_TREES_H -# ifndef DEBUG -# include -# endif +#ifndef DEBUG +#include +#endif -# define SEPARATOR(i, last, width) \ - ((i) == (last)? "\n};\n\n" : \ - ((i) % (width) == (width)-1 ? ",\n" : ", ")) +#define SEPARATOR(i, last, width) \ + ((i) == (last)? "\n};\n\n" : \ + ((i) % (width) == (width)-1 ? ",\n" : ", ")) -void gen_trees_header() +void +gen_trees_header() { - FILE *header = fopen("trees.h", "w"); - int i; - - Assert (header != NULL, "Can't open trees.h"); - fprintf(header, - "/* header created automatically with -DGEN_TREES_H */\n\n"); - - fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n"); - for (i = 0; i < L_CODES+2; i++) { - fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code, - static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5)); - } - - fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n"); - for (i = 0; i < D_CODES; i++) { - fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code, - static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5)); - } - - fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n"); - for (i = 0; i < DIST_CODE_LEN; i++) { - fprintf(header, "%2u%s", _dist_code[i], - SEPARATOR(i, DIST_CODE_LEN-1, 20)); - } - - fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n"); - for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) { - fprintf(header, "%2u%s", _length_code[i], - SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20)); - } - - fprintf(header, "local const int base_length[LENGTH_CODES] = {\n"); - for (i = 0; i < LENGTH_CODES; i++) { - fprintf(header, "%1u%s", base_length[i], - SEPARATOR(i, LENGTH_CODES-1, 20)); - } - - fprintf(header, "local const int base_dist[D_CODES] = {\n"); - for (i = 0; i < D_CODES; i++) { - fprintf(header, "%5u%s", base_dist[i], - SEPARATOR(i, D_CODES-1, 10)); - } - - fclose(header); + FILE *header = fopen("trees.h", "w"); + int i; + + Assert(header != NULL, "Can't open trees.h"); + fprintf(header, + "/* header created automatically with -DGEN_TREES_H */\n\n"); + + fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n"); + for (i = 0; i < L_CODES+2; i++) { + fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code, + static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5)); + } + + fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n"); + for (i = 0; i < D_CODES; i++) { + fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code, + static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5)); + } + + fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n"); + for (i = 0; i < DIST_CODE_LEN; i++) { + fprintf(header, "%2u%s", _dist_code[i], + SEPARATOR(i, DIST_CODE_LEN-1, 20)); + } + + fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n"); + for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) { + fprintf(header, "%2u%s", _length_code[i], + SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20)); + } + + fprintf(header, "local const int base_length[LENGTH_CODES] = {\n"); + for (i = 0; i < LENGTH_CODES; i++) { + fprintf(header, "%1u%s", base_length[i], + SEPARATOR(i, LENGTH_CODES-1, 20)); + } + + fprintf(header, "local const int base_dist[D_CODES] = {\n"); + for (i = 0; i < D_CODES; i++) { + fprintf(header, "%5u%s", base_dist[i], + SEPARATOR(i, D_CODES-1, 10)); + } + + fclose(header); } #endif /* GEN_TREES_H */ -/* =========================================================================== +/* * Initialize the tree data structures for a new zlib stream. */ -void _tr_init(s) - deflate_state *s; +void +_tr_init(deflate_state *s) { - tr_static_init(); + tr_static_init(); - s->l_desc.dyn_tree = s->dyn_ltree; - s->l_desc.stat_desc = &static_l_desc; + s->l_desc.dyn_tree = s->dyn_ltree; + s->l_desc.stat_desc = &static_l_desc; - s->d_desc.dyn_tree = s->dyn_dtree; - s->d_desc.stat_desc = &static_d_desc; + s->d_desc.dyn_tree = s->dyn_dtree; + s->d_desc.stat_desc = &static_d_desc; - s->bl_desc.dyn_tree = s->bl_tree; - s->bl_desc.stat_desc = &static_bl_desc; + s->bl_desc.dyn_tree = s->bl_tree; + s->bl_desc.stat_desc = &static_bl_desc; - s->bi_buf = 0; - s->bi_valid = 0; - s->last_eob_len = 8; /* enough lookahead for inflate */ + s->bi_buf = 0; + s->bi_valid = 0; + s->last_eob_len = 8; /* enough lookahead for inflate */ #ifdef DEBUG - s->compressed_len = 0L; - s->bits_sent = 0L; + s->compressed_len = 0L; + s->bits_sent = 0L; #endif - /* Initialize the first block of the first file: */ - init_block(s); + /* Initialize the first block of the first file: */ + init_block(s); } -/* =========================================================================== +/* * Initialize a new block. */ -local void init_block(s) - deflate_state *s; +local void +init_block(deflate_state *s) { - int n; /* iterates over tree elements */ + int n; /* iterates over tree elements */ - /* Initialize the trees. */ - for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0; - for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0; - for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0; + /* Initialize the trees. */ + for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0; + for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0; + for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0; - s->dyn_ltree[END_BLOCK].Freq = 1; - s->opt_len = s->static_len = 0L; - s->last_lit = s->matches = 0; + s->dyn_ltree[END_BLOCK].Freq = 1; + s->opt_len = s->static_len = 0L; + s->last_lit = s->matches = 0; } -#define SMALLEST 1 +#define SMALLEST 1 /* Index within the heap array of least frequent node in the Huffman tree */ -/* =========================================================================== +/* * Remove the smallest element from the heap and recreate the heap with * one less element. Updates heap and heap_len. */ -#define pqremove(s, tree, top) \ +#define pqremove(s, tree, top) \ {\ - top = s->heap[SMALLEST]; \ - s->heap[SMALLEST] = s->heap[s->heap_len--]; \ - pqdownheap(s, tree, SMALLEST); \ + top = s->heap[SMALLEST]; \ + s->heap[SMALLEST] = s->heap[s->heap_len--]; \ + pqdownheap(s, tree, SMALLEST); \ } -/* =========================================================================== +/* * Compares to subtrees, using the tree depth as tie breaker when * the subtrees have equal frequency. This minimizes the worst case length. */ -#define smaller(tree, n, m, depth) \ - (tree[n].Freq < tree[m].Freq || \ - (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m])) +#define smaller(tree, n, m, depth) \ + (tree[n].Freq < tree[m].Freq || \ + (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m])) -/* =========================================================================== +/* * Restore the heap property by moving down the tree starting at node k, * exchanging a node with the smallest of its two sons if necessary, stopping * when the heap property is re-established (each father smaller than its * two sons). */ -local void pqdownheap(s, tree, k) - deflate_state *s; - ct_data *tree; /* the tree to restore */ - int k; /* node to move down */ +local void +pqdownheap( + deflate_state *s, + ct_data *tree, /* the tree to restore */ + int k) /* node to move down */ { - int v = s->heap[k]; - int j = k << 1; /* left son of k */ - while (j <= s->heap_len) { - /* Set j to the smallest of the two sons: */ - if (j < s->heap_len && - smaller(tree, s->heap[j+1], s->heap[j], s->depth)) { - j++; - } - /* Exit if v is smaller than both sons */ - if (smaller(tree, v, s->heap[j], s->depth)) break; - - /* Exchange v with the smallest son */ - s->heap[k] = s->heap[j]; k = j; - - /* And continue down the tree, setting j to the left son of k */ - j <<= 1; - } - s->heap[k] = v; + int v = s->heap[k]; + int j = k << 1; /* left son of k */ + while (j <= s->heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < s->heap_len && + smaller(tree, s->heap[j+1], s->heap[j], s->depth)) { + j++; + } + /* Exit if v is smaller than both sons */ + if (smaller(tree, v, s->heap[j], s->depth)) + break; + + /* Exchange v with the smallest son */ + s->heap[k] = s->heap[j]; k = j; + + /* And continue down the tree, setting j to the left son of k */ + j <<= 1; + } + s->heap[k] = v; } -/* =========================================================================== +/* * Compute the optimal bit lengths for a tree and update the total bit length * for the current block. * IN assertion: the fields freq and dad are set, heap[heap_max] and @@ -487,86 +505,95 @@ local void pqdownheap(s, tree, k) * The length opt_len is updated; static_len is also updated if stree is * not null. */ -local void gen_bitlen(s, desc) - deflate_state *s; - tree_desc *desc; /* the tree descriptor */ +local void +gen_bitlen( + deflate_state *s, + tree_desc *desc) /* the tree descriptor */ { - ct_data *tree = desc->dyn_tree; - int max_code = desc->max_code; - const ct_data *stree = desc->stat_desc->static_tree; - const intf *extra = desc->stat_desc->extra_bits; - int base = desc->stat_desc->extra_base; - int max_length = desc->stat_desc->max_length; - int h; /* heap index */ - int n, m; /* iterate over the tree elements */ - int bits; /* bit length */ - int xbits; /* extra bits */ - ush f; /* frequency */ - int overflow = 0; /* number of elements with bit length too large */ - - for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0; - - /* In a first pass, compute the optimal bit lengths (which may - * overflow in the case of the bit length tree). - */ - tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */ - - for (h = s->heap_max+1; h < HEAP_SIZE; h++) { - n = s->heap[h]; - bits = tree[tree[n].Dad].Len + 1; - if (bits > max_length) bits = max_length, overflow++; - tree[n].Len = (ush)bits; - /* We overwrite tree[n].Dad which is no longer needed */ - - if (n > max_code) continue; /* not a leaf node */ - - s->bl_count[bits]++; - xbits = 0; - if (n >= base) xbits = extra[n-base]; - f = tree[n].Freq; - s->opt_len += (ulg)f * (bits + xbits); - if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits); - } - if (overflow == 0) return; - - Trace((stderr,"\nbit length overflow\n")); - /* This happens for example on obj2 and pic of the Calgary corpus */ - - /* Find the first bit length which could increase: */ - do { - bits = max_length-1; - while (s->bl_count[bits] == 0) bits--; - s->bl_count[bits]--; /* move one leaf down the tree */ - s->bl_count[bits+1] += 2; /* move one overflow item as its brother */ - s->bl_count[max_length]--; - /* The brother of the overflow item also moves one step up, - * but this does not affect bl_count[max_length] - */ - overflow -= 2; - } while (overflow > 0); - - /* Now recompute all bit lengths, scanning in increasing frequency. - * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all - * lengths instead of fixing only the wrong ones. This idea is taken - * from 'ar' written by Haruhiko Okumura.) - */ - for (bits = max_length; bits != 0; bits--) { - n = s->bl_count[bits]; - while (n != 0) { - m = s->heap[--h]; - if (m > max_code) continue; - if ((unsigned) tree[m].Len != (unsigned) bits) { - Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); - s->opt_len += ((long)bits - (long)tree[m].Len) - *(long)tree[m].Freq; - tree[m].Len = (ush)bits; - } - n--; - } - } + ct_data *tree = desc->dyn_tree; + int max_code = desc->max_code; + const ct_data *stree = desc->stat_desc->static_tree; + const intf *extra = desc->stat_desc->extra_bits; + int base = desc->stat_desc->extra_base; + int max_length = desc->stat_desc->max_length; + int h; /* heap index */ + int n, m; /* iterate over the tree elements */ + int bits; /* bit length */ + int xbits; /* extra bits */ + ush f; /* frequency */ + int overflow = 0; /* number of elements with bit length too large */ + + for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0; + + /* + * In a first pass, compute the optimal bit lengths (which may + * overflow in the case of the bit length tree). + */ + tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */ + + for (h = s->heap_max+1; h < HEAP_SIZE; h++) { + n = s->heap[h]; + bits = tree[tree[n].Dad].Len + 1; + if (bits > max_length) bits = max_length, overflow++; + tree[n].Len = (ush)bits; + /* We overwrite tree[n].Dad which is no longer needed */ + + if (n > max_code) + continue; /* not a leaf node */ + + s->bl_count[bits]++; + xbits = 0; + if (n >= base) xbits = extra[n-base]; + f = tree[n].Freq; + s->opt_len += (ulg)f * (bits + xbits); + if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits); + } + if (overflow == 0) + return; + + Trace((stderr, "\nbit length overflow\n")); + /* This happens for example on obj2 and pic of the Calgary corpus */ + + /* Find the first bit length which could increase: */ + do { + bits = max_length-1; + while (s->bl_count[bits] == 0) bits--; + s->bl_count[bits]--; /* move one leaf down the tree */ + /* move one overflow item as its brother */ + s->bl_count[bits+1] += 2; + s->bl_count[max_length]--; + /* + * The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] + */ + overflow -= 2; + } while (overflow > 0); + + /* + * Now recompute all bit lengths, scanning in increasing frequency. + * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all + * lengths instead of fixing only the wrong ones. This idea is taken + * from 'ar' written by Haruhiko Okumura.) + */ + for (bits = max_length; bits != 0; bits--) { + n = s->bl_count[bits]; + while (n != 0) { + m = s->heap[--h]; + if (m > max_code) + continue; + if ((unsigned)tree[m].Len != (unsigned)bits) { + Trace((stderr, "code %d bits %d->%d\n", m, + tree[m].Len, bits)); + s->opt_len += ((long)bits - (long)tree[m].Len) + *(long)tree[m].Freq; + tree[m].Len = (ush)bits; + } + n--; + } + } } -/* =========================================================================== +/* * Generate the codes for a given tree and bit counts (which need not be * optimal). * IN assertion: the array bl_count contains the bit length statistics for @@ -574,41 +601,47 @@ local void gen_bitlen(s, desc) * OUT assertion: the field code is set for all tree elements of non * zero code length. */ -local void gen_codes (tree, max_code, bl_count) - ct_data *tree; /* the tree to decorate */ - int max_code; /* largest code with non zero frequency */ - ushf *bl_count; /* number of codes at each bit length */ +local void +gen_codes( + ct_data *tree, /* the tree to decorate */ + int max_code, /* largest code with non zero frequency */ + ushf *bl_count) /* number of codes at each bit length */ { - ush next_code[MAX_BITS+1]; /* next code value for each bit length */ - ush code = 0; /* running code value */ - int bits; /* bit index */ - int n; /* code index */ - - /* The distribution counts are first used to generate the code values - * without bit reversal. - */ - for (bits = 1; bits <= MAX_BITS; bits++) { - next_code[bits] = code = (code + bl_count[bits-1]) << 1; - } - /* Check that the bit counts in bl_count are consistent. The last code - * must be all ones. - */ - Assert (code + bl_count[MAX_BITS]-1 == (1<dyn_tree; - const ct_data *stree = desc->stat_desc->static_tree; - int elems = desc->stat_desc->elems; - int n, m; /* iterate over heap elements */ - int max_code = -1; /* largest code with non zero frequency */ - int node; /* new node being created */ - - /* Construct the initial heap, with least frequent element in - * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. - * heap[0] is not used. - */ - s->heap_len = 0, s->heap_max = HEAP_SIZE; - - for (n = 0; n < elems; n++) { - if (tree[n].Freq != 0) { - s->heap[++(s->heap_len)] = max_code = n; - s->depth[n] = 0; - } else { - tree[n].Len = 0; - } - } - - /* The pkzip format requires that at least one distance code exists, - * and that at least one bit should be sent even if there is only one - * possible code. So to avoid special checks later on we force at least - * two codes of non zero frequency. - */ - while (s->heap_len < 2) { - node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0); - tree[node].Freq = 1; - s->depth[node] = 0; - s->opt_len--; if (stree) s->static_len -= stree[node].Len; - /* node is 0 or 1 so it does not have extra bits */ - } - desc->max_code = max_code; - - /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, - * establish sub-heaps of increasing lengths: - */ - for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n); - - /* Construct the Huffman tree by repeatedly combining the least two - * frequent nodes. - */ - node = elems; /* next internal node of the tree */ - do { - pqremove(s, tree, n); /* n = node of least frequency */ - m = s->heap[SMALLEST]; /* m = node of next least frequency */ - - s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */ - s->heap[--(s->heap_max)] = m; - - /* Create a new node father of n and m */ - tree[node].Freq = tree[n].Freq + tree[m].Freq; - s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ? - s->depth[n] : s->depth[m]) + 1); - tree[n].Dad = tree[m].Dad = (ush)node; + ct_data *tree = desc->dyn_tree; + const ct_data *stree = desc->stat_desc->static_tree; + int elems = desc->stat_desc->elems; + int n, m; /* iterate over heap elements */ + int max_code = -1; /* largest code with non zero frequency */ + int node; /* new node being created */ + + /* + * Construct the initial heap, with least frequent element in + * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. + * heap[0] is not used. + */ + s->heap_len = 0, s->heap_max = HEAP_SIZE; + + for (n = 0; n < elems; n++) { + if (tree[n].Freq != 0) { + s->heap[++(s->heap_len)] = max_code = n; + s->depth[n] = 0; + } else { + tree[n].Len = 0; + } + } + + /* + * The pkzip format requires that at least one distance code exists, + * and that at least one bit should be sent even if there is only one + * possible code. So to avoid special checks later on we force at least + * two codes of non zero frequency. + */ + while (s->heap_len < 2) { + node = s->heap[++(s->heap_len)] = + (max_code < 2 ? ++max_code : 0); + tree[node].Freq = 1; + s->depth[node] = 0; + s->opt_len--; if (stree) s->static_len -= stree[node].Len; + /* node is 0 or 1 so it does not have extra bits */ + } + desc->max_code = max_code; + + /* + * The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n); + + /* + * Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + node = elems; /* next internal node of the tree */ + do { + pqremove(s, tree, n); /* n = node of least frequency */ + m = s->heap[SMALLEST]; /* m = node of next least frequency */ + + /* keep the nodes sorted by frequency */ + s->heap[--(s->heap_max)] = n; + s->heap[--(s->heap_max)] = m; + + /* Create a new node father of n and m */ + tree[node].Freq = tree[n].Freq + tree[m].Freq; + s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ? + s->depth[n] : s->depth[m]) + 1); + tree[n].Dad = tree[m].Dad = (ush)node; #ifdef DUMP_BL_TREE - if (tree == s->bl_tree) { - fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)", - node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq); - } + if (tree == s->bl_tree) { + fprintf(stderr, "\nnode %d(%d), sons %d(%d) %d(%d)", + node, tree[node].Freq, n, tree[n].Freq, + m, tree[m].Freq); + } #endif - /* and insert the new node in the heap */ - s->heap[SMALLEST] = node++; - pqdownheap(s, tree, SMALLEST); + /* and insert the new node in the heap */ + s->heap[SMALLEST] = node++; + pqdownheap(s, tree, SMALLEST); - } while (s->heap_len >= 2); + } while (s->heap_len >= 2); - s->heap[--(s->heap_max)] = s->heap[SMALLEST]; + s->heap[--(s->heap_max)] = s->heap[SMALLEST]; - /* At this point, the fields freq and dad are set. We can now - * generate the bit lengths. - */ - gen_bitlen(s, (tree_desc *)desc); + /* + * At this point, the fields freq and dad are set. We can now + * generate the bit lengths. + */ + gen_bitlen(s, (tree_desc *)desc); - /* The field len is now set, we can generate the bit codes */ - gen_codes ((ct_data *)tree, max_code, s->bl_count); + /* The field len is now set, we can generate the bit codes */ + gen_codes((ct_data *)tree, max_code, s->bl_count); } -/* =========================================================================== +/* * Scan a literal or distance tree to determine the frequencies of the codes * in the bit length tree. */ -local void scan_tree (s, tree, max_code) - deflate_state *s; - ct_data *tree; /* the tree to be scanned */ - int max_code; /* and its largest code of non zero frequency */ +local void +scan_tree( + deflate_state *s, + ct_data *tree, /* the tree to be scanned */ + int max_code) /* and its largest code of non zero frequency */ { - int n; /* iterates over all tree elements */ - int prevlen = -1; /* last emitted length */ - int curlen; /* length of current code */ - int nextlen = tree[0].Len; /* length of next code */ - int count = 0; /* repeat count of the current code */ - int max_count = 7; /* max repeat count */ - int min_count = 4; /* min repeat count */ - - if (nextlen == 0) max_count = 138, min_count = 3; - tree[max_code+1].Len = (ush)0xffff; /* guard */ - - for (n = 0; n <= max_code; n++) { - curlen = nextlen; nextlen = tree[n+1].Len; - if (++count < max_count && curlen == nextlen) { - continue; - } else if (count < min_count) { - s->bl_tree[curlen].Freq += (ush)count; - } else if (curlen != 0) { - if (curlen != prevlen) s->bl_tree[curlen].Freq++; - s->bl_tree[REP_3_6].Freq++; - } else if (count <= 10) { - s->bl_tree[REPZ_3_10].Freq++; - } else { - s->bl_tree[REPZ_11_138].Freq++; - } - count = 0; prevlen = curlen; - if (nextlen == 0) { - max_count = 138, min_count = 3; - } else if (curlen == nextlen) { - max_count = 6, min_count = 3; - } else { - max_count = 7, min_count = 4; - } - } + int n; /* iterates over all tree elements */ + int prevlen = -1; /* last emitted length */ + int curlen; /* length of current code */ + int nextlen = tree[0].Len; /* length of next code */ + int count = 0; /* repeat count of the current code */ + int max_count = 7; /* max repeat count */ + int min_count = 4; /* min repeat count */ + + if (nextlen == 0) max_count = 138, min_count = 3; + tree[max_code+1].Len = (ush)0xffff; /* guard */ + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; nextlen = tree[n+1].Len; + if (++count < max_count && curlen == nextlen) { + continue; + } else if (count < min_count) { + s->bl_tree[curlen].Freq += (ush)count; + } else if (curlen != 0) { + if (curlen != prevlen) s->bl_tree[curlen].Freq++; + s->bl_tree[REP_3_6].Freq++; + } else if (count <= 10) { + s->bl_tree[REPZ_3_10].Freq++; + } else { + s->bl_tree[REPZ_11_138].Freq++; + } + count = 0; prevlen = curlen; + if (nextlen == 0) { + max_count = 138, min_count = 3; + } else if (curlen == nextlen) { + max_count = 6, min_count = 3; + } else { + max_count = 7, min_count = 4; + } + } } -/* =========================================================================== +/* * Send a literal or distance tree in compressed form, using the codes in * bl_tree. */ -local void send_tree (s, tree, max_code) - deflate_state *s; - ct_data *tree; /* the tree to be scanned */ - int max_code; /* and its largest code of non zero frequency */ +local void +send_tree( + deflate_state *s, + ct_data *tree, /* the tree to be scanned */ + int max_code) { - int n; /* iterates over all tree elements */ - int prevlen = -1; /* last emitted length */ - int curlen; /* length of current code */ - int nextlen = tree[0].Len; /* length of next code */ - int count = 0; /* repeat count of the current code */ - int max_count = 7; /* max repeat count */ - int min_count = 4; /* min repeat count */ - - /* tree[max_code+1].Len = -1; */ /* guard already set */ - if (nextlen == 0) max_count = 138, min_count = 3; - - for (n = 0; n <= max_code; n++) { - curlen = nextlen; nextlen = tree[n+1].Len; - if (++count < max_count && curlen == nextlen) { - continue; - } else if (count < min_count) { - do { send_code(s, curlen, s->bl_tree); } while (--count != 0); - - } else if (curlen != 0) { - if (curlen != prevlen) { - send_code(s, curlen, s->bl_tree); count--; - } - Assert(count >= 3 && count <= 6, " 3_6?"); - send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2); - - } else if (count <= 10) { - send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3); - - } else { - send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7); - } - count = 0; prevlen = curlen; - if (nextlen == 0) { - max_count = 138, min_count = 3; - } else if (curlen == nextlen) { - max_count = 6, min_count = 3; - } else { - max_count = 7, min_count = 4; - } - } + int n; /* iterates over all tree elements */ + int prevlen = -1; /* last emitted length */ + int curlen; /* length of current code */ + int nextlen = tree[0].Len; /* length of next code */ + int count = 0; /* repeat count of the current code */ + int max_count = 7; /* max repeat count */ + int min_count = 4; /* min repeat count */ + + /* tree[max_code+1].Len = -1; */ /* guard already set */ + if (nextlen == 0) max_count = 138, min_count = 3; + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; nextlen = tree[n+1].Len; + if (++count < max_count && curlen == nextlen) { + continue; + } else if (count < min_count) { + do { + send_code(s, curlen, s->bl_tree); + } while (--count != 0); + + } else if (curlen != 0) { + if (curlen != prevlen) { + send_code(s, curlen, s->bl_tree); count--; + } + Assert(count >= 3 && count <= 6, " 3_6?"); + send_code(s, REP_3_6, s->bl_tree); + send_bits(s, count-3, 2); + + } else if (count <= 10) { + send_code(s, REPZ_3_10, s->bl_tree); + send_bits(s, count-3, 3); + + } else { + send_code(s, REPZ_11_138, s->bl_tree); + send_bits(s, count-11, 7); + } + count = 0; prevlen = curlen; + if (nextlen == 0) { + max_count = 138, min_count = 3; + } else if (curlen == nextlen) { + max_count = 6, min_count = 3; + } else { + max_count = 7, min_count = 4; + } + } } -/* =========================================================================== +/* * Construct the Huffman tree for the bit lengths and return the index in * bl_order of the last bit length code to send. */ -local int build_bl_tree(s) - deflate_state *s; +local int +build_bl_tree(deflate_state *s) { - int max_blindex; /* index of last bit length code of non zero freq */ - - /* Determine the bit length frequencies for literal and distance trees */ - scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code); - scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code); - - /* Build the bit length tree: */ - build_tree(s, (tree_desc *)(&(s->bl_desc))); - /* opt_len now includes the length of the tree representations, except - * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. - */ - - /* Determine the number of bit length codes to send. The pkzip format - * requires that at least 4 bit length codes be sent. (appnote.txt says - * 3 but the actual value used is 4.) - */ - for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { - if (s->bl_tree[bl_order[max_blindex]].Len != 0) break; - } - /* Update opt_len to include the bit length tree and counts */ - s->opt_len += 3*(max_blindex+1) + 5+5+4; - Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", - s->opt_len, s->static_len)); - - return max_blindex; + int max_blindex; /* index of last bit length code of non zero freq */ + +/* Determine the bit length frequencies for literal and distance trees */ + scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code); + scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code); + + /* Build the bit length tree: */ + build_tree(s, (tree_desc *)(&(s->bl_desc))); +/* + * opt_len now includes the length of the tree representations, except + * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. + */ + + /* + * Determine the number of bit length codes to send. The pkzip format + * requires that at least 4 bit length codes be sent. (appnote.txt says + * 3 but the actual value used is 4.) + */ + for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { + if (s->bl_tree[bl_order[max_blindex]].Len != 0) break; + } + /* Update opt_len to include the bit length tree and counts */ + s->opt_len += 3*(max_blindex+1) + 5+5+4; + Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", + s->opt_len, s->static_len)); + + return (max_blindex); } -/* =========================================================================== +/* * Send the header for a block using dynamic Huffman trees: the counts, the * lengths of the bit length codes, the literal tree and the distance tree. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. */ -local void send_all_trees(s, lcodes, dcodes, blcodes) - deflate_state *s; - int lcodes, dcodes, blcodes; /* number of codes for each tree */ +local void +send_all_trees( + deflate_state *s, + int lcodes, + int dcodes, + int blcodes) /* number of codes for each tree */ { - int rank; /* index in bl_order */ - - Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); - Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, - "too many codes"); - Tracev((stderr, "\nbl counts: ")); - send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ - send_bits(s, dcodes-1, 5); - send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ - for (rank = 0; rank < blcodes; rank++) { - Tracev((stderr, "\nbl code %2d ", bl_order[rank])); - send_bits(s, s->bl_tree[bl_order[rank]].Len, 3); - } - Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); - - send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */ - Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); - - send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */ - Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); + int rank; /* index in bl_order */ + + Assert(lcodes >= 257 && dcodes >= 1 && blcodes >= 4, + "not enough codes"); + Assert(lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + "too many codes"); + Tracev((stderr, "\nbl counts: ")); + send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ + send_bits(s, dcodes-1, 5); + send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + Tracev((stderr, "\nbl code %2d ", bl_order[rank])); + send_bits(s, s->bl_tree[bl_order[rank]].Len, 3); + } + Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + + send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */ + Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); + + send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */ + Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); } -/* =========================================================================== +/* * Send a stored block */ -void _tr_stored_block(s, buf, stored_len, eof) - deflate_state *s; - charf *buf; /* input block */ - ulg stored_len; /* length of input block */ - int eof; /* true if this is the last block for a file */ +void +_tr_stored_block( + deflate_state *s, + charf *buf, /* input block */ + ulg stored_len, /* length of input block */ + int eof) /* true if this is the last block for a file */ { - send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */ + send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */ #ifdef DEBUG - s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L; - s->compressed_len += (stored_len + 4) << 3; + s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L; + s->compressed_len += (stored_len + 4) << 3; #endif - copy_block(s, buf, (unsigned)stored_len, 1); /* with header */ + copy_block(s, buf, (unsigned)stored_len, 1); /* with header */ } -/* =========================================================================== +/* * Send one empty static block to give enough lookahead for inflate. * This takes 10 bits, of which 7 may remain in the bit buffer. * The current inflate code requires 9 bits of lookahead. If the @@ -889,331 +945,351 @@ void _tr_stored_block(s, buf, stored_len, eof) * To simplify the code, we assume the worst case of last real code encoded * on one bit only. */ -void _tr_align(s) - deflate_state *s; +void +_tr_align(deflate_state *s) { - send_bits(s, STATIC_TREES<<1, 3); - send_code(s, END_BLOCK, static_ltree); + send_bits(s, STATIC_TREES<<1, 3); + send_code(s, END_BLOCK, static_ltree); #ifdef DEBUG - s->compressed_len += 10L; /* 3 for block type, 7 for EOB */ + s->compressed_len += 10L; /* 3 for block type, 7 for EOB */ #endif - bi_flush(s); - /* Of the 10 bits for the empty block, we have already sent - * (10 - bi_valid) bits. The lookahead for the last real code (before - * the EOB of the previous block) was thus at least one plus the length - * of the EOB plus what we have just sent of the empty static block. - */ - if (1 + s->last_eob_len + 10 - s->bi_valid < 9) { - send_bits(s, STATIC_TREES<<1, 3); - send_code(s, END_BLOCK, static_ltree); + bi_flush(s); + /* + * Of the 10 bits for the empty block, we have already sent + * (10 - bi_valid) bits. The lookahead for the last real code (before + * the EOB of the previous block) was thus at least one plus the length + * of the EOB plus what we have just sent of the empty static block. + */ + if (1 + s->last_eob_len + 10 - s->bi_valid < 9) { + send_bits(s, STATIC_TREES<<1, 3); + send_code(s, END_BLOCK, static_ltree); #ifdef DEBUG - s->compressed_len += 10L; + s->compressed_len += 10L; #endif - bi_flush(s); - } - s->last_eob_len = 7; + bi_flush(s); + } + s->last_eob_len = 7; } -/* =========================================================================== +/* * Determine the best encoding for the current block: dynamic trees, static * trees or store, and output the encoded block to the zip file. */ -void _tr_flush_block(s, buf, stored_len, eof) - deflate_state *s; - charf *buf; /* input block, or NULL if too old */ - ulg stored_len; /* length of input block */ - int eof; /* true if this is the last block for a file */ +void +_tr_flush_block(deflate_state *s, + charf *buf, /* input block, or NULL if too old */ + ulg stored_len, /* length of input block */ + int eof) /* true if this is the last block for a file */ { - ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */ - int max_blindex = 0; /* index of last bit length code of non zero freq */ - - /* Build the Huffman trees unless a stored block is forced */ - if (s->level > 0) { - - /* Check if the file is binary or text */ - if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN) - set_data_type(s); - - /* Construct the literal and distance trees */ - build_tree(s, (tree_desc *)(&(s->l_desc))); - Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, - s->static_len)); - - build_tree(s, (tree_desc *)(&(s->d_desc))); - Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, - s->static_len)); - /* At this point, opt_len and static_len are the total bit lengths of - * the compressed block data, excluding the tree representations. - */ - - /* Build the bit length tree for the above two trees, and get the index - * in bl_order of the last bit length code to send. - */ - max_blindex = build_bl_tree(s); - - /* Determine the best encoding. Compute the block lengths in bytes. */ - opt_lenb = (s->opt_len+3+7)>>3; - static_lenb = (s->static_len+3+7)>>3; - - Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", - opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, - s->last_lit)); - - if (static_lenb <= opt_lenb) opt_lenb = static_lenb; - - } else { - Assert(buf != (char*)0, "lost buf"); - opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ - } + ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + /* index of last bit length code of non zero freq */ + int max_blindex = 0; + + /* Build the Huffman trees unless a stored block is forced */ + if (s->level > 0) { + + /* Check if the file is binary or text */ + if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN) + set_data_type(s); + + /* Construct the literal and distance trees */ + build_tree(s, (tree_desc *)(&(s->l_desc))); + Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, + s->static_len)); + + build_tree(s, (tree_desc *)(&(s->d_desc))); + Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, + s->static_len)); + /* + * At this point, opt_len and static_len are the total bit lengths of + * the compressed block data, excluding the tree representations. + */ + + /* + * Build the bit length tree for the above two trees, and get the index + * in bl_order of the last bit length code to send. + */ + max_blindex = build_bl_tree(s); + + /* Determine the best encoding. Compute the block lengths in bytes. */ + opt_lenb = (s->opt_len+3+7)>>3; + static_lenb = (s->static_len+3+7)>>3; + + Tracev((stderr, + "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", + opt_lenb, s->opt_len, static_lenb, s->static_len, + stored_len, s->last_lit)); + + if (static_lenb <= opt_lenb) opt_lenb = static_lenb; + + } else { + Assert(buf != (char *)0, "lost buf"); + /* force a stored block */ + opt_lenb = static_lenb = stored_len + 5; + } #ifdef FORCE_STORED - if (buf != (char*)0) { /* force stored block */ + if (buf != (char *)0) { /* force stored block */ #else - if (stored_len+4 <= opt_lenb && buf != (char*)0) { - /* 4: two words for the lengths */ + if (stored_len+4 <= opt_lenb && buf != (char *)0) { + /* 4: two words for the lengths */ #endif - /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. - * Otherwise we can't have processed more than WSIZE input bytes since - * the last block flush, because compression would have been - * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to - * transform a block into a stored block. - */ - _tr_stored_block(s, buf, stored_len, eof); + /* + * The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + * Otherwise we can't have processed more than WSIZE input bytes since + * the last block flush, because compression would have been + * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + * transform a block into a stored block. + */ + _tr_stored_block(s, buf, stored_len, eof); #ifdef FORCE_STATIC - } else if (static_lenb >= 0) { /* force static trees */ + } else if (static_lenb >= 0) { /* force static trees */ #else - } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) { + } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) { #endif - send_bits(s, (STATIC_TREES<<1)+eof, 3); - compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree); + send_bits(s, (STATIC_TREES<<1)+eof, 3); + compress_block(s, (ct_data *)static_ltree, + (ct_data *)static_dtree); #ifdef DEBUG - s->compressed_len += 3 + s->static_len; + s->compressed_len += 3 + s->static_len; #endif - } else { - send_bits(s, (DYN_TREES<<1)+eof, 3); - send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1, - max_blindex+1); - compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree); + } else { + send_bits(s, (DYN_TREES<<1)+eof, 3); + send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1, + max_blindex+1); + compress_block(s, (ct_data *)s->dyn_ltree, + (ct_data *)s->dyn_dtree); #ifdef DEBUG - s->compressed_len += 3 + s->opt_len; + s->compressed_len += 3 + s->opt_len; #endif - } - Assert (s->compressed_len == s->bits_sent, "bad compressed size"); - /* The above check is made mod 2^32, for files larger than 512 MB - * and uLong implemented on 32 bits. - */ - init_block(s); - - if (eof) { - bi_windup(s); + } + Assert(s->compressed_len == s->bits_sent, "bad compressed size"); + /* + * The above check is made mod 2^32, for files larger than 512 MB + * and uLong implemented on 32 bits. + */ + init_block(s); + + if (eof) { + bi_windup(s); #ifdef DEBUG - s->compressed_len += 7; /* align on byte boundary */ + s->compressed_len += 7; /* align on byte boundary */ #endif - } - Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, - s->compressed_len-7*eof)); + } + Tracev((stderr, "\ncomprlen %lu(%lu) ", s->compressed_len>>3, + s->compressed_len-7*eof)); } -/* =========================================================================== +/* * Save the match info and tally the frequency counts. Return true if * the current block must be flushed. */ -int _tr_tally (s, dist, lc) - deflate_state *s; - unsigned dist; /* distance of matched string */ - unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ +int +_tr_tally( + deflate_state *s, + unsigned dist, /* distance of matched string */ + unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */ { - s->d_buf[s->last_lit] = (ush)dist; - s->l_buf[s->last_lit++] = (uch)lc; - if (dist == 0) { - /* lc is the unmatched char */ - s->dyn_ltree[lc].Freq++; - } else { - s->matches++; - /* Here, lc is the match length - MIN_MATCH */ - dist--; /* dist = match distance - 1 */ - Assert((ush)dist < (ush)MAX_DIST(s) && - (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && - (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); - - s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++; - s->dyn_dtree[d_code(dist)].Freq++; - } + s->d_buf[s->last_lit] = (ush)dist; + s->l_buf[s->last_lit++] = (uch)lc; + if (dist == 0) { + /* lc is the unmatched char */ + s->dyn_ltree[lc].Freq++; + } else { + s->matches++; + /* Here, lc is the match length - MIN_MATCH */ + dist--; /* dist = match distance - 1 */ + Assert((ush)dist < (ush)MAX_DIST(s) && + (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); + + s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++; + s->dyn_dtree[d_code(dist)].Freq++; + } #ifdef TRUNCATE_BLOCK - /* Try to guess if it is profitable to stop the current block here */ - if ((s->last_lit & 0x1fff) == 0 && s->level > 2) { - /* Compute an upper bound for the compressed length */ - ulg out_length = (ulg)s->last_lit*8L; - ulg in_length = (ulg)((long)s->strstart - s->block_start); - int dcode; - for (dcode = 0; dcode < D_CODES; dcode++) { - out_length += (ulg)s->dyn_dtree[dcode].Freq * - (5L+extra_dbits[dcode]); - } - out_length >>= 3; - Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", - s->last_lit, in_length, out_length, - 100L - out_length*100L/in_length)); - if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1; - } + /* Try to guess if it is profitable to stop the current block here */ + if ((s->last_lit & 0x1fff) == 0 && s->level > 2) { + /* Compute an upper bound for the compressed length */ + ulg out_length = (ulg)s->last_lit*8L; + ulg in_length = (ulg)((long)s->strstart - s->block_start); + int dcode; + for (dcode = 0; dcode < D_CODES; dcode++) { + out_length += (ulg)s->dyn_dtree[dcode].Freq * + (5L+extra_dbits[dcode]); + } + out_length >>= 3; + Tracev((stderr, "\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", + s->last_lit, in_length, out_length, + 100L - out_length*100L/in_length)); + if (s->matches < s->last_lit/2 && out_length < in_length/2) + return (1); + } #endif - return (s->last_lit == s->lit_bufsize-1); - /* We avoid equality with lit_bufsize because of wraparound at 64K - * on 16 bit machines and because stored blocks are restricted to - * 64K-1 bytes. - */ + return (s->last_lit == s->lit_bufsize-1); + /* + * We avoid equality with lit_bufsize because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ } -/* =========================================================================== +/* * Send the block data compressed using the given Huffman trees */ -local void compress_block(s, ltree, dtree) - deflate_state *s; - ct_data *ltree; /* literal tree */ - ct_data *dtree; /* distance tree */ +local void +compress_block( + deflate_state *s, + ct_data *ltree, /* literal tree */ + ct_data *dtree) /* distance tree */ { - unsigned dist; /* distance of matched string */ - int lc; /* match length or unmatched char (if dist == 0) */ - unsigned lx = 0; /* running index in l_buf */ - unsigned code; /* the code to send */ - int extra; /* number of extra bits to send */ - - if (s->last_lit != 0) do { - dist = s->d_buf[lx]; - lc = s->l_buf[lx++]; - if (dist == 0) { - send_code(s, lc, ltree); /* send a literal byte */ - Tracecv(isgraph(lc), (stderr," '%c' ", lc)); - } else { - /* Here, lc is the match length - MIN_MATCH */ - code = _length_code[lc]; - send_code(s, code+LITERALS+1, ltree); /* send the length code */ - extra = extra_lbits[code]; - if (extra != 0) { - lc -= base_length[code]; - send_bits(s, lc, extra); /* send the extra length bits */ - } - dist--; /* dist is now the match distance - 1 */ - code = d_code(dist); - Assert (code < D_CODES, "bad d_code"); - - send_code(s, code, dtree); /* send the distance code */ - extra = extra_dbits[code]; - if (extra != 0) { - dist -= base_dist[code]; - send_bits(s, dist, extra); /* send the extra distance bits */ - } - } /* literal or match pair ? */ - - /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ - Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, - "pendingBuf overflow"); - - } while (lx < s->last_lit); - - send_code(s, END_BLOCK, ltree); - s->last_eob_len = ltree[END_BLOCK].Len; + unsigned dist; /* distance of matched string */ + int lc; /* match length or unmatched char (if dist == 0) */ + unsigned lx = 0; /* running index in l_buf */ + unsigned code; /* the code to send */ + int extra; /* number of extra bits to send */ + + if (s->last_lit != 0) + do { + dist = s->d_buf[lx]; + lc = s->l_buf[lx++]; + if (dist == 0) { + send_code(s, lc, ltree); /* send a literal byte */ + Tracecv(isgraph(lc), (stderr, " '%c' ", lc)); + } else { + /* Here, lc is the match length - MIN_MATCH */ + code = _length_code[lc]; + /* send the length code */ + send_code(s, code+LITERALS+1, ltree); + extra = extra_lbits[code]; + if (extra != 0) { + lc -= base_length[code]; + /* send the extra length bits */ + send_bits(s, lc, extra); + } + dist--; /* dist is now the match distance - 1 */ + code = d_code(dist); + Assert(code < D_CODES, "bad d_code"); + + send_code(s, code, dtree); /* send the distance code */ + extra = extra_dbits[code]; + if (extra != 0) { + dist -= base_dist[code]; + /* send the extra distance bits */ + send_bits(s, dist, extra); + } + } /* literal or match pair ? */ + +/* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ + Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, + "pendingBuf overflow"); + + } while (lx < s->last_lit); + + send_code(s, END_BLOCK, ltree); + s->last_eob_len = ltree[END_BLOCK].Len; } -/* =========================================================================== +/* * Set the data type to BINARY or TEXT, using a crude approximation: * set it to Z_TEXT if all symbols are either printable characters (33 to 255) * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise. * IN assertion: the fields Freq of dyn_ltree are set. */ -local void set_data_type(s) - deflate_state *s; +local void +set_data_type(deflate_state *s) { - int n; - - for (n = 0; n < 9; n++) - if (s->dyn_ltree[n].Freq != 0) - break; - if (n == 9) - for (n = 14; n < 32; n++) - if (s->dyn_ltree[n].Freq != 0) - break; - s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY; + int n; + + for (n = 0; n < 9; n++) + if (s->dyn_ltree[n].Freq != 0) + break; + if (n == 9) + for (n = 14; n < 32; n++) + if (s->dyn_ltree[n].Freq != 0) + break; + s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY; } -/* =========================================================================== +/* * Reverse the first len bits of a code, using straightforward code (a faster * method would use a table) * IN assertion: 1 <= len <= 15 */ -local unsigned bi_reverse(code, len) - unsigned code; /* the value to invert */ - int len; /* its bit length */ +local unsigned +bi_reverse( + unsigned code, /* the value to invert */ + int len) /* its bit length */ { - register unsigned res = 0; - do { - res |= code & 1; - code >>= 1, res <<= 1; - } while (--len > 0); - return res >> 1; + register unsigned res = 0; + do { + res |= code & 1; + code >>= 1, res <<= 1; + } while (--len > 0); + return (res >> 1); } -/* =========================================================================== +/* * Flush the bit buffer, keeping at most 7 bits in it. */ -local void bi_flush(s) - deflate_state *s; +local void +bi_flush(deflate_state *s) { - if (s->bi_valid == 16) { - put_short(s, s->bi_buf); - s->bi_buf = 0; - s->bi_valid = 0; - } else if (s->bi_valid >= 8) { - put_byte(s, (Byte)s->bi_buf); - s->bi_buf >>= 8; - s->bi_valid -= 8; - } + if (s->bi_valid == 16) { + put_short(s, s->bi_buf); + s->bi_buf = 0; + s->bi_valid = 0; + } else if (s->bi_valid >= 8) { + put_byte(s, (Byte)s->bi_buf); + s->bi_buf >>= 8; + s->bi_valid -= 8; + } } -/* =========================================================================== +/* * Flush the bit buffer and align the output on a byte boundary */ -local void bi_windup(s) - deflate_state *s; +local void +bi_windup(deflate_state *s) { - if (s->bi_valid > 8) { - put_short(s, s->bi_buf); - } else if (s->bi_valid > 0) { - put_byte(s, (Byte)s->bi_buf); - } - s->bi_buf = 0; - s->bi_valid = 0; + if (s->bi_valid > 8) { + put_short(s, s->bi_buf); + } else if (s->bi_valid > 0) { + put_byte(s, (Byte)s->bi_buf); + } + s->bi_buf = 0; + s->bi_valid = 0; #ifdef DEBUG - s->bits_sent = (s->bits_sent+7) & ~7; + s->bits_sent = (s->bits_sent+7) & ~7; #endif } -/* =========================================================================== +/* * Copy a stored block, storing first the length and its * one's complement if requested. */ -local void copy_block(s, buf, len, header) - deflate_state *s; - charf *buf; /* the input data */ - unsigned len; /* its length */ - int header; /* true if block header must be written */ +local void +copy_block( + deflate_state *s, + charf *buf, /* the input data */ + unsigned len, /* its length */ + int header) /* true if block header must be written */ { - bi_windup(s); /* align on byte boundary */ - s->last_eob_len = 8; /* enough lookahead for inflate */ + bi_windup(s); /* align on byte boundary */ + s->last_eob_len = 8; /* enough lookahead for inflate */ - if (header) { - put_short(s, (ush)len); - put_short(s, (ush)~len); + if (header) { + put_short(s, (ush)len); + put_short(s, (ush)~len); #ifdef DEBUG - s->bits_sent += 2*16; + s->bits_sent += 2*16; #endif - } + } #ifdef DEBUG - s->bits_sent += (ulg)len<<3; + s->bits_sent += (ulg)len<<3; #endif - while (len--) { - put_byte(s, *buf++); - } + while (len--) { + put_byte(s, *buf++); + } } diff --git a/lib/os/windows/zlib-1.2.3/trees.h b/lib/os/windows/zlib-1.2.3/trees.h index 72facf900f7..10278e14b58 100644 --- a/lib/os/windows/zlib-1.2.3/trees.h +++ b/lib/os/windows/zlib-1.2.3/trees.h @@ -1,78 +1,78 @@ /* header created automatically with -DGEN_TREES_H */ local const ct_data static_ltree[L_CODES+2] = { -{{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}}, -{{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}}, -{{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}}, -{{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}}, -{{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}}, -{{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}}, -{{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}}, -{{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}}, -{{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}}, -{{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}}, -{{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}}, -{{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}}, -{{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}}, -{{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}}, -{{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}}, -{{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}}, -{{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}}, -{{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}}, -{{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}}, -{{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}}, -{{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}}, -{{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}}, -{{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}}, -{{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}}, -{{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}}, -{{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}}, -{{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}}, -{{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}}, -{{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}}, -{{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}}, -{{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}}, -{{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}}, -{{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}}, -{{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}}, -{{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}}, -{{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}}, -{{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}}, -{{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}}, -{{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}}, -{{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}}, -{{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}}, -{{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}}, -{{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}}, -{{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}}, -{{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}}, -{{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}}, -{{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}}, -{{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}}, -{{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}}, -{{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}}, -{{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}}, -{{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}}, -{{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}}, -{{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}}, -{{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}}, -{{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}}, -{{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}}, -{{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}} +{{ 12}, { 8}}, {{140}, { 8}}, {{ 76}, { 8}}, {{204}, { 8}}, {{ 44}, { 8}}, +{{172}, { 8}}, {{108}, { 8}}, {{236}, { 8}}, {{ 28}, { 8}}, {{156}, { 8}}, +{{ 92}, { 8}}, {{220}, { 8}}, {{ 60}, { 8}}, {{188}, { 8}}, {{124}, { 8}}, +{{252}, { 8}}, {{ 2}, { 8}}, {{130}, { 8}}, {{ 66}, { 8}}, {{194}, { 8}}, +{{ 34}, { 8}}, {{162}, { 8}}, {{ 98}, { 8}}, {{226}, { 8}}, {{ 18}, { 8}}, +{{146}, { 8}}, {{ 82}, { 8}}, {{210}, { 8}}, {{ 50}, { 8}}, {{178}, { 8}}, +{{114}, { 8}}, {{242}, { 8}}, {{ 10}, { 8}}, {{138}, { 8}}, {{ 74}, { 8}}, +{{202}, { 8}}, {{ 42}, { 8}}, {{170}, { 8}}, {{106}, { 8}}, {{234}, { 8}}, +{{ 26}, { 8}}, {{154}, { 8}}, {{ 90}, { 8}}, {{218}, { 8}}, {{ 58}, { 8}}, +{{186}, { 8}}, {{122}, { 8}}, {{250}, { 8}}, {{ 6}, { 8}}, {{134}, { 8}}, +{{ 70}, { 8}}, {{198}, { 8}}, {{ 38}, { 8}}, {{166}, { 8}}, {{102}, { 8}}, +{{230}, { 8}}, {{ 22}, { 8}}, {{150}, { 8}}, {{ 86}, { 8}}, {{214}, { 8}}, +{{ 54}, { 8}}, {{182}, { 8}}, {{118}, { 8}}, {{246}, { 8}}, {{ 14}, { 8}}, +{{142}, { 8}}, {{ 78}, { 8}}, {{206}, { 8}}, {{ 46}, { 8}}, {{174}, { 8}}, +{{110}, { 8}}, {{238}, { 8}}, {{ 30}, { 8}}, {{158}, { 8}}, {{ 94}, { 8}}, +{{222}, { 8}}, {{ 62}, { 8}}, {{190}, { 8}}, {{126}, { 8}}, {{254}, { 8}}, +{{ 1}, { 8}}, {{129}, { 8}}, {{ 65}, { 8}}, {{193}, { 8}}, {{ 33}, { 8}}, +{{161}, { 8}}, {{ 97}, { 8}}, {{225}, { 8}}, {{ 17}, { 8}}, {{145}, { 8}}, +{{ 81}, { 8}}, {{209}, { 8}}, {{ 49}, { 8}}, {{177}, { 8}}, {{113}, { 8}}, +{{241}, { 8}}, {{ 9}, { 8}}, {{137}, { 8}}, {{ 73}, { 8}}, {{201}, { 8}}, +{{ 41}, { 8}}, {{169}, { 8}}, {{105}, { 8}}, {{233}, { 8}}, {{ 25}, { 8}}, +{{153}, { 8}}, {{ 89}, { 8}}, {{217}, { 8}}, {{ 57}, { 8}}, {{185}, { 8}}, +{{121}, { 8}}, {{249}, { 8}}, {{ 5}, { 8}}, {{133}, { 8}}, {{ 69}, { 8}}, +{{197}, { 8}}, {{ 37}, { 8}}, {{165}, { 8}}, {{101}, { 8}}, {{229}, { 8}}, +{{ 21}, { 8}}, {{149}, { 8}}, {{ 85}, { 8}}, {{213}, { 8}}, {{ 53}, { 8}}, +{{181}, { 8}}, {{117}, { 8}}, {{245}, { 8}}, {{ 13}, { 8}}, {{141}, { 8}}, +{{ 77}, { 8}}, {{205}, { 8}}, {{ 45}, { 8}}, {{173}, { 8}}, {{109}, { 8}}, +{{237}, { 8}}, {{ 29}, { 8}}, {{157}, { 8}}, {{ 93}, { 8}}, {{221}, { 8}}, +{{ 61}, { 8}}, {{189}, { 8}}, {{125}, { 8}}, {{253}, { 8}}, {{ 19}, { 9}}, +{{275}, { 9}}, {{147}, { 9}}, {{403}, { 9}}, {{ 83}, { 9}}, {{339}, { 9}}, +{{211}, { 9}}, {{467}, { 9}}, {{ 51}, { 9}}, {{307}, { 9}}, {{179}, { 9}}, +{{435}, { 9}}, {{115}, { 9}}, {{371}, { 9}}, {{243}, { 9}}, {{499}, { 9}}, +{{ 11}, { 9}}, {{267}, { 9}}, {{139}, { 9}}, {{395}, { 9}}, {{ 75}, { 9}}, +{{331}, { 9}}, {{203}, { 9}}, {{459}, { 9}}, {{ 43}, { 9}}, {{299}, { 9}}, +{{171}, { 9}}, {{427}, { 9}}, {{107}, { 9}}, {{363}, { 9}}, {{235}, { 9}}, +{{491}, { 9}}, {{ 27}, { 9}}, {{283}, { 9}}, {{155}, { 9}}, {{411}, { 9}}, +{{ 91}, { 9}}, {{347}, { 9}}, {{219}, { 9}}, {{475}, { 9}}, {{ 59}, { 9}}, +{{315}, { 9}}, {{187}, { 9}}, {{443}, { 9}}, {{123}, { 9}}, {{379}, { 9}}, +{{251}, { 9}}, {{507}, { 9}}, {{ 7}, { 9}}, {{263}, { 9}}, {{135}, { 9}}, +{{391}, { 9}}, {{ 71}, { 9}}, {{327}, { 9}}, {{199}, { 9}}, {{455}, { 9}}, +{{ 39}, { 9}}, {{295}, { 9}}, {{167}, { 9}}, {{423}, { 9}}, {{103}, { 9}}, +{{359}, { 9}}, {{231}, { 9}}, {{487}, { 9}}, {{ 23}, { 9}}, {{279}, { 9}}, +{{151}, { 9}}, {{407}, { 9}}, {{ 87}, { 9}}, {{343}, { 9}}, {{215}, { 9}}, +{{471}, { 9}}, {{ 55}, { 9}}, {{311}, { 9}}, {{183}, { 9}}, {{439}, { 9}}, +{{119}, { 9}}, {{375}, { 9}}, {{247}, { 9}}, {{503}, { 9}}, {{ 15}, { 9}}, +{{271}, { 9}}, {{143}, { 9}}, {{399}, { 9}}, {{ 79}, { 9}}, {{335}, { 9}}, +{{207}, { 9}}, {{463}, { 9}}, {{ 47}, { 9}}, {{303}, { 9}}, {{175}, { 9}}, +{{431}, { 9}}, {{111}, { 9}}, {{367}, { 9}}, {{239}, { 9}}, {{495}, { 9}}, +{{ 31}, { 9}}, {{287}, { 9}}, {{159}, { 9}}, {{415}, { 9}}, {{ 95}, { 9}}, +{{351}, { 9}}, {{223}, { 9}}, {{479}, { 9}}, {{ 63}, { 9}}, {{319}, { 9}}, +{{191}, { 9}}, {{447}, { 9}}, {{127}, { 9}}, {{383}, { 9}}, {{255}, { 9}}, +{{511}, { 9}}, {{ 0}, { 7}}, {{ 64}, { 7}}, {{ 32}, { 7}}, {{ 96}, { 7}}, +{{ 16}, { 7}}, {{ 80}, { 7}}, {{ 48}, { 7}}, {{112}, { 7}}, {{ 8}, { 7}}, +{{ 72}, { 7}}, {{ 40}, { 7}}, {{104}, { 7}}, {{ 24}, { 7}}, {{ 88}, { 7}}, +{{ 56}, { 7}}, {{120}, { 7}}, {{ 4}, { 7}}, {{ 68}, { 7}}, {{ 36}, { 7}}, +{{100}, { 7}}, {{ 20}, { 7}}, {{ 84}, { 7}}, {{ 52}, { 7}}, {{116}, { 7}}, +{{ 3}, { 8}}, {{131}, { 8}}, {{ 67}, { 8}}, {{195}, { 8}}, {{ 35}, { 8}}, +{{163}, { 8}}, {{ 99}, { 8}}, {{227}, { 8}} }; local const ct_data static_dtree[D_CODES] = { -{{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}}, -{{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}}, -{{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}}, -{{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}}, -{{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}}, -{{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}} +{{ 0}, { 5}}, {{16}, { 5}}, {{ 8}, { 5}}, {{24}, { 5}}, {{ 4}, { 5}}, +{{20}, { 5}}, {{12}, { 5}}, {{28}, { 5}}, {{ 2}, { 5}}, {{18}, { 5}}, +{{10}, { 5}}, {{26}, { 5}}, {{ 6}, { 5}}, {{22}, { 5}}, {{14}, { 5}}, +{{30}, { 5}}, {{ 1}, { 5}}, {{17}, { 5}}, {{ 9}, { 5}}, {{25}, { 5}}, +{{ 5}, { 5}}, {{21}, { 5}}, {{13}, { 5}}, {{29}, { 5}}, {{ 3}, { 5}}, +{{19}, { 5}}, {{11}, { 5}}, {{27}, { 5}}, {{ 7}, { 5}}, {{23}, { 5}} }; const uch _dist_code[DIST_CODE_LEN] = { - 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, - 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, +0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, +8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, @@ -99,8 +99,8 @@ const uch _dist_code[DIST_CODE_LEN] = { 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 }; -const uch _length_code[MAX_MATCH-MIN_MATCH+1]= { - 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, +const uch _length_code[MAX_MATCH-MIN_MATCH+1] = { +0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, @@ -121,8 +121,7 @@ local const int base_length[LENGTH_CODES] = { }; local const int base_dist[D_CODES] = { - 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, - 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, - 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576 +0, 1, 2, 3, 4, 6, 8, 12, 16, 24, +32, 48, 64, 96, 128, 192, 256, 384, 512, 768, +1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576 }; - diff --git a/lib/os/windows/zlib-1.2.3/uncompr.c b/lib/os/windows/zlib-1.2.3/uncompr.c index 19b5a741db3..4d4a4179dab 100644 --- a/lib/os/windows/zlib-1.2.3/uncompr.c +++ b/lib/os/windows/zlib-1.2.3/uncompr.c @@ -1,33 +1,35 @@ -/* uncompr.c -- decompress a memory buffer +/* + * uncompr.c -- decompress a memory buffer * Copyright (C) 1995-2003 Jean-loup Gailly. * For conditions of distribution and use, see copyright notice in zlib.h */ /* @(#) $Id$ */ -#define ZLIB_INTERNAL +#define ZLIB_INTERNAL #include "zlib.h" -/* =========================================================================== - Decompresses the source buffer into the destination buffer. sourceLen is - the byte length of the source buffer. Upon entry, destLen is the total - size of the destination buffer, which must be large enough to hold the - entire uncompressed data. (The size of the uncompressed data must have - been saved previously by the compressor and transmitted to the decompressor - by some mechanism outside the scope of this compression library.) - Upon exit, destLen is the actual size of the compressed buffer. - This function can be used to decompress a whole file at once if the - input file is mmap'ed. - - uncompress returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_BUF_ERROR if there was not enough room in the output - buffer, or Z_DATA_ERROR if the input data was corrupted. -*/ -int ZEXPORT uncompress(dest, destLen, source, sourceLen) - Bytef *dest; -uLongf *destLen; -const Bytef *source; -uLong sourceLen; +/* + * Decompresses the source buffer into the destination buffer. sourceLen is + * the byte length of the source buffer. Upon entry, destLen is the total + * size of the destination buffer, which must be large enough to hold the + * entire uncompressed data. (The size of the uncompressed data must have + * been saved previously by the compressor and transmitted to the decompressor + * by some mechanism outside the scope of this compression library.) + * Upon exit, destLen is the actual size of the compressed buffer. + * This function can be used to decompress a whole file at once if the + * input file is mmap'ed. + * + * uncompress returns Z_OK if success, Z_MEM_ERROR if there was not + * enough memory, Z_BUF_ERROR if there was not enough room in the output + * buffer, or Z_DATA_ERROR if the input data was corrupted. + */ +int ZEXPORT +uncompress( + Bytef *dest, + uLongf *destLen, + const Bytef *source, + uLong sourceLen) { z_stream stream; int err; @@ -35,27 +37,31 @@ uLong sourceLen; stream.next_in = (Bytef*)source; stream.avail_in = (uInt)sourceLen; /* Check for source > 64K on 16-bit machine: */ - if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR; + if ((uLong)stream.avail_in != sourceLen) + return (Z_BUF_ERROR); stream.next_out = dest; stream.avail_out = (uInt)*destLen; - if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR; + if ((uLong)stream.avail_out != *destLen) + return (Z_BUF_ERROR); stream.zalloc = (alloc_func)0; stream.zfree = (free_func)0; err = inflateInit(&stream); - if (err != Z_OK) return err; + if (err != Z_OK) + return (err); err = inflate(&stream, Z_FINISH); if (err != Z_STREAM_END) { inflateEnd(&stream); - if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0)) - return Z_DATA_ERROR; - return err; + if (err == Z_NEED_DICT || + (err == Z_BUF_ERROR && stream.avail_in == 0)) + return (Z_DATA_ERROR); + return (err); } *destLen = stream.total_out; err = inflateEnd(&stream); - return err; + return (err); } diff --git a/lib/os/windows/zlib-1.2.3/zconf.h b/lib/os/windows/zlib-1.2.3/zconf.h index 868edb16789..070e84337ab 100644 --- a/lib/os/windows/zlib-1.2.3/zconf.h +++ b/lib/os/windows/zlib-1.2.3/zconf.h @@ -1,4 +1,5 @@ -/* zconf.h -- configuration of the zlib compression library +/* + * zconf.h -- configuration of the zlib compression library * Copyright (C) 1995-2005 Jean-loup Gailly. * For conditions of distribution and use, see copyright notice in zlib.h */ @@ -6,79 +7,79 @@ /* @(#) $Id$ */ #ifndef ZCONF_H -#define ZCONF_H +#define ZCONF_H /* * If you *really* need a unique prefix for all types and library functions, * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. */ #ifdef Z_PREFIX -# define deflateInit_ z_deflateInit_ -# define deflate z_deflate -# define deflateEnd z_deflateEnd -# define inflateInit_ z_inflateInit_ -# define inflate z_inflate -# define inflateEnd z_inflateEnd -# define deflateInit2_ z_deflateInit2_ -# define deflateSetDictionary z_deflateSetDictionary -# define deflateCopy z_deflateCopy -# define deflateReset z_deflateReset -# define deflateParams z_deflateParams -# define deflateBound z_deflateBound -# define deflatePrime z_deflatePrime -# define inflateInit2_ z_inflateInit2_ -# define inflateSetDictionary z_inflateSetDictionary -# define inflateSync z_inflateSync -# define inflateSyncPoint z_inflateSyncPoint -# define inflateCopy z_inflateCopy -# define inflateReset z_inflateReset -# define inflateBack z_inflateBack -# define inflateBackEnd z_inflateBackEnd -# define compress z_compress -# define compress2 z_compress2 -# define compressBound z_compressBound -# define uncompress z_uncompress -# define adler32 z_adler32 -# define crc32 z_crc32 -# define get_crc_table z_get_crc_table -# define zError z_zError +#define deflateInit_ z_deflateInit_ +#define deflate z_deflate +#define deflateEnd z_deflateEnd +#define inflateInit_ z_inflateInit_ +#define inflate z_inflate +#define inflateEnd z_inflateEnd +#define deflateInit2_ z_deflateInit2_ +#define deflateSetDictionary z_deflateSetDictionary +#define deflateCopy z_deflateCopy +#define deflateReset z_deflateReset +#define deflateParams z_deflateParams +#define deflateBound z_deflateBound +#define deflatePrime z_deflatePrime +#define inflateInit2_ z_inflateInit2_ +#define inflateSetDictionary z_inflateSetDictionary +#define inflateSync z_inflateSync +#define inflateSyncPoint z_inflateSyncPoint +#define inflateCopy z_inflateCopy +#define inflateReset z_inflateReset +#define inflateBack z_inflateBack +#define inflateBackEnd z_inflateBackEnd +#define compress z_compress +#define compress2 z_compress2 +#define compressBound z_compressBound +#define uncompress z_uncompress +#define adler32 z_adler32 +#define crc32 z_crc32 +#define get_crc_table z_get_crc_table +#define zError z_zError -# define alloc_func z_alloc_func -# define free_func z_free_func -# define in_func z_in_func -# define out_func z_out_func -# define Byte z_Byte -# define uInt z_uInt -# define uLong z_uLong -# define Bytef z_Bytef -# define charf z_charf -# define intf z_intf -# define uIntf z_uIntf -# define uLongf z_uLongf -# define voidpf z_voidpf -# define voidp z_voidp +#define alloc_func z_alloc_func +#define free_func z_free_func +#define in_func z_in_func +#define out_func z_out_func +#define Byte z_Byte +#define uInt z_uInt +#define uLong z_uLong +#define Bytef z_Bytef +#define charf z_charf +#define intf z_intf +#define uIntf z_uIntf +#define uLongf z_uLongf +#define voidpf z_voidpf +#define voidp z_voidp #endif #if defined(__MSDOS__) && !defined(MSDOS) -# define MSDOS +#define MSDOS #endif #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) -# define OS2 +#define OS2 #endif #if defined(_WINDOWS) && !defined(WINDOWS) -# define WINDOWS +#define WINDOWS #endif #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) -# ifndef WIN32 -# define WIN32 -# endif +#ifndef WIN32 +#define WIN32 +#endif #endif #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) -# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) -# ifndef SYS16BIT -# define SYS16BIT -# endif -# endif +#if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) +#ifndef SYS16BIT +#define SYS16BIT +#endif +#endif #endif /* @@ -86,177 +87,182 @@ * than 64k bytes at a time (needed on systems with 16-bit int). */ #ifdef SYS16BIT -# define MAXSEG_64K +#define MAXSEG_64K #endif #ifdef MSDOS -# define UNALIGNED_OK +#define UNALIGNED_OK #endif #ifdef __STDC_VERSION__ -# ifndef STDC -# define STDC -# endif -# if __STDC_VERSION__ >= 199901L -# ifndef STDC99 -# define STDC99 -# endif -# endif +#ifndef STDC +#define STDC +#endif +#if __STDC_VERSION__ >= 199901L +#ifndef STDC99 +#define STDC99 +#endif +#endif #endif #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) -# define STDC +#define STDC #endif #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) -# define STDC +#define STDC #endif #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) -# define STDC +#define STDC #endif #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) -# define STDC +#define STDC #endif -#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ -# define STDC +#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ +#define STDC #endif #ifndef STDC -# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ -# define const /* note: need a more gentle solution here */ -# endif +#ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ +#define const /* note: need a more gentle solution here */ +#endif #endif /* Some Mac compilers merge all .h files incorrectly: */ #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__) -# define NO_DUMMY_DECL +#define NO_DUMMY_DECL #endif /* Maximum value for memLevel in deflateInit2 */ #ifndef MAX_MEM_LEVEL -# ifdef MAXSEG_64K -# define MAX_MEM_LEVEL 8 -# else -# define MAX_MEM_LEVEL 9 -# endif +#ifdef MAXSEG_64K +#define MAX_MEM_LEVEL 8 +#else +#define MAX_MEM_LEVEL 9 +#endif #endif -/* Maximum value for windowBits in deflateInit2 and inflateInit2. +/* + * Maximum value for windowBits in deflateInit2 and inflateInit2. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files * created by gzip. (Files created by minigzip can still be extracted by * gzip.) */ #ifndef MAX_WBITS -# define MAX_WBITS 15 /* 32K LZ77 window */ +#define MAX_WBITS 15 /* 32K LZ77 window */ #endif -/* The memory requirements for deflate are (in bytes): - (1 << (windowBits+2)) + (1 << (memLevel+9)) - that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) - plus a few kilobytes for small objects. For example, if you want to reduce - the default memory requirements from 256K to 128K, compile with - make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" - Of course this will generally degrade compression (there's no free lunch). - - The memory requirements for inflate are (in bytes) 1 << windowBits - that is, 32K for windowBits=15 (default value) plus a few kilobytes - for small objects. -*/ +/* + * The memory requirements for deflate are (in bytes): + * (1 << (windowBits+2)) + (1 << (memLevel+9)) + * that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) + * plus a few kilobytes for small objects. For example, if you want to reduce + * the default memory requirements from 256K to 128K, compile with + * make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" + * Of course this will generally degrade compression (there's no free lunch). + * + * The memory requirements for inflate are (in bytes) 1 << windowBits + * that is, 32K for windowBits=15 (default value) plus a few kilobytes + * for small objects. + */ - /* Type declarations */ +/* Type declarations */ #ifndef OF /* function prototypes */ -# ifdef STDC -# define OF(args) args -# else -# define OF(args) () -# endif +#ifdef STDC +#define OF(args) args +#else +#define OF(args) () +#endif #endif -/* The following definitions for FAR are needed only for MSDOS mixed +/* + * The following definitions for FAR are needed only for MSDOS mixed * model programming (small or medium model with some far allocations). * This was tested only with MSC; for other MSDOS compilers you may have * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, * just define FAR to be empty. */ #ifdef SYS16BIT -# if defined(M_I86SM) || defined(M_I86MM) - /* MSC small or medium model */ -# define SMALL_MEDIUM -# ifdef _MSC_VER -# define FAR _far -# else -# define FAR far -# endif -# endif -# if (defined(__SMALL__) || defined(__MEDIUM__)) - /* Turbo C small or medium model */ -# define SMALL_MEDIUM -# ifdef __BORLANDC__ -# define FAR _far -# else -# define FAR far -# endif -# endif +#if defined(M_I86SM) || defined(M_I86MM) +/* MSC small or medium model */ +#define SMALL_MEDIUM +#ifdef _MSC_VER +#define FAR _far +#else +#define FAR far +#endif +#endif +#if (defined(__SMALL__) || defined(__MEDIUM__)) +/* Turbo C small or medium model */ +#define SMALL_MEDIUM +#ifdef __BORLANDC__ +#define FAR _far +#else +#define FAR far +#endif +#endif #endif #if defined(WINDOWS) || defined(WIN32) - /* If building or using zlib as a DLL, define ZLIB_DLL. - * This is not mandatory, but it offers a little performance increase. - */ -# ifdef ZLIB_DLL -# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) -# ifdef ZLIB_INTERNAL -# define ZEXTERN extern __declspec(dllexport) -# else -# define ZEXTERN extern __declspec(dllimport) -# endif -# endif -# endif /* ZLIB_DLL */ - /* If building or using zlib with the WINAPI/WINAPIV calling convention, - * define ZLIB_WINAPI. - * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. - */ +/* + * If building or using zlib as a DLL, define ZLIB_DLL. + * This is not mandatory, but it offers a little performance increase. + */ +#ifdef ZLIB_DLL +#if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) +#ifdef ZLIB_INTERNAL +#define ZEXTERN extern __declspec(dllexport) +#else +#define ZEXTERN extern __declspec(dllimport) +#endif +#endif +#endif /* ZLIB_DLL */ +/* + * If building or using zlib with the WINAPI/WINAPIV calling convention, + * define ZLIB_WINAPI. + * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. + */ #undef ZLIB_WINAPI -# ifdef ZLIB_WINAPI -# ifdef FAR -# undef FAR -# endif -# include - /* No need for _export, use ZLIB.DEF instead. */ - /* For complete Windows compatibility, use WINAPI, not __stdcall. */ -# define ZEXPORT WINAPI -# ifdef WIN32 -# define ZEXPORTVA WINAPIV -# else -# define ZEXPORTVA FAR CDECL -# endif -# endif +#ifdef ZLIB_WINAPI +#ifdef FAR +#undef FAR +#endif +#include +/* No need for _export, use ZLIB.DEF instead. */ +/* For complete Windows compatibility, use WINAPI, not __stdcall. */ +#define ZEXPORT WINAPI +#ifdef WIN32 +#define ZEXPORTVA WINAPIV +#else +#define ZEXPORTVA FAR CDECL +#endif +#endif #endif -#if defined (__BEOS__) -# ifdef ZLIB_DLL -# ifdef ZLIB_INTERNAL -# define ZEXPORT __declspec(dllexport) -# define ZEXPORTVA __declspec(dllexport) -# else -# define ZEXPORT __declspec(dllimport) -# define ZEXPORTVA __declspec(dllimport) -# endif -# endif +#if defined(__BEOS__) +#ifdef ZLIB_DLL +#ifdef ZLIB_INTERNAL +#define ZEXPORT __declspec(dllexport) +#define ZEXPORTVA __declspec(dllexport) +#else +#define ZEXPORT __declspec(dllimport) +#define ZEXPORTVA __declspec(dllimport) +#endif +#endif #endif #ifndef ZEXTERN -# define ZEXTERN extern +#define ZEXTERN extern #endif #ifndef ZEXPORT -# define ZEXPORT +#define ZEXPORT #endif #ifndef ZEXPORTVA -# define ZEXPORTVA +#define ZEXPORTVA #endif #ifndef FAR -# define FAR +#define FAR #endif #if !defined(__MACTYPES__) @@ -266,10 +272,10 @@ typedef unsigned int uInt; /* 16 bits or more */ typedef unsigned long uLong; /* 32 bits or more */ #ifdef SMALL_MEDIUM - /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ -# define Bytef Byte FAR +/* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ +#define Bytef Byte FAR #else - typedef Byte FAR Bytef; +typedef Byte FAR Bytef; #endif typedef char FAR charf; typedef int FAR intf; @@ -277,58 +283,58 @@ typedef uInt FAR uIntf; typedef uLong FAR uLongf; #ifdef STDC - typedef void const *voidpc; - typedef void FAR *voidpf; - typedef void *voidp; +typedef void const *voidpc; +typedef void FAR *voidpf; +typedef void *voidp; #else - typedef Byte const *voidpc; - typedef Byte FAR *voidpf; - typedef Byte *voidp; +typedef Byte const *voidpc; +typedef Byte FAR *voidpf; +typedef Byte *voidp; #endif -#if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */ -# include /* for off_t */ -# include /* for SEEK_* and off_t */ -# ifdef VMS -# include /* for off_t */ -# endif -# define z_off_t off_t +#if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */ +#include /* for off_t */ +#include /* for SEEK_* and off_t */ +#ifdef VMS +#include /* for off_t */ +#endif +#define z_off_t off_t #endif #ifndef SEEK_SET -# define SEEK_SET 0 /* Seek from beginning of file. */ -# define SEEK_CUR 1 /* Seek from current position. */ -# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ +#define SEEK_SET 0 /* Seek from beginning of file. */ +#define SEEK_CUR 1 /* Seek from current position. */ +#define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ #endif #ifndef z_off_t -# define z_off_t long +#define z_off_t long #endif #if defined(__OS400__) -# define NO_vsnprintf +#define NO_vsnprintf #endif #if defined(__MVS__) -# define NO_vsnprintf -# ifdef FAR -# undef FAR -# endif +#define NO_vsnprintf +#ifdef FAR +#undef FAR +#endif #endif /* MVS linker does not support external names larger than 8 bytes */ #if defined(__MVS__) -# pragma map(deflateInit_,"DEIN") -# pragma map(deflateInit2_,"DEIN2") -# pragma map(deflateEnd,"DEEND") -# pragma map(deflateBound,"DEBND") -# pragma map(inflateInit_,"ININ") -# pragma map(inflateInit2_,"ININ2") -# pragma map(inflateEnd,"INEND") -# pragma map(inflateSync,"INSY") -# pragma map(inflateSetDictionary,"INSEDI") -# pragma map(compressBound,"CMBND") -# pragma map(inflate_table,"INTABL") -# pragma map(inflate_fast,"INFA") -# pragma map(inflate_copyright,"INCOPY") +#pragma map(deflateInit_, "DEIN") +#pragma map(deflateInit2_, "DEIN2") +#pragma map(deflateEnd, "DEEND") +#pragma map(deflateBound, "DEBND") +#pragma map(inflateInit_, "ININ") +#pragma map(inflateInit2_, "ININ2") +#pragma map(inflateEnd, "INEND") +#pragma map(inflateSync, "INSY") +#pragma map(inflateSetDictionary, "INSEDI") +#pragma map(compressBound, "CMBND") +#pragma map(inflate_table, "INTABL") +#pragma map(inflate_fast, "INFA") +#pragma map(inflate_copyright, "INCOPY") #endif #endif /* ZCONF_H */ diff --git a/lib/os/windows/zlib-1.2.3/zconf.in.h b/lib/os/windows/zlib-1.2.3/zconf.in.h index 03a9431c8be..0bf1bd35619 100644 --- a/lib/os/windows/zlib-1.2.3/zconf.in.h +++ b/lib/os/windows/zlib-1.2.3/zconf.in.h @@ -1,4 +1,5 @@ -/* zconf.h -- configuration of the zlib compression library +/* + * zconf.h -- configuration of the zlib compression library * Copyright (C) 1995-2005 Jean-loup Gailly. * For conditions of distribution and use, see copyright notice in zlib.h */ @@ -6,79 +7,79 @@ /* @(#) $Id$ */ #ifndef ZCONF_H -#define ZCONF_H +#define ZCONF_H /* * If you *really* need a unique prefix for all types and library functions, * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. */ #ifdef Z_PREFIX -# define deflateInit_ z_deflateInit_ -# define deflate z_deflate -# define deflateEnd z_deflateEnd -# define inflateInit_ z_inflateInit_ -# define inflate z_inflate -# define inflateEnd z_inflateEnd -# define deflateInit2_ z_deflateInit2_ -# define deflateSetDictionary z_deflateSetDictionary -# define deflateCopy z_deflateCopy -# define deflateReset z_deflateReset -# define deflateParams z_deflateParams -# define deflateBound z_deflateBound -# define deflatePrime z_deflatePrime -# define inflateInit2_ z_inflateInit2_ -# define inflateSetDictionary z_inflateSetDictionary -# define inflateSync z_inflateSync -# define inflateSyncPoint z_inflateSyncPoint -# define inflateCopy z_inflateCopy -# define inflateReset z_inflateReset -# define inflateBack z_inflateBack -# define inflateBackEnd z_inflateBackEnd -# define compress z_compress -# define compress2 z_compress2 -# define compressBound z_compressBound -# define uncompress z_uncompress -# define adler32 z_adler32 -# define crc32 z_crc32 -# define get_crc_table z_get_crc_table -# define zError z_zError +#define deflateInit_ z_deflateInit_ +#define deflate z_deflate +#define deflateEnd z_deflateEnd +#define inflateInit_ z_inflateInit_ +#define inflate z_inflate +#define inflateEnd z_inflateEnd +#define deflateInit2_ z_deflateInit2_ +#define deflateSetDictionary z_deflateSetDictionary +#define deflateCopy z_deflateCopy +#define deflateReset z_deflateReset +#define deflateParams z_deflateParams +#define deflateBound z_deflateBound +#define deflatePrime z_deflatePrime +#define inflateInit2_ z_inflateInit2_ +#define inflateSetDictionary z_inflateSetDictionary +#define inflateSync z_inflateSync +#define inflateSyncPoint z_inflateSyncPoint +#define inflateCopy z_inflateCopy +#define inflateReset z_inflateReset +#define inflateBack z_inflateBack +#define inflateBackEnd z_inflateBackEnd +#define compress z_compress +#define compress2 z_compress2 +#define compressBound z_compressBound +#define uncompress z_uncompress +#define adler32 z_adler32 +#define crc32 z_crc32 +#define get_crc_table z_get_crc_table +#define zError z_zError -# define alloc_func z_alloc_func -# define free_func z_free_func -# define in_func z_in_func -# define out_func z_out_func -# define Byte z_Byte -# define uInt z_uInt -# define uLong z_uLong -# define Bytef z_Bytef -# define charf z_charf -# define intf z_intf -# define uIntf z_uIntf -# define uLongf z_uLongf -# define voidpf z_voidpf -# define voidp z_voidp +#define alloc_func z_alloc_func +#define free_func z_free_func +#define in_func z_in_func +#define out_func z_out_func +#define Byte z_Byte +#define uInt z_uInt +#define uLong z_uLong +#define Bytef z_Bytef +#define charf z_charf +#define intf z_intf +#define uIntf z_uIntf +#define uLongf z_uLongf +#define voidpf z_voidpf +#define voidp z_voidp #endif #if defined(__MSDOS__) && !defined(MSDOS) -# define MSDOS +#define MSDOS #endif #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) -# define OS2 +#define OS2 #endif #if defined(_WINDOWS) && !defined(WINDOWS) -# define WINDOWS +#define WINDOWS #endif #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) -# ifndef WIN32 -# define WIN32 -# endif +#ifndef WIN32 +#define WIN32 +#endif #endif #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) -# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) -# ifndef SYS16BIT -# define SYS16BIT -# endif -# endif +#if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) +#ifndef SYS16BIT +#define SYS16BIT +#endif +#endif #endif /* @@ -86,175 +87,180 @@ * than 64k bytes at a time (needed on systems with 16-bit int). */ #ifdef SYS16BIT -# define MAXSEG_64K +#define MAXSEG_64K #endif #ifdef MSDOS -# define UNALIGNED_OK +#define UNALIGNED_OK #endif #ifdef __STDC_VERSION__ -# ifndef STDC -# define STDC -# endif -# if __STDC_VERSION__ >= 199901L -# ifndef STDC99 -# define STDC99 -# endif -# endif +#ifndef STDC +#define STDC +#endif +#if __STDC_VERSION__ >= 199901L +#ifndef STDC99 +#define STDC99 +#endif +#endif #endif #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) -# define STDC +#define STDC #endif #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) -# define STDC +#define STDC #endif #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) -# define STDC +#define STDC #endif #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) -# define STDC +#define STDC #endif #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ -# define STDC +#define STDC #endif #ifndef STDC -# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ -# define const /* note: need a more gentle solution here */ -# endif +#ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ +#define const /* note: need a more gentle solution here */ +#endif #endif /* Some Mac compilers merge all .h files incorrectly: */ #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__) -# define NO_DUMMY_DECL +#define NO_DUMMY_DECL #endif /* Maximum value for memLevel in deflateInit2 */ #ifndef MAX_MEM_LEVEL -# ifdef MAXSEG_64K -# define MAX_MEM_LEVEL 8 -# else -# define MAX_MEM_LEVEL 9 -# endif +#ifdef MAXSEG_64K +#define MAX_MEM_LEVEL 8 +#else +#define MAX_MEM_LEVEL 9 +#endif #endif -/* Maximum value for windowBits in deflateInit2 and inflateInit2. +/* + * Maximum value for windowBits in deflateInit2 and inflateInit2. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files * created by gzip. (Files created by minigzip can still be extracted by * gzip.) */ #ifndef MAX_WBITS -# define MAX_WBITS 15 /* 32K LZ77 window */ +#define MAX_WBITS 15 /* 32K LZ77 window */ #endif -/* The memory requirements for deflate are (in bytes): - (1 << (windowBits+2)) + (1 << (memLevel+9)) - that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) - plus a few kilobytes for small objects. For example, if you want to reduce - the default memory requirements from 256K to 128K, compile with - make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" - Of course this will generally degrade compression (there's no free lunch). - - The memory requirements for inflate are (in bytes) 1 << windowBits - that is, 32K for windowBits=15 (default value) plus a few kilobytes - for small objects. -*/ +/* + * The memory requirements for deflate are (in bytes): + * (1 << (windowBits+2)) + (1 << (memLevel+9)) + * that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) + * plus a few kilobytes for small objects. For example, if you want to reduce + * the default memory requirements from 256K to 128K, compile with + * make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" + * Of course this will generally degrade compression (there's no free lunch). + * + * The memory requirements for inflate are (in bytes) 1 << windowBits + * that is, 32K for windowBits=15 (default value) plus a few kilobytes + * for small objects. + */ - /* Type declarations */ +/* Type declarations */ #ifndef OF /* function prototypes */ -# ifdef STDC -# define OF(args) args -# else -# define OF(args) () -# endif +#ifdef STDC +#define OF(args) args +#else +#define OF(args) () +#endif #endif -/* The following definitions for FAR are needed only for MSDOS mixed +/* + * The following definitions for FAR are needed only for MSDOS mixed * model programming (small or medium model with some far allocations). * This was tested only with MSC; for other MSDOS compilers you may have * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, * just define FAR to be empty. */ #ifdef SYS16BIT -# if defined(M_I86SM) || defined(M_I86MM) - /* MSC small or medium model */ -# define SMALL_MEDIUM -# ifdef _MSC_VER -# define FAR _far -# else -# define FAR far -# endif -# endif -# if (defined(__SMALL__) || defined(__MEDIUM__)) - /* Turbo C small or medium model */ -# define SMALL_MEDIUM -# ifdef __BORLANDC__ -# define FAR _far -# else -# define FAR far -# endif -# endif +#if defined(M_I86SM) || defined(M_I86MM) +/* MSC small or medium model */ +#define SMALL_MEDIUM +#ifdef _MSC_VER +#define FAR _far +#else +#define FAR far +#endif +#endif +#if (defined(__SMALL__) || defined(__MEDIUM__)) +/* Turbo C small or medium model */ +#define SMALL_MEDIUM +#ifdef __BORLANDC__ +#define FAR _far +#else +#define FAR far +#endif +#endif #endif #if defined(WINDOWS) || defined(WIN32) - /* If building or using zlib as a DLL, define ZLIB_DLL. - * This is not mandatory, but it offers a little performance increase. - */ -# ifdef ZLIB_DLL -# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) -# ifdef ZLIB_INTERNAL -# define ZEXTERN extern __declspec(dllexport) -# else -# define ZEXTERN extern __declspec(dllimport) -# endif -# endif -# endif /* ZLIB_DLL */ - /* If building or using zlib with the WINAPI/WINAPIV calling convention, - * define ZLIB_WINAPI. - * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. - */ -# ifdef ZLIB_WINAPI -# ifdef FAR -# undef FAR -# endif -# include - /* No need for _export, use ZLIB.DEF instead. */ - /* For complete Windows compatibility, use WINAPI, not __stdcall. */ -# define ZEXPORT WINAPI -# ifdef WIN32 -# define ZEXPORTVA WINAPIV -# else -# define ZEXPORTVA FAR CDECL -# endif -# endif +/* + * If building or using zlib as a DLL, define ZLIB_DLL. + * This is not mandatory, but it offers a little performance increase. + */ +#ifdef ZLIB_DLL +#if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) +#ifdef ZLIB_INTERNAL +#define ZEXTERN extern __declspec(dllexport) +#else +#define ZEXTERN extern __declspec(dllimport) +#endif +#endif +#endif /* ZLIB_DLL */ +/* + * If building or using zlib with the WINAPI/WINAPIV calling convention, + * define ZLIB_WINAPI. + * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. + */ +#ifdef ZLIB_WINAPI +#ifdef FAR +#undef FAR +#endif +#include +/* No need for _export, use ZLIB.DEF instead. */ +/* For complete Windows compatibility, use WINAPI, not __stdcall. */ +#define ZEXPORT WINAPI +#ifdef WIN32 +#define ZEXPORTVA WINAPIV +#else +#define ZEXPORTVA FAR CDECL +#endif +#endif #endif -#if defined (__BEOS__) -# ifdef ZLIB_DLL -# ifdef ZLIB_INTERNAL -# define ZEXPORT __declspec(dllexport) -# define ZEXPORTVA __declspec(dllexport) -# else -# define ZEXPORT __declspec(dllimport) -# define ZEXPORTVA __declspec(dllimport) -# endif -# endif +#if defined(__BEOS__) +#ifdef ZLIB_DLL +#ifdef ZLIB_INTERNAL +#define ZEXPORT __declspec(dllexport) +#define ZEXPORTVA __declspec(dllexport) +#else +#define ZEXPORT __declspec(dllimport) +#define ZEXPORTVA __declspec(dllimport) +#endif +#endif #endif #ifndef ZEXTERN -# define ZEXTERN extern +#define ZEXTERN extern #endif #ifndef ZEXPORT -# define ZEXPORT +#define ZEXPORT #endif #ifndef ZEXPORTVA -# define ZEXPORTVA +#define ZEXPORTVA #endif #ifndef FAR -# define FAR +#define FAR #endif #if !defined(__MACTYPES__) @@ -264,10 +270,10 @@ typedef unsigned int uInt; /* 16 bits or more */ typedef unsigned long uLong; /* 32 bits or more */ #ifdef SMALL_MEDIUM - /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ -# define Bytef Byte FAR +/* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ +#define Bytef Byte FAR #else - typedef Byte FAR Bytef; +typedef Byte FAR Bytef; #endif typedef char FAR charf; typedef int FAR intf; @@ -275,58 +281,58 @@ typedef uInt FAR uIntf; typedef uLong FAR uLongf; #ifdef STDC - typedef void const *voidpc; - typedef void FAR *voidpf; - typedef void *voidp; +typedef void const *voidpc; +typedef void FAR *voidpf; +typedef void *voidp; #else - typedef Byte const *voidpc; - typedef Byte FAR *voidpf; - typedef Byte *voidp; +typedef Byte const *voidpc; +typedef Byte FAR *voidpf; +typedef Byte *voidp; #endif -#if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */ -# include /* for off_t */ -# include /* for SEEK_* and off_t */ -# ifdef VMS -# include /* for off_t */ -# endif -# define z_off_t off_t +#if 0 +#include /* for off_t */ +#include /* for SEEK_* and off_t */ +#ifdef VMS +#include /* for off_t */ +#endif +#define z_off_t off_t #endif #ifndef SEEK_SET -# define SEEK_SET 0 /* Seek from beginning of file. */ -# define SEEK_CUR 1 /* Seek from current position. */ -# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ +#define SEEK_SET 0 /* Seek from beginning of file. */ +#define SEEK_CUR 1 /* Seek from current position. */ +#define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ #endif #ifndef z_off_t -# define z_off_t long +#define z_off_t long #endif #if defined(__OS400__) -# define NO_vsnprintf +#define NO_vsnprintf #endif #if defined(__MVS__) -# define NO_vsnprintf -# ifdef FAR -# undef FAR -# endif +#define NO_vsnprintf +#ifdef FAR +#undef FAR +#endif #endif /* MVS linker does not support external names larger than 8 bytes */ #if defined(__MVS__) -# pragma map(deflateInit_,"DEIN") -# pragma map(deflateInit2_,"DEIN2") -# pragma map(deflateEnd,"DEEND") -# pragma map(deflateBound,"DEBND") -# pragma map(inflateInit_,"ININ") -# pragma map(inflateInit2_,"ININ2") -# pragma map(inflateEnd,"INEND") -# pragma map(inflateSync,"INSY") -# pragma map(inflateSetDictionary,"INSEDI") -# pragma map(compressBound,"CMBND") -# pragma map(inflate_table,"INTABL") -# pragma map(inflate_fast,"INFA") -# pragma map(inflate_copyright,"INCOPY") +#pragma map(deflateInit_, "DEIN") +#pragma map(deflateInit2_, "DEIN2") +#pragma map(deflateEnd, "DEEND") +#pragma map(deflateBound, "DEBND") +#pragma map(inflateInit_, "ININ") +#pragma map(inflateInit2_, "ININ2") +#pragma map(inflateEnd, "INEND") +#pragma map(inflateSync, "INSY") +#pragma map(inflateSetDictionary, "INSEDI") +#pragma map(compressBound, "CMBND") +#pragma map(inflate_table, "INTABL") +#pragma map(inflate_fast, "INFA") +#pragma map(inflate_copyright, "INCOPY") #endif #endif /* ZCONF_H */ diff --git a/lib/os/windows/zlib-1.2.3/zlib-dllversion.c b/lib/os/windows/zlib-1.2.3/zlib-dllversion.c deleted file mode 100644 index 68b59e9521f..00000000000 --- a/lib/os/windows/zlib-1.2.3/zlib-dllversion.c +++ /dev/null @@ -1,23 +0,0 @@ -/* See: http://msdn.microsoft.com/library/en-us/shellcc/platform/shell/programmersguide/versions.asp */ -#include -#include -#ifdef __cplusplus -extern "C" { -#endif -/* __declspec(dllexport) */ HRESULT DllGetVersion (DLLVERSIONINFO2 *pdvi); -#ifdef __cplusplus -} -#endif - -HRESULT DllGetVersion (DLLVERSIONINFO2 *pdvi) -{ - if ( !pdvi || (pdvi->info1.cbSize != sizeof (*pdvi)) ) - return (E_INVALIDARG); - pdvi->info1.dwMajorVersion = 1; - pdvi->info1.dwMinorVersion = 2; - pdvi->info1.dwBuildNumber = 3; - pdvi->info1.dwPlatformID = DLLVER_PLATFORM_WINDOWS; - if (pdvi->info1.cbSize == sizeof (DLLVERSIONINFO2)) - pdvi->ullVersion = MAKEDLLVERULL (1, 2, 3, 2027); - return S_OK; -} diff --git a/lib/os/windows/zlib-1.2.3/zlib.h b/lib/os/windows/zlib-1.2.3/zlib.h index 022817927ce..61364b72e81 100644 --- a/lib/os/windows/zlib-1.2.3/zlib.h +++ b/lib/os/windows/zlib-1.2.3/zlib.h @@ -1,35 +1,36 @@ -/* zlib.h -- interface of the 'zlib' general purpose compression library - version 1.2.3, July 18th, 2005 - - Copyright (C) 1995-2005 Jean-loup Gailly and Mark Adler - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jean-loup Gailly Mark Adler - jloup@gzip.org madler@alumni.caltech.edu - - - The data format used by the zlib library is described by RFCs (Request for - Comments) 1950 to 1952 in the files http://www.ietf.org/rfc/rfc1950.txt - (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format). -*/ +/* + * zlib.h -- interface of the 'zlib' general purpose compression library + * version 1.2.3, July 18th, 2005 + * + * Copyright (C) 1995-2005 Jean-loup Gailly and Mark Adler + * + * This software is provided 'as-is', without any express or implied + * warranty. In no event will the authors be held liable for any damages + * arising from the use of this software. + * + * Permission is granted to anyone to use this software for any purpose, + * including commercial applications, and to alter it and redistribute it + * freely, subject to the following restrictions: + * + * 1. The origin of this software must not be misrepresented; you must not + * claim that you wrote the original software. If you use this software + * in a product, an acknowledgment in the product documentation would be + * appreciated but is not required. + * 2. Altered source versions must be plainly marked as such, and must not be + * misrepresented as being the original software. + * 3. This notice may not be removed or altered from any source distribution. + * + * Jean-loup Gailly Mark Adler + * jloup@gzip.org madler@alumni.caltech.edu + * + * + * The data format used by the zlib library is described by RFCs (Request for + * Comments) 1950 to 1952 in the files http://www.ietf.org/rfc/rfc1950.txt + * (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format). + */ #ifndef ZLIB_H -#define ZLIB_H +#define ZLIB_H #include "zconf.h" @@ -37,42 +38,42 @@ extern "C" { #endif -#define ZLIB_VERSION "1.2.3" -#define ZLIB_VERNUM 0x1230 +#define ZLIB_VERSION "1.2.3" +#define ZLIB_VERNUM 0x1230 /* - The 'zlib' compression library provides in-memory compression and - decompression functions, including integrity checks of the uncompressed - data. This version of the library supports only one compression method - (deflation) but other algorithms will be added later and will have the same - stream interface. - - Compression can be done in a single step if the buffers are large - enough (for example if an input file is mmap'ed), or can be done by - repeated calls of the compression function. In the latter case, the - application must provide more input and/or consume the output - (providing more output space) before each call. - - The compressed data format used by default by the in-memory functions is - the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped - around a deflate stream, which is itself documented in RFC 1951. - - The library also supports reading and writing files in gzip (.gz) format - with an interface similar to that of stdio using the functions that start - with "gz". The gzip format is different from the zlib format. gzip is a - gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. - - This library can optionally read and write gzip streams in memory as well. - - The zlib format was designed to be compact and fast for use in memory - and on communications channels. The gzip format was designed for single- - file compression on file systems, has a larger header than zlib to maintain - directory information, and uses a different, slower check method than zlib. - - The library does not install any signal handler. The decoder checks - the consistency of the compressed data, so the library should never - crash even in case of corrupted input. -*/ + * The 'zlib' compression library provides in-memory compression and + * decompression functions, including integrity checks of the uncompressed + * data. This version of the library supports only one compression method + * (deflation) but other algorithms will be added later and will have the same + * stream interface. + * + * Compression can be done in a single step if the buffers are large + * enough (for example if an input file is mmap'ed), or can be done by + * repeated calls of the compression function. In the latter case, the + * application must provide more input and/or consume the output + * (providing more output space) before each call. + * + * The compressed data format used by default by the in-memory functions is + * the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped + * around a deflate stream, which is itself documented in RFC 1951. + * + * The library also supports reading and writing files in gzip (.gz) format + * with an interface similar to that of stdio using the functions that start + * with "gz". The gzip format is different from the zlib format. gzip is a + * gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. + * + * This library can optionally read and write gzip streams in memory as well. + * + * The zlib format was designed to be compact and fast for use in memory + * and on communications channels. The gzip format was designed for single- + * file compression on file systems, has a larger header than zlib to maintain + * directory information, and uses a different, slower check method than zlib. + * + * The library does not install any signal handler. The decoder checks + * the consistency of the compressed data, so the library should never + * crash even in case of corrupted input. + */ typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size)); typedef void (*free_func) OF((voidpf opaque, voidpf address)); @@ -80,1275 +81,1277 @@ typedef void (*free_func) OF((voidpf opaque, voidpf address)); struct internal_state; typedef struct z_stream_s { - Bytef *next_in; /* next input byte */ - uInt avail_in; /* number of bytes available at next_in */ - uLong total_in; /* total nb of input bytes read so far */ + Bytef *next_in; /* next input byte */ + uInt avail_in; /* number of bytes available at next_in */ + uLong total_in; /* total nb of input bytes read so far */ - Bytef *next_out; /* next output byte should be put there */ - uInt avail_out; /* remaining free space at next_out */ - uLong total_out; /* total nb of bytes output so far */ + Bytef *next_out; /* next output byte should be put there */ + uInt avail_out; /* remaining free space at next_out */ + uLong total_out; /* total nb of bytes output so far */ - char *msg; /* last error message, NULL if no error */ - struct internal_state FAR *state; /* not visible by applications */ + char *msg; /* last error message, NULL if no error */ + struct internal_state FAR *state; /* not visible by applications */ - alloc_func zalloc; /* used to allocate the internal state */ - free_func zfree; /* used to free the internal state */ - voidpf opaque; /* private data object passed to zalloc and zfree */ + alloc_func zalloc; /* used to allocate the internal state */ + free_func zfree; /* used to free the internal state */ + voidpf opaque; /* private data object passed to zalloc and zfree */ - int data_type; /* best guess about the data type: binary or text */ - uLong adler; /* adler32 value of the uncompressed data */ - uLong reserved; /* reserved for future use */ + int data_type; /* best guess about the data type: binary or text */ + uLong adler; /* adler32 value of the uncompressed data */ + uLong reserved; /* reserved for future use */ } z_stream; typedef z_stream FAR *z_streamp; /* - gzip header information passed to and from zlib routines. See RFC 1952 - for more details on the meanings of these fields. -*/ + * gzip header information passed to and from zlib routines. See RFC 1952 + * for more details on the meanings of these fields. + */ typedef struct gz_header_s { - int text; /* true if compressed data believed to be text */ - uLong time; /* modification time */ - int xflags; /* extra flags (not used when writing a gzip file) */ - int os; /* operating system */ - Bytef *extra; /* pointer to extra field or Z_NULL if none */ - uInt extra_len; /* extra field length (valid if extra != Z_NULL) */ - uInt extra_max; /* space at extra (only when reading header) */ - Bytef *name; /* pointer to zero-terminated file name or Z_NULL */ - uInt name_max; /* space at name (only when reading header) */ - Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */ - uInt comm_max; /* space at comment (only when reading header) */ - int hcrc; /* true if there was or will be a header crc */ - int done; /* true when done reading gzip header (not used - when writing a gzip file) */ + int text; /* true if compressed data believed to be text */ + uLong time; /* modification time */ + int xflags; /* extra flags (not used when writing a gzip file) */ + int os; /* operating system */ + Bytef *extra; /* pointer to extra field or Z_NULL if none */ + uInt extra_len; /* extra field length (valid if extra != Z_NULL) */ + uInt extra_max; /* space at extra (only when reading header) */ + Bytef *name; /* pointer to zero-terminated file name or Z_NULL */ + uInt name_max; /* space at name (only when reading header) */ + Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */ + uInt comm_max; /* space at comment (only when reading header) */ + int hcrc; /* true if there was or will be a header crc */ + int done; } gz_header; typedef gz_header FAR *gz_headerp; /* - The application must update next_in and avail_in when avail_in has - dropped to zero. It must update next_out and avail_out when avail_out - has dropped to zero. The application must initialize zalloc, zfree and - opaque before calling the init function. All other fields are set by the - compression library and must not be updated by the application. - - The opaque value provided by the application will be passed as the first - parameter for calls of zalloc and zfree. This can be useful for custom - memory management. The compression library attaches no meaning to the - opaque value. - - zalloc must return Z_NULL if there is not enough memory for the object. - If zlib is used in a multi-threaded application, zalloc and zfree must be - thread safe. - - On 16-bit systems, the functions zalloc and zfree must be able to allocate - exactly 65536 bytes, but will not be required to allocate more than this - if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, - pointers returned by zalloc for objects of exactly 65536 bytes *must* - have their offset normalized to zero. The default allocation function - provided by this library ensures this (see zutil.c). To reduce memory - requirements and avoid any allocation of 64K objects, at the expense of - compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h). - - The fields total_in and total_out can be used for statistics or - progress reports. After compression, total_in holds the total size of - the uncompressed data and may be saved for use in the decompressor - (particularly if the decompressor wants to decompress everything in - a single step). -*/ - - /* constants */ - -#define Z_NO_FLUSH 0 -#define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */ -#define Z_SYNC_FLUSH 2 -#define Z_FULL_FLUSH 3 -#define Z_FINISH 4 -#define Z_BLOCK 5 + * The application must update next_in and avail_in when avail_in has + * dropped to zero. It must update next_out and avail_out when avail_out + * has dropped to zero. The application must initialize zalloc, zfree and + * opaque before calling the init function. All other fields are set by the + * compression library and must not be updated by the application. + * + * The opaque value provided by the application will be passed as the first + * parameter for calls of zalloc and zfree. This can be useful for custom + * memory management. The compression library attaches no meaning to the + * opaque value. + * + * zalloc must return Z_NULL if there is not enough memory for the object. + * If zlib is used in a multi-threaded application, zalloc and zfree must be + * thread safe. + * + * On 16-bit systems, the functions zalloc and zfree must be able to allocate + * exactly 65536 bytes, but will not be required to allocate more than this + * if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, + * pointers returned by zalloc for objects of exactly 65536 bytes *must* + * have their offset normalized to zero. The default allocation function + * provided by this library ensures this (see zutil.c). To reduce memory + * requirements and avoid any allocation of 64K objects, at the expense of + * compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h). + * + * The fields total_in and total_out can be used for statistics or + * progress reports. After compression, total_in holds the total size of + * the uncompressed data and may be saved for use in the decompressor + * (particularly if the decompressor wants to decompress everything in + * a single step). + */ + + /* constants */ + +#define Z_NO_FLUSH 0 +#define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */ +#define Z_SYNC_FLUSH 2 +#define Z_FULL_FLUSH 3 +#define Z_FINISH 4 +#define Z_BLOCK 5 /* Allowed flush values; see deflate() and inflate() below for details */ -#define Z_OK 0 -#define Z_STREAM_END 1 -#define Z_NEED_DICT 2 -#define Z_ERRNO (-1) -#define Z_STREAM_ERROR (-2) -#define Z_DATA_ERROR (-3) -#define Z_MEM_ERROR (-4) -#define Z_BUF_ERROR (-5) -#define Z_VERSION_ERROR (-6) -/* Return codes for the compression/decompression functions. Negative +#define Z_OK 0 +#define Z_STREAM_END 1 +#define Z_NEED_DICT 2 +#define Z_ERRNO (-1) +#define Z_STREAM_ERROR (-2) +#define Z_DATA_ERROR (-3) +#define Z_MEM_ERROR (-4) +#define Z_BUF_ERROR (-5) +#define Z_VERSION_ERROR (-6) +/* + * Return codes for the compression/decompression functions. Negative * values are errors, positive values are used for special but normal events. */ -#define Z_NO_COMPRESSION 0 -#define Z_BEST_SPEED 1 -#define Z_BEST_COMPRESSION 9 -#define Z_DEFAULT_COMPRESSION (-1) +#define Z_NO_COMPRESSION 0 +#define Z_BEST_SPEED 1 +#define Z_BEST_COMPRESSION 9 +#define Z_DEFAULT_COMPRESSION (-1) /* compression levels */ -#define Z_FILTERED 1 -#define Z_HUFFMAN_ONLY 2 -#define Z_RLE 3 -#define Z_FIXED 4 -#define Z_DEFAULT_STRATEGY 0 +#define Z_FILTERED 1 +#define Z_HUFFMAN_ONLY 2 +#define Z_RLE 3 +#define Z_FIXED 4 +#define Z_DEFAULT_STRATEGY 0 /* compression strategy; see deflateInit2() below for details */ -#define Z_BINARY 0 -#define Z_TEXT 1 -#define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ -#define Z_UNKNOWN 2 +#define Z_BINARY 0 +#define Z_TEXT 1 +#define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ +#define Z_UNKNOWN 2 /* Possible values of the data_type field (though see inflate()) */ -#define Z_DEFLATED 8 +#define Z_DEFLATED 8 /* The deflate compression method (the only one supported in this version) */ -#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ +#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ -#define zlib_version zlibVersion() +#define zlib_version zlibVersion() /* for compatibility with versions < 1.0.2 */ - /* basic functions */ + /* basic functions */ -ZEXTERN const char * ZEXPORT zlibVersion OF((void)); -/* The application can compare zlibVersion and ZLIB_VERSION for consistency. - If the first character differs, the library code actually used is - not compatible with the zlib.h header file used by the application. - This check is automatically made by deflateInit and inflateInit. +ZEXTERN const char *ZEXPORT zlibVersion OF((void)); +/* + * The application can compare zlibVersion and ZLIB_VERSION for consistency. + * If the first character differs, the library code actually used is + * not compatible with the zlib.h header file used by the application. + * This check is automatically made by deflateInit and inflateInit. */ /* -ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); - - Initializes the internal stream state for compression. The fields - zalloc, zfree and opaque must be initialized before by the caller. - If zalloc and zfree are set to Z_NULL, deflateInit updates them to - use default allocation functions. - - The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: - 1 gives best speed, 9 gives best compression, 0 gives no compression at - all (the input data is simply copied a block at a time). - Z_DEFAULT_COMPRESSION requests a default compromise between speed and - compression (currently equivalent to level 6). - - deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_STREAM_ERROR if level is not a valid compression level, - Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible - with the version assumed by the caller (ZLIB_VERSION). - msg is set to null if there is no error message. deflateInit does not - perform any compression: this will be done by deflate(). -*/ - + * ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); + * + * Initializes the internal stream state for compression. The fields + * zalloc, zfree and opaque must be initialized before by the caller. + * If zalloc and zfree are set to Z_NULL, deflateInit updates them to + * use default allocation functions. + * + * The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: + * 1 gives best speed, 9 gives best compression, 0 gives no compression at + * all (the input data is simply copied a block at a time). + * Z_DEFAULT_COMPRESSION requests a default compromise between speed and + * compression (currently equivalent to level 6). + * + * deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not + * enough memory, Z_STREAM_ERROR if level is not a valid compression level, + * Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible + * with the version assumed by the caller (ZLIB_VERSION). + * msg is set to null if there is no error message. deflateInit does not + * perform any compression: this will be done by deflate(). + */ ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); /* - deflate compresses as much data as possible, and stops when the input - buffer becomes empty or the output buffer becomes full. It may introduce some - output latency (reading input without producing any output) except when - forced to flush. - - The detailed semantics are as follows. deflate performs one or both of the - following actions: - - - Compress more input starting at next_in and update next_in and avail_in - accordingly. If not all input can be processed (because there is not - enough room in the output buffer), next_in and avail_in are updated and - processing will resume at this point for the next call of deflate(). - - - Provide more output starting at next_out and update next_out and avail_out - accordingly. This action is forced if the parameter flush is non zero. - Forcing flush frequently degrades the compression ratio, so this parameter - should be set only when necessary (in interactive applications). - Some output may be provided even if flush is not set. - - Before the call of deflate(), the application should ensure that at least - one of the actions is possible, by providing more input and/or consuming - more output, and updating avail_in or avail_out accordingly; avail_out - should never be zero before the call. The application can consume the - compressed output when it wants, for example when the output buffer is full - (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK - and with zero avail_out, it must be called again after making room in the - output buffer because there might be more output pending. - - Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to - decide how much data to accumualte before producing output, in order to - maximize compression. - - If the parameter flush is set to Z_SYNC_FLUSH, all pending output is - flushed to the output buffer and the output is aligned on a byte boundary, so - that the decompressor can get all input data available so far. (In particular - avail_in is zero after the call if enough output space has been provided - before the call.) Flushing may degrade compression for some compression - algorithms and so it should be used only when necessary. - - If flush is set to Z_FULL_FLUSH, all output is flushed as with - Z_SYNC_FLUSH, and the compression state is reset so that decompression can - restart from this point if previous compressed data has been damaged or if - random access is desired. Using Z_FULL_FLUSH too often can seriously degrade - compression. - - If deflate returns with avail_out == 0, this function must be called again - with the same value of the flush parameter and more output space (updated - avail_out), until the flush is complete (deflate returns with non-zero - avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that - avail_out is greater than six to avoid repeated flush markers due to - avail_out == 0 on return. - - If the parameter flush is set to Z_FINISH, pending input is processed, - pending output is flushed and deflate returns with Z_STREAM_END if there - was enough output space; if deflate returns with Z_OK, this function must be - called again with Z_FINISH and more output space (updated avail_out) but no - more input data, until it returns with Z_STREAM_END or an error. After - deflate has returned Z_STREAM_END, the only possible operations on the - stream are deflateReset or deflateEnd. - - Z_FINISH can be used immediately after deflateInit if all the compression - is to be done in a single step. In this case, avail_out must be at least - the value returned by deflateBound (see below). If deflate does not return - Z_STREAM_END, then it must be called again as described above. - - deflate() sets strm->adler to the adler32 checksum of all input read - so far (that is, total_in bytes). - - deflate() may update strm->data_type if it can make a good guess about - the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered - binary. This field is only for information purposes and does not affect - the compression algorithm in any manner. - - deflate() returns Z_OK if some progress has been made (more input - processed or more output produced), Z_STREAM_END if all input has been - consumed and all output has been produced (only when flush is set to - Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example - if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible - (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not - fatal, and deflate() can be called again with more input and more output - space to continue compressing. -*/ + * deflate compresses as much data as possible, and stops when the input + * buffer becomes empty or the output buffer becomes full. It may + * output latency (reading input without producing any output) except when + * forced to flush. + * + * The detailed semantics are as follows. deflate performs one or both of the + * following actions: + * + * - Compress more input starting at next_in and update next_in and avail_in + * accordingly. If not all input can be processed (because there is not + * enough room in the output buffer), next_in and avail_in are updated and + * processing will resume at this point for the next call of deflate(). + * + * - Provide more output starting at next_out and update next_out and avail_out + * accordingly. This action is forced if the parameter flush is non zero. + * Forcing flush frequently degrades the compression ratio, so this parameter + * should be set only when necessary (in interactive applications). + * Some output may be provided even if flush is not set. + * + * Before the call of deflate(), the application should ensure that at least + * one of the actions is possible, by providing more input and/or consuming + * more output, and updating avail_in or avail_out accordingly; avail_out + * should never be zero before the call. The application can consume the + * compressed output when it wants, for example when the output buffer is full + * (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK + * and with zero avail_out, it must be called again after making room in the + * output buffer because there might be more output pending. + * + * Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to + * decide how much data to accumualte before producing output, in order to + * maximize compression. + * + * If the parameter flush is set to Z_SYNC_FLUSH, all pending output is + * flushed to the output buffer and the output is aligned on a byte + * that the decompressor can get all input data available so far. + * avail_in is zero after the call if enough output space has been provided + * before the call.) Flushing may degrade compression for some compression + * algorithms and so it should be used only when necessary. + * + * If flush is set to Z_FULL_FLUSH, all output is flushed as with + * Z_SYNC_FLUSH, and the compression state is reset so that decompression can + * restart from this point if previous compressed data has been damaged or if + * random access is desired. Using Z_FULL_FLUSH too often can seriously degrade + * compression. + * + * If deflate returns with avail_out == 0, this function must be called again + * with the same value of the flush parameter and more output space (updated + * avail_out), until the flush is complete (deflate returns with non-zero + * avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that + * avail_out is greater than six to avoid repeated flush markers due to + * avail_out == 0 on return. + * + * If the parameter flush is set to Z_FINISH, pending input is processed, + * pending output is flushed and deflate returns with Z_STREAM_END if there + * was enough output space; if deflate returns with Z_OK, this function must be + * called again with Z_FINISH and more output space (updated avail_out) but no + * more input data, until it returns with Z_STREAM_END or an error. After + * deflate has returned Z_STREAM_END, the only possible operations on the + * stream are deflateReset or deflateEnd. + * + * Z_FINISH can be used immediately after deflateInit if all the compression + * is to be done in a single step. In this case, avail_out must be at least + * the value returned by deflateBound (see below). If deflate does not return + * Z_STREAM_END, then it must be called again as described above. + * + * deflate() sets strm->adler to the adler32 checksum of all input read + * so far (that is, total_in bytes). + * + * deflate() may update strm->data_type if it can make a good guess about + * the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered + * binary. This field is only for information purposes and does not affect + * the compression algorithm in any manner. + * + * deflate() returns Z_OK if some progress has been made (more input + * processed or more output produced), Z_STREAM_END if all input has been + * consumed and all output has been produced (only when flush is set to + * Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example + * if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible + * (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not + * fatal, and deflate() can be called again with more input and more output + * space to continue compressing. + */ ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); /* - All dynamically allocated data structures for this stream are freed. - This function discards any unprocessed input and does not flush any - pending output. + * All dynamically allocated data structures for this stream are freed. + * This function discards any unprocessed input and does not flush any + * pending output. + * + * deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the + * stream state was inconsistent, Z_DATA_ERROR if the stream was freed + * prematurely (some input or output was discarded). In the error case, + * msg may be set but then points to a static string (which must not be + * deallocated). + */ - deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the - stream state was inconsistent, Z_DATA_ERROR if the stream was freed - prematurely (some input or output was discarded). In the error case, - msg may be set but then points to a static string (which must not be - deallocated). -*/ +/* + * ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); + * + * Initializes the internal stream state for decompression. The fields + * next_in, avail_in, zalloc, zfree and opaque must be initialized before by + * the caller. If next_in is not Z_NULL and avail_in is large enough (the exact + * value depends on the compression method), inflateInit determines the + * compression method from the zlib header and allocates all data structures + * accordingly; otherwise the allocation will be deferred to the first call of + * inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to + * use default allocation functions. + * + * inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough + * memory, Z_VERSION_ERROR if the zlib library version is incompatible with the + * version assumed by the caller. msg is set to null if there is no error + * message. inflateInit does not perform any decompression apart from reading + * the zlib header if present: this will be done by inflate(). (So next_in and + * avail_in may be modified, but next_out and avail_out are unchanged.) + */ +ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); /* -ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); + * inflate decompresses as much data as possible, and stops when the input + * buffer becomes empty or the output buffer becomes full. It may introduce + * some output latency (reading input without producing any output) except when + * forced to flush. + * + * The detailed semantics are as follows. inflate performs one or both of the + * following actions: + * + * - Decompress more input starting at next_in and update next_in and avail_in + * accordingly. If not all input can be processed (because there is not + * enough room in the output buffer), next_in is updated and processing + * will resume at this point for the next call of inflate(). + * + * - Provide more output starting at next_out and update next_out and avail_out + * accordingly. inflate() provides as much output as possible, until there + * is no more input data or no more space in the output buffer (see below + * about the flush parameter). + * + * Before the call of inflate(), the application should ensure that at least + * one of the actions is possible, by providing more input and/or consuming + * more output, and updating the next_* and avail_* values accordingly. + * The application can consume the uncompressed output when it wants, for + * example when the output buffer is full (avail_out == 0), or after each + * call of inflate(). If inflate returns Z_OK and with zero avail_out, it + * must be called again after making room in the output buffer because there + * might be more output pending. + * + * The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, + * Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much + * output as possible to the output buffer. Z_BLOCK requests that inflate() + * if and when it gets to the next deflate block boundary. When decoding the + * zlib or gzip format, this will cause inflate() to return immediately after + * the header and before the first block. When doing a raw inflate, inflate() + * will go ahead and process the first block, and will return when it gets to + * the end of that block, or when it runs out of data. + * + * The Z_BLOCK option assists in appending to or combining deflate streams. + * Also to assist in this, on return inflate() will set strm->data_type to the + * number of unused bits in the last byte taken from strm->next_in, plus 64 + * if inflate() is currently decoding the last block in the deflate stream, + * plus 128 if inflate() returned immediately after decoding an end-of-block + * code or decoding the complete header up to just before the first byte of the + * deflate stream. The end-of-block will not be indicated until all of the + * uncompressed data from that block has been written to strm->next_out. The + * number of unused bits may in general be greater than seven, except when + * bit 7 of data_type is set, in which case the number of unused bits will be + * less than eight. + * + * inflate() should normally be called until it returns Z_STREAM_END or an + * error. However if all decompression is to be performed in a single step + * (a single call of inflate), the parameter flush should be set to + * Z_FINISH. In this case all pending input is processed and all pending + * output is flushed; avail_out must be large enough to hold all the + * uncompressed data. (The size of the uncompressed data may have been saved + * by the compressor for this purpose.) The next operation on this stream must + * be inflateEnd to deallocate the decompression state. The use of Z_FINISH + * is never required, but can be used to inform inflate that a faster approach + * may be used for the single inflate() call. + * + * In this implementation, inflate() always flushes as much output as + * possible to the output buffer, and always uses the faster approach on the + * first call. So the only effect of the flush parameter in this implementation + * is on the return value of inflate(), as noted below, or when it returns + * because Z_BLOCK is used. + * + * If a preset dictionary is needed after this call (see + * below), inflate sets strm->adler to the adler32 checksum of the dictionary + * chosen by the compressor and returns Z_NEED_DICT; otherwise it sets + * strm->adler to the adler32 checksum of all output produced so far (that is, + * total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as + * below. At the end of the stream, inflate() checks that its computed adler32 + * checksum is equal to that saved by the compressor and returns Z_STREAM_END + * only if the checksum is correct. + * + * inflate() will decompress and check either zlib-wrapped or gzip-wrapped + * deflate data. The header type is detected automatically. Any information + * contained in the gzip header is not retained, so applications that need that + * information should instead use raw inflate, see inflateInit2() below, or + * inflateBack() and perform their own processing of the gzip header and + * trailer. + * + * inflate() returns Z_OK if some progress has been made (more input + * or more output produced), Z_STREAM_END if the end of the compressed data has + * been reached and all uncompressed output has been produced, Z_NEED_DICT if a + * preset dictionary is needed at this point, Z_DATA_ERROR if the input data + * corrupted (input stream not conforming to the zlib format or incorrect check + * value), Z_STREAM_ERROR if the stream structure was inconsistent (for example + * if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough + * Z_BUF_ERROR if no progress is possible or if there was not enough room in + * output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and + * inflate() can be called again with more input and more output space to + * continue decompressing. If Z_DATA_ERROR is returned, the application may + * call inflateSync() to look for a good compression block if a partial + * of the data is desired. + */ - Initializes the internal stream state for decompression. The fields - next_in, avail_in, zalloc, zfree and opaque must be initialized before by - the caller. If next_in is not Z_NULL and avail_in is large enough (the exact - value depends on the compression method), inflateInit determines the - compression method from the zlib header and allocates all data structures - accordingly; otherwise the allocation will be deferred to the first call of - inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to - use default allocation functions. - inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_VERSION_ERROR if the zlib library version is incompatible with the - version assumed by the caller. msg is set to null if there is no error - message. inflateInit does not perform any decompression apart from reading - the zlib header if present: this will be done by inflate(). (So next_in and - avail_in may be modified, but next_out and avail_out are unchanged.) -*/ +ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); +/* + * All dynamically allocated data structures for this stream are freed. + * This function discards any unprocessed input and does not flush any + * pending output. + * + * inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state + * was inconsistent. In the error case, msg may be set but then points to a + * static string (which must not be deallocated). + */ + /* Advanced functions */ -ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); /* - inflate decompresses as much data as possible, and stops when the input - buffer becomes empty or the output buffer becomes full. It may introduce - some output latency (reading input without producing any output) except when - forced to flush. - - The detailed semantics are as follows. inflate performs one or both of the - following actions: - - - Decompress more input starting at next_in and update next_in and avail_in - accordingly. If not all input can be processed (because there is not - enough room in the output buffer), next_in is updated and processing - will resume at this point for the next call of inflate(). - - - Provide more output starting at next_out and update next_out and avail_out - accordingly. inflate() provides as much output as possible, until there - is no more input data or no more space in the output buffer (see below - about the flush parameter). - - Before the call of inflate(), the application should ensure that at least - one of the actions is possible, by providing more input and/or consuming - more output, and updating the next_* and avail_* values accordingly. - The application can consume the uncompressed output when it wants, for - example when the output buffer is full (avail_out == 0), or after each - call of inflate(). If inflate returns Z_OK and with zero avail_out, it - must be called again after making room in the output buffer because there - might be more output pending. - - The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, - Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much - output as possible to the output buffer. Z_BLOCK requests that inflate() stop - if and when it gets to the next deflate block boundary. When decoding the - zlib or gzip format, this will cause inflate() to return immediately after - the header and before the first block. When doing a raw inflate, inflate() - will go ahead and process the first block, and will return when it gets to - the end of that block, or when it runs out of data. - - The Z_BLOCK option assists in appending to or combining deflate streams. - Also to assist in this, on return inflate() will set strm->data_type to the - number of unused bits in the last byte taken from strm->next_in, plus 64 - if inflate() is currently decoding the last block in the deflate stream, - plus 128 if inflate() returned immediately after decoding an end-of-block - code or decoding the complete header up to just before the first byte of the - deflate stream. The end-of-block will not be indicated until all of the - uncompressed data from that block has been written to strm->next_out. The - number of unused bits may in general be greater than seven, except when - bit 7 of data_type is set, in which case the number of unused bits will be - less than eight. - - inflate() should normally be called until it returns Z_STREAM_END or an - error. However if all decompression is to be performed in a single step - (a single call of inflate), the parameter flush should be set to - Z_FINISH. In this case all pending input is processed and all pending - output is flushed; avail_out must be large enough to hold all the - uncompressed data. (The size of the uncompressed data may have been saved - by the compressor for this purpose.) The next operation on this stream must - be inflateEnd to deallocate the decompression state. The use of Z_FINISH - is never required, but can be used to inform inflate that a faster approach - may be used for the single inflate() call. - - In this implementation, inflate() always flushes as much output as - possible to the output buffer, and always uses the faster approach on the - first call. So the only effect of the flush parameter in this implementation - is on the return value of inflate(), as noted below, or when it returns early - because Z_BLOCK is used. - - If a preset dictionary is needed after this call (see inflateSetDictionary - below), inflate sets strm->adler to the adler32 checksum of the dictionary - chosen by the compressor and returns Z_NEED_DICT; otherwise it sets - strm->adler to the adler32 checksum of all output produced so far (that is, - total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described - below. At the end of the stream, inflate() checks that its computed adler32 - checksum is equal to that saved by the compressor and returns Z_STREAM_END - only if the checksum is correct. - - inflate() will decompress and check either zlib-wrapped or gzip-wrapped - deflate data. The header type is detected automatically. Any information - contained in the gzip header is not retained, so applications that need that - information should instead use raw inflate, see inflateInit2() below, or - inflateBack() and perform their own processing of the gzip header and - trailer. - - inflate() returns Z_OK if some progress has been made (more input processed - or more output produced), Z_STREAM_END if the end of the compressed data has - been reached and all uncompressed output has been produced, Z_NEED_DICT if a - preset dictionary is needed at this point, Z_DATA_ERROR if the input data was - corrupted (input stream not conforming to the zlib format or incorrect check - value), Z_STREAM_ERROR if the stream structure was inconsistent (for example - if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory, - Z_BUF_ERROR if no progress is possible or if there was not enough room in the - output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and - inflate() can be called again with more input and more output space to - continue decompressing. If Z_DATA_ERROR is returned, the application may then - call inflateSync() to look for a good compression block if a partial recovery - of the data is desired. -*/ - + * The following functions are needed only in some special applications. + */ -ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); /* - All dynamically allocated data structures for this stream are freed. - This function discards any unprocessed input and does not flush any - pending output. - - inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state - was inconsistent. In the error case, msg may be set but then points to a - static string (which must not be deallocated). -*/ - - /* Advanced functions */ - -/* - The following functions are needed only in some special applications. -*/ - -/* -ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, - int level, - int method, - int windowBits, - int memLevel, - int strategy)); - - This is another version of deflateInit with more compression options. The - fields next_in, zalloc, zfree and opaque must be initialized before by - the caller. - - The method parameter is the compression method. It must be Z_DEFLATED in - this version of the library. - - The windowBits parameter is the base two logarithm of the window size - (the size of the history buffer). It should be in the range 8..15 for this - version of the library. Larger values of this parameter result in better - compression at the expense of memory usage. The default value is 15 if - deflateInit is used instead. - - windowBits can also be -8..-15 for raw deflate. In this case, -windowBits - determines the window size. deflate() will then generate raw deflate data - with no zlib header or trailer, and will not compute an adler32 check value. - - windowBits can also be greater than 15 for optional gzip encoding. Add - 16 to windowBits to write a simple gzip header and trailer around the - compressed data instead of a zlib wrapper. The gzip header will have no - file name, no extra data, no comment, no modification time (set to zero), - no header crc, and the operating system will be set to 255 (unknown). If a - gzip stream is being written, strm->adler is a crc32 instead of an adler32. - - The memLevel parameter specifies how much memory should be allocated - for the internal compression state. memLevel=1 uses minimum memory but - is slow and reduces compression ratio; memLevel=9 uses maximum memory - for optimal speed. The default value is 8. See zconf.h for total memory - usage as a function of windowBits and memLevel. - - The strategy parameter is used to tune the compression algorithm. Use the - value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a - filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no - string match), or Z_RLE to limit match distances to one (run-length - encoding). Filtered data consists mostly of small values with a somewhat - random distribution. In this case, the compression algorithm is tuned to - compress them better. The effect of Z_FILTERED is to force more Huffman - coding and less string matching; it is somewhat intermediate between - Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as - Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy - parameter only affects the compression ratio but not the correctness of the - compressed output even if it is not set appropriately. Z_FIXED prevents the - use of dynamic Huffman codes, allowing for a simpler decoder for special - applications. - - deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid - method). msg is set to null if there is no error message. deflateInit2 does - not perform any compression: this will be done by deflate(). -*/ + * ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, + * int level, + * int method, + * int windowBits, + * int memLevel, + * int strategy)); + * + * This is another version of deflateInit with more compression options. The + * fields next_in, zalloc, zfree and opaque must be initialized before by + * the caller. + * + * The method parameter is the compression method. It must be Z_DEFLATED in + * this version of the library. + * + * The windowBits parameter is the base two logarithm of the window size + * (the size of the history buffer). It should be in the range 8..15 for this + * version of the library. Larger values of this parameter result in better + * compression at the expense of memory usage. The default value is 15 if + * deflateInit is used instead. + * + * windowBits can also be -8..-15 for raw deflate. In this case, -windowBits + * determines the window size. deflate() will then generate raw deflate data + * with no zlib header or trailer, and will not compute an adler32 check + * + * windowBits can also be greater than 15 for optional gzip encoding. Add + * 16 to windowBits to write a simple gzip header and trailer around the + * compressed data instead of a zlib wrapper. The gzip header will have no + * file name, no extra data, no comment, no modification time (set to zero), + * no header crc, and the operating system will be set to 255 (unknown). If a + * gzip stream is being written, strm->adler is a crc32 instead of an adler32. + * + * The memLevel parameter specifies how much memory should be allocated + * for the internal compression state. memLevel=1 uses minimum memory but + * is slow and reduces compression ratio; memLevel=9 uses maximum memory + * for optimal speed. The default value is 8. See zconf.h for total memory + * usage as a function of windowBits and memLevel. + * + * The strategy parameter is used to tune the compression algorithm. Use the + * value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a + * filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no + * string match), or Z_RLE to limit match distances to one (run-length + * encoding). Filtered data consists mostly of small values with a somewhat + * random distribution. In this case, the compression algorithm is tuned to + * compress them better. The effect of Z_FILTERED is to force more Huffman + * coding and less string matching; it is somewhat intermediate between + * Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as + * Z_HUFFMAN_ONLY, but give better compression for PNG image data. The + * parameter only affects the compression ratio but not the correctness of the + * compressed output even if it is not set appropriately. Z_FIXED prevents + * use of dynamic Huffman codes, allowing for a simpler decoder for special + * applications. + * + * deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not + * memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid + * method). msg is set to null if there is no error message. deflateInit2 + * not perform any compression: this will be done by deflate(). + */ ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, - const Bytef *dictionary, - uInt dictLength)); -/* - Initializes the compression dictionary from the given byte sequence - without producing any compressed output. This function must be called - immediately after deflateInit, deflateInit2 or deflateReset, before any - call of deflate. The compressor and decompressor must use exactly the same - dictionary (see inflateSetDictionary). - - The dictionary should consist of strings (byte sequences) that are likely - to be encountered later in the data to be compressed, with the most commonly - used strings preferably put towards the end of the dictionary. Using a - dictionary is most useful when the data to be compressed is short and can be - predicted with good accuracy; the data can then be compressed better than - with the default empty dictionary. - - Depending on the size of the compression data structures selected by - deflateInit or deflateInit2, a part of the dictionary may in effect be - discarded, for example if the dictionary is larger than the window size in - deflate or deflate2. Thus the strings most likely to be useful should be - put at the end of the dictionary, not at the front. In addition, the - current implementation of deflate will use at most the window size minus - 262 bytes of the provided dictionary. - - Upon return of this function, strm->adler is set to the adler32 value - of the dictionary; the decompressor may later use this value to determine - which dictionary has been used by the compressor. (The adler32 value - applies to the whole dictionary even if only a subset of the dictionary is - actually used by the compressor.) If a raw deflate was requested, then the - adler32 value is not computed and strm->adler is not set. - - deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a - parameter is invalid (such as NULL dictionary) or the stream state is - inconsistent (for example if deflate has already been called for this stream - or if the compression method is bsort). deflateSetDictionary does not - perform any compression: this will be done by deflate(). -*/ + const Bytef *dictionary, + uInt dictLength)); +/* + * Initializes the compression dictionary from the given byte sequence + * without producing any compressed output. This function must be called + * immediately after deflateInit, deflateInit2 or deflateReset, before any + * call of deflate. The compressor and decompressor must use exactly the same + * dictionary (see inflateSetDictionary). + * + * The dictionary should consist of strings (byte sequences) that are likely + * to be encountered later in the data to be compressed, with the most + * used strings preferably put towards the end of the dictionary. Using a + * dictionary is most useful when the data to be compressed is short and can + * predicted with good accuracy; the data can then be compressed better than + * with the default empty dictionary. + * + * Depending on the size of the compression data structures selected by + * deflateInit or deflateInit2, a part of the dictionary may in effect be + * discarded, for example if the dictionary is larger than the window size in + * deflate or deflate2. Thus the strings most likely to be useful should be + * put at the end of the dictionary, not at the front. In addition, the + * current implementation of deflate will use at most the window size minus + * 262 bytes of the provided dictionary. + * + * Upon return of this function, strm->adler is set to the adler32 value + * of the dictionary; the decompressor may later use this value to determine + * which dictionary has been used by the compressor. (The adler32 value + * applies to the whole dictionary even if only a subset of the dictionary is + * actually used by the compressor.) If a raw deflate was requested, then the + * adler32 value is not computed and strm->adler is not set. + * + * deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a + * parameter is invalid (such as NULL dictionary) or the stream state is + * inconsistent (for example if deflate has already been called for this + * or if the compression method is bsort). deflateSetDictionary does not + * perform any compression: this will be done by deflate(). + */ ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, - z_streamp source)); + z_streamp source)); /* - Sets the destination stream as a complete copy of the source stream. - - This function can be useful when several compression strategies will be - tried, for example when there are several ways of pre-processing the input - data with a filter. The streams that will be discarded should then be freed - by calling deflateEnd. Note that deflateCopy duplicates the internal - compression state which can be quite large, so this strategy is slow and - can consume lots of memory. - - deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_STREAM_ERROR if the source stream state was inconsistent - (such as zalloc being NULL). msg is left unchanged in both source and - destination. -*/ + * Sets the destination stream as a complete copy of the source stream. + * + * This function can be useful when several compression strategies will be + * tried, for example when there are several ways of pre-processing the input + * data with a filter. The streams that will be discarded should then be freed + * by calling deflateEnd. Note that deflateCopy duplicates the internal + * compression state which can be quite large, so this strategy is slow and + * can consume lots of memory. + * + * deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + * enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + * (such as zalloc being NULL). msg is left unchanged in both source and + * destination. + */ ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); /* - This function is equivalent to deflateEnd followed by deflateInit, - but does not free and reallocate all the internal compression state. - The stream will keep the same compression level and any other attributes - that may have been set by deflateInit2. - - deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent (such as zalloc or state being NULL). -*/ + * This function is equivalent to deflateEnd followed by deflateInit, + * but does not free and reallocate all the internal compression state. + * The stream will keep the same compression level and any other attributes + * that may have been set by deflateInit2. + * + * deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + * stream state was inconsistent (such as zalloc or state being NULL). + */ ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, - int level, - int strategy)); -/* - Dynamically update the compression level and compression strategy. The - interpretation of level and strategy is as in deflateInit2. This can be - used to switch between compression and straight copy of the input data, or - to switch to a different kind of input data requiring a different - strategy. If the compression level is changed, the input available so far - is compressed with the old level (and may be flushed); the new level will - take effect only at the next call of deflate(). - - Before the call of deflateParams, the stream state must be set as for - a call of deflate(), since the currently available input may have to - be compressed and flushed. In particular, strm->avail_out must be non-zero. - - deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source - stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR - if strm->avail_out was zero. -*/ + int level, + int strategy)); +/* + * Dynamically update the compression level and compression strategy. The + * interpretation of level and strategy is as in deflateInit2. This can be + * used to switch between compression and straight copy of the input data, or + * to switch to a different kind of input data requiring a different + * strategy. If the compression level is changed, the input available so far + * is compressed with the old level (and may be flushed); the new level will + * take effect only at the next call of deflate(). + * + * Before the call of deflateParams, the stream state must be set as for + * a call of deflate(), since the currently available input may have to + * be compressed and flushed. In particular, strm->avail_out must be non-zero. + * + * deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source + * stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR + * if strm->avail_out was zero. + */ ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm, - int good_length, - int max_lazy, - int nice_length, - int max_chain)); + int good_length, + int max_lazy, + int nice_length, + int max_chain)); /* - Fine tune deflate's internal compression parameters. This should only be - used by someone who understands the algorithm used by zlib's deflate for - searching for the best matching string, and even then only by the most - fanatic optimizer trying to squeeze out the last compressed bit for their - specific input data. Read the deflate.c source code for the meaning of the - max_lazy, good_length, nice_length, and max_chain parameters. - - deflateTune() can be called after deflateInit() or deflateInit2(), and - returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. + * Fine tune deflate's internal compression parameters. This should only be + * used by someone who understands the algorithm used by zlib's deflate for + * searching for the best matching string, and even then only by the most + * fanatic optimizer trying to squeeze out the last compressed bit for their + * specific input data. Read the deflate.c source code for the meaning of the + * max_lazy, good_length, nice_length, and max_chain parameters. + * + * deflateTune() can be called after deflateInit() or deflateInit2(), and + * returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. */ ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, - uLong sourceLen)); + uLong sourceLen)); /* - deflateBound() returns an upper bound on the compressed size after - deflation of sourceLen bytes. It must be called after deflateInit() - or deflateInit2(). This would be used to allocate an output buffer - for deflation in a single pass, and so would be called before deflate(). -*/ + * deflateBound() returns an upper bound on the compressed size after + * deflation of sourceLen bytes. It must be called after deflateInit() + * or deflateInit2(). This would be used to allocate an output buffer + * for deflation in a single pass, and so would be called before deflate(). + */ ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, - int bits, - int value)); + int bits, + int value)); /* - deflatePrime() inserts bits in the deflate output stream. The intent - is that this function is used to start off the deflate output with the - bits leftover from a previous deflate stream when appending to it. As such, - this function can only be used for raw deflate, and must be used before the - first deflate() call after a deflateInit2() or deflateReset(). bits must be - less than or equal to 16, and that many of the least significant bits of - value will be inserted in the output. - - deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ + * deflatePrime() inserts bits in the deflate output stream. The intent + * is that this function is used to start off the deflate output with the + * bits leftover from a previous deflate stream when appending to it. As such, + * this function can only be used for raw deflate, and must be used before the + * first deflate() call after a deflateInit2() or deflateReset(). bits must be + * less than or equal to 16, and that many of the least significant bits of + * value will be inserted in the output. + * + * deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source + * stream state was inconsistent. + */ ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, - gz_headerp head)); -/* - deflateSetHeader() provides gzip header information for when a gzip - stream is requested by deflateInit2(). deflateSetHeader() may be called - after deflateInit2() or deflateReset() and before the first call of - deflate(). The text, time, os, extra field, name, and comment information - in the provided gz_header structure are written to the gzip header (xflag is - ignored -- the extra flags are set according to the compression level). The - caller must assure that, if not Z_NULL, name and comment are terminated with - a zero byte, and that if extra is not Z_NULL, that extra_len bytes are - available there. If hcrc is true, a gzip header crc is included. Note that - the current versions of the command-line version of gzip (up through version - 1.3.x) do not support header crc's, and will report that it is a "multi-part - gzip file" and give up. - - If deflateSetHeader is not used, the default gzip header has text false, - the time set to zero, and os set to 255, with no extra, name, or comment - fields. The gzip header is returned to the default state by deflateReset(). - - deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -/* -ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, - int windowBits)); - - This is another version of inflateInit with an extra parameter. The - fields next_in, avail_in, zalloc, zfree and opaque must be initialized - before by the caller. - - The windowBits parameter is the base two logarithm of the maximum window - size (the size of the history buffer). It should be in the range 8..15 for - this version of the library. The default value is 15 if inflateInit is used - instead. windowBits must be greater than or equal to the windowBits value - provided to deflateInit2() while compressing, or it must be equal to 15 if - deflateInit2() was not used. If a compressed stream with a larger window - size is given as input, inflate() will return with the error code - Z_DATA_ERROR instead of trying to allocate a larger window. - - windowBits can also be -8..-15 for raw inflate. In this case, -windowBits - determines the window size. inflate() will then process raw deflate data, - not looking for a zlib or gzip header, not generating a check value, and not - looking for any check values for comparison at the end of the stream. This - is for use with other formats that use the deflate compressed data format - such as zip. Those formats provide their own check values. If a custom - format is developed using the raw deflate format for compressed data, it is - recommended that a check value such as an adler32 or a crc32 be applied to - the uncompressed data as is done in the zlib, gzip, and zip formats. For - most applications, the zlib format should be used as is. Note that comments - above on the use in deflateInit2() applies to the magnitude of windowBits. - - windowBits can also be greater than 15 for optional gzip decoding. Add - 32 to windowBits to enable zlib and gzip decoding with automatic header - detection, or add 16 to decode only the gzip format (the zlib format will - return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is - a crc32 instead of an adler32. - - inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg - is set to null if there is no error message. inflateInit2 does not perform - any decompression apart from reading the zlib header if present: this will - be done by inflate(). (So next_in and avail_in may be modified, but next_out - and avail_out are unchanged.) -*/ + gz_headerp head)); +/* + * deflateSetHeader() provides gzip header information for when a gzip + * stream is requested by deflateInit2(). deflateSetHeader() may be called + * after deflateInit2() or deflateReset() and before the first call of + * deflate(). The text, time, os, extra field, name, and comment information + * in the provided gz_header structure are written to the gzip header (xflag + * ignored -- the extra flags are set according to the compression level). + * caller must assure that, if not Z_NULL, name and comment are terminated + * a zero byte, and that if extra is not Z_NULL, that extra_len bytes are + * available there. If hcrc is true, a gzip header crc is included. Note + * the current versions of the command-line version of gzip (up through + * 1.3.x) do not support header crc's, and will report that it is a "multi- + * gzip file" and give up. + * + * If deflateSetHeader is not used, the default gzip header has text false, + * the time set to zero, and os set to 255, with no extra, name, or comment + * fields. The gzip header is returned to the default state by deflateReset(). + * + * deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + * stream state was inconsistent. + */ + +/* + * ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, + * int windowBits)); + * + * This is another version of inflateInit with an extra parameter. The + * fields next_in, avail_in, zalloc, zfree and opaque must be initialized + * before by the caller. + * + * The windowBits parameter is the base two logarithm of the maximum window + * size (the size of the history buffer). It should be in the range 8..15 for + * this version of the library. The default value is 15 if inflateInit is used + * instead. windowBits must be greater than or equal to the windowBits value + * provided to deflateInit2() while compressing, or it must be equal to 15 if + * deflateInit2() was not used. If a compressed stream with a larger window + * size is given as input, inflate() will return with the error code + * Z_DATA_ERROR instead of trying to allocate a larger window. + * + * windowBits can also be -8..-15 for raw inflate. In this case, -windowBits + * determines the window size. inflate() will then process raw deflate data, + * not looking for a zlib or gzip header, not generating a check value, and not + * looking for any check values for comparison at the end of the stream. This + * is for use with other formats that use the deflate compressed data format + * such as zip. Those formats provide their own check values. If a custom + * format is developed using the raw deflate format for compressed data, it is + * recommended that a check value such as an adler32 or a crc32 be applied to + * the uncompressed data as is done in the zlib, gzip, and zip formats. For + * most applications, the zlib format should be used as is. Note that comments + * above on the use in deflateInit2() applies to the magnitude of windowBits. + * + * windowBits can also be greater than 15 for optional gzip decoding. Add + * 32 to windowBits to enable zlib and gzip decoding with automatic header + * detection, or add 16 to decode only the gzip format (the zlib format will + * return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is + * a crc32 instead of an adler32. + * + * inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + * memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg + * is set to null if there is no error message. inflateInit2 does not perform + * any decompression apart from reading the zlib header if present: this will + * be done by inflate(). (So next_in and avail_in may be modified, but next_out + * and avail_out are unchanged.) + */ ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, - const Bytef *dictionary, - uInt dictLength)); -/* - Initializes the decompression dictionary from the given uncompressed byte - sequence. This function must be called immediately after a call of inflate, - if that call returned Z_NEED_DICT. The dictionary chosen by the compressor - can be determined from the adler32 value returned by that call of inflate. - The compressor and decompressor must use exactly the same dictionary (see - deflateSetDictionary). For raw inflate, this function can be called - immediately after inflateInit2() or inflateReset() and before any call of - inflate() to set the dictionary. The application must insure that the - dictionary that was used for compression is provided. - - inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a - parameter is invalid (such as NULL dictionary) or the stream state is - inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the - expected one (incorrect adler32 value). inflateSetDictionary does not - perform any decompression: this will be done by subsequent calls of - inflate(). -*/ + const Bytef *dictionary, + uInt dictLength)); +/* + * Initializes the decompression dictionary from the given uncompressed byte + * sequence. This function must be called immediately after a call of inflate, + * if that call returned Z_NEED_DICT. The dictionary chosen by the compressor + * can be determined from the adler32 value returned by that call of inflate. + * The compressor and decompressor must use exactly the same dictionary (see + * deflateSetDictionary). For raw inflate, this function can be called + * immediately after inflateInit2() or inflateReset() and before any call of + * inflate() to set the dictionary. The application must insure that the + * dictionary that was used for compression is provided. + * + * inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a + * parameter is invalid (such as NULL dictionary) or the stream state is + * inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the + * expected one (incorrect adler32 value). inflateSetDictionary does not + * perform any decompression: this will be done by subsequent calls of + * inflate(). + */ ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); /* - Skips invalid compressed data until a full flush point (see above the - description of deflate with Z_FULL_FLUSH) can be found, or until all - available input is skipped. No output is provided. - - inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR - if no more input was provided, Z_DATA_ERROR if no flush point has been found, - or Z_STREAM_ERROR if the stream structure was inconsistent. In the success - case, the application may save the current current value of total_in which - indicates where valid compressed data was found. In the error case, the - application may repeatedly call inflateSync, providing more input each time, - until success or end of the input data. -*/ + * Skips invalid compressed data until a full flush point (see above the + * description of deflate with Z_FULL_FLUSH) can be found, or until all + * available input is skipped. No output is provided. + * + * inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR + * if no more input was provided, Z_DATA_ERROR if no flush point has been + * or Z_STREAM_ERROR if the stream structure was inconsistent. In the success + * case, the application may save the current current value of total_in which + * indicates where valid compressed data was found. In the error case, the + * application may repeatedly call inflateSync, providing more input each time, + * until success or end of the input data. + */ ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, - z_streamp source)); + z_streamp source)); /* - Sets the destination stream as a complete copy of the source stream. - - This function can be useful when randomly accessing a large stream. The - first pass through the stream can periodically record the inflate state, - allowing restarting inflate at those points when randomly accessing the - stream. - - inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_STREAM_ERROR if the source stream state was inconsistent - (such as zalloc being NULL). msg is left unchanged in both source and - destination. -*/ + * Sets the destination stream as a complete copy of the source stream. + * + * This function can be useful when randomly accessing a large stream. The + * first pass through the stream can periodically record the inflate state, + * allowing restarting inflate at those points when randomly accessing the + * stream. + * + * inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + * enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + * (such as zalloc being NULL). msg is left unchanged in both source and + * destination. + */ ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); /* - This function is equivalent to inflateEnd followed by inflateInit, - but does not free and reallocate all the internal decompression state. - The stream will keep attributes that may have been set by inflateInit2. - - inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent (such as zalloc or state being NULL). -*/ + * This function is equivalent to inflateEnd followed by inflateInit, + * but does not free and reallocate all the internal decompression state. + * The stream will keep attributes that may have been set by inflateInit2. + * + * inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + * stream state was inconsistent (such as zalloc or state being NULL). + */ ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm, - int bits, - int value)); + int bits, + int value)); /* - This function inserts bits in the inflate input stream. The intent is - that this function is used to start inflating at a bit position in the - middle of a byte. The provided bits will be used before any bytes are used - from next_in. This function should only be used with raw inflate, and - should be used before the first inflate() call after inflateInit2() or - inflateReset(). bits must be less than or equal to 16, and that many of the - least significant bits of value will be inserted in the input. - - inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ + * This function inserts bits in the inflate input stream. The intent is + * that this function is used to start inflating at a bit position in the + * middle of a byte. The provided bits will be used before any bytes are used + * from next_in. This function should only be used with raw inflate, and + * should be used before the first inflate() call after inflateInit2() or + * inflateReset(). bits must be less than or equal to 16, and that many of the + * least significant bits of value will be inserted in the input. + * + * inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source + * stream state was inconsistent. + */ ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm, - gz_headerp head)); -/* - inflateGetHeader() requests that gzip header information be stored in the - provided gz_header structure. inflateGetHeader() may be called after - inflateInit2() or inflateReset(), and before the first call of inflate(). - As inflate() processes the gzip stream, head->done is zero until the header - is completed, at which time head->done is set to one. If a zlib stream is - being decoded, then head->done is set to -1 to indicate that there will be - no gzip header information forthcoming. Note that Z_BLOCK can be used to - force inflate() to return immediately after header processing is complete - and before any actual data is decompressed. - - The text, time, xflags, and os fields are filled in with the gzip header - contents. hcrc is set to true if there is a header CRC. (The header CRC - was valid if done is set to one.) If extra is not Z_NULL, then extra_max - contains the maximum number of bytes to write to extra. Once done is true, - extra_len contains the actual extra field length, and extra contains the - extra field, or that field truncated if extra_max is less than extra_len. - If name is not Z_NULL, then up to name_max characters are written there, - terminated with a zero unless the length is greater than name_max. If - comment is not Z_NULL, then up to comm_max characters are written there, - terminated with a zero unless the length is greater than comm_max. When - any of extra, name, or comment are not Z_NULL and the respective field is - not present in the header, then that field is set to Z_NULL to signal its - absence. This allows the use of deflateSetHeader() with the returned - structure to duplicate the header. However if those fields are set to - allocated memory, then the application will need to save those pointers - elsewhere so that they can be eventually freed. - - If inflateGetHeader is not used, then the header information is simply - discarded. The header is always checked for validity, including the header - CRC if present. inflateReset() will reset the process to discard the header - information. The application would need to call inflateGetHeader() again to - retrieve the header from the next gzip stream. - - inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -/* -ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, - unsigned char FAR *window)); - - Initialize the internal stream state for decompression using inflateBack() - calls. The fields zalloc, zfree and opaque in strm must be initialized - before the call. If zalloc and zfree are Z_NULL, then the default library- - derived memory allocation routines are used. windowBits is the base two - logarithm of the window size, in the range 8..15. window is a caller - supplied buffer of that size. Except for special applications where it is - assured that deflate was used with small window sizes, windowBits must be 15 - and a 32K byte window must be supplied to be able to decompress general - deflate streams. - - See inflateBack() for the usage of these routines. - - inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of - the paramaters are invalid, Z_MEM_ERROR if the internal state could not - be allocated, or Z_VERSION_ERROR if the version of the library does not - match the version of the header file. -*/ + gz_headerp head)); +/* + * inflateGetHeader() requests that gzip header information be stored in the + * provided gz_header structure. inflateGetHeader() may be called after + * inflateInit2() or inflateReset(), and before the first call of inflate(). + * As inflate() processes the gzip stream, head->done is zero until the header + * is completed, at which time head->done is set to one. If a zlib stream is + * being decoded, then head->done is set to -1 to indicate that there will be + * no gzip header information forthcoming. Note that Z_BLOCK can be used to + * force inflate() to return immediately after header processing is complete + * and before any actual data is decompressed. + * + * The text, time, xflags, and os fields are filled in with the gzip header + * contents. hcrc is set to true if there is a header CRC. (The header CRC + * was valid if done is set to one.) If extra is not Z_NULL, then extra_max + * contains the maximum number of bytes to write to extra. Once done is true, + * extra_len contains the actual extra field length, and extra contains the + * extra field, or that field truncated if extra_max is less than extra_len. + * If name is not Z_NULL, then up to name_max characters are written there, + * terminated with a zero unless the length is greater than name_max. If + * comment is not Z_NULL, then up to comm_max characters are written there, + * terminated with a zero unless the length is greater than comm_max. When + * any of extra, name, or comment are not Z_NULL and the respective field is + * not present in the header, then that field is set to Z_NULL to signal its + * absence. This allows the use of deflateSetHeader() with the returned + * structure to duplicate the header. However if those fields are set to + * allocated memory, then the application will need to save those pointers + * elsewhere so that they can be eventually freed. + * + * If inflateGetHeader is not used, then the header information is simply + * discarded. The header is always checked for validity, including the header + * CRC if present. inflateReset() will reset the process to discard the header + * information. The application would need to call inflateGetHeader() again to + * retrieve the header from the next gzip stream. + * + * inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + * stream state was inconsistent. + */ + +/* + * ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, + * unsigned char FAR *window)); + * + * Initialize the internal stream state for decompression using inflateBack() + * calls. The fields zalloc, zfree and opaque in strm must be initialized + * before the call. If zalloc and zfree are Z_NULL, then the default library- + * derived memory allocation routines are used. windowBits is the base two + * logarithm of the window size, in the range 8..15. window is a caller + * supplied buffer of that size. Except for special applications where it is + * assured that deflate was used with small window sizes, windowBits must be 15 + * and a 32K byte window must be supplied to be able to decompress general + * deflate streams. + * + * See inflateBack() for the usage of these routines. + * + * inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of + * the paramaters are invalid, Z_MEM_ERROR if the internal state could not + * be allocated, or Z_VERSION_ERROR if the version of the library does not + * match the version of the header file. + */ typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *)); typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned)); ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm, - in_func in, void FAR *in_desc, - out_func out, void FAR *out_desc)); -/* - inflateBack() does a raw inflate with a single call using a call-back - interface for input and output. This is more efficient than inflate() for - file i/o applications in that it avoids copying between the output and the - sliding window by simply making the window itself the output buffer. This - function trusts the application to not change the output buffer passed by - the output function, at least until inflateBack() returns. - - inflateBackInit() must be called first to allocate the internal state - and to initialize the state with the user-provided window buffer. - inflateBack() may then be used multiple times to inflate a complete, raw - deflate stream with each call. inflateBackEnd() is then called to free - the allocated state. - - A raw deflate stream is one with no zlib or gzip header or trailer. - This routine would normally be used in a utility that reads zip or gzip - files and writes out uncompressed files. The utility would decode the - header and process the trailer on its own, hence this routine expects - only the raw deflate stream to decompress. This is different from the - normal behavior of inflate(), which expects either a zlib or gzip header and - trailer around the deflate stream. - - inflateBack() uses two subroutines supplied by the caller that are then - called by inflateBack() for input and output. inflateBack() calls those - routines until it reads a complete deflate stream and writes out all of the - uncompressed data, or until it encounters an error. The function's - parameters and return types are defined above in the in_func and out_func - typedefs. inflateBack() will call in(in_desc, &buf) which should return the - number of bytes of provided input, and a pointer to that input in buf. If - there is no input available, in() must return zero--buf is ignored in that - case--and inflateBack() will return a buffer error. inflateBack() will call - out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out() - should return zero on success, or non-zero on failure. If out() returns - non-zero, inflateBack() will return with an error. Neither in() nor out() - are permitted to change the contents of the window provided to - inflateBackInit(), which is also the buffer that out() uses to write from. - The length written by out() will be at most the window size. Any non-zero - amount of input may be provided by in(). - - For convenience, inflateBack() can be provided input on the first call by - setting strm->next_in and strm->avail_in. If that input is exhausted, then - in() will be called. Therefore strm->next_in must be initialized before - calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called - immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in - must also be initialized, and then if strm->avail_in is not zero, input will - initially be taken from strm->next_in[0 .. strm->avail_in - 1]. - - The in_desc and out_desc parameters of inflateBack() is passed as the - first parameter of in() and out() respectively when they are called. These - descriptors can be optionally used to pass any information that the caller- - supplied in() and out() functions need to do their job. - - On return, inflateBack() will set strm->next_in and strm->avail_in to - pass back any unused input that was provided by the last in() call. The - return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR - if in() or out() returned an error, Z_DATA_ERROR if there was a format - error in the deflate stream (in which case strm->msg is set to indicate the - nature of the error), or Z_STREAM_ERROR if the stream was not properly - initialized. In the case of Z_BUF_ERROR, an input or output error can be - distinguished using strm->next_in which will be Z_NULL only if in() returned - an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to - out() returning non-zero. (in() will always be called before out(), so - strm->next_in is assured to be defined if out() returns non-zero.) Note - that inflateBack() cannot return Z_OK. -*/ + in_func in, void FAR *in_desc, + out_func out, void FAR *out_desc)); +/* + * inflateBack() does a raw inflate with a single call using a call-back + * interface for input and output. This is more efficient than inflate() for + * file i/o applications in that it avoids copying between the output and the + * sliding window by simply making the window itself the output buffer. This + * function trusts the application to not change the output buffer passed by + * the output function, at least until inflateBack() returns. + * + * inflateBackInit() must be called first to allocate the internal state + * and to initialize the state with the user-provided window buffer. + * inflateBack() may then be used multiple times to inflate a complete, raw + * deflate stream with each call. inflateBackEnd() is then called to free + * the allocated state. + * + * A raw deflate stream is one with no zlib or gzip header or trailer. + * This routine would normally be used in a utility that reads zip or gzip + * files and writes out uncompressed files. The utility would decode the + * header and process the trailer on its own, hence this routine expects + * only the raw deflate stream to decompress. This is different from the + * normal behavior of inflate(), which expects either a zlib or gzip header and + * trailer around the deflate stream. + * + * inflateBack() uses two subroutines supplied by the caller that are then + * called by inflateBack() for input and output. inflateBack() calls those + * routines until it reads a complete deflate stream and writes out all of the + * uncompressed data, or until it encounters an error. The function's + * parameters and return types are defined above in the in_func and out_func + * typedefs. inflateBack() will call in(in_desc, &buf) which should return the + * number of bytes of provided input, and a pointer to that input in buf. If + * there is no input available, in() must return zero--buf is ignored in that + * case--and inflateBack() will return a buffer error. inflateBack() will call + * out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out() + * should return zero on success, or non-zero on failure. If out() returns + * non-zero, inflateBack() will return with an error. Neither in() nor out() + * are permitted to change the contents of the window provided to + * inflateBackInit(), which is also the buffer that out() uses to write from. + * The length written by out() will be at most the window size. Any non-zero + * amount of input may be provided by in(). + * + * For convenience, inflateBack() can be provided input on the first call by + * setting strm->next_in and strm->avail_in. If that input is exhausted, then + * in() will be called. Therefore strm->next_in must be initialized before + * calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called + * immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in + * must also be initialized, and then if strm->avail_in is not zero, input will + * initially be taken from strm->next_in[0 .. strm->avail_in - 1]. + * + * The in_desc and out_desc parameters of inflateBack() is passed as the + * first parameter of in() and out() respectively when they are called. These + * descriptors can be optionally used to pass any information that the caller- + * supplied in() and out() functions need to do their job. + * + * On return, inflateBack() will set strm->next_in and strm->avail_in to + * pass back any unused input that was provided by the last in() call. The + * return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR + * if in() or out() returned an error, Z_DATA_ERROR if there was a format + * error in the deflate stream (in which case strm->msg is set to indicate the + * nature of the error), or Z_STREAM_ERROR if the stream was not properly + * initialized. In the case of Z_BUF_ERROR, an input or output error can be + * distinguished using strm->next_in which will be Z_NULL only if in() returned + * an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to + * out() returning non-zero. (in() will always be called before out(), so + * strm->next_in is assured to be defined if out() returns non-zero.) Note + * that inflateBack() cannot return Z_OK. + */ ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm)); /* - All memory allocated by inflateBackInit() is freed. - - inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream - state was inconsistent. -*/ + * All memory allocated by inflateBackInit() is freed. + * + * inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream + * state was inconsistent. + */ ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); -/* Return flags indicating compile-time options. - - Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: - 1.0: size of uInt - 3.2: size of uLong - 5.4: size of voidpf (pointer) - 7.6: size of z_off_t - - Compiler, assembler, and debug options: - 8: DEBUG - 9: ASMV or ASMINF -- use ASM code - 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention - 11: 0 (reserved) - - One-time table building (smaller code, but not thread-safe if true): - 12: BUILDFIXED -- build static block decoding tables when needed - 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed - 14,15: 0 (reserved) - - Library content (indicates missing functionality): - 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking - deflate code when not needed) - 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect - and decode gzip streams (to avoid linking crc code) - 18-19: 0 (reserved) - - Operation variations (changes in library functionality): - 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate - 21: FASTEST -- deflate algorithm with only one, lowest compression level - 22,23: 0 (reserved) - - The sprintf variant used by gzprintf (zero is best): - 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format - 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure! - 26: 0 = returns value, 1 = void -- 1 means inferred string length returned - - Remainder: - 27-31: 0 (reserved) +/* + * Return flags indicating compile-time options. + * + * Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: + * 1.0: size of uInt + * 3.2: size of uLong + * 5.4: size of voidpf (pointer) + * 7.6: size of z_off_t + * + * Compiler, assembler, and debug options: + * 8: DEBUG + * 9: ASMV or ASMINF -- use ASM code + * 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention + * 11: 0 (reserved) + * + * One-time table building (smaller code, but not thread-safe if true): + * 12: BUILDFIXED -- build static block decoding tables when needed + * 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed + * 14,15: 0 (reserved) + * + * Library content (indicates missing functionality): + * 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking + * deflate code when not needed) + * 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect + * and decode gzip streams (to avoid linking crc code) + * 18-19: 0 (reserved) + * + * Operation variations (changes in library functionality): + * 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate + * 21: FASTEST -- deflate algorithm with only one, lowest compression level + * 22,23: 0 (reserved) + * + * The sprintf variant used by gzprintf (zero is best): + * 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format + * 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure! + * 26: 0 = returns value, 1 = void -- 1 means inferred string length returned + * + * Remainder: + * 27-31: 0 (reserved) */ - /* utility functions */ + /* utility functions */ /* - The following utility functions are implemented on top of the - basic stream-oriented functions. To simplify the interface, some - default options are assumed (compression level and memory usage, - standard memory allocation functions). The source code of these - utility functions can easily be modified if you need special options. -*/ + * The following utility functions are implemented on top of the + * basic stream-oriented functions. To simplify the interface, some + * default options are assumed (compression level and memory usage, + * standard memory allocation functions). The source code of these + * utility functions can easily be modified if you need special options. + */ ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen)); -/* - Compresses the source buffer into the destination buffer. sourceLen is - the byte length of the source buffer. Upon entry, destLen is the total - size of the destination buffer, which must be at least the value returned - by compressBound(sourceLen). Upon exit, destLen is the actual size of the - compressed buffer. - This function can be used to compress a whole file at once if the - input file is mmap'ed. - compress returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_BUF_ERROR if there was not enough room in the output - buffer. -*/ + const Bytef *source, uLong sourceLen)); +/* + * Compresses the source buffer into the destination buffer. sourceLen is + * the byte length of the source buffer. Upon entry, destLen is the total + * size of the destination buffer, which must be at least the value returned + * by compressBound(sourceLen). Upon exit, destLen is the actual size of the + * compressed buffer. + * This function can be used to compress a whole file at once if the + * input file is mmap'ed. + * compress returns Z_OK if success, Z_MEM_ERROR if there was not + * enough memory, Z_BUF_ERROR if there was not enough room in the output + * buffer. + */ ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen, - int level)); + const Bytef *source, uLong sourceLen, + int level)); /* - Compresses the source buffer into the destination buffer. The level - parameter has the same meaning as in deflateInit. sourceLen is the byte - length of the source buffer. Upon entry, destLen is the total size of the - destination buffer, which must be at least the value returned by - compressBound(sourceLen). Upon exit, destLen is the actual size of the - compressed buffer. - - compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_BUF_ERROR if there was not enough room in the output buffer, - Z_STREAM_ERROR if the level parameter is invalid. -*/ + * Compresses the source buffer into the destination buffer. The level + * parameter has the same meaning as in deflateInit. sourceLen is the byte + * length of the source buffer. Upon entry, destLen is the total size of the + * destination buffer, which must be at least the value returned by + * compressBound(sourceLen). Upon exit, destLen is the actual size of the + * compressed buffer. + * + * compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + * memory, Z_BUF_ERROR if there was not enough room in the output buffer, + * Z_STREAM_ERROR if the level parameter is invalid. + */ ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen)); /* - compressBound() returns an upper bound on the compressed size after - compress() or compress2() on sourceLen bytes. It would be used before - a compress() or compress2() call to allocate the destination buffer. -*/ + * compressBound() returns an upper bound on the compressed size after + * compress() or compress2() on sourceLen bytes. It would be used before + * a compress() or compress2() call to allocate the destination buffer. + */ ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen)); + const Bytef *source, uLong sourceLen)); /* - Decompresses the source buffer into the destination buffer. sourceLen is - the byte length of the source buffer. Upon entry, destLen is the total - size of the destination buffer, which must be large enough to hold the - entire uncompressed data. (The size of the uncompressed data must have - been saved previously by the compressor and transmitted to the decompressor - by some mechanism outside the scope of this compression library.) - Upon exit, destLen is the actual size of the compressed buffer. - This function can be used to decompress a whole file at once if the - input file is mmap'ed. - - uncompress returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_BUF_ERROR if there was not enough room in the output - buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. -*/ - + * Decompresses the source buffer into the destination buffer. sourceLen is + * the byte length of the source buffer. Upon entry, destLen is the total + * size of the destination buffer, which must be large enough to hold the + * entire uncompressed data. (The size of the uncompressed data must have + * been saved previously by the compressor and transmitted to the decompressor + * by some mechanism outside the scope of this compression library.) + * Upon exit, destLen is the actual size of the compressed buffer. + * This function can be used to decompress a whole file at once if the + * input file is mmap'ed. + * + * uncompress returns Z_OK if success, Z_MEM_ERROR if there was not + * enough memory, Z_BUF_ERROR if there was not enough room in the output + * buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. + */ typedef voidp gzFile; ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); /* - Opens a gzip (.gz) file for reading or writing. The mode parameter - is as in fopen ("rb" or "wb") but can also include a compression level - ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for - Huffman only compression as in "wb1h", or 'R' for run-length encoding - as in "wb1R". (See the description of deflateInit2 for more information - about the strategy parameter.) - - gzopen can be used to read a file which is not in gzip format; in this - case gzread will directly read from the file without decompression. - - gzopen returns NULL if the file could not be opened or if there was - insufficient memory to allocate the (de)compression state; errno - can be checked to distinguish the two cases (if errno is zero, the - zlib error is Z_MEM_ERROR). */ + * Opens a gzip (.gz) file for reading or writing. The mode parameter + * is as in fopen ("rb" or "wb") but can also include a compression level + * ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for + * Huffman only compression as in "wb1h", or 'R' for run-length encoding + * as in "wb1R". (See the description of deflateInit2 for more information + * about the strategy parameter.) + * + * gzopen can be used to read a file which is not in gzip format; in this + * case gzread will directly read from the file without decompression. + * + * gzopen returns NULL if the file could not be opened or if there was + * insufficient memory to allocate the (de)compression state; errno + * can be checked to distinguish the two cases (if errno is zero, the + * zlib error is Z_MEM_ERROR). + */ ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); /* - gzdopen() associates a gzFile with the file descriptor fd. File - descriptors are obtained from calls like open, dup, creat, pipe or - fileno (in the file has been previously opened with fopen). - The mode parameter is as in gzopen. - The next call of gzclose on the returned gzFile will also close the - file descriptor fd, just like fclose(fdopen(fd), mode) closes the file - descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode). - gzdopen returns NULL if there was insufficient memory to allocate - the (de)compression state. -*/ + * gzdopen() associates a gzFile with the file descriptor fd. File + * descriptors are obtained from calls like open, dup, creat, pipe or + * fileno (in the file has been previously opened with fopen). + * The mode parameter is as in gzopen. + * The next call of gzclose on the returned gzFile will also close the + * file descriptor fd, just like fclose(fdopen(fd), mode) closes the file + * descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode). + * gzdopen returns NULL if there was insufficient memory to allocate + * the (de)compression state. + */ ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); /* - Dynamically update the compression level or strategy. See the description - of deflateInit2 for the meaning of these parameters. - gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not - opened for writing. -*/ + * Dynamically update the compression level or strategy. See the description + * of deflateInit2 for the meaning of these parameters. + * gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not + * opened for writing. + */ ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); /* - Reads the given number of uncompressed bytes from the compressed file. - If the input file was not in gzip format, gzread copies the given number - of bytes into the buffer. - gzread returns the number of uncompressed bytes actually read (0 for - end of file, -1 for error). */ + * Reads the given number of uncompressed bytes from the compressed file. + * If the input file was not in gzip format, gzread copies the given number + * of bytes into the buffer. + * gzread returns the number of uncompressed bytes actually read (0 for + * end of file, -1 for error). + */ ZEXTERN int ZEXPORT gzwrite OF((gzFile file, - voidpc buf, unsigned len)); + voidpc buf, unsigned len)); /* - Writes the given number of uncompressed bytes into the compressed file. - gzwrite returns the number of uncompressed bytes actually written - (0 in case of error). -*/ + * Writes the given number of uncompressed bytes into the compressed file. + * gzwrite returns the number of uncompressed bytes actually written + * (0 in case of error). + */ ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...)); /* - Converts, formats, and writes the args to the compressed file under - control of the format string, as in fprintf. gzprintf returns the number of - uncompressed bytes actually written (0 in case of error). The number of - uncompressed bytes written is limited to 4095. The caller should assure that - this limit is not exceeded. If it is exceeded, then gzprintf() will return - return an error (0) with nothing written. In this case, there may also be a - buffer overflow with unpredictable consequences, which is possible only if - zlib was compiled with the insecure functions sprintf() or vsprintf() - because the secure snprintf() or vsnprintf() functions were not available. -*/ + * Converts, formats, and writes the args to the compressed file under + * control of the format string, as in fprintf. gzprintf returns the number of + * uncompressed bytes actually written (0 in case of error). The number of + * uncompressed bytes written is limited to 4095. The caller should assure that + * this limit is not exceeded. If it is exceeded, then gzprintf() will return + * return an error (0) with nothing written. In this case, there may also be a + * buffer overflow with unpredictable consequences, which is possible only if + * zlib was compiled with the insecure functions sprintf() or vsprintf() + * because the secure snprintf() or vsnprintf() functions were not available. + */ ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); /* - Writes the given null-terminated string to the compressed file, excluding - the terminating null character. - gzputs returns the number of characters written, or -1 in case of error. -*/ + * Writes the given null-terminated string to the compressed file, excluding + * the terminating null character. + * gzputs returns the number of characters written, or -1 in case of error. + */ -ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); +ZEXTERN char *ZEXPORT gzgets OF((gzFile file, char *buf, int len)); /* - Reads bytes from the compressed file until len-1 characters are read, or - a newline character is read and transferred to buf, or an end-of-file - condition is encountered. The string is then terminated with a null - character. - gzgets returns buf, or Z_NULL in case of error. -*/ + * Reads bytes from the compressed file until len-1 characters are read, or + * a newline character is read and transferred to buf, or an end-of-file + * condition is encountered. The string is then terminated with a null + * character. + * gzgets returns buf, or Z_NULL in case of error. + */ ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); /* - Writes c, converted to an unsigned char, into the compressed file. - gzputc returns the value that was written, or -1 in case of error. -*/ + * Writes c, converted to an unsigned char, into the compressed file. + * gzputc returns the value that was written, or -1 in case of error. + */ ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); /* - Reads one byte from the compressed file. gzgetc returns this byte - or -1 in case of end of file or error. -*/ + * Reads one byte from the compressed file. gzgetc returns this byte + * or -1 in case of end of file or error. + */ ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); /* - Push one character back onto the stream to be read again later. - Only one character of push-back is allowed. gzungetc() returns the - character pushed, or -1 on failure. gzungetc() will fail if a - character has been pushed but not read yet, or if c is -1. The pushed - character will be discarded if the stream is repositioned with gzseek() - or gzrewind(). -*/ + * Push one character back onto the stream to be read again later. + * Only one character of push-back is allowed. gzungetc() returns the + * character pushed, or -1 on failure. gzungetc() will fail if a + * character has been pushed but not read yet, or if c is -1. The pushed + * character will be discarded if the stream is repositioned with gzseek() + * or gzrewind(). + */ ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); /* - Flushes all pending output into the compressed file. The parameter - flush is as in the deflate() function. The return value is the zlib - error number (see function gzerror below). gzflush returns Z_OK if - the flush parameter is Z_FINISH and all output could be flushed. - gzflush should be called only when strictly necessary because it can - degrade compression. -*/ + * Flushes all pending output into the compressed file. The parameter + * flush is as in the deflate() function. The return value is the zlib + * error number (see function gzerror below). gzflush returns Z_OK if + * the flush parameter is Z_FINISH and all output could be flushed. + * gzflush should be called only when strictly necessary because it can + * degrade compression. + */ ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, - z_off_t offset, int whence)); -/* - Sets the starting position for the next gzread or gzwrite on the - given compressed file. The offset represents a number of bytes in the - uncompressed data stream. The whence parameter is defined as in lseek(2); - the value SEEK_END is not supported. - If the file is opened for reading, this function is emulated but can be - extremely slow. If the file is opened for writing, only forward seeks are - supported; gzseek then compresses a sequence of zeroes up to the new - starting position. - - gzseek returns the resulting offset location as measured in bytes from - the beginning of the uncompressed stream, or -1 in case of error, in - particular if the file is opened for writing and the new starting position - would be before the current position. -*/ + z_off_t offset, int whence)); +/* + * Sets the starting position for the next gzread or gzwrite on the + * given compressed file. The offset represents a number of bytes in the + * uncompressed data stream. The whence parameter is defined as in lseek(2); + * the value SEEK_END is not supported. + * If the file is opened for reading, this function is emulated but can be + * extremely slow. If the file is opened for writing, only forward seeks are + * supported; gzseek then compresses a sequence of zeroes up to the new + * starting position. + * + * gzseek returns the resulting offset location as measured in bytes from + * the beginning of the uncompressed stream, or -1 in case of error, in + * particular if the file is opened for writing and the new starting position + * would be before the current position. + */ ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); /* - Rewinds the given file. This function is supported only for reading. - - gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET) -*/ + * Rewinds the given file. This function is supported only for reading. + * + * gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET) + */ ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); /* - Returns the starting position for the next gzread or gzwrite on the - given compressed file. This position represents a number of bytes in the - uncompressed data stream. - - gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) -*/ + * Returns the starting position for the next gzread or gzwrite on the + * given compressed file. This position represents a number of bytes in the + * uncompressed data stream. + * + * gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) + */ ZEXTERN int ZEXPORT gzeof OF((gzFile file)); /* - Returns 1 when EOF has previously been detected reading the given - input stream, otherwise zero. -*/ + * Returns 1 when EOF has previously been detected reading the given + * input stream, otherwise zero. + */ ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); /* - Returns 1 if file is being read directly without decompression, otherwise - zero. -*/ + * Returns 1 if file is being read directly without decompression, otherwise + * zero. + */ ZEXTERN int ZEXPORT gzclose OF((gzFile file)); /* - Flushes all pending output if necessary, closes the compressed file - and deallocates all the (de)compression state. The return value is the zlib - error number (see function gzerror below). -*/ + * Flushes all pending output if necessary, closes the compressed file + * and deallocates all the (de)compression state. The return value is the zlib + * error number (see function gzerror below). + */ -ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); +ZEXTERN const char *ZEXPORT gzerror OF((gzFile file, int *errnum)); /* - Returns the error message for the last error which occurred on the - given compressed file. errnum is set to zlib error number. If an - error occurred in the file system and not in the compression library, - errnum is set to Z_ERRNO and the application may consult errno - to get the exact error code. -*/ + * Returns the error message for the last error which occurred on the + * given compressed file. errnum is set to zlib error number. If an + * error occurred in the file system and not in the compression library, + * errnum is set to Z_ERRNO and the application may consult errno + * to get the exact error code. + */ ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); /* - Clears the error and end-of-file flags for file. This is analogous to the - clearerr() function in stdio. This is useful for continuing to read a gzip - file that is being written concurrently. -*/ + * Clears the error and end-of-file flags for file. This is analogous to the + * clearerr() function in stdio. This is useful for continuing to read a gzip + * file that is being written concurrently. + */ - /* checksum functions */ + /* checksum functions */ /* - These functions are not related to compression but are exported - anyway because they might be useful in applications using the - compression library. -*/ + * These functions are not related to compression but are exported + * anyway because they might be useful in applications using the + * compression library. + */ ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); /* - Update a running Adler-32 checksum with the bytes buf[0..len-1] and - return the updated checksum. If buf is NULL, this function returns - the required initial value for the checksum. - An Adler-32 checksum is almost as reliable as a CRC32 but can be computed - much faster. Usage example: - - uLong adler = adler32(0L, Z_NULL, 0); - - while (read_buffer(buffer, length) != EOF) { - adler = adler32(adler, buffer, length); - } - if (adler != original_adler) error(); -*/ + * Update a running Adler-32 checksum with the bytes buf[0..len-1] and + * return the updated checksum. If buf is NULL, this function returns + * the required initial value for the checksum. + * An Adler-32 checksum is almost as reliable as a CRC32 but can be computed + * much faster. Usage example: + * + * uLong adler = adler32(0L, Z_NULL, 0); + * + * while (read_buffer(buffer, length) != EOF) { + * adler = adler32(adler, buffer, length); + * } + * if (adler != original_adler) error(); + */ ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, - z_off_t len2)); + z_off_t len2)); /* - Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 - and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for - each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of - seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. -*/ + * Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 + * and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for + * each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of + * seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. + */ ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); /* - Update a running CRC-32 with the bytes buf[0..len-1] and return the - updated CRC-32. If buf is NULL, this function returns the required initial - value for the for the crc. Pre- and post-conditioning (one's complement) is - performed within this function so it shouldn't be done by the application. - Usage example: - - uLong crc = crc32(0L, Z_NULL, 0); - - while (read_buffer(buffer, length) != EOF) { - crc = crc32(crc, buffer, length); - } - if (crc != original_crc) error(); -*/ + * Update a running CRC-32 with the bytes buf[0..len-1] and return the + * updated CRC-32. If buf is NULL, this function returns the required initial + * value for the for the crc. Pre- and post-conditioning (one's complement) is + * performed within this function so it shouldn't be done by the application. + * Usage example: + * + * uLong crc = crc32(0L, Z_NULL, 0); + * + * while (read_buffer(buffer, length) != EOF) { + * crc = crc32(crc, buffer, length); + * } + * if (crc != original_crc) error(); + */ ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2)); /* - Combine two CRC-32 check values into one. For two sequences of bytes, - seq1 and seq2 with lengths len1 and len2, CRC-32 check values were - calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 - check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and - len2. -*/ + * Combine two CRC-32 check values into one. For two sequences of bytes, + * seq1 and seq2 with lengths len1 and len2, CRC-32 check values were + * calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 + * check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and + * len2. + */ - /* various hacks, don't look :) */ + /* various hacks, don't look :) */ -/* deflateInit and inflateInit are macros to allow checking the zlib version +/* + * deflateInit and inflateInit are macros to allow checking the zlib version * and the compiler's view of z_stream: */ ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level, - const char *version, int stream_size)); + const char *version, int stream_size)); ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm, - const char *version, int stream_size)); + const char *version, int stream_size)); ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method, - int windowBits, int memLevel, - int strategy, const char *version, - int stream_size)); + int windowBits, int memLevel, + int strategy, const char *version, + int stream_size)); ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits, - const char *version, int stream_size)); + const char *version, int stream_size)); ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, - unsigned char FAR *window, - const char *version, - int stream_size)); -#define deflateInit(strm, level) \ - deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream)) -#define inflateInit(strm) \ - inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream)) -#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ - deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ - (strategy), ZLIB_VERSION, sizeof(z_stream)) -#define inflateInit2(strm, windowBits) \ - inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream)) -#define inflateBackInit(strm, windowBits, window) \ - inflateBackInit_((strm), (windowBits), (window), \ - ZLIB_VERSION, sizeof(z_stream)) + unsigned char FAR *window, + const char *version, + int stream_size)); +#define deflateInit(strm, level) \ + deflateInit_((strm), (level), ZLIB_VERSION, sizeof (z_stream)) +#define inflateInit(strm) \ + inflateInit_((strm), ZLIB_VERSION, sizeof (z_stream)) +#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ + deflateInit2_((strm), (level), (method), (windowBits), (memLevel), \ + (strategy), ZLIB_VERSION, sizeof (z_stream)) +#define inflateInit2(strm, windowBits) \ + inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof (z_stream)) +#define inflateBackInit(strm, windowBits, window) \ + inflateBackInit_((strm), (windowBits), (window), \ + ZLIB_VERSION, sizeof (z_stream)) #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL) - struct internal_state {int dummy;}; /* hack for buggy compilers */ + struct internal_state {int dummy; }; /* hack for buggy compilers */ #endif -ZEXTERN const char * ZEXPORT zError OF((int)); -ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z)); -ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void)); +ZEXTERN const char *ZEXPORT zError OF((int)); +ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z)); +ZEXTERN const uLongf *ZEXPORT get_crc_table OF((void)); #ifdef __cplusplus } diff --git a/lib/os/windows/zlib-1.2.3/zutil.c b/lib/os/windows/zlib-1.2.3/zutil.c index 98cf20d2d3c..f1809e4c1e1 100644 --- a/lib/os/windows/zlib-1.2.3/zutil.c +++ b/lib/os/windows/zlib-1.2.3/zutil.c @@ -1,4 +1,5 @@ -/* zutil.c -- target dependent utility functions for the compression library +/* + * zutil.c -- target dependent utility functions for the compression library * Copyright (C) 1995-2005 Jean-loup Gailly. * For conditions of distribution and use, see copyright notice in zlib.h */ @@ -8,176 +9,186 @@ #include "zutil.h" #ifndef NO_DUMMY_DECL -struct internal_state {int dummy;}; /* for buggy compilers */ +struct internal_state { int dummy; }; /* for buggy compilers */ #endif const char * const z_errmsg[10] = { -"need dictionary", /* Z_NEED_DICT 2 */ -"stream end", /* Z_STREAM_END 1 */ -"", /* Z_OK 0 */ -"file error", /* Z_ERRNO (-1) */ -"stream error", /* Z_STREAM_ERROR (-2) */ -"data error", /* Z_DATA_ERROR (-3) */ -"insufficient memory", /* Z_MEM_ERROR (-4) */ -"buffer error", /* Z_BUF_ERROR (-5) */ -"incompatible version",/* Z_VERSION_ERROR (-6) */ -""}; - - -const char * ZEXPORT zlibVersion() + "need dictionary", /* Z_NEED_DICT 2 */ + "stream end", /* Z_STREAM_END 1 */ + "", /* Z_OK 0 */ + "file error", /* Z_ERRNO (-1) */ + "stream error", /* Z_STREAM_ERROR (-2) */ + "data error", /* Z_DATA_ERROR (-3) */ + "insufficient memory", /* Z_MEM_ERROR (-4) */ + "buffer error", /* Z_BUF_ERROR (-5) */ + "incompatible version", /* Z_VERSION_ERROR (-6) */ + "" +}; + + +const char *ZEXPORT +zlibVersion() { - return ZLIB_VERSION; + return (ZLIB_VERSION); } -uLong ZEXPORT zlibCompileFlags() +uLong ZEXPORT +zlibCompileFlags() { - uLong flags; - - flags = 0; - switch (sizeof(uInt)) { - case 2: break; - case 4: flags += 1; break; - case 8: flags += 2; break; - default: flags += 3; - } - switch (sizeof(uLong)) { - case 2: break; - case 4: flags += 1 << 2; break; - case 8: flags += 2 << 2; break; - default: flags += 3 << 2; - } - switch (sizeof(voidpf)) { - case 2: break; - case 4: flags += 1 << 4; break; - case 8: flags += 2 << 4; break; - default: flags += 3 << 4; - } - switch (sizeof(z_off_t)) { - case 2: break; - case 4: flags += 1 << 6; break; - case 8: flags += 2 << 6; break; - default: flags += 3 << 6; - } + uLong flags; + + flags = 0; + switch (sizeof (uInt)) { + case 2: break; + case 4: flags += 1; break; + case 8: flags += 2; break; + default: flags += 3; + } + switch (sizeof (uLong)) { + case 2: break; + case 4: flags += 1 << 2; break; + case 8: flags += 2 << 2; break; + default: flags += 3 << 2; + } + switch (sizeof (voidpf)) { + case 2: break; + case 4: flags += 1 << 4; break; + case 8: flags += 2 << 4; break; + default: flags += 3 << 4; + } + switch (sizeof (z_off_t)) { + case 2: break; + case 4: flags += 1 << 6; break; + case 8: flags += 2 << 6; break; + default: flags += 3 << 6; + } #ifdef DEBUG - flags += 1 << 8; + flags += 1 << 8; #endif #if defined(ASMV) || defined(ASMINF) - flags += 1 << 9; + flags += 1 << 9; #endif #ifdef ZLIB_WINAPI - flags += 1 << 10; + flags += 1 << 10; #endif #ifdef BUILDFIXED - flags += 1 << 12; + flags += 1 << 12; #endif #ifdef DYNAMIC_CRC_TABLE - flags += 1 << 13; + flags += 1 << 13; #endif #ifdef NO_GZCOMPRESS - flags += 1L << 16; + flags += 1L << 16; #endif #ifdef NO_GZIP - flags += 1L << 17; + flags += 1L << 17; #endif #ifdef PKZIP_BUG_WORKAROUND - flags += 1L << 20; + flags += 1L << 20; #endif #ifdef FASTEST - flags += 1L << 21; + flags += 1L << 21; #endif #ifdef STDC -# ifdef NO_vsnprintf - flags += 1L << 25; -# ifdef HAS_vsprintf_void - flags += 1L << 26; -# endif -# else -# ifdef HAS_vsnprintf_void - flags += 1L << 26; -# endif -# endif +#ifdef NO_vsnprintf + flags += 1L << 25; +#ifdef HAS_vsprintf_void + flags += 1L << 26; +#endif +#else +#ifdef HAS_vsnprintf_void + flags += 1L << 26; +#endif +#endif +#else + flags += 1L << 24; +#ifdef NO_snprintf + flags += 1L << 25; +#ifdef HAS_sprintf_void + flags += 1L << 26; +#endif #else - flags += 1L << 24; -# ifdef NO_snprintf - flags += 1L << 25; -# ifdef HAS_sprintf_void - flags += 1L << 26; -# endif -# else -# ifdef HAS_snprintf_void - flags += 1L << 26; -# endif -# endif +#ifdef HAS_snprintf_void + flags += 1L << 26; #endif - return flags; +#endif +#endif + return (flags); } #ifdef DEBUG -# ifndef verbose -# define verbose 0 -# endif +#ifndef verbose +#define verbose 0 +#endif int z_verbose = verbose; -void z_error (m) - char *m; +void +z_error(char *m) { - fprintf(stderr, "%s\n", m); - exit(1); + fprintf(stderr, "%s\n", m); + exit(1); } #endif -/* exported to allow conversion of error code to string for compress() and +/* + * exported to allow conversion of error code to string for compress() and * uncompress() */ -const char * ZEXPORT zError(err) - int err; +const char *ZEXPORT +zError(int err) { - return ERR_MSG(err); + return (ERR_MSG(err)); } #if defined(_WIN32_WCE) - /* The Microsoft C Run-Time Library for Windows CE doesn't have - * errno. We define it as a global variable to simplify porting. - * Its value is always 0 and should not be used. - */ - int errno = 0; +/* + * The Microsoft C Run-Time Library for Windows CE doesn't have + * errno. We define it as a global variable to simplify porting. + * Its value is always 0 and should not be used. + */ +int errno = 0; #endif #ifndef HAVE_MEMCPY -void zmemcpy(dest, source, len) - Bytef* dest; - const Bytef* source; - uInt len; +void +zmemcpy( + Bytef *dest, + const Bytef *source, + uInt len) { - if (len == 0) return; - do { - *dest++ = *source++; /* ??? to be unrolled */ - } while (--len != 0); + if (len == 0) + return; + do { + *dest++ = *source++; /* ??? to be unrolled */ + } while (--len != 0); } -int zmemcmp(s1, s2, len) - const Bytef* s1; - const Bytef* s2; +int zmemcmp( + const Bytef *s1, + const Bytef *s2) uInt len; { - uInt j; + uInt j; - for (j = 0; j < len; j++) { - if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1; - } - return 0; + for (j = 0; j < len; j++) { + if (s1[j] != s2[j]) + return (2*(s1[j] > s2[j])-1); + } + return (0); } -void zmemzero(dest, len) - Bytef* dest; - uInt len; +void +zmemzero( + Bytef *dest, + uInt len) { - if (len == 0) return; - do { - *dest++ = 0; /* ??? to be unrolled */ - } while (--len != 0); + if (len == 0) + return; + do { + *dest++ = 0; /* ??? to be unrolled */ + } while (--len != 0); } #endif @@ -187,76 +198,84 @@ void zmemzero(dest, len) #ifdef __TURBOC__ /* Turbo C in 16-bit mode */ -# define MY_ZCALLOC +#define MY_ZCALLOC -/* Turbo C malloc() does not allow dynamic allocation of 64K bytes +/* + * Turbo C malloc() does not allow dynamic allocation of 64K bytes * and farmalloc(64K) returns a pointer with an offset of 8, so we * must fix the pointer. Warning: the pointer must be put back to its * original form in order to free it, use zcfree(). */ -#define MAX_PTR 10 +#define MAX_PTR 10 /* 10*64K = 640K */ local int next_ptr = 0; typedef struct ptr_table_s { - voidpf org_ptr; - voidpf new_ptr; + voidpf org_ptr; + voidpf new_ptr; } ptr_table; local ptr_table table[MAX_PTR]; -/* This table is used to remember the original form of pointers +/* + * This table is used to remember the original form of pointers * to large buffers (64K). Such pointers are normalized with a zero offset. * Since MSDOS is not a preemptive multitasking OS, this table is not * protected from concurrent access. This hack doesn't work anyway on * a protected system like OS/2. Use Microsoft C instead. */ -voidpf zcalloc (voidpf opaque, unsigned items, unsigned size) +voidpf +zcalloc(voidpf opaque, unsigned items, unsigned size) { - voidpf buf = opaque; /* just to make some compilers happy */ - ulg bsize = (ulg)items*size; - - /* If we allocate less than 65520 bytes, we assume that farmalloc - * will return a usable pointer which doesn't have to be normalized. - */ - if (bsize < 65520L) { - buf = farmalloc(bsize); - if (*(ush*)&buf != 0) return buf; - } else { - buf = farmalloc(bsize + 16L); - } - if (buf == NULL || next_ptr >= MAX_PTR) return NULL; - table[next_ptr].org_ptr = buf; - - /* Normalize the pointer to seg:0 */ - *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4; - *(ush*)&buf = 0; - table[next_ptr++].new_ptr = buf; - return buf; + voidpf buf = opaque; /* just to make some compilers happy */ + ulg bsize = (ulg)items*size; + + /* + * If we allocate less than 65520 bytes, we assume that farmalloc + * will return a usable pointer which doesn't have to be normalized. + */ + if (bsize < 65520L) { + buf = farmalloc(bsize); + if (*(ush*)&buf != 0) + return (buf); + } else { + buf = farmalloc(bsize + 16L); + } + if (buf == NULL || next_ptr >= MAX_PTR) + return (NULL); + table[next_ptr].org_ptr = buf; + + /* Normalize the pointer to seg:0 */ + *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4; + *(ush*)&buf = 0; + table[next_ptr++].new_ptr = buf; + return (buf); } -void zcfree (voidpf opaque, voidpf ptr) +void +zcfree(voidpf opaque, voidpf ptr) { - int n; - if (*(ush*)&ptr != 0) { /* object < 64K */ - farfree(ptr); - return; - } - /* Find the original pointer */ - for (n = 0; n < next_ptr; n++) { - if (ptr != table[n].new_ptr) continue; - - farfree(table[n].org_ptr); - while (++n < next_ptr) { - table[n-1] = table[n]; - } - next_ptr--; - return; - } - ptr = opaque; /* just to make some compilers happy */ - Assert(0, "zcfree: ptr not found"); + int n; + if (*(ush*)&ptr != 0) { /* object < 64K */ + farfree(ptr); + return; + } + /* Find the original pointer */ + for (n = 0; n < next_ptr; n++) { + if (ptr != table[n].new_ptr) + continue; + + farfree(table[n].org_ptr); + while (++n < next_ptr) { + table[n-1] = table[n]; + } + next_ptr--; + return; + } + ptr = opaque; /* just to make some compilers happy */ + Assert(0, "zcfree: ptr not found"); } #endif /* __TURBOC__ */ @@ -265,23 +284,25 @@ void zcfree (voidpf opaque, voidpf ptr) #ifdef M_I86 /* Microsoft C in 16-bit mode */ -# define MY_ZCALLOC +#define MY_ZCALLOC #if (!defined(_MSC_VER) || (_MSC_VER <= 600)) -# define _halloc halloc -# define _hfree hfree +#define _halloc halloc +#define _hfree hfree #endif -voidpf zcalloc (voidpf opaque, unsigned items, unsigned size) +voidpf +zcalloc(voidpf opaque, unsigned items, unsigned size) { - if (opaque) opaque = 0; /* to make compiler happy */ - return _halloc((long)items, size); + if (opaque) opaque = 0; /* to make compiler happy */ + return (_halloc((long)items, size)); } -void zcfree (voidpf opaque, voidpf ptr) +void +zcfree(voidpf opaque, voidpf ptr) { - if (opaque) opaque = 0; /* to make compiler happy */ - _hfree(ptr); + if (opaque) opaque = 0; /* to make compiler happy */ + _hfree(ptr); } #endif /* M_I86 */ @@ -290,17 +311,17 @@ void zcfree (voidpf opaque, voidpf ptr) #ifdef _KERNEL #include -voidpf zcalloc(opaque, items, size) -voidpf opaque; -unsigned items; -unsigned size; +voidpf +zcalloc( + voidpf opaque, + unsigned items, + unsigned size) { - return zfs_kmem_alloc(items * size, KM_SLEEP); + return (zfs_kmem_alloc(items * size, KM_SLEEP)); } -void zcfree(opaque, ptr) -voidpf opaque; -voidpf ptr; +void +zcfree(voidpf opaque, voidpf ptr) { zfs_kmem_free(ptr, 0); } @@ -326,22 +347,23 @@ extern voidp calloc OF((uInt items, uInt size)); extern void free OF((voidpf ptr)); #endif -voidpf zcalloc (opaque, items, size) - voidpf opaque; - unsigned items; - unsigned size; +voidpf +zcalloc( + voidpf opaque, + unsigned items, + unsigned size) { - if (opaque) items += size - size; /* make compiler happy */ - return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) : - (voidpf)calloc(items, size); + if (opaque) items += size - size; /* make compiler happy */ + return (sizeof (uInt) > 2 ? (voidpf)malloc(items * size) : + (voidpf)calloc(items, size)); } -void zcfree (opaque, ptr) - voidpf opaque; - voidpf ptr; +void +zcfree( + voidpf opaque, + voidpf ptr) { - free(ptr); - if (opaque) return; /* make compiler happy */ + free(ptr); } #endif /* MY_ZCALLOC */ diff --git a/lib/os/windows/zlib-1.2.3/zutil.h b/lib/os/windows/zlib-1.2.3/zutil.h index b7d5eff81b6..c1562c1a95a 100644 --- a/lib/os/windows/zlib-1.2.3/zutil.h +++ b/lib/os/windows/zlib-1.2.3/zutil.h @@ -1,46 +1,49 @@ -/* zutil.h -- internal interface and configuration of the compression library +/* + * zutil.h -- internal interface and configuration of the compression library * Copyright (C) 1995-2005 Jean-loup Gailly. * For conditions of distribution and use, see copyright notice in zlib.h */ -/* WARNING: this file should *not* be used by applications. It is - part of the implementation of the compression library and is - subject to change. Applications should only use zlib.h. +/* + * WARNING: this file should *not* be used by applications. It is + * part of the implementation of the compression library and is + * subject to change. Applications should only use zlib.h. */ /* @(#) $Id$ */ #ifndef ZUTIL_H -#define ZUTIL_H +#define ZUTIL_H -#define ZLIB_INTERNAL +#define ZLIB_INTERNAL #include "zlib.h" #ifdef STDC -# ifndef _WIN32_WCE -# include -# endif -# include -# include +#ifndef _WIN32_WCE +#include +#endif +#include +#include #endif #ifdef NO_ERRNO_H -# ifdef _WIN32_WCE - /* The Microsoft C Run-Time Library for Windows CE doesn't have - * errno. We define it as a global variable to simplify porting. - * Its value is always 0 and should not be used. We rename it to - * avoid conflict with other libraries that use the same workaround. - */ -# define errno z_errno -# endif - extern int errno; +#ifdef _WIN32_WCE +/* + * The Microsoft C Run-Time Library for Windows CE doesn't have + * errno. We define it as a global variable to simplify porting. + * Its value is always 0 and should not be used. We rename it to + * avoid conflict with other libraries that use the same workaround. + */ +#define errno z_errno +#endif +extern int errno; #else -# ifndef _WIN32_WCE -# include -# endif +#ifndef _WIN32_WCE +#include +#endif #endif #ifndef local -# define local static +#define local static #endif /* compile with -Dlocal if your debugger can't find static symbols */ @@ -53,217 +56,220 @@ typedef unsigned long ulg; extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ /* (size given to avoid silly warnings with Visual C++) */ -#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)] +#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)] -#define ERR_RETURN(strm,err) \ - return (strm->msg = (char*)ERR_MSG(err), (err)) +#define ERR_RETURN(strm, err) \ + return (strm->msg = (char *)ERR_MSG(err), (err)) /* To be used only when the state is known to be valid */ - /* common constants */ +/* common constants */ #ifndef DEF_WBITS -# define DEF_WBITS MAX_WBITS +#define DEF_WBITS MAX_WBITS #endif /* default windowBits for decompression. MAX_WBITS is for compression only */ #if MAX_MEM_LEVEL >= 8 -# define DEF_MEM_LEVEL 8 +#define DEF_MEM_LEVEL 8 #else -# define DEF_MEM_LEVEL MAX_MEM_LEVEL +#define DEF_MEM_LEVEL MAX_MEM_LEVEL #endif /* default memLevel */ -#define STORED_BLOCK 0 -#define STATIC_TREES 1 -#define DYN_TREES 2 +#define STORED_BLOCK 0 +#define STATIC_TREES 1 +#define DYN_TREES 2 /* The three kinds of block type */ -#define MIN_MATCH 3 -#define MAX_MATCH 258 +#define MIN_MATCH 3 +#define MAX_MATCH 258 /* The minimum and maximum match lengths */ -#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */ +#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */ - /* target dependencies */ +/* target dependencies */ #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32)) -# define OS_CODE 0x00 -# if defined(__TURBOC__) || defined(__BORLANDC__) -# if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__)) - /* Allow compilation with ANSI keywords only enabled */ - void _Cdecl farfree( void *block ); - void *_Cdecl farmalloc( unsigned long nbytes ); -# else -# include -# endif -# else /* MSC or DJGPP */ -# include -# endif +#define OS_CODE 0x00 +#if defined(__TURBOC__) || defined(__BORLANDC__) +#if (__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__)) +/* Allow compilation with ANSI keywords only enabled */ +void _Cdecl farfree(void *block); +void *_Cdecl farmalloc(unsigned long nbytes); +#else +#include +#endif +#else /* MSC or DJGPP */ +#include +#endif #endif #ifdef AMIGA -# define OS_CODE 0x01 +#define OS_CODE 0x01 #endif #if defined(VAXC) || defined(VMS) -# define OS_CODE 0x02 -# define F_OPEN(name, mode) \ - fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512") +#define OS_CODE 0x02 +#define F_OPEN(name, mode) \ + fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512") #endif #if defined(ATARI) || defined(atarist) -# define OS_CODE 0x05 +#define OS_CODE 0x05 #endif #ifdef OS2 -# define OS_CODE 0x06 -# ifdef M_I86 - #include -# endif +#define OS_CODE 0x06 +#ifdef M_I86 +#include +#endif #endif #if defined(MACOS) || defined(TARGET_OS_MAC) -# define OS_CODE 0x07 -# if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os -# include /* for fdopen */ -# else -# ifndef fdopen -# define fdopen(fd,mode) NULL /* No fdopen() */ -# endif -# endif +#define OS_CODE 0x07 +#if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os +#include /* for fdopen */ +#else +#ifndef fdopen +#define fdopen(fd, mode) NULL /* No fdopen() */ +#endif +#endif #endif #ifdef TOPS20 -# define OS_CODE 0x0a +#define OS_CODE 0x0a #endif #ifdef WIN32 -# ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */ -# define OS_CODE 0x0b -# endif +#ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */ +#define OS_CODE 0x0b +#endif #endif #ifdef __50SERIES /* Prime/PRIMOS */ -# define OS_CODE 0x0f +#define OS_CODE 0x0f #endif #if defined(_BEOS_) || defined(RISCOS) -# define fdopen(fd,mode) NULL /* No fdopen() */ +#define fdopen(fd, mode) NULL /* No fdopen() */ #endif #if (defined(_MSC_VER) && (_MSC_VER > 600)) -# if defined(_WIN32_WCE) -# define fdopen(fd,mode) NULL /* No fdopen() */ -# ifndef _PTRDIFF_T_DEFINED - typedef int ptrdiff_t; -# define _PTRDIFF_T_DEFINED -# endif -# else -# define fdopen(fd,type) _fdopen(fd,type) -# endif +#if defined(_WIN32_WCE) +#define fdopen(fd, mode) NULL /* No fdopen() */ +#ifndef _PTRDIFF_T_DEFINED +typedef int ptrdiff_t; +#define _PTRDIFF_T_DEFINED +#endif +#else +#define fdopen(fd, type) _fdopen(fd, type) +#endif #endif - /* common defaults */ +/* common defaults */ #ifndef OS_CODE -# define OS_CODE 0x03 /* assume Unix */ +#define OS_CODE 0x03 /* assume Unix */ #endif #ifndef F_OPEN -# define F_OPEN(name, mode) fopen((name), (mode)) +#define F_OPEN(name, mode) fopen((name), (mode)) #endif - /* functions */ +/* functions */ #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550) -# ifndef HAVE_VSNPRINTF -# define HAVE_VSNPRINTF -# endif +#ifndef HAVE_VSNPRINTF +#define HAVE_VSNPRINTF +#endif #endif #if defined(__CYGWIN__) -# ifndef HAVE_VSNPRINTF -# define HAVE_VSNPRINTF -# endif +#ifndef HAVE_VSNPRINTF +#define HAVE_VSNPRINTF +#endif #endif #ifndef HAVE_VSNPRINTF -# ifdef MSDOS - /* vsnprintf may exist on some MS-DOS compilers (DJGPP?), - but for now we just assume it doesn't. */ -# define NO_vsnprintf -# endif -# ifdef __TURBOC__ -# define NO_vsnprintf -# endif -# ifdef WIN32 - /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */ -# if !defined(vsnprintf) && !defined(NO_vsnprintf) -# define vsnprintf _vsnprintf -# endif -# endif -# ifdef __SASC -# define NO_vsnprintf -# endif +#ifdef MSDOS +/* + * vsnprintf may exist on some MS-DOS compilers (DJGPP?), + * but for now we just assume it doesn't. + */ +#define NO_vsnprintf +#endif +#ifdef __TURBOC__ +#define NO_vsnprintf +#endif +#ifdef WIN32 +/* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */ +#if !defined(vsnprintf) && !defined(NO_vsnprintf) +#define vsnprintf _vsnprintf +#endif +#endif +#ifdef __SASC +#define NO_vsnprintf +#endif #endif #ifdef VMS -# define NO_vsnprintf +#define NO_vsnprintf #endif #if defined(pyr) -# define NO_MEMCPY +#define NO_MEMCPY #endif #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__) - /* Use our own functions for small and medium model with MSC <= 5.0. - * You may have to use the same strategy for Borland C (untested). - * The __SC__ check is for Symantec. - */ -# define NO_MEMCPY +/* + * Use our own functions for small and medium model with MSC <= 5.0. + * You may have to use the same strategy for Borland C (untested). + * The __SC__ check is for Symantec. + */ +#define NO_MEMCPY #endif #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY) -# define HAVE_MEMCPY +#define HAVE_MEMCPY #endif #ifdef HAVE_MEMCPY -# ifdef SMALL_MEDIUM /* MSDOS small or medium model */ -# define zmemcpy _fmemcpy -# define zmemcmp _fmemcmp -# define zmemzero(dest, len) _fmemset(dest, 0, len) -# else -# define zmemcpy memcpy -# define zmemcmp memcmp -# define zmemzero(dest, len) memset(dest, 0, len) -# endif +#ifdef SMALL_MEDIUM /* MSDOS small or medium model */ +#define zmemcpy _fmemcpy +#define zmemcmp _fmemcmp +#define zmemzero(dest, len) _fmemset(dest, 0, len) +#else +#define zmemcpy memcpy +#define zmemcmp memcmp +#define zmemzero(dest, len) memset(dest, 0, len) +#endif #else - extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len)); - extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len)); - extern void zmemzero OF((Bytef* dest, uInt len)); +extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len)); +extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len)); +extern void zmemzero OF((Bytef* dest, uInt len)); #endif /* Diagnostic functions */ #ifdef DEBUG -# include - extern int z_verbose; - extern void z_error OF((char *m)); -# define Assert(cond,msg) {if(!(cond)) z_error(msg);} -# define Trace(x) {if (z_verbose>=0) fprintf x ;} -# define Tracev(x) {if (z_verbose>0) fprintf x ;} -# define Tracevv(x) {if (z_verbose>1) fprintf x ;} -# define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;} -# define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;} +#include +extern int z_verbose; +extern void z_error OF((char *m)); +#define Assert(cond, msg) {if (!(cond)) z_error(msg); } +#define Trace(x) { if (z_verbose >= 0) fprintf x; } +#define Tracev(x) { if (z_verbose > 0) fprintf x; } +#define Tracevv(x) { if (z_verbose > 1) fprintf x; } +#define Tracec(c, x) { if (z_verbose > 0 && (c)) fprintf x; } +#define Tracecv(c, x) { if (z_verbose > 1 && (c)) fprintf x; } #else -# define Assert(cond,msg) -# define Trace(x) -# define Tracev(x) -# define Tracevv(x) -# define Tracec(c,x) -# define Tracecv(c,x) +#define Assert(cond, msg) +#define Trace(x) +#define Tracev(x) +#define Tracevv(x) +#define Tracec(c, x) +#define Tracecv(c, x) #endif voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size)); void zcfree OF((voidpf opaque, voidpf ptr)); -#define ZALLOC(strm, items, size) \ - (*((strm)->zalloc))((strm)->opaque, (items), (size)) -#define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr)) -#define TRY_FREE(s, p) {if (p) ZFREE(s, p);} +#define ZALLOC(strm, items, size) \ + (*((strm)->zalloc))((strm)->opaque, (items), (size)) +#define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr)) +#define TRY_FREE(s, p) {if (p) ZFREE(s, p); } #endif /* ZUTIL_H */ diff --git a/module/os/windows/Wpp.c b/module/os/windows/Wpp.c index 7222571a64d..9c0017d9ae4 100644 --- a/module/os/windows/Wpp.c +++ b/module/os/windows/Wpp.c @@ -4,11 +4,11 @@ void ZFSWppInit(PDRIVER_OBJECT pDriverObject, PUNICODE_STRING pRegistryPath) { - WPP_INIT_TRACING(pDriverObject, pRegistryPath); + WPP_INIT_TRACING(pDriverObject, pRegistryPath); } void ZFSWppCleanup(PDRIVER_OBJECT pDriverObject) { - WPP_CLEANUP(pDriverObject); -} \ No newline at end of file + WPP_CLEANUP(pDriverObject); +} diff --git a/module/os/windows/debug.c b/module/os/windows/debug.c index 8d9635659b7..9a4ee88404c 100644 --- a/module/os/windows/debug.c +++ b/module/os/windows/debug.c @@ -18,49 +18,49 @@ * * CDDL HEADER END */ - /* - * Copyright (c) 2018 Julian Heuking - */ +/* + * Copyright (c) 2018 Julian Heuking + */ #include #include #include -#define max_line_length 1024 -//#define windowsStyleLineEndings +#define max_line_length 1024 #ifdef windowsStyleLineEndings - char* endLine = "\r\n"; + char *endLine = "\r\n"; #else - char* endLine = ""; + char *endLine = ""; #endif -char* endBuf = "-EB-"; +char *endBuf = "-EB-"; KSPIN_LOCK cbuf_spin; char *cbuf = NULL; -static unsigned long long cbuf_size = 0x100000; //1MB +static unsigned long long cbuf_size = 0x100000; // 1MB static unsigned long long startOff = 0; - -int initDbgCircularBuffer(void) +int +initDbgCircularBuffer(void) { cbuf = ExAllocatePoolWithTag(NonPagedPoolNx, cbuf_size, '!GBD'); ASSERT(cbuf); KeInitializeSpinLock(&cbuf_spin); - return 0; + return (0); } -int finiDbgCircularBuffer(void) +int +finiDbgCircularBuffer(void) { ExFreePoolWithTag(cbuf, '!GBD'); - return 0; + return (0); } /* * Howto: Read the circular buffer with windbg - * + * * get address of cbuf buffer: * dt OpenZFS!cbuf --> copy shown address * @@ -68,12 +68,12 @@ int finiDbgCircularBuffer(void) * .writemem [filepath] [cbuf address] L[Length as hex] * e.g. .writemem C:\src\cbuf.txt 0xffff870d`d2000000 L100000 * - * Open in your favourite text editor and + * Open in your favourite text editor and * locate -EB-, there's the start/end of the buffer * -*/ - -void addbuffer(char* buf) + */ +void +addbuffer(char *buf) { // unsigned long long writtenBytes = 0; if (buf) { @@ -82,8 +82,8 @@ void addbuffer(char* buf) unsigned long long endBufLen = strlen(endBuf); if (startOff + bufLen + endLineLen + endBufLen >= cbuf_size) { - // too long, set reset start offset - while (startOff < cbuf_size) { // reset the rest of the buffer + // too long, set reset start offset + while (startOff < cbuf_size) { cbuf[startOff] = 0; startOff++; } @@ -91,7 +91,8 @@ void addbuffer(char* buf) } unsigned long long endBufOff = startOff + bufLen + endLineLen; - // print new end buf marker first, before overwriting the old one + // print new end buf marker first, + // before overwriting the old one for (int i = 0; i < endBufLen; i++) { cbuf[endBufOff + i] = endBuf[i]; } @@ -108,10 +109,10 @@ void addbuffer(char* buf) startOff++; } } - } -void printBuffer(const char *fmt, ...) +void +printBuffer(const char *fmt, ...) { // DPCs can't block (mutex) - replace this code with spinlocks KIRQL level; @@ -120,56 +121,60 @@ void printBuffer(const char *fmt, ...) char buf[max_line_length]; _snprintf(buf, 18, "%p: ", PsGetCurrentThread()); - int tmp = _vsnprintf_s(&buf[17], sizeof(buf), max_line_length, fmt, args); + int tmp = _vsnprintf_s(&buf[17], sizeof (buf), max_line_length, + fmt, args); if (tmp >= max_line_length) { _snprintf(&buf[17], 17, "buffer too small"); } - KeAcquireSpinLock(&cbuf_spin,&level); + KeAcquireSpinLock(&cbuf_spin, &level); addbuffer(buf); KeReleaseSpinLock(&cbuf_spin, level); - + va_end(args); } // Signalled by userland to write out the kernel buffer. -void saveBuffer(void) +void +saveBuffer(void) { - UNICODE_STRING UnicodeFilespec; - OBJECT_ATTRIBUTES ObjectAttributes; + UNICODE_STRING UnicodeFilespec; + OBJECT_ATTRIBUTES ObjectAttributes; NTSTATUS status; HANDLE h; printBuffer("saving buffer to disk\n"); - RtlInitUnicodeString(&UnicodeFilespec, L"\\??\\C:\\Windows\\debug\\ZFSin.txt"); + RtlInitUnicodeString(&UnicodeFilespec, + L"\\??\\C:\\Windows\\debug\\ZFSin.txt"); // Attempt to create file, make a weak attempt, give up easily. - ObjectAttributes.Length = sizeof(OBJECT_ATTRIBUTES); + ObjectAttributes.Length = sizeof (OBJECT_ATTRIBUTES); ObjectAttributes.RootDirectory = NULL; - ObjectAttributes.Attributes = /*OBJ_CASE_INSENSITIVE |*/ OBJ_KERNEL_HANDLE; + ObjectAttributes.Attributes = OBJ_KERNEL_HANDLE; ObjectAttributes.ObjectName = &UnicodeFilespec; ObjectAttributes.SecurityDescriptor = NULL; ObjectAttributes.SecurityQualityOfService = NULL; IO_STATUS_BLOCK iostatus; status = ZwCreateFile(&h, - GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE, - &ObjectAttributes, - &iostatus, - 0, - FILE_ATTRIBUTE_NORMAL, - /* FILE_SHARE_WRITE | */ FILE_SHARE_READ, - FILE_OVERWRITE_IF, - FILE_SYNCHRONOUS_IO_NONALERT | FILE_NO_INTERMEDIATE_BUFFERING, - NULL, - 0); + GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE, + &ObjectAttributes, + &iostatus, + 0, + FILE_ATTRIBUTE_NORMAL, + /* FILE_SHARE_WRITE | */ FILE_SHARE_READ, + FILE_OVERWRITE_IF, + FILE_SYNCHRONOUS_IO_NONALERT | FILE_NO_INTERMEDIATE_BUFFERING, + NULL, + 0); if (status != STATUS_SUCCESS) { printBuffer("failed to save buffer: 0x%lx\n", status); return; } - ZwWriteFile(h, 0, NULL, NULL, &iostatus, cbuf, (ULONG)cbuf_size, NULL, NULL); + ZwWriteFile(h, 0, NULL, NULL, &iostatus, cbuf, (ULONG)cbuf_size, + NULL, NULL); ZwClose(h); } diff --git a/module/os/windows/driver.c b/module/os/windows/driver.c index 66148480be3..e88b68df809 100644 --- a/module/os/windows/driver.c +++ b/module/os/windows/driver.c @@ -1,9 +1,29 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ + #include #include #include -#include -//#include +#include #include #include @@ -11,7 +31,6 @@ #include "Trace.h" DRIVER_INITIALIZE DriverEntry; -//EVT_WDF_DRIVER_DEVICE_ADD OpenZFS_Init; extern int initDbgCircularBuffer(void); extern int finiDbgCircularBuffer(void); @@ -20,8 +39,8 @@ extern int spl_stop(void); extern int zfs_start(void); extern void zfs_stop(void); extern void windows_delay(int ticks); -extern int zfs_vfsops_init(void); -extern int zfs_vfsops_fini(void); +extern int zfs_vfsops_init(void); +extern int zfs_vfsops_fini(void); int zfs_kmod_init(void); void zfs_kmod_fini(void); @@ -36,7 +55,9 @@ PDRIVER_DISPATCH STOR_MajorFunction[IRP_MJ_MAXIMUM_FUNCTION + 1]; wzvolDriverInfo STOR_wzvolDriverInfo; DRIVER_UNLOAD OpenZFS_Fini; -void OpenZFS_Fini(PDRIVER_OBJECT DriverObject) + +void +OpenZFS_Fini(PDRIVER_OBJECT DriverObject) { KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "OpenZFS_Fini\n")); @@ -56,23 +77,28 @@ void OpenZFS_Fini(PDRIVER_OBJECT DriverObject) finiDbgCircularBuffer(); if (STOR_wzvolDriverInfo.zvContextArray) { - ExFreePoolWithTag(STOR_wzvolDriverInfo.zvContextArray, MP_TAG_GENERAL); + ExFreePoolWithTag(STOR_wzvolDriverInfo.zvContextArray, + MP_TAG_GENERAL); STOR_wzvolDriverInfo.zvContextArray = NULL; } ZFSWppCleanup(DriverObject); } /* - * Setup a Storage Miniport Driver, used only by ZVOL to create virtual disks. + * Setup a Storage Miniport Driver, used only by ZVOL to create virtual disks. */ -NTSTATUS DriverEntry(_In_ PDRIVER_OBJECT DriverObject, _In_ PUNICODE_STRING pRegistryPath) +NTSTATUS +DriverEntry(_In_ PDRIVER_OBJECT DriverObject, + _In_ PUNICODE_STRING pRegistryPath) { NTSTATUS status; - KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "OpenZFS: DriverEntry\n")); + KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, + "OpenZFS: DriverEntry\n")); ZFSWppInit(DriverObject, pRegistryPath); - - KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "OpenZFS: DriverEntry\n")); + + KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, + "OpenZFS: DriverEntry\n")); // Setup global so zfs_ioctl.c can setup devnode WIN_DriverObject = DriverObject; @@ -90,7 +116,7 @@ NTSTATUS DriverEntry(_In_ PDRIVER_OBJECT DriverObject, _In_ PUNICODE_STRING pRe kstat_windows_init(pRegistryPath); - system_taskq_init(); + system_taskq_init(); /* * Initialise storport for the ZVOL virtual disks. This also @@ -101,86 +127,96 @@ NTSTATUS DriverEntry(_In_ PDRIVER_OBJECT DriverObject, _In_ PUNICODE_STRING pRe if (STATUS_SUCCESS != status) { /* If we failed, we carryon without ZVOL support. */ - KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "OpenZFS: StorPortInitialize() failed, no ZVOL for you. %d/0x%x\n", status, status)); - memset(STOR_MajorFunction, 0, sizeof(STOR_MajorFunction)); + KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, + "OpenZFS: StorPortInitialize() failed, no ZVOL. %d/0x%x\n", + status, status)); + memset(STOR_MajorFunction, 0, sizeof (STOR_MajorFunction)); STOR_DriverUnload = NULL; } else { /* Make a copy of the Driver Callbacks for miniport */ - memcpy(STOR_MajorFunction, WIN_DriverObject->MajorFunction, sizeof(STOR_MajorFunction)); + memcpy(STOR_MajorFunction, WIN_DriverObject->MajorFunction, + sizeof (STOR_MajorFunction)); STOR_DriverUnload = WIN_DriverObject->DriverUnload; } /* Now set the Driver Callbacks to dispatcher and start ZFS */ WIN_DriverObject->DriverUnload = OpenZFS_Fini; - /* Start ZFS itself */ - zfs_kmod_init(); - - /* Register fs with Win */ - zfs_vfsops_init(); + /* Start ZFS itself */ + zfs_kmod_init(); + /* Register fs with Win */ + zfs_vfsops_init(); - KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "OpenZFS: Started\n")); - return STATUS_SUCCESS; + KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, + "OpenZFS: Started\n")); + return (STATUS_SUCCESS); } -//extern unsigned long spl_hostid; extern int random_get_bytes(void *ptr, unsigned long len); -void spl_create_hostid(HANDLE h, PUNICODE_STRING pRegistryPath) +void +spl_create_hostid(HANDLE h, PUNICODE_STRING pRegistryPath) { - NTSTATUS Status; + NTSTATUS Status; - UNICODE_STRING AttachKey; + UNICODE_STRING AttachKey; RtlInitUnicodeString(&AttachKey, L"hostid"); - random_get_bytes(&spl_hostid, sizeof(spl_hostid)); + random_get_bytes(&spl_hostid, sizeof (spl_hostid)); Status = ZwSetValueKey( - h, - &AttachKey, - 0, - REG_DWORD, - &spl_hostid, - sizeof(spl_hostid) - ); + h, + &AttachKey, + 0, + REG_DWORD, + &spl_hostid, + sizeof (spl_hostid)); if (!NT_SUCCESS(Status)) { - KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "%s: Unable to create Registry %wZ/hostid: 0x%x. hostid unset.\n", __func__, pRegistryPath, Status)); + KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, + "%s: Unable to create Registry %wZ/hostid: 0x%x." + " hostid unset.\n", __func__, pRegistryPath, Status)); spl_hostid = 0; } - KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "SPL: created hostid 0x%04x\n", spl_hostid)); + KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, + "SPL: created hostid 0x%04x\n", spl_hostid)); } // Whenever we start up, write the version string to registry. -void spl_update_version(HANDLE h, PUNICODE_STRING pRegistryPath) +void +spl_update_version(HANDLE h, PUNICODE_STRING pRegistryPath) { - NTSTATUS Status; + NTSTATUS Status; - UNICODE_STRING AttachKey; - UNICODE_STRING ValueKey; + UNICODE_STRING AttachKey; + UNICODE_STRING ValueKey; // FIX me RtlInitUnicodeString(&AttachKey, L"version"); RtlInitUnicodeString(&ValueKey, L"fixme"); - //RtlInitUnicodeString(&ValueKey, L"fixme"ZFS_META_VERSION "-" ZFS_META_RELEASE); + // RtlInitUnicodeString(&ValueKey, + // L"fixme"ZFS_META_VERSION "-" ZFS_META_RELEASE); Status = ZwSetValueKey( - h, - &AttachKey, - 0, - REG_SZ, - ValueKey.Buffer, - ValueKey.Length - ); + h, + &AttachKey, + 0, + REG_SZ, + ValueKey.Buffer, + ValueKey.Length); if (!NT_SUCCESS(Status)) { - KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "%s: Unable to create Registry %wZ/version: 0x%x. hostid unset.\n", __func__, pRegistryPath, Status)); + KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, + "%s: Unable to create Registry %wZ/version: 0x%x." + " hostid unset.\n", __func__, pRegistryPath, Status)); } } -int spl_check_assign_types(kstat_named_t *kold, PKEY_VALUE_FULL_INFORMATION regBuffer) +int +spl_check_assign_types(kstat_named_t *kold, + PKEY_VALUE_FULL_INFORMATION regBuffer) { switch (kold->data_type) { @@ -189,78 +225,78 @@ int spl_check_assign_types(kstat_named_t *kold, PKEY_VALUE_FULL_INFORMATION regB case KSTAT_DATA_INT64: { if (regBuffer->Type != REG_QWORD || - regBuffer->DataLength != sizeof(uint64_t)) { - KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "%s: registry '%s' matched in kstat. Type needs to be REG_QWORD. (8 bytes)\n", __func__, - kold->name)); - return 0; + regBuffer->DataLength != sizeof (uint64_t)) { + KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, + "%s: registry '%s' matched in kstat. " + "Type needs to be REG_QWORD. (8 bytes)\n", __func__, + kold->name)); + return (0); } - uint64_t newvalue = *(uint64_t *)((uint8_t *)regBuffer + regBuffer->DataOffset); - KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "%s: kstat '%s': 0x%llx -> 0x%llx\n", __func__, - kold->name, - kold->value.ui64, - newvalue - )); + uint64_t newvalue = + *(uint64_t *)((uint8_t *)regBuffer + regBuffer->DataOffset); + KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, + "%s: kstat '%s': 0x%llx -> 0x%llx\n", __func__, + kold->name, + kold->value.ui64, + newvalue)); kold->value.ui64 = newvalue; - return 1; + return (1); } case KSTAT_DATA_UINT32: case KSTAT_DATA_INT32: { if (regBuffer->Type != REG_DWORD || - regBuffer->DataLength != sizeof(uint32_t)) { - KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "%s: registry '%s' matched in kstat. Type needs to be REG_DWORD. (4 bytes)\n", __func__, - kold->name)); - return 0; + regBuffer->DataLength != sizeof (uint32_t)) { + KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, + "%s: registry '%s' matched in kstat. " + "Type needs to be REG_DWORD. (4 bytes)\n", __func__, + kold->name)); + return (0); } - uint32_t newvalue = *(uint32_t *)((uint8_t *)regBuffer + regBuffer->DataOffset); - KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "%s: kstat '%s': 0x%lx -> 0x%lx\n", __func__, - kold->name, - kold->value.ui32, - newvalue - )); + uint32_t newvalue = + *(uint32_t *)((uint8_t *)regBuffer + regBuffer->DataOffset); + KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, + "%s: kstat '%s': 0x%lx -> 0x%lx\n", __func__, + kold->name, + kold->value.ui32, + newvalue)); kold->value.ui32 = newvalue; - return 1; + return (1); } default: - KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "%s: registry '%s' matched in kstat of unsupported type. Only INT32 and INT64 types supported.\n", __func__, - kold->name)); + KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, + "%s: registry '%s' matched in kstat of unsupported type." + "Only INT32 and INT64 types supported.\n", __func__, + kold->name)); } - return 0; + return (0); } -// -// kstat_osx_init(): -// read kstat values -// spl_kstat_registry(this): -// open registry -// for each registry entry -// match name in kstat - assign value -// close registry -// return 0 (OK) -// write kstat values (if OK) -// extern wchar_t zfs_vdev_protection_filter[64]; -int spl_kstat_registry(void *arg, kstat_t *ksp) +int +spl_kstat_registry(void *arg, kstat_t *ksp) { - OBJECT_ATTRIBUTES ObjectAttributes; - HANDLE h; - NTSTATUS Status; + OBJECT_ATTRIBUTES ObjectAttributes; + HANDLE h; + NTSTATUS Status; PUNICODE_STRING pRegistryPath = arg; InitializeObjectAttributes(&ObjectAttributes, - pRegistryPath, - OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, - NULL, - NULL); + pRegistryPath, + OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, + NULL, + NULL); - Status = ZwOpenKey(&h, // KeyHandle - KEY_ALL_ACCESS, // DesiredAccess - &ObjectAttributes);// ObjectAttributes + Status = ZwOpenKey(&h, // KeyHandle + KEY_ALL_ACCESS, // DesiredAccess + &ObjectAttributes); // ObjectAttributes if (!NT_SUCCESS(Status)) { - KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "%s: Unable to open Registry %wZ: 0x%x. Going with defaults.\n", __func__, pRegistryPath, Status)); - return 0; + KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, + "%s: Unable to open Registry %wZ: 0x%x." + "Going with defaults.\n", __func__, pRegistryPath, Status)); + return (0); } // Iterate all Registry entries. @@ -273,18 +309,22 @@ int spl_kstat_registry(void *arg, kstat_t *ksp) for (index = 0; status != STATUS_NO_MORE_ENTRIES; index++) { // Get the buffer size necessary - status = ZwEnumerateValueKey(h, index, KeyValueFullInformation, NULL, 0, &length); + status = ZwEnumerateValueKey(h, index, KeyValueFullInformation, + NULL, 0, &length); - if ((status != STATUS_BUFFER_TOO_SMALL) && (status != STATUS_BUFFER_OVERFLOW)) + if ((status != STATUS_BUFFER_TOO_SMALL) && + (status != STATUS_BUFFER_OVERFLOW)) break; // Something is wrong - or we finished // Allocate space to hold - regBuffer = (PKEY_VALUE_FULL_INFORMATION)ExAllocatePoolWithTag(NonPagedPoolNx, length, 'zfsr'); + regBuffer = (PKEY_VALUE_FULL_INFORMATION)ExAllocatePoolWithTag( + NonPagedPoolNx, length, 'zfsr'); if (regBuffer == NULL) continue; - status = ZwEnumerateValueKey(h, index, KeyValueFullInformation, regBuffer, length, &length); + status = ZwEnumerateValueKey(h, index, KeyValueFullInformation, + regBuffer, length, &length); if (!NT_SUCCESS(status)) { ExFreePool(regBuffer); continue; @@ -293,55 +333,72 @@ int spl_kstat_registry(void *arg, kstat_t *ksp) // Convert name to straight ascii so we compare with kstat ULONG outlen; status = RtlUnicodeToUTF8N(keyname, KSTAT_STRLEN, &outlen, - regBuffer->Name, regBuffer->NameLength); + regBuffer->Name, regBuffer->NameLength); // Conversion failed? move along.. if (status != STATUS_SUCCESS && - status != STATUS_SOME_NOT_MAPPED) { + status != STATUS_SOME_NOT_MAPPED) { ExFreePool(regBuffer); continue; } - // Output string is only null terminated if input is, so do so now. + // Output string is only null terminated if input is, do so now. keyname[outlen] = 0; - // Support for registry values that are not tunable through kstat. Those bypass the kstat name matching loop + // Support registry values that are not tunable through kstat. + // Those bypass the kstat name matching loop // and get directly set in the corresponding code variable. // if (strcasecmp("zfs_vdev_protection_filter", keyname) == 0) { if (regBuffer->Type != REG_SZ || - regBuffer->DataLength > (sizeof(zfs_vdev_protection_filter)-sizeof(wchar_t))) { // will be NULL terminated - KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "%s: registry '%s'. Type needs to be REG_SZ (63 wchar max)\n", __func__, - keyname)); + regBuffer->DataLength > + (sizeof (zfs_vdev_protection_filter) - + sizeof (wchar_t))) { + // will be NULL terminated + KdPrintEx((DPFLTR_IHVDRIVER_ID, + DPFLTR_ERROR_LEVEL, + "%s: registry '%s'. " + "Type needs to be REG_SZ (63 wchar max)\n", + __func__, + keyname)); ExFreePool(regBuffer); continue; } - char* newvalue = (char*)((uint8_t*)regBuffer + regBuffer->DataOffset); - KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "%s: registry '%s': %S\n", __func__, - keyname, newvalue)); - - bzero(zfs_vdev_protection_filter, sizeof(zfs_vdev_protection_filter)); - bcopy(newvalue, zfs_vdev_protection_filter, min(sizeof(zfs_vdev_protection_filter), regBuffer->DataLength)); - } - else { - // Now iterate kstats and attempt to match name with 'keyname'. + char *newvalue = (char *)((uint8_t *)regBuffer + + regBuffer->DataOffset); + KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, + "%s: registry '%s': %S\n", __func__, + keyname, newvalue)); + + bzero(zfs_vdev_protection_filter, + sizeof (zfs_vdev_protection_filter)); + bcopy(newvalue, zfs_vdev_protection_filter, + min(sizeof (zfs_vdev_protection_filter), + regBuffer->DataLength)); + } else { + // Now iterate kstats and match name with 'keyname'. kstat_named_t *kold; kold = ksp->ks_data; - for (unsigned int i = 0; i < ksp->ks_ndata; i++, kold++) { + for (unsigned int i = 0; i < ksp->ks_ndata; + i++, kold++) { // Find name? if (kold != NULL && - !strcasecmp(kold->name, keyname)) { + !strcasecmp(kold->name, keyname)) { // Check types match and are supported - if (!spl_check_assign_types(kold, regBuffer)) + if (!spl_check_assign_types(kold, + regBuffer)) break; - // Special case 'hostid' is automatically generated if not - // set, so if we read it in, signal to not set it. - // KSTAT_UPDATE is called after this function completes. + // Special case 'hostid' is + // automatically generated if + // not set, so if we read it + // in, signal to not set it. + // KSTAT_UPDATE is called after + // this function completes. if (spl_hostid == 0 && - strcasecmp("hostid", keyname) == 0) + strcasecmp("hostid", keyname) == 0) spl_hostid = 1; // Non-zero changed++; @@ -349,11 +406,12 @@ int spl_kstat_registry(void *arg, kstat_t *ksp) } } } - + ExFreePool(regBuffer); } // for() all keys - // Now check that hostid was read it, if it wasn't, make up a random one. + // Now check that hostid was read it, if it wasn't, + // make up a random one. if (spl_hostid == 0) { spl_create_hostid(h, pRegistryPath); } @@ -364,65 +422,3 @@ int spl_kstat_registry(void *arg, kstat_t *ksp) ZwClose(h); return (changed); } - -/* -* Visual Studio -1> C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.28.29333\bin\HostX86\x64\CL.exe -/c -/IC:\src\openzfs\contrib\windows\OpenZFS\..\..\..\include\os\windows\spl -/IC:\src\openzfs\contrib\windows\OpenZFS\..\..\..\include\os\windows\zfs -/IC:\src\openzfs\contrib\windows\OpenZFS\..\..\..\include\os\windows -/Ix64\Debug\ -/Zi -/nologo -/W3 -/WX- -/diagnostics:column -/Od -/Oi -/Oy- -/D _KERNEL -/D _KERNEL_ -/D _WIN64 -/D _AMD64_ -/D AMD64 -/D _WIN64 -/D _AMD64_ -/D AMD64 -/D DEPRECATE_DDK_FUNCTIONS=1 -/D MSC_NOOPT -/D _WIN32_WINNT=0x0601 -/D WINVER=0x0601 -/D WINNT=1 -/D NTDDI_VERSION=0x06010000 -/D DBG=1 -/D KMDF_VERSION_MAJOR=1 -/D KMDF_VERSION_MINOR=9 -/GF -/Gm- -/Zp8 -/GS -/guard:cf -/Gy -/fp:precise -/Qspectre -/Zc:wchar_t- -/Zc:forScope -/Zc:inline -/GR- -/Fo"x64\Debug\\" -/Fd"x64\Debug\vc142.pdb" -/Gz -/wd4748 /wd4603 /wd4627 /wd4986 /wd4987 -/FI"C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\shared\warning.h" -/FC /errorReport:prompt -/kernel --cbstring -d2epilogunwind -/d1import_no_registry -/d2AllowCompatibleILVersions -/d2Zi+ ..\..\..\..\module\os\windows\driver.c -* -* 1> C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.28.29333\bin\HostX86\x64\link.exe /ERRORREPORT:PROMPT /OUT:"C:\src\openzfs\contrib\windows\OpenZFS\x64\Debug\OpenZFS.sys" /VERSION:"10.0" /INCREMENTAL:NO /NOLOGO /LIBPATH:"C:\src\openzfs\contrib\windows\OpenZFS\..\..\..\out\build\x64-Debug\module\os\windows\spl" /LIBPATH:"C:\src\openzfs\contrib\windows\OpenZFS\..\..\..\out\build\x64-Debug\module\os\windows\zfs" /LIBPATH:"C:\src\openzfs\contrib\windows\OpenZFS\..\..\..\out\build\x64-Debug\module\icp" /LIBPATH:"C:\src\openzfs\contrib\windows\OpenZFS\..\..\..\out\build\x64-Debug\module\lua" /LIBPATH:"C:\src\openzfs\contrib\windows\OpenZFS\..\..\..\out\build\x64-Debug\module\nvpair" /LIBPATH:"C:\src\openzfs\contrib\windows\OpenZFS\..\..\..\out\build\x64-Debug\module\unicode" /LIBPATH:"C:\src\openzfs\contrib\windows\OpenZFS\..\..\..\out\build\x64-Debug\module\zcommon" /LIBPATH:"C:\src\openzfs\contrib\windows\OpenZFS\..\..\..\out\build\x64-Debug\module\zfs" /LIBPATH:"C:\src\openzfs\contrib\windows\OpenZFS\..\..\..\out\build\x64-Debug\module\zstd" /LIBPATH:"C:\src\openzfs\contrib\windows\OpenZFS\..\..\..\out\build\x64-Debug\lib\os\windows\zlib-1.2.3" /WX /SECTION:"INIT,d" wdmsec.lib Storport.lib scsiwmi.lib splkern.lib icpkern.lib luakern.lib nvpairkern.lib unicodekern.lib zcommonkern.lib zlibkern.lib zstdkern.lib zfskern.lib zfskern_os.lib "C:\Program Files (x86)\Windows Kits\10\lib\10.0.19041.0\km\x64\BufferOverflowK.lib" "C:\Program Files (x86)\Windows Kits\10\lib\10.0.19041.0\km\x64\ntoskrnl.lib" "C:\Program Files (x86)\Windows Kits\10\lib\10.0.19041.0\km\x64\hal.lib" "C:\Program Files (x86)\Windows Kits\10\lib\10.0.19041.0\km\x64\wmilib.lib" "C:\Program Files (x86)\Windows Kits\10\lib\wdf\kmdf\x64\1.9\WdfLdr.lib" "C:\Program Files (x86)\Windows Kits\10\lib\wdf\kmdf\x64\1.9\WdfDriverEntry.lib" "C:\Program Files (x86)\Windows Kits\10\lib\10.0.19041.0\km\x64\BufferOverflowK.lib" "C:\Program Files (x86)\Windows Kits\10\lib\10.0.19041.0\km\x64\ntoskrnl.lib" "C:\Program Files (x86)\Windows Kits\10\lib\10.0.19041.0\km\x64\hal.lib" "C:\Program Files (x86)\Windows Kits\10\lib\10.0.19041.0\km\x64\wmilib.lib" "C:\Program Files (x86)\Windows Kits\10\lib\wdf\kmdf\x64\1.9\WdfLdr.lib" "C:\Program Files (x86)\Windows Kits\10\lib\wdf\kmdf\x64\1.9\WdfDriverEntry.lib" /NODEFAULTLIB /MANIFEST:NO /DEBUG:FASTLINK /PDB:"C:\src\openzfs\contrib\windows\OpenZFS\x64\Debug\OpenZFS.pdb" /SUBSYSTEM:NATIVE,"6.01" /Driver /OPT:REF /OPT:ICF /ENTRY:"FxDriverEntry" /RELEASE /IMPLIB:"C:\src\openzfs\contrib\windows\OpenZFS\x64\Debug\OpenZFS.lib" /MERGE:"_TEXT=.text;_PAGE=PAGE" /MACHINE:X64 /PROFILE /guard:cf /kernel /IGNORE:4198,4010,4037,4039,4065,4070,4078,4087,4089,4221,4108,4088,4218,4218,4235 /osversion:10.0 /pdbcompress /debugtype:pdata x64\Debug\debug.obj - -* */ - diff --git a/module/os/windows/spl/spl-atomic.c b/module/os/windows/spl/spl-atomic.c index 897adcb544e..d2a6d1b68bc 100644 --- a/module/os/windows/spl/spl-atomic.c +++ b/module/os/windows/spl/spl-atomic.c @@ -18,9 +18,9 @@ * * CDDL HEADER END * - ***************************************************************************** + * *************************************************************************** * Solaris Porting Layer (SPL) Atomic Implementation. - ***************************************************************************** + * *************************************************************************** */ /* @@ -30,24 +30,17 @@ */ #include -//#include - - -//#include #include -//#include #include #ifdef _KERNEL -/* nothing */ - - -void *atomic_cas_ptr(volatile void *_target, void *_cmp, void *_new) +void * +atomic_cas_ptr(volatile void *_target, void *_cmp, void *_new) { - return InterlockedCompareExchangePointer((volatile PVOID *)_target, _new, _cmp); + return (InterlockedCompareExchangePointer((volatile PVOID *)_target, + _new, _cmp)); } - #endif diff --git a/module/os/windows/spl/spl-condvar.c b/module/os/windows/spl/spl-condvar.c index 0b2ca5f021f..69874adb144 100644 --- a/module/os/windows/spl/spl-condvar.c +++ b/module/os/windows/spl/spl-condvar.c @@ -23,62 +23,61 @@ * * Copyright (C) 2017 Jorgen Lundman * - * Following the guide at http://www.cs.wustl.edu/~schmidt/win32-cv-1.html and implementing the - * second-to-last suggestion, albeit in kernel mode, and replacing CriticalSection with Atomics. - * At some point, we should perhaps look at the final "SignalObjectAndWait" solution, presumably + * Following the guide at http://www.cs.wustl.edu/~schmidt/win32-cv-1.html + * and implementing the second-to-last suggestion, albeit in kernel mode, + * and replacing CriticalSection with Atomics. At some point, we should + * perhaps look at the final "SignalObjectAndWait" solution, presumably * by using the Wait argument to Mutex, and call WaitForObject. */ #include #include #include -//#include #include #ifdef SPL_DEBUG_MUTEX void spl_wdlist_settime(void *mpleak, uint64_t value); #endif -#define CONDVAR_INIT 0x12345678 +#define CONDVAR_INIT 0x12345678 void spl_cv_init(kcondvar_t *cvp, char *name, kcv_type_t type, void *arg) { (void) cvp; (void) name; (void) type; (void) arg; - //DbgBreakPoint(); - KeInitializeEvent(&cvp->kevent[CV_SIGNAL], SynchronizationEvent, FALSE); - KeInitializeEvent(&cvp->kevent[CV_BROADCAST], NotificationEvent, FALSE); -// KeInitializeSpinLock(&cvp->waiters_count_lock); - cvp->waiters_count = 0; - cvp->initialised = CONDVAR_INIT; + + KeInitializeEvent(&cvp->cv_kevent[CV_SIGNAL], SynchronizationEvent, + FALSE); + KeInitializeEvent(&cvp->cv_kevent[CV_BROADCAST], NotificationEvent, + FALSE); + + cvp->cv_waiters_count = 0; + cvp->cv_initialised = CONDVAR_INIT; } void spl_cv_destroy(kcondvar_t *cvp) { - if (cvp->initialised != CONDVAR_INIT) - panic("%s: not initialised", __func__); + if (cvp->cv_initialised != CONDVAR_INIT) + panic("%s: not cv_initialised", __func__); // We have probably already signalled the waiters, but we need to // kick around long enough for them to wake. - while (cvp->waiters_count > 0) + while (cvp->cv_waiters_count > 0) cv_broadcast(cvp); - ASSERT0(cvp->waiters_count); - cvp->initialised = 0; + ASSERT0(cvp->cv_waiters_count); + cvp->cv_initialised = 0; } void spl_cv_signal(kcondvar_t *cvp) { - if (cvp->initialised != CONDVAR_INIT) - panic("%s: not initialised", __func__); -// KIRQL oldIrq; + if (cvp->cv_initialised != CONDVAR_INIT) + panic("%s: not cv_initialised", __func__); -// KeAcquireSpinLock(&cvp->waiters_count_lock, &oldIrq); - uint32_t have_waiters = cvp->waiters_count > 0; -// KeReleaseSpinLock(&cvp->waiters_count_lock, oldIrq); + uint32_t have_waiters = cvp->cv_waiters_count > 0; if (have_waiters) - KeSetEvent(&cvp->kevent[CV_SIGNAL], 0, FALSE); + KeSetEvent(&cvp->cv_kevent[CV_SIGNAL], 0, FALSE); } // WakeConditionVariable or WakeAllConditionVariable function. @@ -86,16 +85,13 @@ spl_cv_signal(kcondvar_t *cvp) void spl_cv_broadcast(kcondvar_t *cvp) { - if (cvp->initialised != CONDVAR_INIT) - panic("%s: not initialised", __func__); -// KIRQL oldIrq; + if (cvp->cv_initialised != CONDVAR_INIT) + panic("%s: not cv_initialised", __func__); -// KeAcquireSpinLock(&cvp->waiters_count_lock, &oldIrq); - int have_waiters = cvp->waiters_count > 0; -// KeReleaseSpinLock(&cvp->waiters_count_lock, oldIrq); + int have_waiters = cvp->cv_waiters_count > 0; if (have_waiters) - KeSetEvent(&cvp->kevent[CV_BROADCAST], 0, FALSE); + KeSetEvent(&cvp->cv_kevent[CV_BROADCAST], 0, FALSE); } /* @@ -106,49 +102,41 @@ int spl_cv_wait(kcondvar_t *cvp, kmutex_t *mp, int flags, const char *msg) { int result; - if (cvp->initialised != CONDVAR_INIT) - panic("%s: not initialised", __func__); + if (cvp->cv_initialised != CONDVAR_INIT) + panic("%s: not cv_initialised", __func__); - if (msg != NULL && msg[0] == '&') - ++msg; /* skip over '&' prefixes */ + if (msg != NULL && msg[0] == '&') + ++msg; /* skip over '&' prefixes */ #ifdef SPL_DEBUG_MUTEX spl_wdlist_settime(mp->leak, 0); #endif -// KIRQL oldIrq; -// KeAcquireSpinLock(&cvp->waiters_count_lock, &oldIrq); - atomic_inc_32(&cvp->waiters_count); -// KeReleaseSpinLock(&cvp->waiters_count_lock, oldIrq); + + atomic_inc_32(&cvp->cv_waiters_count); mutex_exit(mp); - void *locks[CV_MAX_EVENTS] = { &cvp->kevent[CV_SIGNAL], &cvp->kevent[CV_BROADCAST] }; - result = KeWaitForMultipleObjects(2, locks, WaitAny, Executive, KernelMode, FALSE, NULL, NULL); -// KeAcquireSpinLock(&cvp->waiters_count_lock, &oldIrq); + void *locks[CV_MAX_EVENTS] = + { &cvp->cv_kevent[CV_SIGNAL], &cvp->cv_kevent[CV_BROADCAST] }; + + result = KeWaitForMultipleObjects(2, locks, WaitAny, Executive, + KernelMode, FALSE, NULL, NULL); + // If last listener, clear BROADCAST event. (Even if it was SIGNAL // overclearing will not hurt?) mutex_enter(mp); - if (cvp->waiters_count == 1) - KeClearEvent(&cvp->kevent[CV_BROADCAST]); - - atomic_dec_32(&cvp->waiters_count); - - //int last_waiter = - // result == STATUS_WAIT_0 + CV_BROADCAST - // && cvp->waiters_count == 0; -// KeReleaseSpinLock(&cvp->waiters_count_lock, oldIrq); - - //if (last_waiter) - // KeClearEvent(&cvp->kevent[CV_BROADCAST]); + if (cvp->cv_waiters_count == 1) + KeClearEvent(&cvp->cv_kevent[CV_BROADCAST]); + atomic_dec_32(&cvp->cv_waiters_count); #ifdef SPL_DEBUG_MUTEX spl_wdlist_settime(mp->leak, gethrestime_sec()); #endif - /* - * 1 - condvar got cv_signal()/cv_broadcast() - * 0 - received signal (kill -signal) - */ - return (result == STATUS_ALERTED ? 0 : 1); + /* + * 1 - condvar got cv_signal()/cv_broadcast() + * 0 - received signal (kill -signal) + */ + return (result == STATUS_ALERTED ? 0 : 1); } /* @@ -160,18 +148,18 @@ spl_cv_wait(kcondvar_t *cvp, kmutex_t *mp, int flags, const char *msg) */ int spl_cv_timedwait(kcondvar_t *cvp, kmutex_t *mp, clock_t tim, int flags, - const char *msg) + const char *msg) { - int result; + int result; clock_t timenow; LARGE_INTEGER timeout; (void) cvp; (void) flags; - if (cvp->initialised != CONDVAR_INIT) - panic("%s: not initialised", __func__); - + if (cvp->cv_initialised != CONDVAR_INIT) + panic("%s: not cv_initialised", __func__); + if (msg != NULL && msg[0] == '&') - ++msg; /* skip over '&' prefixes */ + ++msg; /* skip over '&' prefixes */ timenow = zfs_lbolt(); @@ -191,26 +179,24 @@ spl_cv_timedwait(kcondvar_t *cvp, kmutex_t *mp, clock_t tim, int flags, #ifdef SPL_DEBUG_MUTEX spl_wdlist_settime(mp->leak, 0); #endif -// KIRQL oldIrq; -// KeAcquireSpinLock(&cvp->waiters_count_lock, &oldIrq); - atomic_inc_32(&cvp->waiters_count); -// KeReleaseSpinLock(&cvp->waiters_count_lock, oldIrq); + + atomic_inc_32(&cvp->cv_waiters_count); mutex_exit(mp); - void *locks[CV_MAX_EVENTS] = { &cvp->kevent[CV_SIGNAL], &cvp->kevent[CV_BROADCAST] }; - result = KeWaitForMultipleObjects(2, locks, WaitAny, Executive, KernelMode, FALSE, &timeout, NULL); + void *locks[CV_MAX_EVENTS] = + { &cvp->cv_kevent[CV_SIGNAL], &cvp->cv_kevent[CV_BROADCAST] }; + + result = KeWaitForMultipleObjects(2, locks, WaitAny, Executive, + KernelMode, FALSE, &timeout, NULL); -// KeAcquireSpinLock(&cvp->waiters_count_lock, &oldIrq); - int last_waiter = - result == STATUS_WAIT_0 + CV_BROADCAST - && cvp->waiters_count == 1; -// KeReleaseSpinLock(&cvp->waiters_count_lock, oldIrq); + result == STATUS_WAIT_0 + CV_BROADCAST && + cvp->cv_waiters_count == 1; if (last_waiter) - KeClearEvent(&cvp->kevent[CV_BROADCAST]); + KeClearEvent(&cvp->cv_kevent[CV_BROADCAST]); - atomic_dec_32(&cvp->waiters_count); + atomic_dec_32(&cvp->cv_waiters_count); mutex_enter(mp); @@ -218,75 +204,73 @@ spl_cv_timedwait(kcondvar_t *cvp, kmutex_t *mp, clock_t tim, int flags, spl_wdlist_settime(mp->leak, gethrestime_sec()); #endif - switch (result) { + switch (result) { - case STATUS_ALERTED: /* Signal */ - case ERESTART: - return (0); + case STATUS_ALERTED: /* Signal */ + case ERESTART: + return (0); - case STATUS_TIMEOUT: /* Timeout */ - return (-1); - } + case STATUS_TIMEOUT: /* Timeout */ + return (-1); + } - return (1); + return (1); } /* -* Compatibility wrapper for the cv_timedwait_hires() Illumos interface. -*/ + * Compatibility wrapper for the cv_timedwait_hires() Illumos interface. + */ int cv_timedwait_hires(kcondvar_t *cvp, kmutex_t *mp, hrtime_t tim, - hrtime_t res, int flag) + hrtime_t res, int flag) { - int result; + int result; LARGE_INTEGER timeout; - if (cvp->initialised != CONDVAR_INIT) - panic("%s: not initialised", __func__); - ASSERT(cvp->initialised == CONDVAR_INIT); + if (cvp->cv_initialised != CONDVAR_INIT) + panic("%s: not cv_initialised", __func__); + ASSERT(cvp->cv_initialised == CONDVAR_INIT); if (res > 1) { - /* - * Align expiration to the specified resolution. - */ - if (flag & CALLOUT_FLAG_ROUNDUP) - tim += res - 1; - tim = (tim / res) * res; - } + /* + * Align expiration to the specified resolution. + */ + if (flag & CALLOUT_FLAG_ROUNDUP) + tim += res - 1; + tim = (tim / res) * res; + } if (flag & CALLOUT_FLAG_ABSOLUTE) { - // 'tim' here is absolute UNIX time (from gethrtime()) so convert it to - // absolute Windows time + // 'tim' here is absolute UNIX time (from gethrtime()) so + // convert it to absolute Windows time hrtime_t now = gethrtime(); - tim -= now; // Remove the ticks, what remains should be "sleep" amount. + tim -= now; // Remove the ticks, what remains is "sleep" amount. } timeout.QuadPart = -tim / 100; #ifdef SPL_DEBUG_MUTEX spl_wdlist_settime(mp->leak, 0); #endif -// KIRQL oldIrq; -// KeAcquireSpinLock(&cvp->waiters_count_lock, &oldIrq); - atomic_inc_32(&cvp->waiters_count); -// KeReleaseSpinLock(&cvp->waiters_count_lock, oldIrq); + + atomic_inc_32(&cvp->cv_waiters_count); mutex_exit(mp); - void *locks[CV_MAX_EVENTS] = { &cvp->kevent[CV_SIGNAL], &cvp->kevent[CV_BROADCAST] }; - result = KeWaitForMultipleObjects(2, locks, WaitAny, Executive, KernelMode, FALSE, &timeout, NULL); + void *locks[CV_MAX_EVENTS] = + { &cvp->cv_kevent[CV_SIGNAL], &cvp->cv_kevent[CV_BROADCAST] }; + + result = KeWaitForMultipleObjects(2, locks, WaitAny, Executive, + KernelMode, FALSE, &timeout, NULL); -// KeAcquireSpinLock(&cvp->waiters_count_lock, &oldIrq); - int last_waiter = - result == STATUS_WAIT_0 + CV_BROADCAST - && cvp->waiters_count == 1; -// KeReleaseSpinLock(&cvp->waiters_count_lock, oldIrq); + result == STATUS_WAIT_0 + CV_BROADCAST && + cvp->cv_waiters_count == 1; if (last_waiter) - KeClearEvent(&cvp->kevent[CV_BROADCAST]); - - atomic_dec_32(&cvp->waiters_count); + KeClearEvent(&cvp->cv_kevent[CV_BROADCAST]); + + atomic_dec_32(&cvp->cv_waiters_count); mutex_enter(mp); @@ -294,15 +278,15 @@ cv_timedwait_hires(kcondvar_t *cvp, kmutex_t *mp, hrtime_t tim, spl_wdlist_settime(mp->leak, gethrestime_sec()); #endif - switch (result) { + switch (result) { - case STATUS_ALERTED: /* Signal */ - case ERESTART: - return (0); + case STATUS_ALERTED: /* Signal */ + case ERESTART: + return (0); - case STATUS_TIMEOUT: /* Timeout */ - return (-1); - } + case STATUS_TIMEOUT: /* Timeout */ + return (-1); + } - return (1); + return (1); } diff --git a/module/os/windows/spl/spl-cred.c b/module/os/windows/spl/spl-cred.c index 50fafbe8bc6..6e3abcfcb92 100644 --- a/module/os/windows/spl/spl-cred.c +++ b/module/os/windows/spl/spl-cred.c @@ -27,15 +27,14 @@ #include #include -//#include /* Return the effective user id */ uid_t crgetuid(const cred_t *cr) { - if (!cr) return 0; - // return kauth_cred_getuid((kauth_cred_t)cr); - return (uint64_t)-1; + if (!cr) + return (0); + return ((uint64_t)-1); } @@ -43,61 +42,62 @@ crgetuid(const cred_t *cr) uid_t crgetruid(const cred_t *cr) { - if (!cr) return 0; - //return kauth_cred_getruid((kauth_cred_t)cr); - return (uint64_t)-1; + if (!cr) + return (0); + return ((uint64_t)-1); } /* Return the saved user id */ uid_t crgetsuid(const cred_t *cr) { - if (!cr) return 0; - //return kauth_cred_getsvuid((kauth_cred_t)cr); - return (uint64_t)-1; + if (!cr) + return (0); + return ((uint64_t)-1); } /* Return the filesystem user id */ uid_t crgetfsuid(const cred_t *cr) { - if (!cr) return 0; - return (uint64_t)-1; + if (!cr) + return (0); + return ((uint64_t)-1); } /* Return the effective group id */ gid_t crgetgid(const cred_t *cr) { - if (!cr) return 0; -// return kauth_cred_getgid((kauth_cred_t)cr); - return (uint64_t)-1; + if (!cr) + return (0); + return ((uint64_t)-1); } /* Return the real group id */ gid_t crgetrgid(const cred_t *cr) { - if (!cr) return 0; -// return kauth_cred_getrgid((kauth_cred_t)cr); - return (uint64_t)-1; + if (!cr) + return (0); + return ((uint64_t)-1); } /* Return the saved group id */ gid_t crgetsgid(const cred_t *cr) { - if (!cr) return 0; -// return kauth_cred_getsvgid((kauth_cred_t)cr); - return (uint64_t)-1; + if (!cr) + return (0); + return ((uint64_t)-1); } /* Return the filesystem group id */ gid_t crgetfsgid(const cred_t *cr) { - (void)cr; - return (uint64_t)-1; + (void) cr; + return ((uint64_t)-1); } @@ -106,18 +106,11 @@ crgetfsgid(const cred_t *cr) * memcpy's them over. No real clean way to get around that, but at least * these calls are done sparingly. */ -int crgetngroups(const cred_t *cr) +int +crgetngroups(const cred_t *cr) { - (void)cr; - // gid_t gids[NGROUPS]; -// int count = NGROUPS; -// int ret; -// -// ret = kauth_cred_getgroups((kauth_cred_t) cr, gids, &count); -// -// if (!ret) return count; - - return 0; + (void) cr; + return (0); } @@ -126,40 +119,43 @@ int crgetngroups(const cred_t *cr) * be until after the call. Unlike IllumOS, the ptr returned is allocated * and must be returned by a call to crgetgroupsfree(). */ -gid_t *crgetgroups(const cred_t *cr) +gid_t * +crgetgroups(const cred_t *cr) { gid_t *gids; int count = NGROUPS; - (void)cr; + (void) cr; - gids = kmem_zalloc(sizeof(gid_t) * count, KM_SLEEP); - if (!gids) return NULL; + gids = kmem_zalloc(sizeof (gid_t) * count, KM_SLEEP); + if (!gids) + return (NULL); - //kauth_cred_getgroups((kauth_cred_t) cr, gids, &count); - - return gids; + return (gids); } -void crgetgroupsfree(gid_t *gids) +void +crgetgroupsfree(gid_t *gids) { - if (!gids) return; - kmem_free(gids, sizeof(gid_t) * NGROUPS); + if (!gids) + return; + kmem_free(gids, sizeof (gid_t) * NGROUPS); } /* * Return true if "cr" belongs in group "gid". */ -int spl_cred_ismember_gid(cred_t *cr, gid_t gid) +int +spl_cred_ismember_gid(cred_t *cr, gid_t gid) { int ret = 0; // Is not member. - (void)cr; (void)gid; - //kauth_cred_ismember_gid((kauth_cred_t)cr, gid, &ret); + (void) cr; (void) gid; if (ret == 1) - return TRUE; - return FALSE; + return (TRUE); + return (FALSE); } -int groupmember(gid_t gid, kauth_cred_t *cred) +int +groupmember(gid_t gid, kauth_cred_t *cred) { - return 0; -} \ No newline at end of file + return (0); +} diff --git a/module/os/windows/spl/spl-ddi.c b/module/os/windows/spl/spl-ddi.c index c3e96932b67..ba36849d20f 100644 --- a/module/os/windows/spl/spl-ddi.c +++ b/module/os/windows/spl/spl-ddi.c @@ -23,7 +23,6 @@ #include #include #include -//#include /* * Allocate a set of pointers to 'n_items' objects of size 'size' @@ -277,8 +276,6 @@ ddi_soft_state_fini(void **state_p) static char msg[] = "ddi_soft_state_fini:"; if (state_p == NULL || (ss = *state_p) == NULL) { - //cmn_err(CE_WARN, "%s null handle", - // msg); return; } @@ -314,67 +311,41 @@ ddi_create_minor_node(dev_info_t *dip, char *name, int spec_type, minor_t minor_num, char *node_type, int flag) { dev_t dev; - int error=0; - char *r, *dup; + int error = 0; + char *r, *dup; - //printf("ddi_create_minor_node: name %s: %d,%d\n", name, flag, minor_num); - - //dev = makedev(flag, minor_num); dev = minor_num; dip->dev = dev; - /* - * http://lists.apple.com/archives/darwin-kernel/2007/Nov/msg00038.html - * - * devfs_make_name() has an off-by-one error when using directories - * and it appears Apple does not want to fix it. - * - * We then change "/" to "_" and create more Apple-like /dev names - * - */ - MALLOC(dup, char *, strlen(name)+1, M_TEMP, M_WAITOK); - if (dup == NULL) return ENOMEM; - bcopy(name, dup, strlen(name)); + MALLOC(dup, char *, strlen(name)+1, M_TEMP, M_WAITOK); + if (dup == NULL) + return (ENOMEM); + bcopy(name, dup, strlen(name)); dup[strlen(name)] = '\0'; - for (r = dup; - (r=strchr(r, '/')); - *r = '_') /* empty */ ; - - dip->devc = NULL; - dip->devb = NULL; -#if 0 - if (spec_type == S_IFCHR) - dip->devc = devfs_make_node(dev, DEVFS_CHAR, /* Make the node */ - UID_ROOT, GID_OPERATOR, - 0600, "rdisk_%s", dup); - //0600, "rdisk3", dup); - else - dip->devb = devfs_make_node(dev, DEVFS_BLOCK, /* Make the node */ - UID_ROOT, GID_OPERATOR, - 0600, "disk_%s", dup); - //0600, "disk3", dup); -#endif - //printf("ddi_create_minor: devfs_make_name '%s'\n", dup ); + for (r = dup; + (r = strchr(r, '/')); + *r = '_') + /* empty */; + + dip->devc = NULL; + dip->devb = NULL; - FREE(dup, M_TEMP); + FREE(dup, M_TEMP); - return error; + return (error); } void ddi_remove_minor_node(dev_info_t *dip, char *name) { - //printf("zvol: remove minor: '%s'\n", name ? name : ""); - if (dip->devc) { -// devfs_remove(dip->devc); - dip->devc = NULL; - } - if (dip->devb) { - // devfs_remove(dip->devb); - dip->devb = NULL; - } + if (dip->devc) { + dip->devc = NULL; + } + if (dip->devb) { + dip->devb = NULL; + } } @@ -416,18 +387,18 @@ ddi_strtol(const char *str, char **nptr, int base, long *result) else base = 8; /* - * for any base > 10, the digits incrementally following - * 9 are assumed to be "abc...z" or "ABC...Z" - */ + * for any base > 10, the digits incrementally following + * 9 are assumed to be "abc...z" or "ABC...Z" + */ if (!lisalnum(c) || (xx = DIGIT(c)) >= base) { /* no number formed */ return (EINVAL); } if (base == 16 && c == '0' && (ustr[1] == 'x' || ustr[1] == 'X') && - isxdigit(ustr[2])) + isxdigit(ustr[2])) c = *(ustr += 2); /* skip over leading "0x" or "0X" */ - /* this code assumes that abs(LONG_MIN) >= abs(LONG_MAX) */ + /* this code assumes that abs(LONG_MIN) >= abs(LONG_MAX) */ if (neg) limit = LONG_MIN; else @@ -457,7 +428,7 @@ ddi_strtol(const char *str, char **nptr, int base, long *result) return (ERANGE); } -char * __cdecl +char *__cdecl strpbrk(const char *s, const char *b) { const char *p; @@ -530,18 +501,18 @@ ddi_strtoll(const char *str, char **nptr, int base, long long *result) else base = 8; /* - * for any base > 10, the digits incrementally following - * 9 are assumed to be "abc...z" or "ABC...Z" - */ + * for any base > 10, the digits incrementally following + * 9 are assumed to be "abc...z" or "ABC...Z" + */ if (!lisalnum(c) || (xx = DIGIT(c)) >= base) { /* no number formed */ return (EINVAL); } if (base == 16 && c == '0' && (ustr[1] == 'x' || ustr[1] == 'X') && - isxdigit(ustr[2])) + isxdigit(ustr[2])) c = *(ustr += 2); /* skip over leading "0x" or "0X" */ - /* this code assumes that abs(LONG_MIN) >= abs(LONG_MAX) */ + /* this code assumes that abs(LONG_MIN) >= abs(LONG_MAX) */ if (neg) limit = LONGLONG_MIN; else @@ -572,15 +543,15 @@ ddi_strtoll(const char *str, char **nptr, int base, long long *result) } uint32_t -ddi_strcspn(const char * __restrict s, const char * __restrict charset) +ddi_strcspn(const char *__restrict s, const char *__restrict charset) { /* * NB: idx and bit are temporaries whose use causes gcc 3.4.2 to * generate better code. Without them, gcc gets a little confused. */ const char *s1; - u_long bit; - u_long tbl[(255 + 1) / LONG_BIT]; + ulong_t bit; + ulong_t tbl[(255 + 1) / LONG_BIT]; int idx; if (*s == '\0') return (0); @@ -588,7 +559,7 @@ ddi_strcspn(const char * __restrict s, const char * __restrict charset) // 64bit code tbl[0] = 1; tbl[3] = tbl[2] = tbl[1] = 0; - for (; *charset != '\0'; charset++) { + for (; *charset != '\0'; charset++) { idx = IDX(*charset); bit = BIT(*charset); tbl[idx] |= bit; @@ -604,45 +575,39 @@ ddi_strcspn(const char * __restrict s, const char * __restrict charset) return (uint32_t)(s1 - s); } -#ifndef __clong__ extern size_t strlcpy(char *s, const char *t, size_t n) { - const char* o = t; + const char *o = t; if (n) - do - { - if (!--n) - { + do { + if (!--n) { *s = 0; break; } } while (*s++ = *t++); - if (!n) - while (*t++); - return (uint32_t)(t - o - 1); + if (!n) + while (*t++) + ; + return (uint32_t)(t - o - 1); } extern size_t strlcat(char *s, const char *t, size_t n) { register size_t m; - const char* o = t; + const char *o = t; - if (m = n) - { - while (n && *s) - { + if (m = n) { + while (n && *s) { n--; s++; } m -= n; if (n) - do - { - if (!--n) - { + do { + if (!--n) { *s = 0; break; } @@ -651,7 +616,7 @@ strlcat(char *s, const char *t, size_t n) *s = 0; } if (!n) - while (*t++); - return (t - o) + m - 1; + while (*t++) + ; + return ((t - o) + m - 1); } -#endif diff --git a/module/os/windows/spl/spl-debug.c b/module/os/windows/spl/spl-debug.c index fcb9754ce35..d0681ec4413 100644 --- a/module/os/windows/spl/spl-debug.c +++ b/module/os/windows/spl/spl-debug.c @@ -21,10 +21,9 @@ #include #include -#include -#include -void panic(const char *fmt, ...) __attribute__((__noreturn__)) +void +panic(const char *fmt, ...) __attribute__((__noreturn__)) { va_list ap; va_start(ap, fmt); @@ -33,7 +32,7 @@ void panic(const char *fmt, ...) __attribute__((__noreturn__)) DbgBreakPoint(); windows_delay(hz); } while (1); - va_end(ap); + va_end(ap); } diff --git a/module/os/windows/spl/spl-err.c b/module/os/windows/spl/spl-err.c index d51c047f81b..f54ff5405e2 100644 --- a/module/os/windows/spl/spl-err.c +++ b/module/os/windows/spl/spl-err.c @@ -41,16 +41,16 @@ vcmn_err(int ce, const char *fmt, va_list ap) switch (ce) { case CE_IGNORE: break; - case CE_CONT: + case CE_CONT: dprintf("%s", msg); break; - case CE_NOTE: + case CE_NOTE: dprintf("SPL: Notice: %s\n", msg); break; - case CE_WARN: + case CE_WARN: TraceEvent(TRACE_WARNING, "SPL: Warning: %s\n", msg); break; - case CE_PANIC: + case CE_PANIC: PANIC("%s", msg); break; } @@ -59,9 +59,9 @@ vcmn_err(int ce, const char *fmt, va_list ap) void cmn_err(int ce, const char *fmt, ...) { - va_list ap; + va_list ap; - va_start(ap, fmt); - vcmn_err(ce, fmt, ap); - va_end(ap); + va_start(ap, fmt); + vcmn_err(ce, fmt, ap); + va_end(ap); } /* cmn_err() */ diff --git a/module/os/windows/spl/spl-kmem.c b/module/os/windows/spl/spl-kmem.c index 85023144f68..d19fac5dffe 100644 --- a/module/os/windows/spl/spl-kmem.c +++ b/module/os/windows/spl/spl-kmem.c @@ -29,31 +29,26 @@ */ #include -//#include #include #include -//#include #include #include #include -//#include #include #include #include #include -//#include #include -//#include #include // =============================================================== // Options // =============================================================== -// #define PRINT_CACHE_STATS 1 +// #define PRINT_CACHE_STATS 1 // Uncomment to turn on kmems' debug features. -//#define DEBUG +// #define DEBUG // =============================================================== // OS Interface // =============================================================== @@ -65,11 +60,15 @@ // proxy to the machine experiencing memory pressure. // // xnu vm variables -extern volatile unsigned int vm_page_free_wanted; // 0 by default smd -extern unsigned int vm_page_free_min; // 3500 by default smd kern.vm_page_free_min, rarely changes -extern volatile unsigned int vm_page_free_count; // will tend to vm_page_free_min smd -#define SMALL_PRESSURE_INCURSION_PAGES (vm_page_free_min >> 5) +// 0 by default smd +extern volatile unsigned int vm_page_free_wanted; +// 3500 by default smd kern.vm_page_free_min, rarely changes +extern unsigned int vm_page_free_min; +// will tend to vm_page_free_min smd +extern volatile unsigned int vm_page_free_count; + +#define SMALL_PRESSURE_INCURSION_PAGES (vm_page_free_min >> 5) static kcondvar_t spl_free_thread_cv; static kmutex_t spl_free_thread_lock; @@ -124,20 +123,11 @@ extern uint64_t total_memory; // Amount of RAM in bytes, in host machine (Windows) extern uint64_t real_total_memory; -#define MULT 1 +#define MULT 1 static const char *KMEM_VA_PREFIX = "kmem_va"; static const char *KMEM_MAGAZINE_PREFIX = "kmem_magazine_"; -// static char kext_version[64] = SPL_META_VERSION "-" SPL_META_RELEASE SPL_DEBUG_STR; - -//struct sysctl_oid_list sysctl__spl_children; -//SYSCTL_DECL(_spl); -//SYSCTL_NODE(, OID_AUTO, spl, CTLFLAG_RD, 0, ""); -//SYSCTL_STRING(_spl, OID_AUTO, kext_version, -// CTLFLAG_RD | CTLFLAG_LOCKED, -// kext_version, 0, "SPL KEXT Version"); - extern void kstat_init(void); @@ -327,10 +317,10 @@ uint32_t kmem_content_maxsave = 256; /* KMF_CONTENTS max bytes to log */ uint32_t kmem_lite_minsize = 0; /* minimum buffer size for KMF_LITE */ uint32_t kmem_lite_maxalign = 8192; /* maximum buffer alignment for KMF_LITE */ int kmem_lite_pcs = 4; /* number of PCs to store in KMF_LITE mode */ -uint32_t kmem_maxverify; /* maximum bytes to inspect in debug routines */ +uint32_t kmem_maxverify; /* maximum bytes to inspect in debug routines */ uint32_t kmem_minfirewall; /* hardware-enforced redzone threshold */ -uint32_t kmem_max_cached = KMEM_BIG_MAXBUF; /* maximum kmem_alloc cache */ +uint32_t kmem_max_cached = KMEM_BIG_MAXBUF; /* maximum kmem_alloc cache */ /* * Be aware that KMF_AUDIT does not release memory, and you will eventually @@ -453,9 +443,12 @@ static boolean_t kmem_move_any_partial; * caches are not fragmented (they may never be). These intervals are mean time * in cache maintenance intervals (kmem_cache_update). */ -uint32_t kmem_mtb_move = 20; /* defrag 1 slab (~15min) */ // smd: 60=15m, 20=5min -uint32_t kmem_mtb_reap = 240; /* defrag all slabs (~7.5hrs) */ // 1800=7.5h, 720=3h, 240=1h -uint32_t kmem_mtb_reap_count = 0; // how many times have we done an mtb reap? +/* defrag 1 slab (~15min) */ // smd: 60=15m, 20=5min +uint32_t kmem_mtb_move = 20; +/* defrag all slabs (~7.5hrs) */ // 1800=7.5h, 720=3h, 240=1h +uint32_t kmem_mtb_reap = 240; +// how many times have we done an mtb reap? +uint32_t kmem_mtb_reap_count = 0; #endif /* DEBUG */ static kmem_cache_t *kmem_defrag_cache; @@ -780,7 +773,8 @@ verify_pattern(uint64_t pattern, void *buf_arg, uint32_t size) } static void * -verify_and_copy_pattern(uint64_t old, uint64_t new, void *buf_arg, uint32_t size) +verify_and_copy_pattern(uint64_t old, uint64_t new, void *buf_arg, + uint32_t size) { uint64_t *bufend = (uint64_t *)((char *)buf_arg + size); uint64_t *buf; @@ -788,7 +782,7 @@ verify_and_copy_pattern(uint64_t old, uint64_t new, void *buf_arg, uint32_t size for (buf = buf_arg; buf < bufend; buf++) { if (*buf != old) { copy_pattern(old, buf_arg, - (uint32_t) ((char *)buf - (char *)buf_arg)); + (uint32_t)((char *)buf - (char *)buf_arg)); return (buf); } *buf = new; @@ -804,10 +798,10 @@ kmem_cache_applyall(void (*func)(kmem_cache_t *), taskq_t *tq, int tqflag) mutex_enter(&kmem_cache_lock); for (cp = list_head(&kmem_caches); cp != NULL; - cp = list_next(&kmem_caches, cp)) + cp = list_next(&kmem_caches, cp)) if (tq != NULL) (void) taskq_dispatch(tq, (task_func_t *)func, cp, - tqflag); + tqflag); else func(cp); mutex_exit(&kmem_cache_lock); @@ -820,12 +814,12 @@ kmem_cache_applyall_id(void (*func)(kmem_cache_t *), taskq_t *tq, int tqflag) mutex_enter(&kmem_cache_lock); for (cp = list_head(&kmem_caches); cp != NULL; - cp = list_next(&kmem_caches, cp)) { + cp = list_next(&kmem_caches, cp)) { if (!(cp->cache_cflags & KMC_IDENTIFIER)) continue; if (tq != NULL) (void) taskq_dispatch(tq, (task_func_t *)func, cp, - tqflag); + tqflag); else func(cp); } @@ -842,14 +836,14 @@ kmem_findslab(kmem_cache_t *cp, void *buf) mutex_enter(&cp->cache_lock); for (sp = list_head(&cp->cache_complete_slabs); sp != NULL; - sp = list_next(&cp->cache_complete_slabs, sp)) { + sp = list_next(&cp->cache_complete_slabs, sp)) { if (KMEM_SLAB_MEMBER(sp, buf)) { mutex_exit(&cp->cache_lock); return (sp); } } for (sp = avl_first(&cp->cache_partial_slabs); sp != NULL; - sp = AVL_NEXT(&cp->cache_partial_slabs, sp)) { + sp = AVL_NEXT(&cp->cache_partial_slabs, sp)) { if (KMEM_SLAB_MEMBER(sp, buf)) { mutex_exit(&cp->cache_lock); return (sp); @@ -877,7 +871,7 @@ kmem_error(int error, kmem_cache_t *cparg, void *bufarg) sp = kmem_findslab(cp, buf); if (sp == NULL) { for (cp = list_tail(&kmem_caches); cp != NULL; - cp = list_prev(&kmem_caches, cp)) { + cp = list_prev(&kmem_caches, cp)) { if ((sp = kmem_findslab(cp, buf)) != NULL) break; } @@ -891,8 +885,8 @@ kmem_error(int error, kmem_cache_t *cparg, void *bufarg) error = KMERR_BADCACHE; else buf = (char *)bufarg - - ((uintptr_t)bufarg - - (uintptr_t)sp->slab_base) % cp->cache_chunksize; + ((uintptr_t)bufarg - + (uintptr_t)sp->slab_base) % cp->cache_chunksize; if (buf != bufarg) error = KMERR_BADBASE; if (cp->cache_flags & KMF_BUFTAG) @@ -906,8 +900,8 @@ kmem_error(int error, kmem_cache_t *cparg, void *bufarg) if (bcp == NULL && btp != NULL) bcp = btp->bt_bufctl; if (kmem_findslab(cp->cache_bufctl_cache, bcp) == - NULL || P2PHASE((uintptr_t)bcp, KMEM_ALIGN) || - bcp->bc_addr != buf) { + NULL || P2PHASE((uintptr_t)bcp, KMEM_ALIGN) || + bcp->bc_addr != buf) { error = KMERR_BADBUFCTL; bcp = NULL; } @@ -927,33 +921,40 @@ kmem_error(int error, kmem_cache_t *cparg, void *bufarg) switch (error) { case KMERR_MODIFIED: - TraceEvent(TRACE_ERROR, "buffer modified after being freed\n"); - off = verify_pattern(KMEM_FREE_PATTERN, buf, cp->cache_verify); + TraceEvent(TRACE_ERROR, + "buffer modified after being freed\n"); + off = verify_pattern(KMEM_FREE_PATTERN, buf, + cp->cache_verify); if (off == NULL) /* shouldn't happen */ off = buf; - TraceEvent(TRACE_ERROR, "SPL: modification occurred at offset 0x%lx " - "(0x%llx replaced by 0x%llx)\n", - (uintptr_t)off - (uintptr_t)buf, - (longlong_t)KMEM_FREE_PATTERN, (longlong_t)*off); + TraceEvent(TRACE_ERROR, + "SPL: modification occurred at offset 0x%lx " + "(0x%llx replaced by 0x%llx)\n", + (uintptr_t)off - (uintptr_t)buf, + (longlong_t)KMEM_FREE_PATTERN, (longlong_t)*off); break; case KMERR_REDZONE: - TraceEvent(TRACE_ERROR, "redzone violation: write past end of buffer\n"); + TraceEvent(TRACE_ERROR, + "redzone violation: write past end of buffer\n"); break; case KMERR_BADADDR: - TraceEvent(TRACE_ERROR, "invalid free: buffer not in cache\n"); + TraceEvent(TRACE_ERROR, + "invalid free: buffer not in cache\n"); break; case KMERR_DUPFREE: - TraceEvent(TRACE_ERROR, "duplicate free: buffer freed twice\n"); + TraceEvent(TRACE_ERROR, + "duplicate free: buffer freed twice\n"); break; case KMERR_BADBUFTAG: TraceEvent(TRACE_ERROR, "boundary tag corrupted\n"); - TraceEvent(TRACE_ERROR, "SPL: bcp ^ bxstat = %lx, should be %lx\n", - (intptr_t)btp->bt_bufctl ^ btp->bt_bxstat, - KMEM_BUFTAG_FREE); + TraceEvent(TRACE_ERROR, + "SPL: bcp ^ bxstat = %lx, should be %lx\n", + (intptr_t)btp->bt_bufctl ^ btp->bt_bxstat, + KMEM_BUFTAG_FREE); break; case KMERR_BADBUFCTL: @@ -961,63 +962,56 @@ kmem_error(int error, kmem_cache_t *cparg, void *bufarg) break; case KMERR_BADCACHE: - TraceEvent(TRACE_ERROR, "buffer freed to wrong cache\n"); - TraceEvent(TRACE_ERROR, "SPL: buffer was allocated from %s,\n", cp->cache_name); - TraceEvent(TRACE_ERROR, "SPL: caller attempting free to %s.\n", cparg->cache_name); + TraceEvent(TRACE_ERROR, + "buffer freed to wrong cache\n"); + TraceEvent(TRACE_ERROR, + "SPL: buffer was allocated from %s,\n", + cp->cache_name); + TraceEvent(TRACE_ERROR, + "SPL: caller attempting free to %s.\n", + cparg->cache_name); break; case KMERR_BADSIZE: - TraceEvent(TRACE_ERROR, "bad free: free size (%u) != alloc size (%u)\n", - KMEM_SIZE_DECODE(((uint32_t *)btp)[0]), - KMEM_SIZE_DECODE(((uint32_t *)btp)[1])); + TraceEvent(TRACE_ERROR, + "bad free: free size (%u) != alloc size (%u)\n", + KMEM_SIZE_DECODE(((uint32_t *)btp)[0]), + KMEM_SIZE_DECODE(((uint32_t *)btp)[1])); break; case KMERR_BADBASE: - TraceEvent(TRACE_ERROR, "bad free: free address (%p) != alloc address (%p)\n", - bufarg, buf); + TraceEvent(TRACE_ERROR, + "bad free: free address (%p) != alloc " + "address (%p)\n", + bufarg, buf); break; } dprintf("SPL: buffer=%p bufctl=%p cache: %s\n", - bufarg, (void *)bcp, cparg->cache_name); + bufarg, (void *)bcp, cparg->cache_name); if (bcp != NULL && (cp->cache_flags & KMF_AUDIT) && - error != KMERR_BADBUFCTL) { + error != KMERR_BADBUFCTL) { int d; timestruc_t ts = {0, 0}; kmem_bufctl_audit_t *bcap = (kmem_bufctl_audit_t *)bcp; hrt2ts(kmem_panic_info.kmp_timestamp - bcap->bc_timestamp, &ts); dprintf("SPL: previous transaction on buffer %p:\n", buf); - dprintf("SPL: thread=%p time=T-%ld.%09ld slab=%p cache: %s\n", - (void *)bcap->bc_thread, ts.tv_sec, ts.tv_nsec, - (void *)sp, cp->cache_name); - -//#include <../um/DbgHelp.h> -//#pragma comment(lib, "Dbghelp.lib") -// HANDLE process; -// process = GetCurrentProcess(); -// SymInitialize(process, NULL, TRUE); -// SYMBOL_INFO symbol; + dprintf("SPL: thread=%p time=T-%ld.%09ld slab=%p cache: %s\n", + (void *)bcap->bc_thread, ts.tv_sec, ts.tv_nsec, + (void *)sp, cp->cache_name); for (d = 0; d < MIN(bcap->bc_depth, KMEM_STACK_DEPTH); d++) { - -// SymFromAddr(process, (DWORD64)(bcap->bc_stack[d]), 0, NULL); dprintf(" : %p\n, ", bcap->bc_stack[d]); } } if (kmem_panic > 0) { - //delay(hz); - //IOSleep(1000000); DbgBreakPoint(); panic("kernel heap corruption detected"); } - // if (kmem_panic == 0) { - // debug_enter(NULL); - // Debugger("Kernel heap corruption detected"); - // } DbgBreakPoint(); kmem_logging = 1; /* resume logging */ @@ -1028,7 +1022,8 @@ kmem_log_init(uint32_t logsize) { kmem_log_header_t *lhp; unsigned int nchunks = 4 * max_ncpus; - uint32_t lhsize = (uint32_t)(uint64_t)(&((kmem_log_header_t *)0)->lh_cpu[max_ncpus]); + uint32_t lhsize = + (uint32_t)(uint64_t)(&((kmem_log_header_t *)0)->lh_cpu[max_ncpus]); unsigned int i; /* @@ -1037,16 +1032,16 @@ kmem_log_init(uint32_t logsize) */ lhsize = P2ROUNDUP(lhsize, KMEM_ALIGN); lhp = vmem_xalloc(kmem_log_arena, lhsize, 64, P2NPHASE(lhsize, 64), 0, - NULL, NULL, VM_SLEEP); + NULL, NULL, VM_SLEEP); bzero(lhp, lhsize); mutex_init(&lhp->lh_lock, NULL, MUTEX_DEFAULT, NULL); lhp->lh_nchunks = nchunks; lhp->lh_chunksize = P2ROUNDUP(logsize / nchunks + 1, PAGESIZE); lhp->lh_base = vmem_alloc(kmem_log_arena, - lhp->lh_chunksize * nchunks, VM_SLEEP); + lhp->lh_chunksize * nchunks, VM_SLEEP); lhp->lh_free = vmem_alloc(kmem_log_arena, - nchunks * sizeof (int), VM_SLEEP); + nchunks * sizeof (int), VM_SLEEP); bzero(lhp->lh_base, lhp->lh_chunksize * nchunks); for (i = 0; i < max_ncpus; i++) { @@ -1069,30 +1064,26 @@ static void kmem_log_fini(kmem_log_header_t *lhp) { int nchunks = 4 * max_ncpus; - uint32_t lhsize = (uint32_t)(uint64_t)(&((kmem_log_header_t *)0)->lh_cpu[max_ncpus]); + uint32_t lhsize = + (uint32_t)(uint64_t)(&((kmem_log_header_t *)0)->lh_cpu[max_ncpus]); unsigned int i; - - for (i = 0; i < max_ncpus; i++) { kmem_cpu_log_header_t *clhp = &lhp->lh_cpu[i]; mutex_destroy(&clhp->clh_lock); } vmem_free(kmem_log_arena, - lhp->lh_free, - nchunks * sizeof (int)); + lhp->lh_free, nchunks * sizeof (int)); vmem_free(kmem_log_arena, - lhp->lh_base, - lhp->lh_chunksize * nchunks); + lhp->lh_base, lhp->lh_chunksize * nchunks); mutex_destroy(&lhp->lh_lock); lhsize = P2ROUNDUP(lhsize, KMEM_ALIGN); vmem_xfree(kmem_log_arena, - lhp, - lhsize); + lhp, lhsize); } @@ -1117,7 +1108,7 @@ kmem_log_enter(kmem_log_header_t *lhp, void *data, uint32_t size) clhp->clh_chunk = lhp->lh_free[lhp->lh_head]; lhp->lh_head = (lhp->lh_head + 1) % lhp->lh_nchunks; clhp->clh_current = lhp->lh_base + - clhp->clh_chunk * lhp->lh_chunksize; + clhp->clh_chunk * lhp->lh_chunksize; clhp->clh_avail = lhp->lh_chunksize; if (size > lhp->lh_chunksize) size = lhp->lh_chunksize; @@ -1131,18 +1122,18 @@ kmem_log_enter(kmem_log_header_t *lhp, void *data, uint32_t size) return (logspace); } -#define KMEM_AUDIT(lp, cp, bcp) \ -{ \ -kmem_bufctl_audit_t *_bcp = (kmem_bufctl_audit_t *)(bcp); \ -_bcp->bc_timestamp = gethrtime(); \ -_bcp->bc_thread = spl_current_thread(); \ -_bcp->bc_depth = getpcstack(_bcp->bc_stack, KMEM_STACK_DEPTH); \ -_bcp->bc_lastlog = kmem_log_enter((lp), _bcp, sizeof (*_bcp)); \ -} +#define KMEM_AUDIT(lp, cp, bcp) \ + { \ + kmem_bufctl_audit_t *_bcp = (kmem_bufctl_audit_t *)(bcp); \ + _bcp->bc_timestamp = gethrtime(); \ + _bcp->bc_thread = spl_current_thread(); \ + _bcp->bc_depth = getpcstack(_bcp->bc_stack, KMEM_STACK_DEPTH); \ + _bcp->bc_lastlog = kmem_log_enter((lp), _bcp, sizeof (*_bcp)); \ + } static void kmem_log_event(kmem_log_header_t *lp, kmem_cache_t *cp, - kmem_slab_t *sp, void *addr) + kmem_slab_t *sp, void *addr) { kmem_bufctl_audit_t bca; @@ -1217,7 +1208,7 @@ kmem_slab_create(kmem_cache_t *cp, int kmflag) goto bufctl_alloc_failure; if (cache_flags & KMF_AUDIT) { kmem_bufctl_audit_t *bcap = - (kmem_bufctl_audit_t *)bcp; + (kmem_bufctl_audit_t *)bcp; bzero(bcap, sizeof (kmem_bufctl_audit_t)); bcap->bc_cache = cp; } @@ -1233,7 +1224,7 @@ kmem_slab_create(kmem_cache_t *cp, int kmflag) btp->bt_bxstat = (intptr_t)bcp ^ KMEM_BUFTAG_FREE; if (cache_flags & KMF_DEADBEEF) { copy_pattern(KMEM_FREE_PATTERN, buf, - cp->cache_verify); + cp->cache_verify); } } bcp->bc_next = sp->slab_head; @@ -1305,7 +1296,7 @@ kmem_slab_alloc_impl(kmem_cache_t *cp, kmem_slab_t *sp, boolean_t prefill) * slab is newly created. */ ASSERT(new_slab || (KMEM_SLAB_IS_PARTIAL(sp) && - (sp == avl_first(&cp->cache_partial_slabs)))); + (sp == avl_first(&cp->cache_partial_slabs)))); ASSERT(sp->slab_cache == cp); cp->cache_slab_alloc++; @@ -1354,7 +1345,7 @@ kmem_slab_alloc_impl(kmem_cache_t *cp, kmem_slab_t *sp, boolean_t prefill) * so the peek could be wrong, but there's no harm in it. */ if (new_slab && prefill && (cp->cache_flags & KMF_PREFILL) && - (KMEM_CPU_CACHE(cp)->cc_magsize != 0)) { + (KMEM_CPU_CACHE(cp)->cc_magsize != 0)) { kmem_slab_prefill(cp, sp); return (buf); } @@ -1405,14 +1396,14 @@ kmem_slab_alloc(kmem_cache_t *cp, int kmflag) buf = kmem_slab_alloc_impl(cp, sp, B_TRUE); ASSERT((cp->cache_slab_create - cp->cache_slab_destroy) == - (cp->cache_complete_slab_count + - avl_numnodes(&cp->cache_partial_slabs) + - (cp->cache_defrag == NULL ? 0 : cp->cache_defrag->kmd_deadcount))); + (cp->cache_complete_slab_count + + avl_numnodes(&cp->cache_partial_slabs) + + (cp->cache_defrag == NULL ? 0 : cp->cache_defrag->kmd_deadcount))); mutex_exit(&cp->cache_lock); if (test_destructor && cp->cache_destructor != NULL) { copy_pattern(KMEM_UNINITIALIZED_PATTERN, buf, - cp->cache_bufsize); + cp->cache_bufsize); if (cp->cache_flags & KMF_DEADBEEF) { copy_pattern(KMEM_FREE_PATTERN, buf, cp->cache_verify); } @@ -1476,8 +1467,8 @@ kmem_slab_free(kmem_cache_t *cp, void *buf) if ((cp->cache_flags & (KMF_AUDIT | KMF_BUFTAG)) == KMF_AUDIT) { if (cp->cache_flags & KMF_CONTENTS) ((kmem_bufctl_audit_t *)bcp)->bc_contents = - kmem_log_enter(kmem_content_log, buf, - cp->cache_contents); + kmem_log_enter(kmem_content_log, buf, + cp->cache_contents); KMEM_AUDIT(kmem_transaction_log, cp, bcp); } @@ -1513,21 +1504,22 @@ kmem_slab_free(kmem_cache_t *cp, void *buf) * sets one of those low order bits whenever it frees a buffer). */ if (cp->cache_defrag == NULL || - (avl_is_empty(&cp->cache_defrag->kmd_moves_pending) && - !(sp->slab_flags & KMEM_SLAB_MOVE_PENDING))) { + (avl_is_empty(&cp->cache_defrag->kmd_moves_pending) && + !(sp->slab_flags & KMEM_SLAB_MOVE_PENDING))) { cp->cache_slab_destroy++; mutex_exit(&cp->cache_lock); kmem_slab_destroy(cp, sp); } else { - list_t *deadlist = &cp->cache_defrag->kmd_deadlist; - /* - * Slabs are inserted at both ends of the deadlist to - * distinguish between slabs freed while move callbacks - * are pending (list head) and a slab freed while the - * lock is dropped in kmem_move_buffers() (list tail) so - * that in both cases slab_destroy() is called from the - * right context. - */ + list_t *deadlist = + &cp->cache_defrag->kmd_deadlist; + /* + * Slabs are inserted at both ends of the deadlist to + * distinguish between slabs freed while move callbacks + * are pending (list head) and a slab freed while the + * lock is dropped in kmem_move_buffers() (list tail) so + * that in both cases slab_destroy() is called from the + * right context. + */ if (sp->slab_flags & KMEM_SLAB_MOVE_PENDING) { list_insert_tail(deadlist, sp); } else { @@ -1559,9 +1551,9 @@ kmem_slab_free(kmem_cache_t *cp, void *buf) } ASSERT((cp->cache_slab_create - cp->cache_slab_destroy) == - (cp->cache_complete_slab_count + - avl_numnodes(&cp->cache_partial_slabs) + - (cp->cache_defrag == NULL ? 0 : cp->cache_defrag->kmd_deadcount))); + (cp->cache_complete_slab_count + + avl_numnodes(&cp->cache_partial_slabs) + + (cp->cache_defrag == NULL ? 0 : cp->cache_defrag->kmd_deadcount))); mutex_exit(&cp->cache_lock); } @@ -1570,7 +1562,7 @@ kmem_slab_free(kmem_cache_t *cp, void *buf) */ static int kmem_cache_alloc_debug(kmem_cache_t *cp, void *buf, int kmflag, int construct, - caddr_t caller) + caddr_t caller) { kmem_buftag_t *btp = KMEM_BUFTAG(cp, buf); kmem_bufctl_audit_t *bcp = (kmem_bufctl_audit_t *)btp->bt_bufctl; @@ -1601,8 +1593,8 @@ kmem_cache_alloc_debug(kmem_cache_t *cp, void *buf, int kmflag, int construct, } else { construct = 1; if (verify_and_copy_pattern(KMEM_FREE_PATTERN, - KMEM_UNINITIALIZED_PATTERN, buf, - cp->cache_verify)) { + KMEM_UNINITIALIZED_PATTERN, buf, + cp->cache_verify)) { kmem_error(KMERR_MODIFIED, cp, buf); return (-1); } @@ -1611,8 +1603,8 @@ kmem_cache_alloc_debug(kmem_cache_t *cp, void *buf, int kmflag, int construct, btp->bt_redzone = KMEM_REDZONE_PATTERN; if ((mtbf = kmem_mtbf | cp->cache_mtbf) != 0 && - gethrtime() % mtbf == 0 && - (kmflag & (KM_NOSLEEP | KM_PANIC)) == KM_NOSLEEP) { + gethrtime() % mtbf == 0 && + (kmflag & (KM_NOSLEEP | KM_PANIC)) == KM_NOSLEEP) { kmem_log_event(kmem_failure_log, cp, NULL, NULL); if (!construct && cp->cache_destructor != NULL) cp->cache_destructor(buf, cp->cache_private); @@ -1621,7 +1613,7 @@ kmem_cache_alloc_debug(kmem_cache_t *cp, void *buf, int kmflag, int construct, } if (mtbf || (construct && cp->cache_constructor != NULL && - cp->cache_constructor(buf, cp->cache_private, kmflag) != 0)) { + cp->cache_constructor(buf, cp->cache_private, kmflag) != 0)) { atomic_inc_64(&cp->cache_alloc_fail); btp->bt_bxstat = (intptr_t)bcp ^ KMEM_BUFTAG_FREE; if (cp->cache_flags & KMF_DEADBEEF) @@ -1635,7 +1627,7 @@ kmem_cache_alloc_debug(kmem_cache_t *cp, void *buf, int kmflag, int construct, } if ((cp->cache_flags & KMF_LITE) && - !(cp->cache_cflags & KMC_KMEM_ALLOC)) { + !(cp->cache_cflags & KMC_KMEM_ALLOC)) { KMEM_BUFTAG_LITE_ENTER(btp, kmem_lite_count, caller); } @@ -1677,12 +1669,12 @@ kmem_cache_free_debug(kmem_cache_t *cp, void *buf, caddr_t caller) if (cp->cache_flags & KMF_AUDIT) { if (cp->cache_flags & KMF_CONTENTS) bcp->bc_contents = kmem_log_enter(kmem_content_log, - buf, cp->cache_contents); + buf, cp->cache_contents); KMEM_AUDIT(kmem_transaction_log, cp, bcp); } if ((cp->cache_flags & KMF_LITE) && - !(cp->cache_cflags & KMC_KMEM_ALLOC)) { + !(cp->cache_cflags & KMC_KMEM_ALLOC)) { KMEM_BUFTAG_LITE_ENTER(btp, kmem_lite_count, caller); } @@ -1707,19 +1699,19 @@ kmem_magazine_destroy(kmem_cache_t *cp, kmem_magazine_t *mp, int nrounds) int round; ASSERT(!list_link_active(&cp->cache_link) || - taskq_member(kmem_taskq, curthread)); + taskq_member(kmem_taskq, curthread)); for (round = 0; round < nrounds; round++) { void *buf = mp->mag_round[round]; if (cp->cache_flags & KMF_DEADBEEF) { if (verify_pattern(KMEM_FREE_PATTERN, buf, - cp->cache_verify) != NULL) { + cp->cache_verify) != NULL) { kmem_error(KMERR_MODIFIED, cp, buf); continue; } if ((cp->cache_flags & KMF_LITE) && - cp->cache_destructor != NULL) { + cp->cache_destructor != NULL) { kmem_buftag_t *btp = KMEM_BUFTAG(cp, buf); *(uint64_t *)buf = btp->bt_redzone; cp->cache_destructor(buf, cp->cache_private); @@ -1816,7 +1808,6 @@ kmem_depot_ws_zero(kmem_cache_t *cp) * causes us to preempt reaping up to hundres of times per second. Using a * larger value (1GB) causes this to have virtually no effect. */ -//size_t kmem_reap_preempt_bytes = 1024 * 1024 * 1024; uint32_t kmem_reap_preempt_bytes = 64 * 1024 * 1024; @@ -1831,7 +1822,7 @@ kmem_depot_ws_reap(kmem_cache_t *cp) kmem_magazine_t *mp; ASSERT(!list_link_active(&cp->cache_link) || - taskq_member(kmem_taskq, curthread)); + taskq_member(kmem_taskq, curthread)); reap = MIN(cp->cache_full.ml_reaplimit, cp->cache_full.ml_min); while (reap-- && @@ -1860,7 +1851,7 @@ static void kmem_cpu_reload(kmem_cpu_cache_t *ccp, kmem_magazine_t *mp, int rounds) { ASSERT((ccp->cc_loaded == NULL && ccp->cc_rounds == -1) || - (ccp->cc_loaded && ccp->cc_rounds + rounds == ccp->cc_magsize)); + (ccp->cc_loaded && ccp->cc_rounds + rounds == ccp->cc_magsize)); ASSERT(ccp->cc_magsize > 0); ccp->cc_ploaded = ccp->cc_loaded; @@ -1952,8 +1943,8 @@ kmem_dump_init(uint32_t size) if (kmem_dump_log == NULL) kmem_dump_log = - (kmem_dump_log_t *)zfs_kmem_zalloc( - KMEM_DUMP_LOGS * sizeof (kmem_dump_log_t), KM_SLEEP); + (kmem_dump_log_t *)zfs_kmem_zalloc( + KMEM_DUMP_LOGS * sizeof (kmem_dump_log_t), KM_SLEEP); kmem_dump_start = zfs_kmem_alloc(size, KM_SLEEP); @@ -1981,7 +1972,7 @@ kmem_dump_begin(void) kmem_cache_t *cp; for (cp = list_head(&kmem_caches); cp != NULL; - cp = list_next(&kmem_caches, cp)) { + cp = list_next(&kmem_caches, cp)) { kmem_cpu_cache_t *ccp = KMEM_CPU_CACHE(cp); if (cp->cache_arena->vm_cflags & VMC_DUMPSAFE) { @@ -2020,16 +2011,16 @@ kmem_dump_finish(char *buf, uint32_t size) if (kmem_dump_size == 0 || kmem_dump_verbose == 0) return (0); - used = (uint32_t) ((char *)kmem_dump_curr - (char *)kmem_dump_start); + used = (uint32_t)((char *)kmem_dump_curr - (char *)kmem_dump_start); percent = (int)((used * 100LL) / kmem_dump_size); kmem_dumppr(&p, e, "%% heap used,%d\n", percent); kmem_dumppr(&p, e, "used bytes,%ld\n", used); kmem_dumppr(&p, e, "heap size,%ld\n", kmem_dump_size); kmem_dumppr(&p, e, "Oversize allocs,%d\n", - kmem_dump_oversize_allocs); + kmem_dump_oversize_allocs); kmem_dumppr(&p, e, "Oversize max size,%ld\n", - kmem_dump_oversize_max); + kmem_dump_oversize_max); for (kdi_idx = 0; kdi_idx < kdi_end; kdi_idx++) { kdl = &kmem_dump_log[kdi_idx]; @@ -2040,14 +2031,14 @@ kmem_dump_finish(char *buf, uint32_t size) ++warn; if (header == 0) { kmem_dumppr(&p, e, - "Cache Name,Allocs,Frees,Alloc Fails," - "Nondump Frees,Unsafe Allocs/Frees\n"); + "Cache Name,Allocs,Frees,Alloc Fails," + "Nondump Frees,Unsafe Allocs/Frees\n"); header = 1; } kmem_dumppr(&p, e, "%s,%d,%d,%d,%d,%d\n", - cp->cache_name, kdl->kdl_allocs, kdl->kdl_frees, - kdl->kdl_alloc_fails, kdl->kdl_free_nondump, - kdl->kdl_unsafe); + cp->cache_name, kdl->kdl_allocs, kdl->kdl_frees, + kdl->kdl_alloc_fails, kdl->kdl_free_nondump, + kdl->kdl_unsafe); } /* return buffer size used */ @@ -2102,11 +2093,11 @@ kmem_cache_alloc_dump(kmem_cache_t *cp, int kmflag) /* run constructor */ if (cp->cache_constructor != NULL && - cp->cache_constructor(buf, cp->cache_private, kmflag) - != 0) { + cp->cache_constructor(buf, cp->cache_private, kmflag) + != 0) { #ifdef DEBUG dprintf("name='%s' cache=0x%p: kmem cache constructor failed\n", - cp->cache_name, (void *)cp); + cp->cache_name, (void *)cp); #endif /* reset curr pointer iff no allocs were done */ if (kmem_dump_curr == bufend) @@ -2129,7 +2120,7 @@ kmem_cache_free_dump(kmem_cache_t *cp, void *buf) { /* save constructed buffers for next time */ if ((char *)buf >= (char *)kmem_dump_start && - (char *)buf < (char *)kmem_dump_end) { + (char *)buf < (char *)kmem_dump_end) { KMEM_DUMPCTL(cp, buf)->kdc_next = cp->cache_dumpfreelist; cp->cache_dumpfreelist = buf; KDI_LOG(cp, kdl_frees); @@ -2169,12 +2160,12 @@ kmem_cache_alloc(kmem_cache_t *cp, int kmflag) if (ccp->cc_flags & (KMF_BUFTAG | KMF_DUMPUNSAFE)) { if (ccp->cc_flags & KMF_DUMPUNSAFE) { ASSERT(!(ccp->cc_flags & - KMF_DUMPDIVERT)); + KMF_DUMPDIVERT)); KDI_LOG(cp, kdl_unsafe); } if ((ccp->cc_flags & KMF_BUFTAG) && - kmem_cache_alloc_debug(cp, buf, kmflag, 0, - caller()) != 0) { + kmem_cache_alloc_debug(cp, buf, kmflag, 0, + caller()) != 0) { if (kmflag & KM_NOSLEEP) return (NULL); mutex_enter(&ccp->cc_lock); @@ -2204,7 +2195,7 @@ kmem_cache_alloc(kmem_cache_t *cp, int kmflag) KDI_LOG(cp, kdl_unsafe); } else { if ((buf = kmem_cache_alloc_dump(cp, kmflag)) != - NULL) { + NULL) { mutex_exit(&ccp->cc_lock); return (buf); } @@ -2225,7 +2216,7 @@ kmem_cache_alloc(kmem_cache_t *cp, int kmflag) if (fmp != NULL) { if (ccp->cc_ploaded != NULL) kmem_depot_free(cp, &cp->cache_empty, - ccp->cc_ploaded); + ccp->cc_ploaded); kmem_cpu_reload(ccp, fmp, ccp->cc_magsize); continue; } @@ -2268,7 +2259,7 @@ kmem_cache_alloc(kmem_cache_t *cp, int kmflag) } if (cp->cache_constructor != NULL && - cp->cache_constructor(buf, cp->cache_private, kmflag) != 0) { + cp->cache_constructor(buf, cp->cache_private, kmflag) != 0) { atomic_inc_64(&cp->cache_alloc_fail); kmem_slab_free(cp, buf); return (NULL); @@ -2295,7 +2286,7 @@ kmem_slab_free_constructed(kmem_cache_t *cp, void *buf, boolean_t freed) * kmem_cache_free_debug() will have already applied the destructor. */ if ((cp->cache_flags & (KMF_DEADBEEF | KMF_LITE)) != KMF_DEADBEEF && - cp->cache_destructor != NULL) { + cp->cache_destructor != NULL) { if (cp->cache_flags & KMF_DEADBEEF) { /* KMF_LITE implied */ kmem_buftag_t *btp = KMEM_BUFTAG(cp, buf); *(uint64_t *)buf = btp->bt_redzone; @@ -2324,15 +2315,15 @@ kmem_cpucache_magazine_alloc(kmem_cpu_cache_t *ccp, kmem_cache_t *cp) ASSERT(MUTEX_HELD(&ccp->cc_lock)); ASSERT(((uint_t)ccp->cc_rounds == (uint_t)ccp->cc_magsize || - ((uint_t)ccp->cc_rounds == (uint_t)-1)) && - ((uint_t)ccp->cc_prounds == (uint_t)ccp->cc_magsize || - ((uint_t)ccp->cc_prounds == (uint_t)-1))); + ((uint_t)ccp->cc_rounds == (uint_t)-1)) && + ((uint_t)ccp->cc_prounds == (uint_t)ccp->cc_magsize || + ((uint_t)ccp->cc_prounds == (uint_t)-1))); emp = kmem_depot_alloc(cp, &cp->cache_empty); if (emp != NULL) { if (ccp->cc_ploaded != NULL) kmem_depot_free(cp, &cp->cache_full, - ccp->cc_ploaded); + ccp->cc_ploaded); kmem_cpu_reload(ccp, emp, 0); return (1); } @@ -2401,7 +2392,7 @@ kmem_cache_parent_arena_fragmented(kmem_cache_t *cp) // we are fragmented if at least 1/8 of the // total arena space is free if (vk_free > 0 && vk_total > 0) { - const int64_t eighth_total= vk_total / 8; + const int64_t eighth_total = vk_total / 8; if (vk_free >= eighth_total) return (B_TRUE); } @@ -2422,9 +2413,9 @@ kmem_cache_free(kmem_cache_t *cp, void *buf) * callback function. */ ASSERT(cp->cache_defrag == NULL || - cp->cache_defrag->kmd_thread != spl_current_thread() || - (buf != cp->cache_defrag->kmd_from_buf && - buf != cp->cache_defrag->kmd_to_buf)); + cp->cache_defrag->kmd_thread != spl_current_thread() || + (buf != cp->cache_defrag->kmd_from_buf && + buf != cp->cache_defrag->kmd_to_buf)); if (ccp->cc_flags & (KMF_BUFTAG | KMF_DUMPDIVERT | KMF_DUMPUNSAFE)) { if (ccp->cc_flags & KMF_DUMPUNSAFE) { @@ -2517,9 +2508,9 @@ kmem_cache_free_to_slab(kmem_cache_t *cp, void *buf) * callback function. */ ASSERT(cp->cache_defrag == NULL || - cp->cache_defrag->kmd_thread != spl_current_thread() || - (buf != cp->cache_defrag->kmd_from_buf && - buf != cp->cache_defrag->kmd_to_buf)); + cp->cache_defrag->kmd_thread != spl_current_thread() || + (buf != cp->cache_defrag->kmd_from_buf && + buf != cp->cache_defrag->kmd_to_buf)); if (ccp->cc_flags & (KMF_BUFTAG | KMF_DUMPDIVERT | KMF_DUMPUNSAFE)) { if (ccp->cc_flags & KMF_DUMPUNSAFE) { @@ -2581,7 +2572,7 @@ kmem_slab_prefill(kmem_cache_t *cp, kmem_slab_t *sp) */ if ((uint_t)ccp->cc_rounds < ccp->cc_magsize) { ccp->cc_loaded->mag_round[ccp->cc_rounds++] = - buf; + buf; ccp->cc_free++; nbufs--; head = head->bc_next; @@ -2595,7 +2586,7 @@ kmem_slab_prefill(kmem_cache_t *cp, kmem_slab_t *sp) */ if (ccp->cc_prounds == 0) { kmem_cpu_reload(ccp, ccp->cc_ploaded, - ccp->cc_prounds); + ccp->cc_prounds); continue; } @@ -2649,7 +2640,7 @@ zfs_kmem_zalloc(size_t size, int kmflag) if (cp->cache_flags & KMF_LITE) { KMEM_BUFTAG_LITE_ENTER(btp, - kmem_lite_count, caller()); + kmem_lite_count, caller()); } } bzero(buf, size); @@ -2669,24 +2660,25 @@ zfs_kmem_alloc(size_t size, int kmflag) kmem_cache_t *cp; void *buf; - if (size == 0) return KMEM_ZERO_SIZE_PTR; + if (size == 0) + return (KMEM_ZERO_SIZE_PTR); if ((index = ((size - 1) >> KMEM_ALIGN_SHIFT)) < KMEM_ALLOC_TABLE_MAX) { cp = kmem_alloc_table[index]; /* fall through to kmem_cache_alloc() */ } else if ((index = ((size - 1) >> KMEM_BIG_SHIFT)) < - kmem_big_alloc_table_max) { + kmem_big_alloc_table_max) { cp = kmem_big_alloc_table[index]; /* fall through to kmem_cache_alloc() */ } else { buf = vmem_alloc(kmem_oversize_arena, size, - kmflag & KM_VMFLAGS); + kmflag & KM_VMFLAGS); if (buf == NULL) kmem_log_event(kmem_failure_log, NULL, NULL, - (void *)size); + (void *)size); else if (KMEM_DUMP(kmem_slab_cache)) { /* stats for dump intercept */ kmem_dump_oversize_allocs++; @@ -2723,7 +2715,7 @@ zfs_kmem_free(void *buf, size_t size) /* fall through to kmem_cache_free() */ } else if ((index = ((size - 1) >> KMEM_BIG_SHIFT)) < - kmem_big_alloc_table_max) { + kmem_big_alloc_table_max) { cp = kmem_big_alloc_table[index]; /* fall through to kmem_cache_free() */ @@ -2755,7 +2747,7 @@ zfs_kmem_free(void *buf, size_t size) btp->bt_redzone = KMEM_REDZONE_PATTERN; if (cp->cache_flags & KMF_LITE) { KMEM_BUFTAG_LITE_ENTER(btp, kmem_lite_count, - caller()); + caller()); } } kmem_cache_free(cp, buf); @@ -2831,7 +2823,8 @@ kmem_reap_timeout(void *flag_arg) { uint32_t *flag = (uint32_t *)flag_arg; - ASSERT(flag == (void *)&kmem_reaping || flag == (void *)&kmem_reaping_idspace); + ASSERT(flag == (void *)&kmem_reaping || + flag == (void *)&kmem_reaping_idspace); *flag = 0; } @@ -2872,7 +2865,7 @@ kmem_reap_common(void *flag_arg) if (MUTEX_HELD(&kmem_cache_lock) || kmem_taskq == NULL || - atomic_cas_32(flag, 0, 1) != 0) + atomic_cas_32(flag, 0, 1) != 0) return; /* @@ -2920,7 +2913,7 @@ kmem_cache_magazine_purge(kmem_cache_t *cp) int rounds, prounds, cpu_seqid; ASSERT(!list_link_active(&cp->cache_link) || - taskq_member(kmem_taskq, curthread)); + taskq_member(kmem_taskq, curthread)); ASSERT(MUTEX_NOT_HELD(&cp->cache_lock)); for (cpu_seqid = 0; cpu_seqid < (int)max_ncpus; cpu_seqid++) { @@ -3010,7 +3003,7 @@ kmem_cache_reap_now(kmem_cache_t *cp) kmem_depot_ws_zero(cp); (void) taskq_dispatch(kmem_taskq, - (task_func_t *)kmem_depot_ws_reap, cp, TQ_SLEEP); + (task_func_t *)kmem_depot_ws_reap, cp, TQ_SLEEP); taskq_wait(kmem_taskq); } @@ -3037,7 +3030,7 @@ kmem_cache_magazine_resize(kmem_cache_t *cp) mutex_enter(&cp->cache_depot_lock); cp->cache_magtype = ++mtp; cp->cache_depot_contention_prev = - cp->cache_depot_contention + INT_MAX; + cp->cache_depot_contention + INT_MAX; mutex_exit(&cp->cache_depot_lock); kmem_cache_magazine_enable(cp); } @@ -3056,14 +3049,14 @@ kmem_hash_rescale(kmem_cache_t *cp) ASSERT(taskq_member(kmem_taskq, curthread)); new_size = MAX(KMEM_HASH_INITIAL, - 1 << (highbit(3 * cp->cache_buftotal + 4) - 2)); + 1 << (highbit(3 * cp->cache_buftotal + 4) - 2)); old_size = cp->cache_hash_mask + 1; if ((old_size >> 1) <= new_size && new_size <= (old_size << 1)) return; new_table = vmem_alloc(kmem_hash_arena, new_size * sizeof (void *), - VM_NOSLEEP); + VM_NOSLEEP); if (new_table == NULL) return; bzero(new_table, new_size * sizeof (void *)); @@ -3111,9 +3104,9 @@ kmem_cache_update(kmem_cache_t *cp) mutex_enter(&cp->cache_lock); if ((cp->cache_flags & KMF_HASH) && - (cp->cache_buftotal > (cp->cache_hash_mask << 1) || - (cp->cache_buftotal < (cp->cache_hash_mask >> 1) && - cp->cache_hash_mask > KMEM_HASH_INITIAL))) + (cp->cache_buftotal > (cp->cache_hash_mask << 1) || + (cp->cache_buftotal < (cp->cache_hash_mask >> 1) && + cp->cache_hash_mask > KMEM_HASH_INITIAL))) need_hash_rescale = 1; mutex_exit(&cp->cache_lock); @@ -3130,8 +3123,8 @@ kmem_cache_update(kmem_cache_t *cp) mutex_enter(&cp->cache_depot_lock); if (cp->cache_chunksize < cp->cache_magtype->mt_maxbuf && - (int)(cp->cache_depot_contention - - cp->cache_depot_contention_prev) > kmem_depot_contention) + (int)(cp->cache_depot_contention - + cp->cache_depot_contention_prev) > kmem_depot_contention) need_magazine_resize = 1; cp->cache_depot_contention_prev = cp->cache_depot_contention; @@ -3140,17 +3133,17 @@ kmem_cache_update(kmem_cache_t *cp) if (need_hash_rescale) (void) taskq_dispatch(kmem_taskq, - (task_func_t *)kmem_hash_rescale, cp, TQ_NOSLEEP); + (task_func_t *)kmem_hash_rescale, cp, TQ_NOSLEEP); if (need_magazine_resize) (void) taskq_dispatch(kmem_taskq, - (task_func_t *)kmem_cache_magazine_resize, - cp, TQ_NOSLEEP); + (task_func_t *)kmem_cache_magazine_resize, + cp, TQ_NOSLEEP); // smd : the following if is only TRUE for the dnode cache if (cp->cache_defrag != NULL) (void) taskq_dispatch(kmem_taskq, - (task_func_t *)kmem_cache_scan, cp, TQ_NOSLEEP); + (task_func_t *)kmem_cache_scan, cp, TQ_NOSLEEP); #ifdef DEBUG else { @@ -3161,9 +3154,9 @@ kmem_cache_update(kmem_cache_t *cp) (void) random_get_bytes((uint8_t *)&debug_rand, 2); if (!kmem_move_noreap && - ((debug_rand % kmem_mtb_reap) == 0)) { - // no mutex above, so no need to give it up as in kmem_cache_scan() - // dprintf("SPL: kmem_cache_update random debug reap %u, doing %s\n", + ((debug_rand % kmem_mtb_reap) == 0)) { + // no mutex above, so no need to give it up as in + // kmem_cache_scan() // ++kmem_mtb_reap_count, cp->cache_name); // kmem_cache_reap(cp); // XXX } @@ -3215,10 +3208,10 @@ kmem_cache_kstat_update(kstat_t *ksp, int rw) kmcp->kmc_free.value.ui64 = cp->cache_slab_free; kmcp->kmc_slab_alloc.value.ui64 = cp->cache_slab_alloc; kmcp->kmc_slab_free.value.ui64 = cp->cache_slab_free; - kmcp->kmc_no_vba_success.value.ui64 = cp->no_vba_success; - kmcp->kmc_no_vba_fail.value.ui64 = cp->no_vba_fail; - kmcp->kmc_arc_no_grow_set.value.ui64 = cp->arc_no_grow_set; - kmcp->kmc_arc_no_grow.value.ui64 = cp->arc_no_grow; + kmcp->kmc_no_vba_success.value.ui64 = cp->no_vba_success; + kmcp->kmc_no_vba_fail.value.ui64 = cp->no_vba_fail; + kmcp->kmc_arc_no_grow_set.value.ui64 = cp->arc_no_grow_set; + kmcp->kmc_arc_no_grow.value.ui64 = cp->arc_no_grow; for (cpu_seqid = 0; cpu_seqid < (int)max_ncpus; cpu_seqid++) { kmem_cpu_cache_t *ccp = &cp->cache_cpu[cpu_seqid]; @@ -3246,8 +3239,8 @@ kmem_cache_kstat_update(kstat_t *ksp, int rw) kmcp->kmc_full_magazines.value.ui64 = cp->cache_full.ml_total; kmcp->kmc_empty_magazines.value.ui64 = cp->cache_empty.ml_total; kmcp->kmc_magazine_size.value.ui64 = - (cp->cache_flags & KMF_NOMAGAZINE) ? - 0 : cp->cache_magtype->mt_magsize; + (cp->cache_flags & KMF_NOMAGAZINE) ? + 0 : cp->cache_magtype->mt_magsize; kmcp->kmc_alloc.value.ui64 += cp->cache_full.ml_alloc; kmcp->kmc_free.value.ui64 += cp->cache_empty.ml_alloc; @@ -3271,7 +3264,7 @@ kmem_cache_kstat_update(kstat_t *ksp, int rw) kmcp->kmc_slab_create.value.ui64 = cp->cache_slab_create; kmcp->kmc_slab_destroy.value.ui64 = cp->cache_slab_destroy; kmcp->kmc_hash_size.value.ui64 = (cp->cache_flags & KMF_HASH) ? - cp->cache_hash_mask + 1 : 0; + cp->cache_hash_mask + 1 : 0; kmcp->kmc_hash_lookup_depth.value.ui64 = cp->cache_lookup_depth; kmcp->kmc_hash_rescale.value.ui64 = cp->cache_rescale; kmcp->kmc_vmem_source.value.ui64 = cp->cache_arena->vm_id; @@ -3348,11 +3341,13 @@ spl_minimal_physmem_p_logic() { // Are we using more than ZFS has? if (segkmem_total_mem_allocated > total_memory) { - vm_page_free_wanted = (segkmem_total_mem_allocated - total_memory) / PAGE_SIZE; + vm_page_free_wanted = + (segkmem_total_mem_allocated - total_memory) / PAGE_SIZE; vm_page_free_count = 0; } else { vm_page_free_wanted = 0; - vm_page_free_count = (total_memory - segkmem_total_mem_allocated) / PAGE_SIZE; + vm_page_free_count = + (total_memory - segkmem_total_mem_allocated) / PAGE_SIZE; } // do we have enough memory to avoid throttling? @@ -3470,7 +3465,7 @@ kmem_partial_slab_cmp(const void *pp0, const void *pp1) // compare slab age if available hrtime_t c0 = s0->slab_create_time, c1 = s1->slab_create_time; - if (c0 !=0 && c1 != 0 && c0 != c1) { + if (c0 != 0 && c1 != 0 && c0 != c1) { // higher time is newer; newer sorts before older if (c0 < c1) // c0 is older than c1 return (1); // so c0 sorts after c1 @@ -3494,15 +3489,15 @@ kmem_partial_slab_cmp(const void *pp0, const void *pp1) */ kmem_cache_t * kmem_cache_create( - char *name, /* descriptive name for this cache */ - uint32_t bufsize, /* size of the objects it manages */ - uint32_t align, /* required object alignment */ - int (*constructor)(void *, void *, int), /* object constructor */ - void (*destructor)(void *, void *), /* object destructor */ - void (*reclaim)(void *), /* memory reclaim callback */ - void *private, /* pass-thru arg for constr/destr/reclaim */ - vmem_t *vmp, /* vmem source for slab allocation */ - int cflags) /* cache creation flags */ + char *name, /* descriptive name for this cache */ + uint32_t bufsize, /* size of the objects it manages */ + uint32_t align, /* required object alignment */ + int (*constructor)(void *, void *, int), /* object constructor */ + void (*destructor)(void *, void *), /* object destructor */ + void (*reclaim)(void *), /* memory reclaim callback */ + void *private, /* pass-thru arg for constr/destr/reclaim */ + vmem_t *vmp, /* vmem source for slab allocation */ + int cflags) /* cache creation flags */ { int cpu_seqid; uint32_t chunksize; @@ -3516,9 +3511,9 @@ kmem_cache_create( */ if (!strident_valid(name)) { cmn_err(CE_CONT, - "kmem_cache_create: '%s' is an invalid cache name\n" - "cache names must conform to the rules for " - "C identifiers\n", name); + "kmem_cache_create: '%s' is an invalid cache name\n" + "cache names must conform to the rules for " + "C identifiers\n", name); } #endif /* DEBUG */ @@ -3539,9 +3534,9 @@ kmem_cache_create( * FALSE sharing of per-CPU data. */ cp = vmem_xalloc(kmem_cache_arena, csize, - KMEM_CPU_CACHE_SIZE, - P2NPHASE(csize, KMEM_CPU_CACHE_SIZE), - 0, NULL, NULL, VM_SLEEP); + KMEM_CPU_CACHE_SIZE, + P2NPHASE(csize, KMEM_CPU_CACHE_SIZE), + 0, NULL, NULL, VM_SLEEP); bzero(cp, csize); list_link_init(&cp->cache_link); @@ -3562,7 +3557,7 @@ kmem_cache_create( mutex_enter(&kmem_flags_lock); if (kmem_flags & KMF_RANDOMIZE) kmem_flags = (((kmem_flags | ~KMF_RANDOM) + 1) & KMF_RANDOM) | - KMF_RANDOMIZE; + KMF_RANDOMIZE; cp->cache_flags = (kmem_flags | cflags) & KMF_DEBUG; mutex_exit(&kmem_flags_lock); @@ -3573,8 +3568,8 @@ kmem_cache_create( if (cp->cache_flags & KMF_LITE) { if (bufsize >= kmem_lite_minsize && - align <= kmem_lite_maxalign && - P2PHASE(bufsize, kmem_lite_maxalign) != 0) { + align <= kmem_lite_maxalign && + P2PHASE(bufsize, kmem_lite_maxalign) != 0) { cp->cache_flags |= KMF_BUFTAG; cp->cache_flags &= ~(KMF_AUDIT | KMF_FIREWALL); } else { @@ -3610,7 +3605,7 @@ kmem_cache_create( cp->cache_flags &= ~KMF_CONTENTS; if ((cp->cache_flags & KMF_BUFTAG) && bufsize >= kmem_minfirewall && - !(cp->cache_flags & KMF_LITE) && !(cflags & KMC_NOHASH)) + !(cp->cache_flags & KMF_LITE) && !(cflags & KMC_NOHASH)) cp->cache_flags |= KMF_FIREWALL; if (vmp != kmem_default_arena || kmem_firewall_arena == NULL) @@ -3673,9 +3668,9 @@ kmem_cache_create( size_t vquantum = vmp->vm_quantum; if ((cflags & KMC_ARENA_SLAB) == KMC_ARENA_SLAB) { - VERIFY3U((vmp->vm_cflags & VMC_NO_QCACHE),==,VMC_NO_QCACHE); - VERIFY3U(vmp->vm_min_import,>,0); - VERIFY3U(vmp->vm_min_import,>=,(2 * vmp->vm_quantum)); + VERIFY3U((vmp->vm_cflags & VMC_NO_QCACHE), ==, VMC_NO_QCACHE); + VERIFY3U(vmp->vm_min_import, >, 0); + VERIFY3U(vmp->vm_min_import, >=, (2 * vmp->vm_quantum)); VERIFY(ISP2(vmp->vm_min_import)); vquantum = vmp->vm_min_import >> 1; } @@ -3687,13 +3682,13 @@ kmem_cache_create( cp->cache_flags |= KMF_HASH; ASSERT(!(cp->cache_flags & KMF_BUFTAG)); } else if ((cflags & KMC_NOHASH) || (!(cflags & KMC_NOTOUCH) && - !(cp->cache_flags & KMF_AUDIT) && - chunksize < vquantum / - KMEM_VOID_FRACTION)) { + !(cp->cache_flags & KMF_AUDIT) && + chunksize < vquantum / + KMEM_VOID_FRACTION)) { cp->cache_slabsize = vquantum; cp->cache_mincolor = 0; cp->cache_maxcolor = - (cp->cache_slabsize - sizeof (kmem_slab_t)) % chunksize; + (cp->cache_slabsize - sizeof (kmem_slab_t)) % chunksize; ASSERT(chunksize + sizeof (kmem_slab_t) <= cp->cache_slabsize); ASSERT(!(cp->cache_flags & KMF_AUDIT)); } else { @@ -3702,7 +3697,7 @@ kmem_cache_create( for (chunks = 1; chunks <= KMEM_VOID_FRACTION; chunks++) { slabsize = P2ROUNDUP(chunksize * chunks, - vquantum); + vquantum); chunks = slabsize / chunksize; waste = (slabsize % chunksize) / chunks; if (waste < minwaste) { @@ -3728,14 +3723,14 @@ kmem_cache_create( * metadata cache because of potential recursion. */ if (vmp == kmem_msb_arena || - cp->cache_flags & (KMF_HASH | KMF_BUFTAG) || - cp->cache_constructor != NULL) + cp->cache_flags & (KMF_HASH | KMF_BUFTAG) || + cp->cache_constructor != NULL) cp->cache_flags &= ~KMF_PREFILL; if (cp->cache_flags & KMF_HASH) { ASSERT(!(cflags & KMC_NOHASH)); cp->cache_bufctl_cache = (cp->cache_flags & KMF_AUDIT) ? - kmem_bufctl_audit_cache : kmem_bufctl_cache; + kmem_bufctl_audit_cache : kmem_bufctl_cache; } if (cp->cache_maxcolor >= vquantum) @@ -3749,19 +3744,19 @@ kmem_cache_create( mutex_init(&cp->cache_lock, NULL, MUTEX_DEFAULT, NULL); avl_create(&cp->cache_partial_slabs, kmem_partial_slab_cmp, - sizeof (kmem_slab_t), offsetof(kmem_slab_t, slab_link)); + sizeof (kmem_slab_t), offsetof(kmem_slab_t, slab_link)); /* LINTED: E_TRUE_LOGICAL_EXPR */ ASSERT(sizeof (list_node_t) <= sizeof (avl_node_t)); /* reuse partial slab AVL linkage for complete slab list linkage */ list_create(&cp->cache_complete_slabs, - sizeof (kmem_slab_t), offsetof(kmem_slab_t, slab_link)); + sizeof (kmem_slab_t), offsetof(kmem_slab_t, slab_link)); if (cp->cache_flags & KMF_HASH) { cp->cache_hash_table = vmem_alloc(kmem_hash_arena, - KMEM_HASH_INITIAL * sizeof (void *), - VM_SLEEP); + KMEM_HASH_INITIAL * sizeof (void *), + VM_SLEEP); bzero(cp->cache_hash_table, - KMEM_HASH_INITIAL * sizeof (void *)); + KMEM_HASH_INITIAL * sizeof (void *)); cp->cache_hash_mask = KMEM_HASH_INITIAL - 1; cp->cache_hash_shift = highbit((ulong_t)chunksize) - 1; } @@ -3791,9 +3786,9 @@ kmem_cache_create( * Create the cache's kstats. */ if ((cp->cache_kstat = kstat_create("unix", 0, cp->cache_name, - "kmem_cache", KSTAT_TYPE_NAMED, - sizeof (kmem_cache_kstat) / sizeof (kstat_named_t), - KSTAT_FLAG_VIRTUAL)) != NULL) { + "kmem_cache", KSTAT_TYPE_NAMED, + sizeof (kmem_cache_kstat) / sizeof (kstat_named_t), + KSTAT_FLAG_VIRTUAL)) != NULL) { cp->cache_kstat->ks_data = &kmem_cache_kstat; cp->cache_kstat->ks_update = kmem_cache_kstat_update; cp->cache_kstat->ks_private = cp; @@ -3868,7 +3863,7 @@ spl_kmem_cache_entry_size(kmem_cache_t *cache) void kmem_cache_set_move(kmem_cache_t *cp, - kmem_cbrc_t (*move)(void *, void *, uint32_t, void *)) + kmem_cbrc_t (*move)(void *, void *, uint32_t, void *)) { kmem_defrag_t *defrag; @@ -3899,14 +3894,14 @@ kmem_cache_set_move(kmem_cache_t *cp, defrag = NULL; /* nothing to free */ bzero(cp->cache_defrag, sizeof (kmem_defrag_t)); avl_create(&cp->cache_defrag->kmd_moves_pending, - kmem_move_cmp, sizeof (kmem_move_t), - offsetof(kmem_move_t, kmm_entry)); + kmem_move_cmp, sizeof (kmem_move_t), + offsetof(kmem_move_t, kmm_entry)); /* LINTED: E_TRUE_LOGICAL_EXPR */ ASSERT(sizeof (list_node_t) <= sizeof (avl_node_t)); /* reuse the slab's AVL linkage for deadlist linkage */ list_create(&cp->cache_defrag->kmd_deadlist, - sizeof (kmem_slab_t), - offsetof(kmem_slab_t, slab_link)); + sizeof (kmem_slab_t), + offsetof(kmem_slab_t, slab_link)); kmem_reset_reclaim_threshold(cp->cache_defrag); } cp->cache_move = move; @@ -3923,13 +3918,13 @@ void kmem_qcache_destroy() { kmem_cache_t *cp; - kmem_cache_t* cache_to_destroy = NULL; + kmem_cache_t *cache_to_destroy = NULL; do { cache_to_destroy = NULL; mutex_enter(&kmem_cache_lock); for (cp = list_head(&kmem_caches); cp != NULL; - cp = list_next(&kmem_caches, cp)) { + cp = list_next(&kmem_caches, cp)) { if (cp->cache_cflags & KMC_QCACHE) { cache_to_destroy = cp; break; @@ -3969,7 +3964,7 @@ kmem_cache_destroy(kmem_cache_t *cp) if (cp->cache_buftotal != 0) cmn_err(CE_WARN, "kmem_cache_destroy: '%s' (%p) not empty", - cp->cache_name, (void *)cp); + cp->cache_name, (void *)cp); if (cp->cache_defrag != NULL) { avl_destroy(&cp->cache_defrag->kmd_moves_pending); list_destroy(&cp->cache_defrag->kmd_deadlist); @@ -3992,10 +3987,10 @@ kmem_cache_destroy(kmem_cache_t *cp) if (cp->cache_hash_table != NULL) vmem_free(kmem_hash_arena, cp->cache_hash_table, - (cp->cache_hash_mask + 1) * sizeof (void *)); + (cp->cache_hash_mask + 1) * sizeof (void *)); for (cpu_seqid = 0; cpu_seqid < (int)max_ncpus; cpu_seqid++) - mutex_destroy(&cp->cache_cpu[cpu_seqid].cc_lock); // XNU + mutex_destroy(&cp->cache_cpu[cpu_seqid].cc_lock); // XNU mutex_destroy(&cp->cache_depot_lock); mutex_destroy(&cp->cache_lock); @@ -4005,8 +4000,8 @@ kmem_cache_destroy(kmem_cache_t *cp) static void kmem_alloc_caches_create(const int *array, uint32_t count, - kmem_cache_t **alloc_table, uint32_t maxbuf, - uint_t shift) + kmem_cache_t **alloc_table, uint32_t maxbuf, + uint_t shift) { char name[KMEM_CACHE_NAMELEN + 1]; uint32_t table_unit = (1 << shift); /* range of one alloc_table entry */ @@ -4034,9 +4029,9 @@ kmem_alloc_caches_create(const int *array, uint32_t count, if (IS_P2ALIGNED(cache_size, PAGESIZE)) align = PAGESIZE; (void) snprintf(name, sizeof (name), - "kmem_alloc_%lu", cache_size); + "kmem_alloc_%lu", cache_size); cp = kmem_cache_create(name, cache_size, align, - NULL, NULL, NULL, NULL, NULL, KMC_KMEM_ALLOC | KMF_HASH); + NULL, NULL, NULL, NULL, NULL, KMC_KMEM_ALLOC | KMF_HASH); while (size <= cache_size) { alloc_table[(size - 1) >> shift] = cp; @@ -4060,7 +4055,7 @@ kmem_alloc_caches_destroy() mutex_enter(&kmem_cache_lock); for (cp = list_head(&kmem_caches); cp != NULL; - cp = list_next(&kmem_caches, cp)) { + cp = list_next(&kmem_caches, cp)) { if (cp->cache_cflags & KMC_KMEM_ALLOC) { cache_to_destroy = cp; break; @@ -4090,7 +4085,7 @@ kmem_destroy_cache_by_name(const char *substr) mutex_enter(&kmem_cache_lock); for (cp = list_head(&kmem_caches); cp != NULL; - cp = list_next(&kmem_caches, cp)) { + cp = list_next(&kmem_caches, cp)) { if (kmem_strstr(cp->cache_name, substr)) { cache_to_destroy = cp; break; @@ -4119,40 +4114,40 @@ kmem_cache_init(int pass, int use_large_pages) mtp = &kmem_magtype[i]; (void) snprintf(name, KMEM_CACHE_NAMELEN, "%s%d", - KMEM_MAGAZINE_PREFIX, - mtp->mt_magsize); + KMEM_MAGAZINE_PREFIX, + mtp->mt_magsize); mtp->mt_cache = kmem_cache_create( - name, - (mtp->mt_magsize + 1) * sizeof (void *), - mtp->mt_align, NULL, NULL, NULL, NULL, - kmem_msb_arena, KMC_NOHASH); + name, + (mtp->mt_magsize + 1) * sizeof (void *), + mtp->mt_align, NULL, NULL, NULL, NULL, + kmem_msb_arena, KMC_NOHASH); } kmem_slab_cache = kmem_cache_create("kmem_slab_cache", - sizeof (kmem_slab_t), 0, NULL, NULL, - NULL, NULL, - kmem_msb_arena, KMC_NOHASH); + sizeof (kmem_slab_t), 0, NULL, NULL, + NULL, NULL, + kmem_msb_arena, KMC_NOHASH); kmem_bufctl_cache = kmem_cache_create("kmem_bufctl_cache", - sizeof (kmem_bufctl_t), 0, - NULL, NULL, NULL, NULL, - kmem_msb_arena, KMC_NOHASH); + sizeof (kmem_bufctl_t), 0, + NULL, NULL, NULL, NULL, + kmem_msb_arena, KMC_NOHASH); kmem_bufctl_audit_cache = kmem_cache_create("kmem_bufctl_audit_cache", - sizeof (kmem_bufctl_audit_t), - 0, NULL, NULL, NULL, NULL, - kmem_msb_arena, KMC_NOHASH); + sizeof (kmem_bufctl_audit_t), + 0, NULL, NULL, NULL, NULL, + kmem_msb_arena, KMC_NOHASH); if (pass == 2) { kmem_va_arena = vmem_create(KMEM_VA_PREFIX, - NULL, 0, PAGESIZE, - vmem_alloc, vmem_free, heap_arena, - 2 * PAGESIZE, VM_SLEEP); + NULL, 0, PAGESIZE, + vmem_alloc, vmem_free, heap_arena, + 2 * PAGESIZE, VM_SLEEP); kmem_default_arena = vmem_create("kmem_default", - NULL, 0, PAGESIZE, - vmem_alloc, vmem_free, kmem_va_arena, - 0, VMC_DUMPSAFE | VM_SLEEP); + NULL, 0, PAGESIZE, + vmem_alloc, vmem_free, kmem_va_arena, + 0, VMC_DUMPSAFE | VM_SLEEP); /* Figure out what our maximum cache size is */ maxbuf = kmem_max_cached; @@ -4162,7 +4157,7 @@ kmem_cache_init(int pass, int use_large_pages) } else { uint32_t size = 0; uint32_t max = - sizeof (kmem_big_alloc_sizes) / sizeof (int); + sizeof (kmem_big_alloc_sizes) / sizeof (int); /* * Round maxbuf up to an existing cache size. If maxbuf * is larger than the largest cache, we truncate it to @@ -4194,12 +4189,12 @@ kmem_cache_init(int pass, int use_large_pages) * Set up the default caches to back kmem_alloc() */ kmem_alloc_caches_create( - kmem_alloc_sizes, sizeof (kmem_alloc_sizes) / sizeof (int), - kmem_alloc_table, KMEM_MAXBUF, KMEM_ALIGN_SHIFT); + kmem_alloc_sizes, sizeof (kmem_alloc_sizes) / sizeof (int), + kmem_alloc_table, KMEM_MAXBUF, KMEM_ALIGN_SHIFT); kmem_alloc_caches_create( - kmem_big_alloc_sizes, sizeof (kmem_big_alloc_sizes) / sizeof (int), - kmem_big_alloc_table, maxbuf, KMEM_BIG_SHIFT); + kmem_big_alloc_sizes, sizeof (kmem_big_alloc_sizes) / sizeof (int), + kmem_big_alloc_table, maxbuf, KMEM_BIG_SHIFT); kmem_big_alloc_table_max = maxbuf >> KMEM_BIG_SHIFT; } @@ -4224,24 +4219,27 @@ kmem_cache_build_slablist(kmem_cache_t *cp) struct free_slab *fs; for (sp = list_head(&cp->cache_complete_slabs); sp != NULL; - sp = list_next(&cp->cache_complete_slabs, sp)) { + sp = list_next(&cp->cache_complete_slabs, sp)) { - MALLOC(fs, struct free_slab *, sizeof(struct free_slab), - M_TEMP, M_WAITOK); + MALLOC(fs, struct free_slab *, sizeof (struct free_slab), + M_TEMP, M_WAITOK); fs->vmp = vmp; fs->slabsize = cp->cache_slabsize; - fs->slab = (void *)P2ALIGN((uintptr_t)sp->slab_base, vmp->vm_quantum); + fs->slab = (void *)P2ALIGN((uintptr_t)sp->slab_base, + vmp->vm_quantum); list_link_init(&fs->next); list_insert_tail(&freelist, fs); } for (sp = avl_first(&cp->cache_partial_slabs); sp != NULL; - sp = AVL_NEXT(&cp->cache_partial_slabs, sp)) { + sp = AVL_NEXT(&cp->cache_partial_slabs, sp)) { - MALLOC(fs, struct free_slab *, sizeof(struct free_slab), M_TEMP, M_WAITOK); + MALLOC(fs, struct free_slab *, sizeof (struct free_slab), + M_TEMP, M_WAITOK); fs->vmp = vmp; fs->slabsize = cp->cache_slabsize; - fs->slab = (void *)P2ALIGN((uintptr_t)sp->slab_base, vmp->vm_quantum); + fs->slab = (void *)P2ALIGN((uintptr_t)sp->slab_base, + vmp->vm_quantum); list_link_init(&fs->next); list_insert_tail(&freelist, fs); @@ -4252,10 +4250,10 @@ kmem_cache_build_slablist(kmem_cache_t *cp) if (cp->cache_hash_table != NULL) vmem_free(kmem_hash_arena, cp->cache_hash_table, - (cp->cache_hash_mask + 1) * sizeof (void *)); + (cp->cache_hash_mask + 1) * sizeof (void *)); for (cpu_seqid = 0; cpu_seqid < (int)max_ncpus; cpu_seqid++) - mutex_destroy(&cp->cache_cpu[cpu_seqid].cc_lock); // XNU + mutex_destroy(&cp->cache_cpu[cpu_seqid].cc_lock); // XNU mutex_destroy(&cp->cache_depot_lock); mutex_destroy(&cp->cache_lock); @@ -4272,7 +4270,7 @@ kmem_cache_fini() struct free_slab *fs; list_create(&freelist, sizeof (struct free_slab), - offsetof(struct free_slab, next)); + offsetof(struct free_slab, next)); mutex_enter(&kmem_cache_lock); @@ -4320,9 +4318,9 @@ spl_free_last_pressure_wrapper(void) } int64_t -spl_free_set_and_wait_pressure(int64_t new_p, boolean_t fast, clock_t check_interval) +spl_free_set_and_wait_pressure(int64_t new_p, boolean_t fast, + clock_t check_interval) { - int64_t snapshot_pressure = 0; if (new_p <= 0) @@ -4345,7 +4343,7 @@ spl_free_set_and_wait_pressure(int64_t new_p, boolean_t fast, clock_t check_inte spl_free_last_pressure = start; - for (; spl_free_manual_pressure != 0; ) { + for (; spl_free_manual_pressure != 0; ) { // has another thread set spl_free_manual_pressure? if (spl_free_manual_pressure < new_p) spl_free_manual_pressure = new_p; @@ -4354,9 +4352,10 @@ spl_free_set_and_wait_pressure(int64_t new_p, boolean_t fast, clock_t check_inte cv_timedwait_hires(&spl_free_thread_cv, &spl_free_thread_lock, check_interval, 0, 0); mutex_exit(&spl_free_thread_lock); - now = zfs_lbolt(); + now = zfs_lbolt(); if (now > end_by) { - TraceEvent(TRACE_ERROR, "%s: timed out after one minute!\n", __func__); + TraceEvent(TRACE_ERROR, + "%s: timed out after one minute!\n", __func__); break; } else if (now > double_again_at && !doubled_again) { doubled_again = TRUE; @@ -4479,7 +4478,7 @@ spl_maybe_send_large_pressure(uint64_t now, uint64_t minutes, boolean_t full) spl_free_set_emergency_pressure(howmuch); - return(TRUE); + return (TRUE); } static void @@ -4505,7 +4504,7 @@ spl_free_thread(void *notused) mutex_enter(&spl_free_thread_lock); dprintf("SPL: beginning spl_free_thread() loop, spl_free == %lld\n", - spl_free); + spl_free); uint64_t recent_lowmem = 0; uint64_t last_disequilibrium = 0; @@ -4533,8 +4532,9 @@ spl_free_thread(void *notused) new_spl_free = 0LL; - // if there is pressure that has not yet reached arc_reclaim_thread() - // then start with a negative new_spl_free + // if there is pressure that has not yet reached + // arc_reclaim_thread() then start with a negative + // new_spl_free if (spl_free_manual_pressure > 0) { int64_t old_pressure = spl_free_manual_pressure; new_spl_free -= old_pressure * 2LL; @@ -4545,9 +4545,10 @@ spl_free_thread(void *notused) } } - // can we allocate at least a 64 MiB segment from spl_heap_arena? - // this probes the reserve and also the largest imported spans, - // which vmem_alloc can fragment if needed. + // can we allocate at least a 64 MiB segment from + // spl_heap_arena? this probes the reserve and also + // the largest imported spans, which vmem_alloc can + // fragment if needed. boolean_t reserve_low = FALSE; extern vmem_t *spl_heap_arena; @@ -4559,7 +4560,7 @@ spl_free_thread(void *notused) if ((rvfreebits & rvmask) == 0) { reserve_low = TRUE; } else { - new_spl_free += (int64_t) sixtyfour; + new_spl_free += (int64_t)sixtyfour; } // do we have lots of memory in the spl_heap_arena ? @@ -4569,9 +4570,10 @@ spl_free_thread(void *notused) const uint64_t sixteen = 16ULL*1024ULL*1024ULL; if (!reserve_low) { early_lots_free = TRUE; - } else if (vmem_size_semi_atomic(spl_heap_arena, VMEM_FREE) > onetwentyeight) { + } else if (vmem_size_semi_atomic(spl_heap_arena, VMEM_FREE) > + onetwentyeight) { early_lots_free = TRUE; - new_spl_free += (int64_t) sixteen; + new_spl_free += (int64_t)sixteen; } // do we have lots of memory in the bucket_arenas ? @@ -4579,20 +4581,21 @@ spl_free_thread(void *notused) extern int64_t vmem_buckets_size(int); // non-locking int64_t buckets_free = vmem_buckets_size(VMEM_FREE); if ((uint64_t)buckets_free != spl_buckets_mem_free) - spl_buckets_mem_free = (uint64_t) buckets_free; + spl_buckets_mem_free = (uint64_t)buckets_free; if (buckets_free >= 512LL*1024LL*1024LL) { early_lots_free = TRUE; - new_spl_free += (int64_t) sixteen; + new_spl_free += (int64_t)sixteen; } if (buckets_free >= 1024LL*1024LL*1024LL) { reserve_low = FALSE; - new_spl_free += (int64_t) sixteen; + new_spl_free += (int64_t)sixteen; } // if we have neither alloced or freed in several minutes, // then we do not need to shrink back if there is a momentary - // transient memory spike (i.e., one that lasts less than a second) + // transient memory spike (i.e., one that lasts less than a + // second) boolean_t memory_equilibrium = FALSE; const uint64_t five_minutes = 300ULL; @@ -4602,7 +4605,8 @@ spl_free_thread(void *notused) if (last_xat_alloc_seconds + five_minutes > time_now_seconds && last_xat_free_seconds + five_minutes > time_now_seconds) { - if (last_disequilibrium + one_minute > time_now_seconds) { + if (last_disequilibrium + one_minute > + time_now_seconds) { memory_equilibrium = TRUE; last_disequilibrium = 0; } @@ -4614,21 +4618,24 @@ spl_free_thread(void *notused) if (last_xat_alloc_seconds + 1 > time_now_seconds) just_alloced = TRUE; - // this is a sign of a period of time of low system memory, however - // XNU's generation of this variable is not very predictable, - // but generally it should be taken seriously when it's positive - // (it is often FALSEly 0) + // this is a sign of a period of time of low system memory, + // however XNU's generation of this variable is not very + // predictable, but generally it should be taken seriously + // when it's positive (it is often FALSEly 0) - if ((vm_page_free_wanted > 0 && reserve_low && !early_lots_free && - !memory_equilibrium && !just_alloced) || + if ((vm_page_free_wanted > 0 && reserve_low && + !early_lots_free && + !memory_equilibrium && !just_alloced) || vm_page_free_wanted >= 1024) { - int64_t bminus = (int64_t)vm_page_free_wanted * (int64_t)PAGESIZE * -16LL; + int64_t bminus = + (int64_t)vm_page_free_wanted * + (int64_t)PAGESIZE * -16LL; if (bminus > -16LL*1024LL*1024LL) bminus = -16LL*1024LL*1024LL; new_spl_free += bminus; lowmem = TRUE; emergency_lowmem = TRUE; - // atomic swaps to set these variables used in .../zfs/arc.c + // atomic swaps to set these variables used in arc.c int64_t previous_highest_pressure = 0; int64_t new_p = -bminus; previous_highest_pressure = spl_free_manual_pressure; @@ -4636,16 +4643,18 @@ spl_free_thread(void *notused) boolean_t fast = FALSE; if (vm_page_free_wanted > vm_page_free_min / 8) fast = TRUE; - spl_free_set_pressure_both(-16LL * new_spl_free, fast); + spl_free_set_pressure_both(-16LL * new_spl_free, + fast); } last_disequilibrium = time_now_seconds; } else if (vm_page_free_wanted > 0) { - int64_t bytes_wanted = (int64_t)vm_page_free_wanted * (int64_t)PAGESIZE; + int64_t bytes_wanted = + (int64_t)vm_page_free_wanted * (int64_t)PAGESIZE; new_spl_free -= bytes_wanted; - if (reserve_low && !early_lots_free) { - lowmem = TRUE; - if (recent_lowmem == 0) { - recent_lowmem = time_now; + if (reserve_low && !early_lots_free) { + lowmem = TRUE; + if (recent_lowmem == 0) { + recent_lowmem = time_now; } if (!memory_equilibrium) { last_disequilibrium = time_now_seconds; @@ -4655,27 +4664,31 @@ spl_free_thread(void *notused) // these variables are reliably maintained by XNU // if vm_page_free_count > vm_page_free_min, then XNU - // is scanning pages and we may want to try to free some memory up - - int64_t above_min_free_pages = (int64_t)vm_page_free_count - (int64_t)vm_page_free_min; - int64_t above_min_free_bytes = (int64_t)PAGESIZE * above_min_free_pages; - - // vm_page_free_min normally 3500, page free target normally 4000 but not exported - // so we are not scanning if we are 500 pages above vm_page_free_min. - - // even if we're scanning we may have plenty of space in the reserve arena, - // in which case we should not react too strongly - - // if we have been in memory equilibrium, also don't react too strongly - - if (above_min_free_bytes < (int64_t)PAGESIZE * 500LL && reserve_low - && !early_lots_free && !memory_equilibrium) { + // is scanning pages and we may want to try to free + // some memory up + + int64_t above_min_free_pages = + (int64_t)vm_page_free_count - (int64_t)vm_page_free_min; + int64_t above_min_free_bytes = + (int64_t)PAGESIZE * above_min_free_pages; + + // vm_page_free_min normally 3500, page free target + // normally 4000 but not exported so we are not scanning + // if we are 500 pages above vm_page_free_min. even if + // we're scanning we may have plenty of space in the + // reserve arena, in which case we should not react + // too strongly. if we have been in memory equilibrium, + // also don't react too strongly + + if (above_min_free_bytes < (int64_t)PAGESIZE * 500LL && + reserve_low && !early_lots_free && !memory_equilibrium) { // trigger a reap below lowmem = TRUE; } extern volatile unsigned int vm_page_speculative_count; - if ((above_min_free_bytes < 0LL && reserve_low && !early_lots_free && - !memory_equilibrium && !just_alloced) || + if ((above_min_free_bytes < 0LL && reserve_low && + !early_lots_free && + !memory_equilibrium && !just_alloced) || above_min_free_bytes <= -4LL*1024LL*1024LL) { int64_t new_p = -1LL * above_min_free_bytes; boolean_t fast = FALSE; @@ -4683,10 +4696,13 @@ spl_free_thread(void *notused) lowmem = TRUE; recent_lowmem = time_now; last_disequilibrium = time_now_seconds; - int64_t spec_bytes = (int64_t)vm_page_speculative_count * (int64_t)PAGESIZE; + int64_t spec_bytes = + (int64_t)vm_page_speculative_count * + (int64_t)PAGESIZE; if (vm_page_free_wanted > 0 || new_p > spec_bytes) { - // force a stronger reaction from ARC if we are also low on - // speculative pages (xnu prefetched file blocks with no clients yet) + // force a stronger reaction from ARC if we are + // also low on speculative pages (xnu prefetched + // file blocks with no clients yet) fast = TRUE; } spl_free_set_pressure_both(new_p, fast); @@ -4700,21 +4716,21 @@ spl_free_thread(void *notused) new_spl_free += above_min_free_bytes; - // If we have already detected a memory shortage and we - // have not reaped in a while (a short while for emergency_lowmem), - // then do a kmem_reap() now. - // See http://comments.gmane.org/gmane.os.illumos.devel/22552 - // (notably Richard Elling's "A kernel module can call kmem_reap() whenever - // it wishes and some modules, like zfs, do so." - // If we reap, stop processing spl_free on this pass, to - // let the reaps (and arc, if pressure has been set above) - // do their job for a few milliseconds. +// If we have already detected a memory shortage and we +// have not reaped in a while (a short while for emergency_lowmem), +// then do a kmem_reap() now. +// See http:/ /comments.gmane.org/gmane.os.illumos.devel/22552 +// (notably Richard Elling's "A kernel module can call kmem_reap() whenever +// it wishes and some modules, like zfs, do so." +// If we reap, stop processing spl_free on this pass, to +// let the reaps (and arc, if pressure has been set above) +// do their job for a few milliseconds. now = time_now; - elapsed = 60*hz; + elapsed = 60 * hz; reap_now = FALSE; if (emergency_lowmem) - elapsed = 15*hz; // minimum frequency from kmem_reap_interval + elapsed = 15 * hz; // kmem_reap_interval /* * Trigger a reap periodically @@ -4723,10 +4739,10 @@ spl_free_thread(void *notused) reap_now = TRUE; if (emergency_lowmem || lowmem || reap_now) { - /* - * skip reap if lowmem or emergency_lowmem and minimum reap interval is - * not expired. - */ +/* + * skip reap if lowmem or emergency_lowmem and minimum reap interval is + * not expired. + */ if ((emergency_lowmem || lowmem) && reap_now == FALSE) goto skip_reap; @@ -4747,34 +4763,37 @@ spl_free_thread(void *notused) } skip_reap: - // a number or exceptions to reverse the lowmem / emergency_lowmem states - // if we have recently reaped. we also take the strong reaction sting - // out of the set pressure by turning off spl_free_fast_pressure, since - // that automatically provokes an arc shrink and arc reap +// a number or exceptions to reverse the lowmem / emergency_lowmem states +// if we have recently reaped. we also take the strong reaction sting +// out of the set pressure by turning off spl_free_fast_pressure, since +// that automatically provokes an arc shrink and arc reap - if (!reserve_low || early_lots_free || memory_equilibrium || just_alloced) { + if (!reserve_low || early_lots_free || memory_equilibrium || + just_alloced) { lowmem = FALSE; emergency_lowmem = FALSE; spl_free_fast_pressure = FALSE; } if (vm_page_speculative_count > 0) { - // speculative memory can be squeezed a bit; it is file blocks that - // have been prefetched by xnu but are not (yet) in use by any - // consumer - if (vm_page_speculative_count / 4 + vm_page_free_count > vm_page_free_min) { +// speculative memory can be squeezed a bit; it is file blocks that +// have been prefetched by xnu but are not (yet) in use by any +// consumer + if (vm_page_speculative_count / 4 + vm_page_free_count > + vm_page_free_min) { emergency_lowmem = FALSE; spl_free_fast_pressure = FALSE; } - if (vm_page_speculative_count / 2 + vm_page_free_count > vm_page_free_min) { + if (vm_page_speculative_count / 2 + vm_page_free_count > + vm_page_free_min) { lowmem = FALSE; spl_free_fast_pressure = FALSE; } } - // Stay in a low memory condition for several seconds after we - // first detect that we are in it, giving the system (arc, xnu and userland) - // time to adapt +// Stay in a low memory condition for several seconds after we +// first detect that we are in it, giving the system (arc, xnu and userland) +// time to adapt if (!lowmem && recent_lowmem > 0) { if (recent_lowmem + 4*hz < time_now) @@ -4783,23 +4802,25 @@ spl_free_thread(void *notused) recent_lowmem = 0; } - // if we are in a lowmem "hangover", cure it with pressure, then wait - // for the pressure to take effect in arc.c code +// if we are in a lowmem "hangover", cure it with pressure, then wait +// for the pressure to take effect in arc.c code - // triggered when we have had at least one lowmem in the previous - // few seconds -- possibly two (one that causes a reap, one - // that falls through to the 4 second hold above). +// triggered when we have had at least one lowmem in the previous +// few seconds -- possibly two (one that causes a reap, one +// that falls through to the 4 second hold above). - if (recent_lowmem == time_now && early_lots_free && reserve_low) { - // we can't grab 64 MiB as a single segment, - // but otherwise have ample memory brought in from xnu, - // but recently we had lowmem... and still have lowmem. - // cure this condition with a dose of pressure. + if (recent_lowmem == time_now && early_lots_free && + reserve_low) { +// we can't grab 64 MiB as a single segment, +// but otherwise have ample memory brought in from xnu, +// but recently we had lowmem... and still have lowmem. +// cure this condition with a dose of pressure. if (above_min_free_bytes < 0) { int64_t old_p = spl_free_manual_pressure; if (old_p <= -above_min_free_bytes) { recent_lowmem = 0; - spl_free_manual_pressure = -above_min_free_bytes; + spl_free_manual_pressure = + -above_min_free_bytes; goto justwait; } } @@ -4811,30 +4832,42 @@ spl_free_thread(void *notused) // cf arc_available_memory() if (!emergency_lowmem) { extern vmem_t *spl_default_arena; - int64_t heap_free = (int64_t)vmem_size_semi_atomic(spl_heap_arena, VMEM_FREE); - // grabbed buckets_free up above; we are OK with change to it in the meanwhile, - // it'll get an update on the next run. + int64_t heap_free = + (int64_t)vmem_size_semi_atomic(spl_heap_arena, + VMEM_FREE); +// grabbed buckets_free up above; we are OK with change to it in the meanwhile, +// it'll get an update on the next run. int64_t combined_free = heap_free + buckets_free; if (combined_free != 0) { const int64_t mb = 1024*1024; - if (!lowmem && above_min_free_bytes > (int64_t)PAGESIZE * 10000LL) { + if (!lowmem && above_min_free_bytes > + (int64_t)PAGESIZE * 10000LL) { if (above_min_free_bytes < 64LL * mb) - new_spl_free += combined_free / 16; - else if (above_min_free_bytes < 128LL * mb) - new_spl_free += combined_free / 8; - else if (above_min_free_bytes < 256LL * mb) - new_spl_free += combined_free / 4; + new_spl_free += + combined_free / 16; + else if (above_min_free_bytes < + 128LL * mb) + new_spl_free += + combined_free / 8; + else if (above_min_free_bytes < + 256LL * mb) + new_spl_free += + combined_free / 4; else - new_spl_free += combined_free / 2; + new_spl_free += + combined_free / 2; } else { new_spl_free -= 16LL * mb; } } - // memory footprint has gotten really big, decrease spl_free substantially - int64_t total_mem_used = (int64_t) segkmem_total_mem_allocated; - int64_t mem_used_perc = (int64_t)(segkmem_total_mem_allocated * 100LL / real_total_memory); +// memory footprint has gotten really big, decrease spl_free substantially + int64_t total_mem_used = + (int64_t)segkmem_total_mem_allocated; + int64_t mem_used_perc = + (int64_t)(segkmem_total_mem_allocated * 100LL / + real_total_memory); if (mem_used_perc > 70 && mem_used_perc <= 75) { new_spl_free -= total_mem_used / 64; } else if (mem_used_perc > 75) { @@ -4849,14 +4882,17 @@ spl_free_thread(void *notused) // to the relative value of each up to arc.c. // O3X arc.c does not (yet) take these arena sizes into // account like Illumos's does. - uint64_t zio_size = vmem_size_semi_atomic(zio_arena_parent, VMEM_ALLOC | VMEM_FREE); + uint64_t zio_size = + vmem_size_semi_atomic(zio_arena_parent, + VMEM_ALLOC|VMEM_FREE); // wrap this in a basic block for lexical scope SSA convenience if (zio_size > 0) { static uint64_t zio_last_too_big = 0; static int64_t imposed_cap = 75; const uint64_t seconds_of_lower_cap = 10*hz; uint64_t now = time_now; - uint32_t zio_pct = (uint32_t)(zio_size * 100ULL / real_total_memory); + uint32_t zio_pct = + (uint32_t)(zio_size * 100ULL / real_total_memory); // if not hungry for memory, shrink towards a // 75% total memory cap on zfs_file_data if (!lowmem && !emergency_lowmem && zio_pct > 75 && @@ -4865,17 +4901,18 @@ spl_free_thread(void *notused) zio_last_too_big = now; imposed_cap = 75; } else if (lowmem || emergency_lowmem) { - // shrink towards stricter caps if we are hungry for memory + // shrink towards stricter caps if hungry for memory const uint32_t lowmem_cap = 25; const uint32_t emergency_lowmem_cap = 5; - // we don't want the lowest cap to be so low that - // we will not make any use of the fixed size reserve + // we don't want the lowest cap to be so low that + // we will not make any use of the fixed size reserve if (lowmem && zio_pct > lowmem_cap) { new_spl_free -= zio_size / 32; zio_last_too_big = now; imposed_cap = lowmem_cap; } - if (emergency_lowmem && zio_pct > emergency_lowmem_cap) { + if (emergency_lowmem && zio_pct > + emergency_lowmem_cap) { new_spl_free -= zio_size / 8; zio_last_too_big = now; imposed_cap = emergency_lowmem_cap; @@ -4891,51 +4928,57 @@ spl_free_thread(void *notused) // try to get 1/64 of spl_heap_arena freed up if (emergency_lowmem && new_spl_free >= 0LL) { extern vmem_t *spl_root_arena; - uint64_t root_size = vmem_size_semi_atomic(spl_heap_arena, VMEM_ALLOC | VMEM_FREE); - uint64_t root_free = vmem_size_semi_atomic(spl_heap_arena, VMEM_FREE); + uint64_t root_size = + vmem_size_semi_atomic(spl_heap_arena, + VMEM_ALLOC | VMEM_FREE); + uint64_t root_free = + vmem_size_semi_atomic(spl_heap_arena, VMEM_FREE); int64_t difference = root_size - root_free; int64_t target = root_size / 64; if (difference < target) { new_spl_free -= target; } - // and we should definitely not be returning positive now + // and we should definitely not be returning positive now if (new_spl_free >= 0LL) new_spl_free = -1024LL; } - uint64_t delta = (uint64_t)new_spl_free - (uint64_t)last_spl_free; - + uint64_t delta = + (uint64_t)new_spl_free - (uint64_t)last_spl_free; boolean_t spl_free_is_negative = FALSE; - if (new_spl_free < 0LL) { + if (new_spl_free < 0LL) { spl_stats.spl_spl_free_negative_count.value.ui64++; spl_free_is_negative = TRUE; } - // NOW set spl_free from calculated new_spl_free - spl_free = new_spl_free; - // the direct equivalent of : - // __c11_atomic_store(&spl_free, new_spl_free, __ATOMIC_SEQ_CST); +// NOW set spl_free from calculated new_spl_free + spl_free = new_spl_free; +// the direct equivalent of : +// __c11_atomic_store(&spl_free, new_spl_free, __ATOMIC_SEQ_CST); - // Because we're already negative, arc is likely to have been - // signalled already. We can rely on the _maybe_ in - // spl-vmem.c:xnu_alloc_throttled() [XAT] to try to give arc a - // kick with greater probability. - // However, if we've gone negative several times, and have not - // tried a full kick in a long time, do so now; if the full kick - // is refused because there has been a kick too few minutes ago, - // try a gentler kick. - // We do this outside the lock, as spl_maybe_send_large_pressure - // may need to take a mutex, and we forbid further mutex entry when - // spl_free_lock is held. +// Because we're already negative, arc is likely to have been +// signalled already. We can rely on the _maybe_ in +// spl-vmem.c:xnu_alloc_throttled() [XAT] to try to give arc a +// kick with greater probability. +// However, if we've gone negative several times, and have not +// tried a full kick in a long time, do so now; if the full kick +// is refused because there has been a kick too few minutes ago, +// try a gentler kick. +// We do this outside the lock, as spl_maybe_send_large_pressure +// may need to take a mutex, and we forbid further mutex entry when +// spl_free_lock is held. if (spl_free_is_negative) { - static volatile _Atomic uint32_t negatives_since_last_kick = 0; + static volatile _Atomic uint32_t + negatives_since_last_kick = 0; if (negatives_since_last_kick++ > 8) { - if (spl_maybe_send_large_pressure(time_now, 360, TRUE) || - spl_maybe_send_large_pressure(time_now, 60, FALSE)) { + if (spl_maybe_send_large_pressure(time_now, 360, + TRUE) || + spl_maybe_send_large_pressure(time_now, 60, + FALSE)) { negatives_since_last_kick = 0; } } @@ -4959,13 +5002,13 @@ spl_free_thread(void *notused) justwait: mutex_enter(&spl_free_thread_lock); CALLB_CPR_SAFE_BEGIN(&cpr); - (void) cv_timedwait_hires(&spl_free_thread_cv, &spl_free_thread_lock, - MSEC2NSEC(10), 0, 0); + (void) cv_timedwait_hires(&spl_free_thread_cv, + &spl_free_thread_lock, MSEC2NSEC(10), 0, 0); CALLB_CPR_SAFE_END(&cpr, &spl_free_thread_lock); } spl_free_thread_exit = FALSE; dprintf("SPL: spl_free_thread_exit set to FALSE " \ - "and exiting: cv_broadcasting\n"); + "and exiting: cv_broadcasting\n"); spl_free_manual_pressure = 0; cv_broadcast(&spl_free_thread_cv); CALLB_CPR_EXIT(&cpr); @@ -4979,11 +5022,16 @@ spl_event_thread(void *notused) // callb_cpr_t cpr; NTSTATUS Status; - DECLARE_CONST_UNICODE_STRING(low_mem_name, L"\\KernelObjects\\LowMemoryCondition"); + DECLARE_CONST_UNICODE_STRING(low_mem_name, + L"\\KernelObjects\\LowMemoryCondition"); HANDLE low_mem_handle; - low_mem_event = IoCreateNotificationEvent((PUNICODE_STRING)&low_mem_name, &low_mem_handle); + low_mem_event = + IoCreateNotificationEvent((PUNICODE_STRING)&low_mem_name, + &low_mem_handle); if (low_mem_event == NULL) { - TraceEvent(TRACE_ERROR, "%s: failed IoCreateNotificationEvent(\\KernelObjects\\LowMemoryCondition)", __func__); + TraceEvent(TRACE_ERROR, + "%s: failed IoCreateNotificationEvent(\\KernelObjects" + "\\LowMemoryCondition)", __func__); thread_exit(); } KeClearEvent(low_mem_event); @@ -4996,12 +5044,14 @@ spl_event_thread(void *notused) delay(hz); /* Sleep forever waiting for event */ - Status = KeWaitForSingleObject(low_mem_event, Executive, KernelMode, FALSE, NULL); + Status = KeWaitForSingleObject(low_mem_event, Executive, + KernelMode, FALSE, NULL); KeClearEvent(low_mem_event); - xprintf("%s: LOWMEMORY EVENT *** 0x%x (memusage: %llu)\n", __func__, Status, segkmem_total_mem_allocated); + xprintf("%s: LOWMEMORY EVENT *** 0x%x (memusage: %llu)\n", + __func__, Status, segkmem_total_mem_allocated); /* We were signalled */ - //vm_page_free_wanted = vm_page_free_min; + // vm_page_free_wanted = vm_page_free_min; spl_free_set_pressure(vm_page_free_min); vm_page_free_wanted = vm_page_free_min; cv_broadcast(&spl_free_thread_cv); @@ -5024,25 +5074,33 @@ spl_kstat_update(kstat_t *ksp, int rw) if (rw == KSTAT_WRITE) { - if (ks->spl_spl_free_manual_pressure.value.i64 != spl_free_manual_pressure) { - spl_free_set_pressure(ks->spl_spl_free_manual_pressure.value.i64 * 1024 *1024); + if (ks->spl_spl_free_manual_pressure.value.i64 != + spl_free_manual_pressure) { + spl_free_set_pressure( + ks->spl_spl_free_manual_pressure.value.i64 * + 1024 * 1024); if (ks->spl_spl_free_manual_pressure.value.i64 > 0) { spl_free_reap_caches(); } } - if (ks->spl_spl_free_fast_pressure.value.i64 != spl_free_fast_pressure) { + if (ks->spl_spl_free_fast_pressure.value.i64 != + spl_free_fast_pressure) { if (spl_free_wrapper() != 0) { spl_free_set_fast_pressure(TRUE); } } - if (ks->spl_bucket_tunable_large_span.value.ui64 != spl_bucket_tunable_large_span) { - spl_set_bucket_tunable_large_span(ks->spl_bucket_tunable_large_span.value.ui64); + if (ks->spl_bucket_tunable_large_span.value.ui64 != + spl_bucket_tunable_large_span) { + spl_set_bucket_tunable_large_span( + ks->spl_bucket_tunable_large_span.value.ui64); } - if (ks->spl_bucket_tunable_small_span.value.ui64 != spl_bucket_tunable_small_span) { - spl_set_bucket_tunable_small_span(ks->spl_bucket_tunable_small_span.value.ui64); + if (ks->spl_bucket_tunable_small_span.value.ui64 != + spl_bucket_tunable_small_span) { + spl_set_bucket_tunable_small_span( + ks->spl_bucket_tunable_small_span.value.ui64); } if (ks->spl_frag_max_walk.value.ui64 != spl_frag_max_walk) { @@ -5062,28 +5120,40 @@ spl_kstat_update(kstat_t *ksp, int rw) ks->spl_active_rwlock.value.ui64 = zfs_active_rwlock; ks->spl_active_tsd.value.ui64 = spl_tsd_size(); ks->spl_spl_free.value.i64 = spl_free; - ks->spl_spl_free_manual_pressure.value.i64 = spl_free_manual_pressure; - ks->spl_spl_free_fast_pressure.value.i64 = spl_free_fast_pressure; + ks->spl_spl_free_manual_pressure.value.i64 = + spl_free_manual_pressure; + ks->spl_spl_free_fast_pressure.value.i64 = + spl_free_fast_pressure; ks->spl_spl_free_delta_ema.value.i64 = spl_free_delta_ema; - ks->spl_osif_malloc_success.value.ui64 = stat_osif_malloc_success; + ks->spl_osif_malloc_success.value.ui64 = + stat_osif_malloc_success; ks->spl_osif_malloc_bytes.value.ui64 = stat_osif_malloc_bytes; ks->spl_osif_free.value.ui64 = stat_osif_free; ks->spl_osif_free_bytes.value.ui64 = stat_osif_free_bytes; - ks->spl_bucket_non_pow2_allocs.value.ui64 = spl_bucket_non_pow2_allocs; - - ks->spl_vmem_unconditional_allocs.value.ui64 = spl_vmem_unconditional_allocs; - ks->spl_vmem_unconditional_alloc_bytes.value.ui64 = spl_vmem_unconditional_alloc_bytes; - ks->spl_vmem_conditional_allocs.value.ui64 = spl_vmem_conditional_allocs; - ks->spl_vmem_conditional_alloc_bytes.value.ui64 = spl_vmem_conditional_alloc_bytes; - ks->spl_vmem_conditional_alloc_deny.value.ui64 = spl_vmem_conditional_alloc_deny; - ks->spl_vmem_conditional_alloc_deny_bytes.value.ui64 = spl_vmem_conditional_alloc_deny_bytes; + ks->spl_bucket_non_pow2_allocs.value.ui64 = + spl_bucket_non_pow2_allocs; + + ks->spl_vmem_unconditional_allocs.value.ui64 = + spl_vmem_unconditional_allocs; + ks->spl_vmem_unconditional_alloc_bytes.value.ui64 = + spl_vmem_unconditional_alloc_bytes; + ks->spl_vmem_conditional_allocs.value.ui64 = + spl_vmem_conditional_allocs; + ks->spl_vmem_conditional_alloc_bytes.value.ui64 = + spl_vmem_conditional_alloc_bytes; + ks->spl_vmem_conditional_alloc_deny.value.ui64 = + spl_vmem_conditional_alloc_deny; + ks->spl_vmem_conditional_alloc_deny_bytes.value.ui64 = + spl_vmem_conditional_alloc_deny_bytes; ks->spl_xat_success.value.ui64 = spl_xat_success; ks->spl_xat_late_success.value.ui64 = spl_xat_late_success; - ks->spl_xat_late_success_nosleep.value.ui64 = spl_xat_late_success_nosleep; + ks->spl_xat_late_success_nosleep.value.ui64 = + spl_xat_late_success_nosleep; ks->spl_xat_pressured.value.ui64 = spl_xat_pressured; ks->spl_xat_bailed.value.ui64 = spl_xat_bailed; - ks->spl_xat_bailed_contended.value.ui64 = spl_xat_bailed_contended; + ks->spl_xat_bailed_contended.value.ui64 = + spl_xat_bailed_contended; ks->spl_xat_lastalloc.value.ui64 = spl_xat_lastalloc; ks->spl_xat_lastfree.value.ui64 = spl_xat_lastfree; ks->spl_xat_forced.value.ui64 = spl_xat_forced; @@ -5092,18 +5162,24 @@ spl_kstat_update(kstat_t *ksp, int rw) ks->spl_xat_no_waiters.value.ui64 = spl_xat_no_waiters; ks->spl_xft_wait.value.ui64 = spl_xft_wait; - ks->spl_vba_parent_memory_appeared.value.ui64 = spl_vba_parent_memory_appeared; - ks->spl_vba_parent_memory_blocked.value.ui64 = spl_vba_parent_memory_blocked; + ks->spl_vba_parent_memory_appeared.value.ui64 = + spl_vba_parent_memory_appeared; + ks->spl_vba_parent_memory_blocked.value.ui64 = + spl_vba_parent_memory_blocked; ks->spl_vba_hiprio_blocked.value.ui64 = spl_vba_hiprio_blocked; ks->spl_vba_cv_timeout.value.ui64 = spl_vba_cv_timeout; ks->spl_vba_loop_timeout.value.ui64 = spl_vba_loop_timeout; - ks->spl_vba_cv_timeout_blocked.value.ui64 = spl_vba_cv_timeout_blocked; - ks->spl_vba_loop_timeout_blocked.value.ui64 = spl_vba_loop_timeout_blocked; + ks->spl_vba_cv_timeout_blocked.value.ui64 = + spl_vba_cv_timeout_blocked; + ks->spl_vba_loop_timeout_blocked.value.ui64 = + spl_vba_loop_timeout_blocked; ks->spl_vba_sleep.value.ui64 = spl_vba_sleep; ks->spl_vba_loop_entries.value.ui64 = spl_vba_loop_entries; - ks->spl_bucket_tunable_large_span.value.ui64 = spl_bucket_tunable_large_span; - ks->spl_bucket_tunable_small_span.value.ui64 = spl_bucket_tunable_small_span; + ks->spl_bucket_tunable_large_span.value.ui64 = + spl_bucket_tunable_large_span; + ks->spl_bucket_tunable_small_span.value.ui64 = + spl_bucket_tunable_small_span; ks->spl_buckets_mem_free.value.ui64 = spl_buckets_mem_free; ks->spl_arc_no_grow_bits.value.ui64 = spl_arc_no_grow_bits; @@ -5114,9 +5190,11 @@ spl_kstat_update(kstat_t *ksp, int rw) ks->spl_frag_walk_cnt.value.ui64 = spl_frag_walk_cnt; - ks->spl_arc_reclaim_avoided.value.ui64 = spl_arc_reclaim_avoided; + ks->spl_arc_reclaim_avoided.value.ui64 = + spl_arc_reclaim_avoided; - ks->kmem_free_to_slab_when_fragmented.value.ui64 = kmem_free_to_slab_when_fragmented; + ks->kmem_free_to_slab_when_fragmented.value.ui64 = + kmem_free_to_slab_when_fragmented; } return (0); @@ -5131,13 +5209,11 @@ spl_kmem_init(uint64_t xtotal_memory) dprintf("SPL: Total memory %llu\n", xtotal_memory); - //sysctl_register_oid(&sysctl__spl); - //sysctl_register_oid(&sysctl__spl_kext_version); - // Initialise the kstat lock - mutex_init(&kmem_cache_lock, "kmem_cache_lock", MUTEX_DEFAULT, NULL); // XNU - mutex_init(&kmem_flags_lock, "kmem_flags_lock", MUTEX_DEFAULT, NULL); // XNU - mutex_init(&kmem_cache_kstat_lock, "kmem_kstat_lock", MUTEX_DEFAULT, NULL); // XNU + mutex_init(&kmem_cache_lock, "kmem_cache_lock", MUTEX_DEFAULT, NULL); + mutex_init(&kmem_flags_lock, "kmem_flags_lock", MUTEX_DEFAULT, NULL); + mutex_init(&kmem_cache_kstat_lock, "kmem_kstat_lock", MUTEX_DEFAULT, + NULL); /* kstat mutex init */ spl_kstat_init(); @@ -5167,28 +5243,28 @@ spl_kmem_init(uint64_t xtotal_memory) ASSERT(sizeof (kmem_cpu_cache_t) == KMEM_CPU_CACHE_SIZE); list_create(&kmem_caches, sizeof (kmem_cache_t), - offsetof(kmem_cache_t, cache_link)); + offsetof(kmem_cache_t, cache_link)); kmem_metadata_arena = vmem_create("kmem_metadata", NULL, 0, PAGESIZE, - vmem_alloc, vmem_free, heap_arena, 8 * PAGESIZE, - VM_SLEEP | VMC_NO_QCACHE); + vmem_alloc, vmem_free, heap_arena, 8 * PAGESIZE, + VM_SLEEP | VMC_NO_QCACHE); kmem_msb_arena = vmem_create("kmem_msb", NULL, 0, - PAGESIZE, vmem_alloc, vmem_free, kmem_metadata_arena, 0, - VMC_DUMPSAFE | VM_SLEEP); + PAGESIZE, vmem_alloc, vmem_free, kmem_metadata_arena, 0, + VMC_DUMPSAFE | VM_SLEEP); kmem_cache_arena = vmem_create("kmem_cache", NULL, 0, KMEM_ALIGN, - vmem_alloc, vmem_free, kmem_metadata_arena, 0, VM_SLEEP); + vmem_alloc, vmem_free, kmem_metadata_arena, 0, VM_SLEEP); kmem_hash_arena = vmem_create("kmem_hash", NULL, 0, KMEM_ALIGN, - vmem_alloc, vmem_free, kmem_metadata_arena, 0, VM_SLEEP); + vmem_alloc, vmem_free, kmem_metadata_arena, 0, VM_SLEEP); kmem_log_arena = vmem_create("kmem_log", NULL, 0, KMEM_ALIGN, - vmem_alloc, vmem_free, kmem_metadata_arena, 0, VM_SLEEP); + vmem_alloc, vmem_free, kmem_metadata_arena, 0, VM_SLEEP); /* temporary oversize arena for mod_read_system_file */ kmem_oversize_arena = vmem_create("kmem_oversize", NULL, 0, PAGESIZE, - vmem_alloc, vmem_free, heap_arena, 0, VM_SLEEP); + vmem_alloc, vmem_free, heap_arena, 0, VM_SLEEP); // statically declared above kmem_reap_interval = 15 * hz; @@ -5236,15 +5312,17 @@ spl_kmem_init(uint64_t xtotal_memory) if (kmem_flags & (KMF_AUDIT | KMF_RANDOMIZE)) { if (kmem_transaction_log_size == 0) - kmem_transaction_log_size = (uint32_t) MIN(kmem_maxavail() / 50ULL, - PAGESIZE<<4); + kmem_transaction_log_size = + (uint32_t)MIN(kmem_maxavail() / 50ULL, + PAGESIZE<<4); kmem_transaction_log = kmem_log_init(kmem_transaction_log_size); } if (kmem_flags & (KMF_CONTENTS | KMF_RANDOMIZE)) { if (kmem_content_log_size == 0) - kmem_content_log_size = (uint32_t) MIN(kmem_maxavail() / 50ULL, - PAGESIZE<<4); + kmem_content_log_size = (uint32_t) + MIN(kmem_maxavail() / 50ULL, + PAGESIZE<<4); kmem_content_log = kmem_log_init(kmem_content_log_size); } @@ -5258,11 +5336,11 @@ spl_kmem_init(uint64_t xtotal_memory) * Always warn about unsupported values. */ if (((kmem_flags & ~(KMF_AUDIT | KMF_DEADBEEF | KMF_REDZONE | - KMF_CONTENTS | KMF_LITE)) != 0) || - ((kmem_flags & KMF_LITE) && kmem_flags != KMF_LITE)) + KMF_CONTENTS | KMF_LITE)) != 0) || + ((kmem_flags & KMF_LITE) && kmem_flags != KMF_LITE)) cmn_err(CE_WARN, "kmem_flags set to unsupported value 0x%x. " - "See the Solaris Tunable Parameters Reference Manual.", - kmem_flags); + "See the Solaris Tunable Parameters Reference Manual.", + kmem_flags); #ifdef DEBUG if ((kmem_flags & KMF_DEBUG) == 0) @@ -5276,11 +5354,11 @@ spl_kmem_init(uint64_t xtotal_memory) * isn't set (since that disables AUDIT). */ if (!(kmem_flags & KMF_LITE) && - (kmem_flags & (KMF_AUDIT | KMF_DEADBEEF)) != 0) + (kmem_flags & (KMF_AUDIT | KMF_DEADBEEF)) != 0) cmn_err(CE_WARN, "High-overhead kmem debugging features " - "enabled (kmem_flags = 0x%x). Performance degradation " - "and large memory overhead possible. See the Solaris " - "Tunable Parameters Reference Manual.", kmem_flags); + "enabled (kmem_flags = 0x%x). Performance degradation " + "and large memory overhead possible. See the Solaris " + "Tunable Parameters Reference Manual.", kmem_flags); #endif /* not DEBUG */ segkmem_zio_init(); @@ -5291,8 +5369,8 @@ spl_kmem_init(uint64_t xtotal_memory) // Install spl kstats spl_ksp = kstat_create("spl", 0, "spl_misc", "misc", KSTAT_TYPE_NAMED, - sizeof (spl_stats) / sizeof (kstat_named_t), - KSTAT_FLAG_VIRTUAL|KSTAT_FLAG_WRITABLE); + sizeof (spl_stats) / sizeof (kstat_named_t), + KSTAT_FLAG_VIRTUAL|KSTAT_FLAG_WRITABLE); if (spl_ksp != NULL) { spl_ksp->ks_data = &spl_stats; @@ -5304,8 +5382,6 @@ spl_kmem_init(uint64_t xtotal_memory) void spl_kmem_fini(void) { - //sysctl_unregister_oid(&sysctl__spl_kext_version); - //sysctl_unregister_oid(&sysctl__spl); kmem_cache_applyall(kmem_cache_magazine_disable, NULL, TQ_SLEEP); @@ -5316,13 +5392,14 @@ spl_kmem_fini(void) if (kmem_flags & (KMF_CONTENTS | KMF_RANDOMIZE)) { if (kmem_content_log_size == 0) - kmem_content_log_size = (uint32_t) kmem_maxavail() / 50; + kmem_content_log_size = (uint32_t)kmem_maxavail() / 50; kmem_log_fini(kmem_content_log); } if (kmem_flags & (KMF_AUDIT | KMF_RANDOMIZE)) { if (kmem_transaction_log_size == 0) - kmem_transaction_log_size = (uint32_t) kmem_maxavail() / 50; + kmem_transaction_log_size = + (uint32_t)kmem_maxavail() / 50; kmem_log_fini(kmem_transaction_log); } @@ -5368,11 +5445,11 @@ static void kmem_move_init(void) { kmem_defrag_cache = kmem_cache_create("kmem_defrag_cache", - sizeof (kmem_defrag_t), 0, NULL, NULL, NULL, NULL, - kmem_msb_arena, KMC_NOHASH); + sizeof (kmem_defrag_t), 0, NULL, NULL, NULL, NULL, + kmem_msb_arena, KMC_NOHASH); kmem_move_cache = kmem_cache_create("kmem_move_cache", - sizeof (kmem_move_t), 0, NULL, NULL, NULL, NULL, - kmem_msb_arena, KMC_NOHASH); + sizeof (kmem_move_t), 0, NULL, NULL, NULL, NULL, + kmem_msb_arena, KMC_NOHASH); /* * kmem guarantees that move callbacks are sequential and that even @@ -5381,7 +5458,7 @@ kmem_move_init(void) * does not interfere with internal maintenance tasks. */ kmem_move_taskq = taskq_create("kmem_move_taskq", 1, - minclsyspri, 100, INT_MAX, TASKQ_PREPOPULATE); + minclsyspri, 100, INT_MAX, TASKQ_PREPOPULATE); } void @@ -5403,10 +5480,11 @@ spl_kmem_thread_init(void) kmem_move_init(); // Initialize the spl_free locks - mutex_init(&spl_free_thread_lock, "spl_free_thead_lock", MUTEX_DEFAULT, NULL); + mutex_init(&spl_free_thread_lock, "spl_free_thead_lock", + MUTEX_DEFAULT, NULL); kmem_taskq = taskq_create("kmem_taskq", 1, minclsyspri, - 300, INT_MAX, TASKQ_PREPOPULATE); + 300, INT_MAX, TASKQ_PREPOPULATE); spl_free_thread_exit = FALSE; // zfsin/212 @@ -5414,7 +5492,7 @@ spl_kmem_thread_init(void) (void) thread_create(NULL, 0, spl_free_thread, 0, 0, 0, 0, 92); spl_event_thread_exit = FALSE; - (void)thread_create(NULL, 0, spl_event_thread, 0, 0, 0, 0, 92); + (void) thread_create(NULL, 0, spl_event_thread, 0, 0, 0, 0, 92); } void @@ -5434,13 +5512,13 @@ spl_kmem_thread_fini(void) dprintf("SPL: stop spl_free_thread\n"); mutex_enter(&spl_free_thread_lock); - dprintf("SPL: stop spl_free_thread, lock acquired, setting exit variable and waiting\n"); + dprintf("SPL: stop spl_free_thread, setting exit and waiting\n"); spl_free_thread_exit = TRUE; while (spl_free_thread_exit) { cv_signal(&spl_free_thread_cv); cv_wait(&spl_free_thread_cv, &spl_free_thread_lock); } - dprintf("SPL: spl_free_thread stop: while loop ended, dropping mutex\n"); + dprintf("SPL: spl_free_thread stop: while loop ended\n"); mutex_exit(&spl_free_thread_lock); dprintf("SPL: spl_free_thread stop: destroying cv and mutex\n"); cv_destroy(&spl_free_thread_cv); @@ -5448,9 +5526,6 @@ spl_kmem_thread_fini(void) dprintf("SPL: bsd_untimeout\n"); - //bsd_untimeout(kmem_update, 0); - //bsd_untimeout(kmem_reap_timeout, &kmem_reaping); - //bsd_untimeout(kmem_reap_timeout, &kmem_reaping_idspace); bsd_untimeout(kmem_update, &kmem_update_timer); bsd_untimeout(kmem_reap_timeout, &kmem_reaping); bsd_untimeout(kmem_reap_timeout, &kmem_reaping_idspace); @@ -5459,8 +5534,8 @@ spl_kmem_thread_fini(void) KeCancelTimer(&kmem_update_timer.timer); KeCancelTimer(&kmem_reaping.timer); KeCancelTimer(&kmem_reaping_idspace.timer); - kmem_free(kmem_reaping.timer_callback, sizeof(KDPC)); - kmem_free(kmem_reaping_idspace.timer_callback, sizeof(KDPC)); + kmem_free(kmem_reaping.timer_callback, sizeof (KDPC)); + kmem_free(kmem_reaping_idspace.timer_callback, sizeof (KDPC)); #endif dprintf("SPL: wait for taskqs to empty\n"); @@ -5496,8 +5571,8 @@ kmem_slab_allocated(kmem_cache_t *cp, kmem_slab_t *sp, void *buf) if (cp->cache_flags & KMF_HASH) { for (bcp = *KMEM_HASH(cp, buf); - (bcp != NULL) && (bcp->bc_addr != buf); - bcp = bcp->bc_next) { + (bcp != NULL) && (bcp->bc_addr != buf); + bcp = bcp->bc_next) { continue; } ASSERT(sp != NULL && bcp != NULL ? sp == bcp->bc_slab : 1); @@ -5510,8 +5585,8 @@ kmem_slab_allocated(kmem_cache_t *cp, kmem_slab_t *sp, void *buf) } bufbcp = KMEM_BUFCTL(cp, buf); for (bcp = sp->slab_head; - (bcp != NULL) && (bcp != bufbcp); - bcp = bcp->bc_next) { + (bcp != NULL) && (bcp != bufbcp); + bcp = bcp->bc_next) { continue; } return (bcp == NULL ? sp : NULL); @@ -5531,7 +5606,7 @@ kmem_slab_is_reclaimable(kmem_cache_t *cp, kmem_slab_t *sp, int flags) */ if (flags & KMM_DEBUG) { return ((flags & KMM_DESPERATE) || - ((sp->slab_flags & KMEM_SLAB_NOMOVE) == 0)); + ((sp->slab_flags & KMEM_SLAB_NOMOVE) == 0)); } /* If we're desperate, we don't care if the client said NO. */ @@ -5557,12 +5632,12 @@ kmem_slab_is_reclaimable(kmem_cache_t *cp, kmem_slab_t *sp, int flags) * sp->slab_chunks KMEM_VOID_FRACTION */ return ((refcnt * KMEM_VOID_FRACTION) < - (sp->slab_chunks * cp->cache_defrag->kmd_reclaim_numer)); + (sp->slab_chunks * cp->cache_defrag->kmd_reclaim_numer)); } static void * kmem_hunt_mag(kmem_cache_t *cp, kmem_magazine_t *m, int n, void *buf, - void *tbuf) + void *tbuf) { int i; /* magazine round index */ @@ -5570,7 +5645,7 @@ kmem_hunt_mag(kmem_cache_t *cp, kmem_magazine_t *m, int n, void *buf, if (buf == m->mag_round[i]) { if (cp->cache_flags & KMF_BUFTAG) { (void) kmem_cache_free_debug(cp, tbuf, - caller()); + caller()); } m->mag_round[i] = tbuf; return (buf); @@ -5747,7 +5822,7 @@ kmem_move_buffer(kmem_move_t *callback) if (!kmem_slab_is_reclaimable(cp, sp, callback->kmm_flags)) { KMEM_STAT_ADD(kmem_move_stats.kms_no_longer_reclaimable); KMEM_STAT_COND_ADD((callback->kmm_flags & KMM_NOTIFY), - kmem_move_stats.kms_notify_no_longer_reclaimable); + kmem_move_stats.kms_notify_no_longer_reclaimable); kmem_slab_free(cp, callback->kmm_to_buf); kmem_move_end(cp, callback); return; @@ -5761,7 +5836,7 @@ kmem_move_buffer(kmem_move_t *callback) */ mutex_enter(&cp->cache_lock); free_on_slab = (kmem_slab_allocated(cp, sp, - callback->kmm_from_buf) == NULL); + callback->kmm_from_buf) == NULL); mutex_exit(&cp->cache_lock); if (free_on_slab) { @@ -5776,36 +5851,36 @@ kmem_move_buffer(kmem_move_t *callback) * Make kmem_cache_alloc_debug() apply the constructor for us. */ if (kmem_cache_alloc_debug(cp, callback->kmm_to_buf, - KM_NOSLEEP, 1, caller()) != 0) { + KM_NOSLEEP, 1, caller()) != 0) { KMEM_STAT_ADD(kmem_move_stats.kms_alloc_fail); kmem_move_end(cp, callback); return; } } else if (cp->cache_constructor != NULL && - cp->cache_constructor(callback->kmm_to_buf, cp->cache_private, - KM_NOSLEEP) != 0) { - atomic_inc_64(&cp->cache_alloc_fail); - KMEM_STAT_ADD(kmem_move_stats.kms_constructor_fail); - kmem_slab_free(cp, callback->kmm_to_buf); - kmem_move_end(cp, callback); - return; - } + cp->cache_constructor(callback->kmm_to_buf, cp->cache_private, + KM_NOSLEEP) != 0) { + atomic_inc_64(&cp->cache_alloc_fail); + KMEM_STAT_ADD(kmem_move_stats.kms_constructor_fail); + kmem_slab_free(cp, callback->kmm_to_buf); + kmem_move_end(cp, callback); + return; + } KMEM_STAT_ADD(kmem_move_stats.kms_callbacks); KMEM_STAT_COND_ADD((callback->kmm_flags & KMM_NOTIFY), - kmem_move_stats.kms_notify_callbacks); + kmem_move_stats.kms_notify_callbacks); cp->cache_defrag->kmd_callbacks++; cp->cache_defrag->kmd_thread = spl_current_thread(); cp->cache_defrag->kmd_from_buf = callback->kmm_from_buf; cp->cache_defrag->kmd_to_buf = callback->kmm_to_buf; DTRACE_PROBE2(kmem__move__start, kmem_cache_t *, cp, kmem_move_t *, - callback); + callback); response = cp->cache_move(callback->kmm_from_buf, - callback->kmm_to_buf, cp->cache_bufsize, cp->cache_private); + callback->kmm_to_buf, cp->cache_bufsize, cp->cache_private); DTRACE_PROBE3(kmem__move__end, kmem_cache_t *, cp, kmem_move_t *, - callback, kmem_cbrc_t, response); + callback, kmem_cbrc_t, response); cp->cache_defrag->kmd_thread = NULL; cp->cache_defrag->kmd_from_buf = NULL; cp->cache_defrag->kmd_to_buf = NULL; @@ -5843,17 +5918,19 @@ kmem_move_buffer(kmem_move_t *callback) if (++sp->slab_later_count >= KMEM_DISBELIEF) { KMEM_STAT_ADD(kmem_move_stats.kms_disbelief); - kmem_slab_move_no(cp, sp, callback->kmm_from_buf); + kmem_slab_move_no(cp, sp, + callback->kmm_from_buf); } else if (!(sp->slab_flags & KMEM_SLAB_NOMOVE)) { sp->slab_stuck_offset = KMEM_SLAB_OFFSET(sp, - callback->kmm_from_buf); + callback->kmm_from_buf); } mutex_exit(&cp->cache_lock); break; case KMEM_CBRC_DONT_NEED: KMEM_STAT_ADD(kmem_move_stats.kms_dont_need); cp->cache_defrag->kmd_dont_need++; - kmem_slab_free_constructed(cp, callback->kmm_from_buf, B_FALSE); + kmem_slab_free_constructed(cp, + callback->kmm_from_buf, B_FALSE); if (sp->slab_refcnt == 0) cp->cache_defrag->kmd_slabs_freed++; mutex_enter(&cp->cache_lock); @@ -5863,21 +5940,26 @@ kmem_move_buffer(kmem_move_t *callback) case KMEM_CBRC_DONT_KNOW: KMEM_STAT_ADD(kmem_move_stats.kms_dont_know); cp->cache_defrag->kmd_dont_know++; - if (kmem_hunt_mags(cp, callback->kmm_from_buf) != NULL) { - KMEM_STAT_ADD(kmem_move_stats.kms_hunt_found_mag); + if (kmem_hunt_mags(cp, callback->kmm_from_buf) != + NULL) { + KMEM_STAT_ADD( + kmem_move_stats.kms_hunt_found_mag); cp->cache_defrag->kmd_hunt_found++; - kmem_slab_free_constructed(cp, callback->kmm_from_buf, - B_TRUE); + kmem_slab_free_constructed(cp, + callback->kmm_from_buf, + B_TRUE); if (sp->slab_refcnt == 0) cp->cache_defrag->kmd_slabs_freed++; mutex_enter(&cp->cache_lock); - kmem_slab_move_yes(cp, sp, callback->kmm_from_buf); + kmem_slab_move_yes(cp, sp, + callback->kmm_from_buf); mutex_exit(&cp->cache_lock); } break; default: - panic("'%s' (%p) unexpected move callback response %d\n", - cp->cache_name, (void *)cp, response); + panic("'%s' (%p) unexpected move callback " + "response %d\n", + cp->cache_name, (void *)cp, response); } kmem_slab_free_constructed(cp, callback->kmm_to_buf, B_FALSE); @@ -5932,14 +6014,14 @@ kmem_move_begin(kmem_cache_t *cp, kmem_slab_t *sp, void *buf, int flags) } to_buf = kmem_slab_alloc_impl(cp, avl_first(&cp->cache_partial_slabs), - B_FALSE); + B_FALSE); callback->kmm_to_buf = to_buf; avl_insert(&cp->cache_defrag->kmd_moves_pending, callback, index); mutex_exit(&cp->cache_lock); if (!taskq_dispatch(kmem_move_taskq, (task_func_t *)kmem_move_buffer, - callback, TQ_NOSLEEP)) { + callback, TQ_NOSLEEP)) { KMEM_STAT_ADD(kmem_move_stats.kms_callback_taskq_fail); mutex_enter(&cp->cache_lock); avl_remove(&cp->cache_defrag->kmd_moves_pending, callback); @@ -5963,7 +6045,7 @@ kmem_move_end(kmem_cache_t *cp, kmem_move_t *callback) mutex_enter(&cp->cache_lock); VERIFY(avl_find(&cp->cache_defrag->kmd_moves_pending, - callback->kmm_from_buf, &index) != NULL); + callback->kmm_from_buf, &index) != NULL); avl_remove(&cp->cache_defrag->kmd_moves_pending, callback); if (avl_is_empty(&cp->cache_defrag->kmd_moves_pending)) { list_t *deadlist = &cp->cache_defrag->kmd_deadlist; @@ -6010,7 +6092,7 @@ kmem_move_end(kmem_cache_t *cp, kmem_move_t *callback) */ static int kmem_move_buffers(kmem_cache_t *cp, uint32_t max_scan, uint32_t max_slabs, - int flags) + int flags) { kmem_slab_t *sp; void *buf; @@ -6026,7 +6108,7 @@ kmem_move_buffers(kmem_cache_t *cp, uint32_t max_scan, uint32_t max_slabs, ASSERT(kmem_move_cache != NULL); ASSERT(cp->cache_move != NULL && cp->cache_defrag != NULL); ASSERT((flags & KMM_DEBUG) ? !avl_is_empty(&cp->cache_partial_slabs) : - avl_numnodes(&cp->cache_partial_slabs) > 1); + avl_numnodes(&cp->cache_partial_slabs) > 1); if (kmem_move_blocked) { return (0); @@ -6051,10 +6133,11 @@ kmem_move_buffers(kmem_cache_t *cp, uint32_t max_scan, uint32_t max_slabs, sp = avl_last(&cp->cache_partial_slabs); ASSERT(KMEM_SLAB_IS_PARTIAL(sp)); - for (i = 0, s = 0; (i < (int)max_scan) && (s < (int)max_slabs) && (sp != NULL) && - ((sp != avl_first(&cp->cache_partial_slabs)) || - (flags & KMM_DEBUG)); - sp = AVL_PREV(&cp->cache_partial_slabs, sp), i++) { + for (i = 0, s = 0; (i < (int)max_scan) && (s < (int)max_slabs) && + (sp != NULL) && + ((sp != avl_first(&cp->cache_partial_slabs)) || + (flags & KMM_DEBUG)); + sp = AVL_PREV(&cp->cache_partial_slabs, sp), i++) { if (!kmem_slab_is_reclaimable(cp, sp, flags)) { continue; @@ -6063,8 +6146,8 @@ kmem_move_buffers(kmem_cache_t *cp, uint32_t max_scan, uint32_t max_slabs, /* Look for allocated buffers to move. */ for (j = 0, b = 0, buf = sp->slab_base; - (j < sp->slab_chunks) && (b < sp->slab_refcnt); - buf = (((char *)buf) + cp->cache_chunksize), j++) { + (j < sp->slab_chunks) && (b < sp->slab_refcnt); + buf = (((char *)buf) + cp->cache_chunksize), j++) { if (kmem_slab_allocated(cp, sp, buf) == NULL) { continue; @@ -6112,11 +6195,11 @@ kmem_move_buffers(kmem_cache_t *cp, uint32_t max_scan, uint32_t max_slabs, if (sp->slab_refcnt == 0) { list_t *deadlist = - &cp->cache_defrag->kmd_deadlist; + &cp->cache_defrag->kmd_deadlist; list_remove(deadlist, sp); if (!avl_is_empty( - &cp->cache_defrag->kmd_moves_pending)) { + &cp->cache_defrag->kmd_moves_pending)) { /* * A pending move makes it unsafe to * destroy the slab, because even though @@ -6132,7 +6215,7 @@ kmem_move_buffers(kmem_cache_t *cp, uint32_t max_scan, uint32_t max_slabs, */ list_insert_head(deadlist, sp); KMEM_STAT_ADD(kmem_move_stats. - kms_endscan_slab_dead); + kms_endscan_slab_dead); return (-1); } @@ -6148,9 +6231,9 @@ kmem_move_buffers(kmem_cache_t *cp, uint32_t max_scan, uint32_t max_slabs, mutex_exit(&cp->cache_lock); kmem_slab_destroy(cp, sp); KMEM_STAT_ADD(kmem_move_stats. - kms_dead_slabs_freed); + kms_dead_slabs_freed); KMEM_STAT_ADD(kmem_move_stats. - kms_endscan_slab_destroyed); + kms_endscan_slab_destroyed); mutex_enter(&cp->cache_lock); /* * Since we can't pick up the scan where we left @@ -6167,7 +6250,7 @@ kmem_move_buffers(kmem_cache_t *cp, uint32_t max_scan, uint32_t max_slabs, * number of reclaimable slabs. */ KMEM_STAT_COND_ADD(s < (int)max_slabs, - kmem_move_stats.kms_endscan_nomem); + kmem_move_stats.kms_endscan_nomem); return (-1); } @@ -6184,13 +6267,13 @@ kmem_move_buffers(kmem_cache_t *cp, uint32_t max_scan, uint32_t max_slabs, * case, we're not interested in counting it. */ KMEM_STAT_COND_ADD(!(flags & KMM_DEBUG) && - (s < (int)max_slabs), - kmem_move_stats.kms_endscan_refcnt_changed); + (s < (int)max_slabs), + kmem_move_stats.kms_endscan_refcnt_changed); return (-1); } if ((sp->slab_flags & KMEM_SLAB_NOMOVE) != nomove) { KMEM_STAT_COND_ADD(s < (int)max_slabs, - kmem_move_stats.kms_endscan_nomove_changed); + kmem_move_stats.kms_endscan_nomove_changed); return (-1); } @@ -6220,9 +6303,9 @@ kmem_move_buffers(kmem_cache_t *cp, uint32_t max_scan, uint32_t max_slabs, end_scan: KMEM_STAT_COND_ADD(!(flags & KMM_DEBUG) && - (s < (int)max_slabs) && - (sp == avl_first(&cp->cache_partial_slabs)), - kmem_move_stats.kms_endscan_freelist); + (s < (int)max_slabs) && + (sp == avl_first(&cp->cache_partial_slabs)), + kmem_move_stats.kms_endscan_freelist); return (s); } @@ -6261,7 +6344,7 @@ kmem_cache_move_notify_task(void *arg) * to move a buffer. */ if (!(sp->slab_flags & KMEM_SLAB_NOMOVE) && - (sp->slab_later_count == 0)) { + (sp->slab_later_count == 0)) { mutex_exit(&cp->cache_lock); return; } @@ -6280,11 +6363,11 @@ kmem_cache_move_notify_task(void *arg) list_remove(deadlist, sp); if (!avl_is_empty( - &cp->cache_defrag->kmd_moves_pending)) { + &cp->cache_defrag->kmd_moves_pending)) { list_insert_head(deadlist, sp); mutex_exit(&cp->cache_lock); KMEM_STAT_ADD(kmem_move_stats. - kms_notify_slab_dead); + kms_notify_slab_dead); return; } @@ -6293,7 +6376,8 @@ kmem_cache_move_notify_task(void *arg) mutex_exit(&cp->cache_lock); kmem_slab_destroy(cp, sp); KMEM_STAT_ADD(kmem_move_stats.kms_dead_slabs_freed); - KMEM_STAT_ADD(kmem_move_stats.kms_notify_slab_destroyed); + KMEM_STAT_ADD( + kmem_move_stats.kms_notify_slab_destroyed); return; } } else { @@ -6313,8 +6397,8 @@ kmem_cache_move_notify(kmem_cache_t *cp, void *buf) args->kmna_cache = cp; args->kmna_buf = buf; if (!taskq_dispatch(kmem_taskq, - (task_func_t *)kmem_cache_move_notify_task, args, - TQ_NOSLEEP)) + (task_func_t *)kmem_cache_move_notify_task, args, + TQ_NOSLEEP)) zfs_kmem_free(args, sizeof (kmem_move_notify_args_t)); } } @@ -6347,7 +6431,7 @@ kmem_cache_frag_threshold(kmem_cache_t *cp, uint64_t nfree) * cp->cache_buftotal kmem_frag_denom */ return ((nfree * kmem_frag_denom) > - (cp->cache_buftotal * kmem_frag_numer)); + (cp->cache_buftotal * kmem_frag_numer)); } static boolean_t @@ -6365,14 +6449,14 @@ kmem_cache_is_fragmented(kmem_cache_t *cp, boolean_t *doreap) } } else { if ((cp->cache_complete_slab_count + avl_numnodes( - &cp->cache_partial_slabs)) < kmem_frag_minslabs) { + &cp->cache_partial_slabs)) < kmem_frag_minslabs) { return (B_FALSE); } } nfree = cp->cache_bufslab; fragmented = ((avl_numnodes(&cp->cache_partial_slabs) > 1) && - kmem_cache_frag_threshold(cp, nfree)); + kmem_cache_frag_threshold(cp, nfree)); /* * Free buffers in the magazine layer appear allocated from the point of @@ -6432,7 +6516,7 @@ kmem_cache_scan(kmem_cache_t *cp) KMEM_STAT_ADD(kmem_move_stats.kms_scans); kmd->kmd_scans++; slabs_found = kmem_move_buffers(cp, kmem_reclaim_scan_range, - kmem_reclaim_max_slabs, 0); + kmem_reclaim_max_slabs, 0); kmd->kmd_slabs_sought += kmem_reclaim_max_slabs; kmd->kmd_slabs_found += slabs_found; @@ -6447,7 +6531,7 @@ kmem_cache_scan(kmem_cache_t *cp) if (kmd->kmd_slabs_found == kmd->kmd_slabs_sought) { kmem_adjust_reclaim_threshold(kmd, -1); } else if ((kmd->kmd_slabs_found * 2) < - kmd->kmd_slabs_sought) { + kmd->kmd_slabs_sought) { kmem_adjust_reclaim_threshold(kmd, 1); } kmd->kmd_slabs_sought = 0; @@ -6464,33 +6548,28 @@ kmem_cache_scan(kmem_cache_t *cp) */ uint16_t debug_rand; - // smd: note that this only gets called for the dnode cache - // because only the dnode cache has kmem_cache_set_move() applied to it - // brendon says move is voluntary and "tricky" - // the reason this is not called is because the source is - // kmem_cache_update(), that only calls this function (kmem_cache_scan()) - // if there is a move/defrag (same thing) associated with it - // so hoist some of this code up to to kmem_cache_update +// smd: note that this only gets called for the dnode cache +// because only the dnode cache has kmem_cache_set_move() applied to it +// brendon says move is voluntary and "tricky" +// the reason this is not called is because the source is +// kmem_cache_update(), that only calls this function (kmem_cache_scan()) +// if there is a move/defrag (same thing) associated with it +// so hoist some of this code up to to kmem_cache_update (void) random_get_bytes((uint8_t *)&debug_rand, 2); - // dprintf("SPL: kmem_cache_scan debug_rand = %u, kmem_mtb_reap = %u, kmem_mtb_move = %u, mod1 %u, mod2 %u\n", - // debug_rand, kmem_mtb_reap, kmem_mtb_move, (debug_rand % kmem_mtb_reap), (debug_rand % kmem_mtb_move)); if (!kmem_move_noreap && - ((debug_rand % kmem_mtb_reap) == 0)) { + ((debug_rand % kmem_mtb_reap) == 0)) { mutex_exit(&cp->cache_lock); KMEM_STAT_ADD(kmem_move_stats.kms_debug_reaps); kmem_mtb_reap_count++; - // dprintf("SPL: kmem_cache_scan random debug reap %llu\n", kmem_move_stats.kms_debug_reaps); // kmem_cache_reap(cp); // XXX return; } else if ((debug_rand % kmem_mtb_move) == 0) { KMEM_STAT_ADD(kmem_move_stats.kms_scans); KMEM_STAT_ADD(kmem_move_stats.kms_debug_scans); - // dprintf("SPL: kmem_cache_scan random debug move scans=%llu debug_scans=%llu\n", - // kmem_move_stats.kms_scans, kmem_move_stats.kms_debug_scans); kmd->kmd_scans++; (void) kmem_move_buffers(cp, - kmem_reclaim_scan_range, 1, KMM_DEBUG); + kmem_reclaim_scan_range, 1, KMM_DEBUG); } } #endif /* DEBUG */ @@ -6552,34 +6631,19 @@ kmem_strfree(char *str) char * kvasdprintf(const char *fmt, va_list ap) { - // unsigned int len; char *p = NULL; - // va_list aq; -// va_copy(aq, ap); -// len = _vsndprintf(NULL, 0, fmt, aq); -// va_end(aq); -// p = zfs_kmem_alloc(len+1, KM_SLEEP); if (!p) return (NULL); - //_vsndprintf(p, len+1, fmt, ap); - return (p); } char * kmem_vasdprintf(const char *fmt, va_list ap) { - // va_list aq; char *ptr = NULL; -// do { -// va_copy(aq, ap); -// ptr = kvasdprintf(fmt, aq); -// va_end(aq); -// } while (ptr == NULL); - return (ptr); } @@ -6612,13 +6676,16 @@ kmem_asprintf(const char *fmt, ...) buf = kmem_alloc(size, KM_SLEEP); va_start(adx, fmt); - (void)_vsnprintf(buf, size, fmt, adx); + (void) _vsnprintf(buf, size, fmt, adx); va_end(adx); return (buf); } -/* Copyright (C) 2014 insane coder (http://insanecoding.blogspot.com/, http://asprintf.insanecoding.org/) */ +/* + * Copyright (C) 2014 insane coder + * (http://insanecoding.blogspot.com/, http://asprintf.insanecoding.org/) + */ char * kmem_vasprintf(const char *fmt, va_list ap) { @@ -6626,21 +6693,21 @@ kmem_vasprintf(const char *fmt, va_list ap) int size; int r = -1; - size = vsnprintf(NULL, 0, fmt, ap); - if ((size >= 0) && (size < INT_MAX)) { - ptr = (char *)kmem_alloc(size + 1, KM_SLEEP); //+1 for null + size = vsnprintf(NULL, 0, fmt, ap); + if ((size >= 0) && (size < INT_MAX)) { + ptr = (char *)kmem_alloc(size + 1, KM_SLEEP); // +1 for null if (ptr) { - r = vsnprintf(ptr, size + 1, fmt, ap); //+1 for null + r = vsnprintf(ptr, size + 1, fmt, ap); // +1 for null if ((r < 0) || (r > size)) { kmem_free(ptr, size); r = -1; } } - } else { - ptr = 0; + } else { + ptr = 0; } - return(ptr); + return (ptr); } char * @@ -6651,7 +6718,7 @@ kmem_strstr(const char *in, const char *str) c = *str++; if (!c) - return ((char *) in); // Trivial empty string case + return ((char *)in); // Trivial empty string case len = (uint32_t)strlen(str); do { @@ -6660,30 +6727,30 @@ kmem_strstr(const char *in, const char *str) do { sc = *in++; if (!sc) - return ((char *) 0); + return ((char *)0); } while (sc != c); } while (strncmp(in, str, len) != 0); - return ((char *) (in - 1)); + return ((char *)(in - 1)); } // suppress timer and related logic for this kmem cache can live here -// three new per-kmem-cache stats: counters: non-vba-success non-vba-fail; flag: arc_no_grow - +// three new per-kmem-cache stats: counters: non-vba-success non-vba-fail; +// flag: arc_no_grow // from zfs/include/sys/spa.h -#define SPA_MINBLOCKSHIFT 9 -#define SPA_MAXBLOCKSHIFT 24 -#define SPA_MINBLOCKSIZE (1ULL << SPA_MINBLOCKSHIFT) -#define SPA_MAXBLOCKSIZE (1ULL << SPA_MAXBLOCKSHIFT) +#define SPA_MINBLOCKSHIFT 9 +#define SPA_MAXBLOCKSHIFT 24 +#define SPA_MINBLOCKSIZE (1ULL << SPA_MINBLOCKSHIFT) +#define SPA_MAXBLOCKSIZE (1ULL << SPA_MAXBLOCKSHIFT) typedef struct { - //_Atomic (kmem_cache_t *)cp_metadata; - //_Atomic (kmem_cache_t *)cp_filedata; + // _Atomic (kmem_cache_t *)cp_metadata; + // _Atomic (kmem_cache_t *)cp_filedata; _Atomic kmem_cache_t *cp_metadata; _Atomic kmem_cache_t *cp_filedata; - uint16_t pointed_to; + uint16_t pointed_to; _Atomic int64_t suppress_count; _Atomic uint64_t last_bumped; } ksupp_t; @@ -6692,7 +6759,8 @@ typedef struct { ksupp_t *ks_entry; } iksupp_t; -ksupp_t ksvec[SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT] = { { NULL, NULL, FALSE, 0, 0 } }; +ksupp_t ksvec[SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT] = + { { NULL, NULL, FALSE, 0, 0 } }; iksupp_t iksvec[SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT] = { { NULL } }; static boolean_t spl_zio_no_grow_inited = FALSE; @@ -6730,14 +6798,16 @@ ks_set_cp(ksupp_t *ks, kmem_cache_t *cp, const uint32_t cachenum) if (cp_is_metadata) { for (uint32_t i = 0; ; i++) { if (i >= 1000000) { - panic("SPL: %s: iterated out trying to set ks->cp_metadata (%s)\n", + panic("SPL: %s: iterated out trying to set " + "ks->cp_metadata (%s)\n", __func__, cp->cache_name); } kmem_cache_t *expected = NULL; - //if (__c11_atomic_compare_exchange_strong(&ks->cp_metadata, &expected, cp, - // __ATOMIC_SEQ_CST, __ATOMIC_RELAXED)) { - if (InterlockedCompareExchangePointer((void *volatile *)&ks->cp_metadata, cp, expected) == expected) { - dprintf("SPL: %s: set iskvec[%llu].ks->cp_metadata (%s) OK\n", + if (InterlockedCompareExchangePointer( + (void *volatile *)&ks->cp_metadata, cp, + expected) == expected) { + dprintf("SPL: %s: set iskvec[%llu]." + "ks->cp_metadata (%s) OK\n", __func__, b, cp->cache_name); return; } else if (ks->cp_metadata == cp) { @@ -6745,21 +6815,26 @@ ks_set_cp(ksupp_t *ks, kmem_cache_t *cp, const uint32_t cachenum) } else if (ks->cp_metadata == NULL) { continue; } else { - panic("%s: CAS failed for iksvec[%llu].ks->cp_metadata: %s wanted %s set\n", - __func__, b, cp->cache_name, ks->cp_metadata->cache_name); + panic("%s: CAS failed for iksvec[%llu]." + "ks->cp_metadata: %s wanted %s set\n", + __func__, b, cp->cache_name, + ks->cp_metadata->cache_name); } } } else { for (int32_t j = 0; ; j++) { if (j >= 1000000) { - panic("SPL: %s: iterated out trying to set ks->cp_filedata (%s)\n", + panic("SPL: %s: iterated out trying to set " + "ks->cp_filedata (%s)\n", __func__, cp->cache_name); } kmem_cache_t *expected = NULL; - //if (__c11_atomic_compare_exchange_strong(&ks->cp_filedata, &expected, cp, - // __ATOMIC_SEQ_CST, __ATOMIC_RELAXED)) { - if (InterlockedCompareExchangePointer((void *volatile *)&ks->cp_filedata, cp, expected) == expected) { - dprintf("SPL: %s: set iskvec[%llu].ks->cp_filedata (%s) OK\n", + + if (InterlockedCompareExchangePointer( + (void *volatile *)&ks->cp_filedata, + cp, expected) == expected) { + dprintf("SPL: %s: set iskvec[%llu]." + "ks->cp_filedata (%s) OK\n", __func__, b, cp->cache_name); return; } else if (ks->cp_filedata == cp) { @@ -6767,8 +6842,10 @@ ks_set_cp(ksupp_t *ks, kmem_cache_t *cp, const uint32_t cachenum) } else if (ks->cp_filedata == NULL) { continue; } else { - panic("%s: CAS failed for iksvec[%llu].ks->cp_metadata: %s wanted %s set\n", - __func__, b, cp->cache_name, ks->cp_filedata->cache_name); + panic("%s: CAS failed for iksvec[%llu]." + "ks->cp_metadata: %s wanted %s set\n", + __func__, b, cp->cache_name, + ks->cp_filedata->cache_name); } } } @@ -6791,13 +6868,13 @@ spl_zio_no_grow_init(void) while (!ISP2(p2)) p2 &= p2 - 1; - if (size <= 4 * SPA_MINBLOCKSIZE) { - align = SPA_MINBLOCKSIZE; - } else if (size <= 128 * 1024 && IS_P2ALIGNED(size, p2 >> 4)) { - align = MIN(p2 >> 4, PAGESIZE); - } else if (IS_P2ALIGNED(size, p2 >> 3)) { - align = MIN(p2 >> 3, PAGESIZE); - } + if (size <= 4 * SPA_MINBLOCKSIZE) { + align = SPA_MINBLOCKSIZE; + } else if (size <= 128 * 1024 && IS_P2ALIGNED(size, p2 >> 4)) { + align = MIN(p2 >> 4, PAGESIZE); + } else if (IS_P2ALIGNED(size, p2 >> 3)) { + align = MIN(p2 >> 3, PAGESIZE); + } if (align != 0) { iksvec[c].ks_entry = &ksvec[c]; @@ -6844,7 +6921,8 @@ spl_zio_no_grow_fini(void) } static void -spl_zio_set_no_grow(const uint32_t size, kmem_cache_t *cp, const uint32_t cachenum) +spl_zio_set_no_grow(const uint32_t size, kmem_cache_t *cp, + const uint32_t cachenum) { ASSERT(spl_zio_no_grow_inited == TRUE); ASSERT(iksvec[cachenum].ks_entry != NULL); @@ -6865,8 +6943,8 @@ spl_zio_set_no_grow(const uint32_t size, kmem_cache_t *cp, const uint32_t cachen } boolean_t -spl_zio_is_suppressed(const uint32_t size, const uint64_t now, const boolean_t buf_is_metadata, - kmem_cache_t **zp) +spl_zio_is_suppressed(const uint32_t size, const uint64_t now, + const boolean_t buf_is_metadata, kmem_cache_t **zp) { ASSERT(spl_zio_no_grow_inited == TRUE); @@ -6881,8 +6959,11 @@ spl_zio_is_suppressed(const uint32_t size, const uint64_t now, const boolean_t b return (FALSE); } else if (ks->pointed_to < 1) { ASSERT(ks->pointed_to > 0); // throw an assertion - TraceEvent(TRACE_ERROR, "SPL: %s: ERROR: iksvec[%llu].ks_entry->pointed_to == %u for size %llu\n", - __func__, (uint64_t)cachenum, ks->pointed_to, (uint64_t)size); + TraceEvent(TRACE_ERROR, + "SPL: %s: ERROR: iksvec[%llu].ks_entry->pointed_to" + "== %u for size %llu\n", + __func__, (uint64_t)cachenum, ks->pointed_to, + (uint64_t)size); return (FALSE); } else if (ks->suppress_count == 0) { return (FALSE); @@ -6899,10 +6980,13 @@ spl_zio_is_suppressed(const uint32_t size, const uint64_t now, const boolean_t b if (ks->cp_metadata == NULL) { ks_set_cp(ks, zp[cachenum], cachenum); if (ks->cp_metadata != NULL) { - atomic_inc_64(&ks->cp_metadata->arc_no_grow); + atomic_inc_64( + &ks->cp_metadata->arc_no_grow); } else { - TraceEvent(TRACE_WARNING, "WARNING: %s: " - "ks_set_cp->metadata == NULL after ks_set_cp !" + TraceEvent(TRACE_WARNING, + "WARNING: %s: " + "ks_set_cp->metadata == NULL " + "after ks_set_cp !" "size = %lu\n", __func__, size); } @@ -6913,10 +6997,13 @@ spl_zio_is_suppressed(const uint32_t size, const uint64_t now, const boolean_t b if (ks->cp_filedata == NULL) { ks_set_cp(ks, zp[cachenum], cachenum); if (ks->cp_filedata != NULL) { - atomic_inc_64(&ks->cp_filedata->arc_no_grow); + atomic_inc_64( + &ks->cp_filedata->arc_no_grow); } else { - TraceEvent(TRACE_WARNING, "WARNING: %s: " - "ks_set_cp->filedata == NULL after ks_set_cp !" + TraceEvent(TRACE_WARNING, + "WARNING: %s: " + "ks_set_cp->filedata == NULL " + "after ks_set_cp !" "size = %lu\n", __func__, size); } @@ -6931,22 +7018,24 @@ spl_zio_is_suppressed(const uint32_t size, const uint64_t now, const boolean_t b /* - * spl_zio_kmem_cache_alloc(): try to get an allocation without descending to the bucket layer, - * and if that fails, set a flag for spl_arc_no_grow() then perform the allocation normally. + * spl_zio_kmem_cache_alloc(): try to get an allocation without descending + * to the bucket layer, and if that fails, set a flag for spl_arc_no_grow() + * then perform the allocation normally. */ void * -spl_zio_kmem_cache_alloc(kmem_cache_t *cp, int kmflag, uint32_t size, uint32_t cachenum) -{ - // called by: - // spl_zio_kmem_cache_alloc(zio_buf_cache[size], kmflag, size, cachenum) or - // spl_zio_kmem_cache_alloc(zio_data_buf_cache[size], kmflag, size, cachenum) - // those are e.g. - // kmem_cache_t *zio_buf_cache[SPA_MAXBLOCKSIZE >> SPAMINBLOCKSHIFT] - // and are indexed as uint32_t cachenum = (size - 1) >> SPA_MIN~BLOCKSHIFT - // VERIFY3U(cachenum, <, SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT); - - // try to get memory from no lower than the bucket_heap +spl_zio_kmem_cache_alloc(kmem_cache_t *cp, int kmflag, uint32_t size, + uint32_t cachenum) +{ +// called by: +// spl_zio_kmem_cache_alloc(zio_buf_cache[size], kmflag, size, cachenum) or +// spl_zio_kmem_cache_alloc(zio_data_buf_cache[size], kmflag, size, cachenum) +// those are e.g. +// kmem_cache_t *zio_buf_cache[SPA_MAXBLOCKSIZE >> SPAMINBLOCKSHIFT] +// and are indexed as uint32_t cachenum = (size - 1) >> SPA_MIN~BLOCKSHIFT +// VERIFY3U(cachenum, <, SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT); + +// try to get memory from no lower than the bucket_heap void *m = kmem_cache_alloc(cp, kmflag | KM_NO_VBA | KM_NOSLEEP); if (m != NULL) { @@ -6975,27 +7064,27 @@ spl_zio_kmem_cache_alloc(kmem_cache_t *cp, int kmflag, uint32_t size, uint32_t c // perform the allocation as requested void *n = kmem_cache_alloc(cp, kmflag); - return(n); + return (n); } /* -* return true if the reclaim thread should be awakened -* because we do not have enough memory on hand -*/ + * return true if the reclaim thread should be awakened + * because we do not have enough memory on hand + */ boolean_t spl_arc_reclaim_needed(const size_t bytes, kmem_cache_t **zp) { /* - * fast path: - * if our argument is 0, then do the equivalent of - * if (arc_available_memory() < 0) return (B_TRUE); - * which is traditional arc.c appraoch - * so we can arc_reclaim_needed() -> spl_arc_reclaim_needed(0) - * if we desire. - */ + * fast path: + * if our argument is 0, then do the equivalent of + * if (arc_available_memory() < 0) return (B_TRUE); + * which is traditional arc.c appraoch + * so we can arc_reclaim_needed() -> spl_arc_reclaim_needed(0) + * if we desire. + */ if (bytes == 0 && spl_free < 0) { return (B_TRUE); } @@ -7023,8 +7112,7 @@ spl_arc_reclaim_needed(const size_t bytes, kmem_cache_t **zp) if (f <= low_threshold) { return (B_TRUE); - } - else if (f > high_threshold) { + } else if (f > high_threshold) { if (spl_free < 0) atomic_inc_64(&spl_arc_reclaim_avoided); return (B_FALSE); @@ -7032,8 +7120,7 @@ spl_arc_reclaim_needed(const size_t bytes, kmem_cache_t **zp) if (spl_free < 0) { return (B_TRUE); - } - else { + } else { return (B_FALSE); } } @@ -7064,31 +7151,35 @@ kmem_cache_buf_in_cache(kmem_cache_t *cparg, void *bufarg) sp = kmem_findslab(cp, buf); if (sp == NULL) { for (cp = list_tail(&kmem_caches); cp != NULL; - cp = list_prev(&kmem_caches, cp)) { + cp = list_prev(&kmem_caches, cp)) { if ((sp = kmem_findslab(cp, buf)) != NULL) break; } } if (sp == NULL) { - TraceEvent(TRACE_ERROR, "SPL: %s: KMERR_BADADDR orig cache = %s\n", - __func__, cparg->cache_name); + TraceEvent(TRACE_ERROR, + "SPL: %s: KMERR_BADADDR orig cache = %s\n", + __func__, cparg->cache_name); return (NULL); } if (cp == NULL) { - TraceEvent(TRACE_ERROR, "SPL: %s: ERROR cp == NULL; cparg == %s", - __func__, cparg->cache_name); + TraceEvent(TRACE_ERROR, + "SPL: %s: ERROR cp == NULL; cparg == %s", + __func__, cparg->cache_name); return (NULL); } if (cp != cparg) { - TraceEvent(TRACE_ERROR, "SPL: %s: KMERR_BADCACHE arg cache = %s but found in %s instead\n", - __func__, cparg->cache_name, cp->cache_name); - return(cp); + TraceEvent(TRACE_ERROR, + "SPL: %s: KMERR_BADCACHE arg cache = %s but " + "found in %s instead\n", + __func__, cparg->cache_name, cp->cache_name); + return (cp); } - ASSERT(cp==cparg); + ASSERT(cp == cparg); return (cp); } diff --git a/module/os/windows/spl/spl-kstat.c b/module/os/windows/spl/spl-kstat.c index 4f37387378c..eaa85649530 100644 --- a/module/os/windows/spl/spl-kstat.c +++ b/module/os/windows/spl/spl-kstat.c @@ -38,102 +38,94 @@ /* kstat_fr.c */ /* -* Copyright (c) 1992, 2010, Oracle and/or its affiliates. All rights reserved. -* Copyright 2014, Joyent, Inc. All rights reserved. -* Copyright 2015 Nexenta Systems, Inc. All rights reserved. -*/ + * Copyright (c) 1992, 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright 2014, Joyent, Inc. All rights reserved. + * Copyright 2015 Nexenta Systems, Inc. All rights reserved. + */ /* -* Kernel statistics framework -*/ + * Kernel statistics framework + */ #include #include #include #include -#include #include #include #include #include #include #include -//#include #include #include -//#include #include #include #include -//#include #include #include -//#include #include #include -//#include -//#include -//#include #include #include /* -* Global lock to protect the AVL trees and kstat_chain_id. -*/ + * Global lock to protect the AVL trees and kstat_chain_id. + */ static kmutex_t kstat_chain_lock; /* -* Every install/delete kstat bumps kstat_chain_id. This is used by: -* -* (1) /dev/kstat, to detect changes in the kstat chain across ioctls; -* -* (2) kstat_create(), to assign a KID (kstat ID) to each new kstat. -* /dev/kstat uses the KID as a cookie for kstat lookups. -* -* We reserve the first two IDs because some kstats are created before -* the well-known ones (kstat_headers = 0, kstat_types = 1). -* -* We also bump the kstat_chain_id if a zone is gaining or losing visibility -* into a particular kstat, which is logically equivalent to a kstat being -* installed/deleted. -*/ + * Every install/delete kstat bumps kstat_chain_id. This is used by: + * + * (1) /dev/kstat, to detect changes in the kstat chain across ioctls; + * + * (2) kstat_create(), to assign a KID (kstat ID) to each new kstat. + * /dev/kstat uses the KID as a cookie for kstat lookups. + * + * We reserve the first two IDs because some kstats are created before + * the well-known ones (kstat_headers = 0, kstat_types = 1). + * + * We also bump the kstat_chain_id if a zone is gaining or losing visibility + * into a particular kstat, which is logically equivalent to a kstat being + * installed/deleted. + */ kid_t kstat_chain_id = 2; /* -* As far as zones are concerned, there are 3 types of kstat: -* -* 1) Those which have a well-known name, and which should return per-zone data -* depending on which zone is doing the kstat_read(). sockfs:0:sock_unix_list -* is an example of this type of kstat. -* -* 2) Those which should only be exported to a particular list of zones. -* For example, in the case of nfs:*:mntinfo, we don't want zone A to be -* able to see NFS mounts associated with zone B, while we want the -* global zone to be able to see all mounts on the system. -* -* 3) Those that can be exported to all zones. Most system-related -* kstats fall within this category. -* -* An ekstat_t thus contains a list of kstats that the zone is to be -* exported to. The lookup of a name:instance:module thus translates to a -* lookup of name:instance:module:myzone; if the kstat is not exported -* to all zones, and does not have the caller's zoneid explicitly -* enumerated in the list of zones to be exported to, it is the same as -* if the kstat didn't exist. -* -* Writing to kstats is currently disallowed from within a non-global -* zone, although this restriction could be removed in the future. -*/ + * As far as zones are concerned, there are 3 types of kstat: + * + * 1) Those which have a well-known name, and which should return per-zone data + * depending on which zone is doing the kstat_read(). sockfs:0:sock_unix_list + * is an example of this type of kstat. + * + * 2) Those which should only be exported to a particular list of zones. + * For example, in the case of nfs:*:mntinfo, we don't want zone A to be + * able to see NFS mounts associated with zone B, while we want the + * global zone to be able to see all mounts on the system. + * + * 3) Those that can be exported to all zones. Most system-related + * kstats fall within this category. + * + * An ekstat_t thus contains a list of kstats that the zone is to be + * exported to. The lookup of a name:instance:module thus translates to a + * lookup of name:instance:module:myzone; if the kstat is not exported + * to all zones, and does not have the caller's zoneid explicitly + * enumerated in the list of zones to be exported to, it is the same as + * if the kstat didn't exist. + * + * Writing to kstats is currently disallowed from within a non-global + * zone, although this restriction could be removed in the future. + */ typedef struct kstat_zone { zoneid_t zoneid; struct kstat_zone *next; } kstat_zone_t; /* -* Extended kstat structure -- for internal use only. -*/ + * Extended kstat structure -- for internal use only. + */ typedef struct ekstat { kstat_t e_ks; /* the kstat itself */ size_t e_size; /* total allocation size */ @@ -145,290 +137,292 @@ typedef struct ekstat { } ekstat_t; struct sbuf { - char *s_buf; /* storage buffer */ - void *s_unused; /* binary compatibility. */ - int s_size; /* size of storage buffer */ - int s_len; /* current length of string */ -#define SBUF_FIXEDLEN 0x00000000 /* fixed length buffer (default) */ -#define SBUF_AUTOEXTEND 0x00000001 /* automatically extend buffer */ -#define SBUF_USRFLAGMSK 0x0000ffff /* mask of flags the user may specify */ -#define SBUF_DYNAMIC 0x00010000 /* s_buf must be freed */ -#define SBUF_FINISHED 0x00020000 /* set by sbuf_finish() */ -#define SBUF_OVERFLOWED 0x00040000 /* sbuf overflowed */ -#define SBUF_DYNSTRUCT 0x00080000 /* sbuf must be freed */ - int s_flags; /* flags */ + char *s_buf; /* storage buffer */ + void *s_unused; /* binary compatibility. */ + int s_size; /* size of storage buffer */ + int s_len; /* current length of string */ +#define SBUF_FIXEDLEN 0x00000000 /* fixed length buffer (default) */ +#define SBUF_AUTOEXTEND 0x00000001 /* automatically extend buffer */ +#define SBUF_USRFLAGMSK 0x0000ffff /* mask of flags the user may specify */ +#define SBUF_DYNAMIC 0x00010000 /* s_buf must be freed */ +#define SBUF_FINISHED 0x00020000 /* set by sbuf_finish() */ +#define SBUF_OVERFLOWED 0x00040000 /* sbuf overflowed */ +#define SBUF_DYNSTRUCT 0x00080000 /* sbuf must be freed */ + int s_flags; /* flags */ }; /* sbuf_new() and family does exist in XNU, but Apple wont let us call them */ -#define M_SBUF 105 /* string buffers */ -#define SBMALLOC(size) (struct sbuf *)ExAllocatePoolWithTag(NonPagedPoolNx, (size), '!SFZ') -#define SBFREE(buf) ExFreePoolWithTag((buf), '!SFZ') - -#define SBUF_SETFLAG(s, f) do { (s)->s_flags |= (f); } while (0) -#define SBUF_CLEARFLAG(s, f) do { (s)->s_flags &= ~(f); } while (0) -#define SBUF_ISDYNAMIC(s) ((s)->s_flags & SBUF_DYNAMIC) -#define SBUF_ISDYNSTRUCT(s) ((s)->s_flags & SBUF_DYNSTRUCT) -#define SBUF_HASOVERFLOWED(s) ((s)->s_flags & SBUF_OVERFLOWED) -#define SBUF_HASROOM(s) ((s)->s_len < (s)->s_size - 1) -#define SBUF_FREESPACE(s) ((s)->s_size - (s)->s_len - 1) -#define SBUF_CANEXTEND(s) ((s)->s_flags & SBUF_AUTOEXTEND) - -#define SBUF_MINEXTENDSIZE 16 /* Should be power of 2. */ -#define SBUF_MAXEXTENDSIZE PAGE_SIZE -#define SBUF_MAXEXTENDINCR PAGE_SIZE +#define M_SBUF 105 /* string buffers */ +#define SBMALLOC(size) \ + (struct sbuf *)ExAllocatePoolWithTag(NonPagedPoolNx, (size), '!SFZ') +#define SBFREE(buf) ExFreePoolWithTag((buf), '!SFZ') + +#define SBUF_SETFLAG(s, f) do { (s)->s_flags |= (f); } while (0) +#define SBUF_CLEARFLAG(s, f) do { (s)->s_flags &= ~(f); } while (0) +#define SBUF_ISDYNAMIC(s) ((s)->s_flags & SBUF_DYNAMIC) +#define SBUF_ISDYNSTRUCT(s) ((s)->s_flags & SBUF_DYNSTRUCT) +#define SBUF_HASOVERFLOWED(s) ((s)->s_flags & SBUF_OVERFLOWED) +#define SBUF_HASROOM(s) ((s)->s_len < (s)->s_size - 1) +#define SBUF_FREESPACE(s) ((s)->s_size - (s)->s_len - 1) +#define SBUF_CANEXTEND(s) ((s)->s_flags & SBUF_AUTOEXTEND) + +#define SBUF_MINEXTENDSIZE 16 /* Should be power of 2. */ +#define SBUF_MAXEXTENDSIZE PAGE_SIZE +#define SBUF_MAXEXTENDINCR PAGE_SIZE void sbuf_finish(struct sbuf *s) { - s->s_buf[s->s_len] = '\0'; - SBUF_CLEARFLAG(s, SBUF_OVERFLOWED); - SBUF_SETFLAG(s, SBUF_FINISHED); + s->s_buf[s->s_len] = '\0'; + SBUF_CLEARFLAG(s, SBUF_OVERFLOWED); + SBUF_SETFLAG(s, SBUF_FINISHED); } char * sbuf_data(struct sbuf *s) { - return (s->s_buf); + return (s->s_buf); } int sbuf_len(struct sbuf *s) { - if (SBUF_HASOVERFLOWED(s)) { - return (-1); - } - return (s->s_len); + if (SBUF_HASOVERFLOWED(s)) { + return (-1); + } + return (s->s_len); } void sbuf_delete(struct sbuf *s) { - int isdyn; - if (SBUF_ISDYNAMIC(s)) { - SBFREE(s->s_buf); - } - isdyn = SBUF_ISDYNSTRUCT(s); - bzero(s, sizeof (*s)); - if (isdyn) { - SBFREE(s); - } + int isdyn; + if (SBUF_ISDYNAMIC(s)) { + SBFREE(s->s_buf); + } + isdyn = SBUF_ISDYNSTRUCT(s); + bzero(s, sizeof (*s)); + if (isdyn) { + SBFREE(s); + } } static int sbuf_extendsize(int size) { - int newsize; - - newsize = SBUF_MINEXTENDSIZE; - while (newsize < size) { - if (newsize < (int)SBUF_MAXEXTENDSIZE) { - newsize *= 2; - } else { - newsize += SBUF_MAXEXTENDINCR; - } - } - - return (newsize); + int newsize; + + newsize = SBUF_MINEXTENDSIZE; + while (newsize < size) { + if (newsize < (int)SBUF_MAXEXTENDSIZE) { + newsize *= 2; + } else { + newsize += SBUF_MAXEXTENDINCR; + } + } + + return (newsize); } static int sbuf_extend(struct sbuf *s, int addlen) { - char *newbuf; - int newsize; - - if (!SBUF_CANEXTEND(s)) { - return (-1); - } - - newsize = sbuf_extendsize(s->s_size + addlen); - newbuf = (char *)SBMALLOC(newsize); - if (newbuf == NULL) { - return (-1); - } - bcopy(s->s_buf, newbuf, s->s_size); - if (SBUF_ISDYNAMIC(s)) { - SBFREE(s->s_buf); - } else { - SBUF_SETFLAG(s, SBUF_DYNAMIC); - } - s->s_buf = newbuf; - s->s_size = newsize; - return (0); + char *newbuf; + int newsize; + + if (!SBUF_CANEXTEND(s)) { + return (-1); + } + + newsize = sbuf_extendsize(s->s_size + addlen); + newbuf = (char *)SBMALLOC(newsize); + if (newbuf == NULL) { + return (-1); + } + bcopy(s->s_buf, newbuf, s->s_size); + if (SBUF_ISDYNAMIC(s)) { + SBFREE(s->s_buf); + } else { + SBUF_SETFLAG(s, SBUF_DYNAMIC); + } + s->s_buf = newbuf; + s->s_size = newsize; + return (0); } struct sbuf * sbuf_new(struct sbuf *s, char *buf, int length, int flags) { - flags &= SBUF_USRFLAGMSK; - if (s == NULL) { - s = (struct sbuf *)SBMALLOC(sizeof (*s)); - if (s == NULL) { - return (NULL); - } - bzero(s, sizeof (*s)); - s->s_flags = flags; - SBUF_SETFLAG(s, SBUF_DYNSTRUCT); - } else { - bzero(s, sizeof (*s)); - s->s_flags = flags; - } - s->s_size = length; - if (buf) { - s->s_buf = buf; - return (s); - } - if (flags & SBUF_AUTOEXTEND) { - s->s_size = sbuf_extendsize(s->s_size); - } - s->s_buf = (char *)SBMALLOC(s->s_size); - if (s->s_buf == NULL) { - if (SBUF_ISDYNSTRUCT(s)) { - SBFREE(s); - } - return (NULL); - } - SBUF_SETFLAG(s, SBUF_DYNAMIC); - return (s); + flags &= SBUF_USRFLAGMSK; + if (s == NULL) { + s = (struct sbuf *)SBMALLOC(sizeof (*s)); + if (s == NULL) { + return (NULL); + } + bzero(s, sizeof (*s)); + s->s_flags = flags; + SBUF_SETFLAG(s, SBUF_DYNSTRUCT); + } else { + bzero(s, sizeof (*s)); + s->s_flags = flags; + } + s->s_size = length; + if (buf) { + s->s_buf = buf; + return (s); + } + if (flags & SBUF_AUTOEXTEND) { + s->s_size = sbuf_extendsize(s->s_size); + } + s->s_buf = (char *)SBMALLOC(s->s_size); + if (s->s_buf == NULL) { + if (SBUF_ISDYNSTRUCT(s)) { + SBFREE(s); + } + return (NULL); + } + SBUF_SETFLAG(s, SBUF_DYNAMIC); + return (s); } -#define va_copy(A,B) A = B +#define va_copy(A, B) A = B int sbuf_vprintf(struct sbuf *s, const char *fmt, va_list ap) { - __builtin_va_list ap_copy; - int len; - - if (SBUF_HASOVERFLOWED(s)) { - return (-1); - } - - do { - va_copy(ap_copy, ap); - len = vsnprintf(&s->s_buf[s->s_len], SBUF_FREESPACE(s) + 1, - fmt, ap_copy); - // va_end(ap_copy); // left-side must be assignable. Win tries to set to 0. - } while (len > SBUF_FREESPACE(s) && - sbuf_extend(s, len - SBUF_FREESPACE(s)) == 0); - s->s_len += min(len, SBUF_FREESPACE(s)); - if (!SBUF_HASROOM(s) && !SBUF_CANEXTEND(s)) { - SBUF_SETFLAG(s, SBUF_OVERFLOWED); - } - - if (SBUF_HASOVERFLOWED(s)) { - return (-1); - } - return (0); + __builtin_va_list ap_copy; + int len; + + if (SBUF_HASOVERFLOWED(s)) { + return (-1); + } + + do { + va_copy(ap_copy, ap); + len = vsnprintf(&s->s_buf[s->s_len], SBUF_FREESPACE(s) + 1, + fmt, ap_copy); + // left-side must be assignable. Win tries to set to 0. + // va_end(ap_copy); + } while (len > SBUF_FREESPACE(s) && + sbuf_extend(s, len - SBUF_FREESPACE(s)) == 0); + s->s_len += min(len, SBUF_FREESPACE(s)); + if (!SBUF_HASROOM(s) && !SBUF_CANEXTEND(s)) { + SBUF_SETFLAG(s, SBUF_OVERFLOWED); + } + + if (SBUF_HASOVERFLOWED(s)) { + return (-1); + } + return (0); } int sbuf_printf(struct sbuf *s, const char *fmt, ...) { - va_list ap; - int result; + va_list ap; + int result; - va_start(ap, fmt); - result = sbuf_vprintf(s, fmt, ap); - va_end(ap); - return (result); + va_start(ap, fmt); + result = sbuf_vprintf(s, fmt, ap); + va_end(ap); + return (result); } static int kstat_default_update(kstat_t *ksp, int rw) { - ASSERT(ksp != NULL); + ASSERT(ksp != NULL); - if (rw == KSTAT_WRITE) - return (EACCES); + if (rw == KSTAT_WRITE) + return (EACCES); - return (0); + return (0); } static int kstat_resize_raw(kstat_t *ksp) { - if (ksp->ks_raw_bufsize == KSTAT_RAW_MAX) - return (ENOMEM); + if (ksp->ks_raw_bufsize == KSTAT_RAW_MAX) + return (ENOMEM); - SBMFREE(ksp->ks_raw_buf, ksp->ks_raw_bufsize); - ksp->ks_raw_bufsize = MIN(ksp->ks_raw_bufsize * 2, KSTAT_RAW_MAX); - ksp->ks_raw_buf = SBMALLOC(ksp->ks_raw_bufsize); + SBMFREE(ksp->ks_raw_buf, ksp->ks_raw_bufsize); + ksp->ks_raw_bufsize = MIN(ksp->ks_raw_bufsize * 2, KSTAT_RAW_MAX); + ksp->ks_raw_buf = SBMALLOC(ksp->ks_raw_bufsize); - return (0); + return (0); } static void * kstat_raw_default_addr(kstat_t *ksp, loff_t n) { - if (n == 0) - return (ksp->ks_data); - return (NULL); + if (n == 0) + return (ksp->ks_data); + return (NULL); } -#define HD_COLUMN_MASK 0xff -#define HD_DELIM_MASK 0xff00 -#define HD_OMIT_COUNT (1 << 16) -#define HD_OMIT_HEX (1 << 17) -#define HD_OMIT_CHARS (1 << 18) +#define HD_COLUMN_MASK 0xff +#define HD_DELIM_MASK 0xff00 +#define HD_OMIT_COUNT (1 << 16) +#define HD_OMIT_HEX (1 << 17) +#define HD_OMIT_CHARS (1 << 18) void sbuf_hexdump(struct sbuf *sb, const void *ptr, int length, const char *hdr, int flags) { - int i, j, k; - int cols; - const unsigned char *cp; - char delim; - - if ((flags & HD_DELIM_MASK) != 0) - delim = (flags & HD_DELIM_MASK) >> 8; - else - delim = ' '; - - if ((flags & HD_COLUMN_MASK) != 0) - cols = flags & HD_COLUMN_MASK; - else - cols = 16; - - cp = ptr; - for (i = 0; i < length; i += cols) { - if (hdr != NULL) - sbuf_printf(sb, "%s", hdr); - - if ((flags & HD_OMIT_COUNT) == 0) - sbuf_printf(sb, "%04x ", i); - - if ((flags & HD_OMIT_HEX) == 0) { - for (j = 0; j < cols; j++) { - k = i + j; - if (k < length) - sbuf_printf(sb, "%c%02x", delim, cp[k]); - else - sbuf_printf(sb, " "); - } - } - - if ((flags & HD_OMIT_CHARS) == 0) { - sbuf_printf(sb, " |"); - for (j = 0; j < cols; j++) { - k = i + j; - if (k >= length) - sbuf_printf(sb, " "); - else if (cp[k] >= ' ' && cp[k] <= '~') - sbuf_printf(sb, "%c", cp[k]); - else - sbuf_printf(sb, "."); - } - sbuf_printf(sb, "|"); - } - sbuf_printf(sb, "\n"); - } + int i, j, k; + int cols; + const unsigned char *cp; + char delim; + + if ((flags & HD_DELIM_MASK) != 0) + delim = (flags & HD_DELIM_MASK) >> 8; + else + delim = ' '; + + if ((flags & HD_COLUMN_MASK) != 0) + cols = flags & HD_COLUMN_MASK; + else + cols = 16; + + cp = ptr; + for (i = 0; i < length; i += cols) { + if (hdr != NULL) + sbuf_printf(sb, "%s", hdr); + + if ((flags & HD_OMIT_COUNT) == 0) + sbuf_printf(sb, "%04x ", i); + + if ((flags & HD_OMIT_HEX) == 0) { + for (j = 0; j < cols; j++) { + k = i + j; + if (k < length) + sbuf_printf(sb, "%c%02x", delim, cp[k]); + else + sbuf_printf(sb, " "); + } + } + + if ((flags & HD_OMIT_CHARS) == 0) { + sbuf_printf(sb, " |"); + for (j = 0; j < cols; j++) { + k = i + j; + if (k >= length) + sbuf_printf(sb, " "); + else if (cp[k] >= ' ' && cp[k] <= '~') + sbuf_printf(sb, "%c", cp[k]); + else + sbuf_printf(sb, "."); + } + sbuf_printf(sb, "|"); + } + sbuf_printf(sb, "\n"); + } } static uint64_t kstat_initial[8192]; static void *kstat_initial_ptr = kstat_initial; -static size_t kstat_initial_avail = sizeof(kstat_initial); +static size_t kstat_initial_avail = sizeof (kstat_initial); static vmem_t *kstat_arena; #define KSTAT_ALIGN (sizeof (uint64_t)) @@ -437,8 +431,8 @@ static avl_tree_t kstat_avl_bykid; static avl_tree_t kstat_avl_byname; /* -* Various pointers we need to create kstats at boot time in kstat_init() -*/ + * Various pointers we need to create kstats at boot time in kstat_init() + */ extern kstat_named_t *segmapcnt_ptr; extern uint_t segmapcnt_ndata; extern int segmap_kstat_update(kstat_t *, int); @@ -457,19 +451,16 @@ static struct { uint_t min_ndata; uint_t max_ndata; } kstat_data_type[KSTAT_NUM_TYPES] = { - { "raw", 1, 0, INT_MAX }, - { "name=value", sizeof(kstat_named_t), 0, INT_MAX }, - { "interrupt", sizeof(kstat_intr_t), 1, 1 }, - { "i/o", sizeof(kstat_io_t), 1, 1 }, - { "event_timer", sizeof(kstat_timer_t), 0, INT_MAX }, + { "raw", 1, 0, INT_MAX }, + { "name=value", sizeof (kstat_named_t), 0, INT_MAX }, + { "interrupt", sizeof (kstat_intr_t), 1, 1 }, + { "i/o", sizeof (kstat_io_t), 1, 1 }, + { "event_timer", sizeof (kstat_timer_t), 0, INT_MAX }, }; static int header_kstat_update(kstat_t *, int); static int header_kstat_snapshot(kstat_t *, void *, int); - - - int kstat_zone_find(kstat_t *k, zoneid_t zoneid) { @@ -512,7 +503,7 @@ kstat_zone_remove(kstat_t *k, zoneid_t zoneid) out: kstat_chain_id++; mutex_exit(&kstat_chain_lock); - kmem_free(kz, sizeof(*kz)); + kmem_free(kz, sizeof (*kz)); } void @@ -521,7 +512,7 @@ kstat_zone_add(kstat_t *k, zoneid_t zoneid) ekstat_t *e = (ekstat_t *)k; kstat_zone_t *kz; - kz = kmem_alloc(sizeof(*kz), KM_NOSLEEP); + kz = kmem_alloc(sizeof (*kz), KM_NOSLEEP); if (kz == NULL) return; mutex_enter(&kstat_chain_lock); @@ -533,12 +524,12 @@ kstat_zone_add(kstat_t *k, zoneid_t zoneid) } /* -* Compare the list of zones for the given kstats, returning 0 if they match -* (ie, one list contains ALL_ZONES or both lists contain the same zoneid). -* In practice, this is called indirectly by kstat_hold_byname(), so one of the -* two lists always has one element, and this is an O(n) operation rather than -* O(n^2). -*/ + * Compare the list of zones for the given kstats, returning 0 if they match + * (ie, one list contains ALL_ZONES or both lists contain the same zoneid). + * In practice, this is called indirectly by kstat_hold_byname(), so one of the + * two lists always has one element, and this is an O(n) operation rather than + * O(n^2). + */ static int kstat_zone_compare(ekstat_t *e1, ekstat_t *e2) { @@ -548,7 +539,7 @@ kstat_zone_compare(ekstat_t *e1, ekstat_t *e2) for (kz1 = &e1->e_zone; kz1 != NULL; kz1 = kz1->next) { for (kz2 = &e2->e_zone; kz2 != NULL; kz2 = kz2->next) { if (kz1->zoneid == ALL_ZONES || - kz2->zoneid == ALL_ZONES) + kz2->zoneid == ALL_ZONES) return (0); if (kz1->zoneid == kz2->zoneid) return (0); @@ -558,8 +549,8 @@ kstat_zone_compare(ekstat_t *e1, ekstat_t *e2) } /* -* Support for keeping kstats sorted in AVL trees for fast lookups. -*/ + * Support for keeping kstats sorted in AVL trees for fast lookups. + */ static int kstat_compare_bykid(const void *a1, const void *a2) { @@ -648,7 +639,7 @@ kstat_hold_bykid(kid_t kid, zoneid_t zoneid) kstat_t * kstat_hold_byname(const char *ks_module, int ks_instance, const char *ks_name, - zoneid_t ks_zoneid) + zoneid_t ks_zoneid) { ekstat_t e; @@ -665,7 +656,7 @@ kstat_alloc(size_t size) { ekstat_t *e = NULL; - size = P2ROUNDUP(sizeof(ekstat_t) + size, KSTAT_ALIGN); + size = P2ROUNDUP(sizeof (ekstat_t) + size, KSTAT_ALIGN); if (kstat_arena == NULL) { if (size <= kstat_initial_avail) { @@ -698,8 +689,8 @@ void *segkmem_alloc(vmem_t *vmp, uint32_t size, int vmflag); void segkmem_free(vmem_t *vmp, void *inaddr, uint32_t size); /* -* Create various system kstats. -*/ + * Create various system kstats. + */ void kstat_init(void) { @@ -708,29 +699,29 @@ kstat_init(void) avl_tree_t *t = &kstat_avl_bykid; /* - * Set up the kstat vmem arena. - */ + * Set up the kstat vmem arena. + */ kstat_arena = vmem_create("kstat", - (void *)kstat_initial, sizeof(kstat_initial), KSTAT_ALIGN, - segkmem_alloc, segkmem_free, heap_arena, 0, VM_SLEEP); + (void *)kstat_initial, sizeof (kstat_initial), KSTAT_ALIGN, + segkmem_alloc, segkmem_free, heap_arena, 0, VM_SLEEP); /* - * Make initial kstats appear as though they were allocated. - */ + * Make initial kstats appear as though they were allocated. + */ for (e = avl_first(t); e != NULL; e = avl_walk(t, e, AVL_AFTER)) (void) vmem_xalloc(kstat_arena, e->e_size, KSTAT_ALIGN, - 0, 0, e, (char *)e + e->e_size, - VM_NOSLEEP | VM_BESTFIT | VM_PANIC); + 0, 0, e, (char *)e + e->e_size, + VM_NOSLEEP | VM_BESTFIT | VM_PANIC); /* - * The mother of all kstats. The first kstat in the system, which - * always has KID 0, has the headers for all kstats (including itself) - * as its data. Thus, the kstat driver does not need any special - * interface to extract the kstat chain. - */ + * The mother of all kstats. The first kstat in the system, which + * always has KID 0, has the headers for all kstats (including itself) + * as its data. Thus, the kstat driver does not need any special + * interface to extract the kstat chain. + */ kstat_chain_id = 0; ksp = kstat_create("unix", 0, "kstat_headers", "kstat", KSTAT_TYPE_RAW, - 0, KSTAT_FLAG_VIRTUAL | KSTAT_FLAG_VAR_SIZE); + 0, KSTAT_FLAG_VIRTUAL | KSTAT_FLAG_VAR_SIZE); if (ksp) { ksp->ks_lock = &kstat_chain_lock; ksp->ks_update = header_kstat_update; @@ -741,14 +732,14 @@ kstat_init(void) } ksp = kstat_create("unix", 0, "kstat_types", "kstat", - KSTAT_TYPE_NAMED, KSTAT_NUM_TYPES, 0); + KSTAT_TYPE_NAMED, KSTAT_NUM_TYPES, 0); if (ksp) { int i; kstat_named_t *kn = KSTAT_NAMED_PTR(ksp); for (i = 0; i < KSTAT_NUM_TYPES; i++) { kstat_named_init(&kn[i], kstat_data_type[i].name, - KSTAT_DATA_ULONG); + KSTAT_DATA_ULONG); kn[i].value.ul = i; } kstat_install(ksp); @@ -757,17 +748,17 @@ kstat_init(void) } /* -* Caller of this should ensure that the string pointed by src -* doesn't change while kstat's lock is held. Not doing so defeats -* kstat's snapshot strategy as explained in -*/ + * Caller of this should ensure that the string pointed by src + * doesn't change while kstat's lock is held. Not doing so defeats + * kstat's snapshot strategy as explained in + */ void kstat_named_setstr(kstat_named_t *knp, const char *src) { if (knp->data_type != KSTAT_DATA_STRING) panic("kstat_named_setstr('%p', '%p'): " - "named kstat is not of type KSTAT_DATA_STRING", - (void *)knp, (void *)src); + "named kstat is not of type KSTAT_DATA_STRING", + (void *)knp, (void *)src); KSTAT_NAMED_STR_PTR(knp) = (char *)src; if (src != NULL) @@ -780,7 +771,7 @@ void kstat_set_string(char *dst, const char *src) { bzero(dst, KSTAT_STRLEN); - (void)strncpy(dst, src, KSTAT_STRLEN - 1); + (void) strncpy(dst, src, KSTAT_STRLEN - 1); } void @@ -808,22 +799,22 @@ default_kstat_update(kstat_t *ksp, int rw) kstat_named_t *knp; /* - * Named kstats with variable-length long strings have a standard - * way of determining how much space is needed to hold the snapshot: - */ + * Named kstats with variable-length long strings have a standard + * way of determining how much space is needed to hold the snapshot: + */ if (ksp->ks_data != NULL && ksp->ks_type == KSTAT_TYPE_NAMED && - (ksp->ks_flags & (KSTAT_FLAG_VAR_SIZE | KSTAT_FLAG_LONGSTRINGS))) { + (ksp->ks_flags & (KSTAT_FLAG_VAR_SIZE | KSTAT_FLAG_LONGSTRINGS))) { /* - * Add in the space required for the strings - */ + * Add in the space required for the strings + */ knp = KSTAT_NAMED_PTR(ksp); for (i = 0; i < ksp->ks_ndata; i++, knp++) { if (knp->data_type == KSTAT_DATA_STRING) len += KSTAT_NAMED_STR_BUFLEN(knp); } ksp->ks_data_size = - ksp->ks_ndata * sizeof(kstat_named_t) + len; + ksp->ks_ndata * sizeof (kstat_named_t) + len; } return (0); } @@ -845,29 +836,29 @@ default_kstat_snapshot(kstat_t *ksp, void *buf, int rw) } /* - * KSTAT_TYPE_NAMED kstats are defined to have ks_ndata - * number of kstat_named_t structures, followed by an optional - * string segment. The ks_data generally holds only the - * kstat_named_t structures. So we copy it first. The strings, - * if any, are copied below. For other kstat types, ks_data holds the - * entire buffer. - */ - - namedsz = sizeof(kstat_named_t) * ksp->ks_ndata; + * KSTAT_TYPE_NAMED kstats are defined to have ks_ndata + * number of kstat_named_t structures, followed by an optional + * string segment. The ks_data generally holds only the + * kstat_named_t structures. So we copy it first. The strings, + * if any, are copied below. For other kstat types, ks_data holds the + * entire buffer. + */ + + namedsz = sizeof (kstat_named_t) * ksp->ks_ndata; if (ksp->ks_type == KSTAT_TYPE_NAMED && ksp->ks_data_size > namedsz) bcopy(ksp->ks_data, buf, namedsz); else bcopy(ksp->ks_data, buf, ksp->ks_data_size); /* - * Apply kstat type-specific data massaging - */ + * Apply kstat type-specific data massaging + */ switch (ksp->ks_type) { case KSTAT_TYPE_IO: /* - * Normalize time units and deal with incomplete transactions - */ + * Normalize time units and deal with incomplete transactions + */ #if 0 kiop = (kstat_io_t *)buf; @@ -898,20 +889,20 @@ default_kstat_snapshot(kstat_t *ksp, void *buf, int rw) case KSTAT_TYPE_NAMED: /* - * Massage any long strings in at the end of the buffer - */ + * Massage any long strings in at the end of the buffer + */ if (ksp->ks_data_size > namedsz) { uint_t i; kstat_named_t *knp = buf; char *dst = (char *)(knp + ksp->ks_ndata); /* - * Copy strings and update pointers - */ + * Copy strings and update pointers + */ for (i = 0; i < ksp->ks_ndata; i++, knp++) { if (knp->data_type == KSTAT_DATA_STRING && - KSTAT_NAMED_STR_PTR(knp) != NULL) { + KSTAT_NAMED_STR_PTR(knp) != NULL) { bcopy(KSTAT_NAMED_STR_PTR(knp), dst, - KSTAT_NAMED_STR_BUFLEN(knp)); + KSTAT_NAMED_STR_BUFLEN(knp)); KSTAT_NAMED_STR_PTR(knp) = dst; dst += KSTAT_NAMED_STR_BUFLEN(knp); } @@ -939,20 +930,20 @@ header_kstat_update(kstat_t *header_ksp, int rw) zoneid = crgetzoneid(); for (e = avl_first(t); e != NULL; e = avl_walk(t, e, AVL_AFTER)) { if (kstat_zone_find((kstat_t *)e, zoneid) && - (e->e_ks.ks_flags & KSTAT_FLAG_INVALID) == 0) { + (e->e_ks.ks_flags & KSTAT_FLAG_INVALID) == 0) { nkstats++; } } header_ksp->ks_ndata = nkstats; - header_ksp->ks_data_size = nkstats * sizeof(kstat_t); + header_ksp->ks_data_size = nkstats * sizeof (kstat_t); return (0); } /* -* Copy out the data section of kstat 0, which consists of the list -* of all kstat headers. By specification, these headers must be -* copied out in order of increasing KID. -*/ + * Copy out the data section of kstat 0, which consists of the list + * of all kstat headers. By specification, these headers must be + * copied out in order of increasing KID. + */ static int header_kstat_snapshot(kstat_t *header_ksp, void *buf, int rw) { @@ -970,9 +961,9 @@ header_kstat_snapshot(kstat_t *header_ksp, void *buf, int rw) zoneid = crgetzoneid(); for (e = avl_first(t); e != NULL; e = avl_walk(t, e, AVL_AFTER)) { if (kstat_zone_find((kstat_t *)e, zoneid) && - (e->e_ks.ks_flags & KSTAT_FLAG_INVALID) == 0) { - bcopy(&e->e_ks, buf, sizeof(kstat_t)); - buf = (char *)buf + sizeof(kstat_t); + (e->e_ks.ks_flags & KSTAT_FLAG_INVALID) == 0) { + bcopy(&e->e_ks, buf, sizeof (kstat_t)); + buf = (char *)buf + sizeof (kstat_t); } } @@ -981,22 +972,22 @@ header_kstat_snapshot(kstat_t *header_ksp, void *buf, int rw) kstat_t * kstat_create(const char *ks_module, int ks_instance, const char *ks_name, - const char *ks_class, uchar_t ks_type, uint_t ks_ndata, uchar_t ks_flags) + const char *ks_class, uchar_t ks_type, uint_t ks_ndata, uchar_t ks_flags) { return (kstat_create_zone(ks_module, ks_instance, ks_name, ks_class, - ks_type, ks_ndata, ks_flags, ALL_ZONES)); + ks_type, ks_ndata, ks_flags, ALL_ZONES)); } /* -* Allocate and initialize a kstat structure. Or, if a dormant kstat with -* the specified name exists, reactivate it. Returns a pointer to the kstat -* on success, NULL on failure. The kstat will not be visible to the -* kstat driver until kstat_install(). -*/ + * Allocate and initialize a kstat structure. Or, if a dormant kstat with + * the specified name exists, reactivate it. Returns a pointer to the kstat + * on success, NULL on failure. The kstat will not be visible to the + * kstat driver until kstat_install(). + */ kstat_t * kstat_create_zone(const char *ks_module, int ks_instance, const char *ks_name, - const char *ks_class, uchar_t ks_type, uint_t ks_ndata, uchar_t ks_flags, - zoneid_t ks_zoneid) + const char *ks_class, uchar_t ks_type, uint_t ks_ndata, uchar_t ks_flags, + zoneid_t ks_zoneid) { size_t ks_data_size; kstat_t *ksp; @@ -1009,130 +1000,130 @@ kstat_create_zone(const char *ks_module, int ks_instance, const char *ks_name, if (avl_numnodes(&kstat_avl_bykid) == 0) { avl_create(&kstat_avl_bykid, kstat_compare_bykid, - sizeof(ekstat_t), offsetof(struct ekstat, e_avl_bykid)); + sizeof (ekstat_t), offsetof(struct ekstat, e_avl_bykid)); avl_create(&kstat_avl_byname, kstat_compare_byname, - sizeof(ekstat_t), offsetof(struct ekstat, e_avl_byname)); + sizeof (ekstat_t), offsetof(struct ekstat, e_avl_byname)); } /* - * If ks_name == NULL, set the ks_name to . - */ + * If ks_name == NULL, set the ks_name to . + */ if (ks_name == NULL) { char buf[KSTAT_STRLEN]; kstat_set_string(buf, ks_module); - (void)sprintf(namebuf, "%s%d", buf, ks_instance); + (void) sprintf(namebuf, "%s%d", buf, ks_instance); ks_name = namebuf; } /* - * Make sure it's a valid kstat data type - */ + * Make sure it's a valid kstat data type + */ if (ks_type >= KSTAT_NUM_TYPES) { cmn_err(CE_WARN, "kstat_create('%s', %d, '%s'): " - "invalid kstat type %d", - ks_module, ks_instance, ks_name, ks_type); + "invalid kstat type %d", + ks_module, ks_instance, ks_name, ks_type); return (NULL); } /* - * Don't allow persistent virtual kstats -- it makes no sense. - * ks_data points to garbage when the client goes away. - */ + * Don't allow persistent virtual kstats -- it makes no sense. + * ks_data points to garbage when the client goes away. + */ if ((ks_flags & KSTAT_FLAG_PERSISTENT) && - (ks_flags & KSTAT_FLAG_VIRTUAL)) { + (ks_flags & KSTAT_FLAG_VIRTUAL)) { cmn_err(CE_WARN, "kstat_create('%s', %d, '%s'): " - "cannot create persistent virtual kstat", - ks_module, ks_instance, ks_name); + "cannot create persistent virtual kstat", + ks_module, ks_instance, ks_name); return (NULL); } /* - * Don't allow variable-size physical kstats, since the framework's - * memory allocation for physical kstat data is fixed at creation time. - */ + * Don't allow variable-size physical kstats, since the framework's + * memory allocation for physical kstat data is fixed at creation time. + */ if ((ks_flags & KSTAT_FLAG_VAR_SIZE) && - !(ks_flags & KSTAT_FLAG_VIRTUAL)) { + !(ks_flags & KSTAT_FLAG_VIRTUAL)) { cmn_err(CE_WARN, "kstat_create('%s', %d, '%s'): " - "cannot create variable-size physical kstat", - ks_module, ks_instance, ks_name); + "cannot create variable-size physical kstat", + ks_module, ks_instance, ks_name); return (NULL); } /* - * Make sure the number of data fields is within legal range - */ + * Make sure the number of data fields is within legal range + */ if (ks_ndata < kstat_data_type[ks_type].min_ndata || - ks_ndata > kstat_data_type[ks_type].max_ndata) { + ks_ndata > kstat_data_type[ks_type].max_ndata) { cmn_err(CE_WARN, "kstat_create('%s', %d, '%s'): " - "ks_ndata=%d out of range [%d, %d]", - ks_module, ks_instance, ks_name, (int)ks_ndata, - kstat_data_type[ks_type].min_ndata, - kstat_data_type[ks_type].max_ndata); + "ks_ndata=%d out of range [%d, %d]", + ks_module, ks_instance, ks_name, (int)ks_ndata, + kstat_data_type[ks_type].min_ndata, + kstat_data_type[ks_type].max_ndata); return (NULL); } ks_data_size = kstat_data_type[ks_type].size * ks_ndata; /* - * If the named kstat already exists and is dormant, reactivate it. - */ + * If the named kstat already exists and is dormant, reactivate it. + */ ksp = kstat_hold_byname(ks_module, ks_instance, ks_name, ks_zoneid); if (ksp != NULL) { if (!(ksp->ks_flags & KSTAT_FLAG_DORMANT)) { /* - * The named kstat exists but is not dormant -- - * this is a kstat namespace collision. - */ + * The named kstat exists but is not dormant -- + * this is a kstat namespace collision. + */ kstat_rele(ksp); cmn_err(CE_WARN, - "kstat_create('%s', %d, '%s'): namespace collision", - ks_module, ks_instance, ks_name); + "kstat_create('%s', %d, '%s'): namespace collision", + ks_module, ks_instance, ks_name); return (NULL); } if ((strcmp(ksp->ks_class, ks_class) != 0) || - (ksp->ks_type != ks_type) || - (ksp->ks_ndata != ks_ndata) || - (ks_flags & KSTAT_FLAG_VIRTUAL)) { + (ksp->ks_type != ks_type) || + (ksp->ks_ndata != ks_ndata) || + (ks_flags & KSTAT_FLAG_VIRTUAL)) { /* - * The name is the same, but the other key parameters - * differ from those of the dormant kstat -- bogus. - */ + * The name is the same, but the other key parameters + * differ from those of the dormant kstat -- bogus. + */ kstat_rele(ksp); cmn_err(CE_WARN, "kstat_create('%s', %d, '%s'): " - "invalid reactivation of dormant kstat", - ks_module, ks_instance, ks_name); + "invalid reactivation of dormant kstat", + ks_module, ks_instance, ks_name); return (NULL); } /* - * Return dormant kstat pointer to caller. As usual, - * the kstat is marked invalid until kstat_install(). - */ + * Return dormant kstat pointer to caller. As usual, + * the kstat is marked invalid until kstat_install(). + */ ksp->ks_flags |= KSTAT_FLAG_INVALID; kstat_rele(ksp); return (ksp); } /* - * Allocate memory for the new kstat header and, if this is a physical - * kstat, the data section. - */ + * Allocate memory for the new kstat header and, if this is a physical + * kstat, the data section. + */ e = kstat_alloc(ks_flags & KSTAT_FLAG_VIRTUAL ? 0 : ks_data_size); if (e == NULL) { cmn_err(CE_NOTE, "kstat_create('%s', %d, '%s'): " - "insufficient kernel memory", - ks_module, ks_instance, ks_name); + "insufficient kernel memory", + ks_module, ks_instance, ks_name); return (NULL); } /* - * Initialize as many fields as we can. The caller may reset - * ks_lock, ks_update, ks_private, and ks_snapshot as necessary. - * Creators of virtual kstats may also reset ks_data. It is - * also up to the caller to initialize the kstat data section, - * if necessary. All initialization must be complete before - * calling kstat_install(). - */ + * Initialize as many fields as we can. The caller may reset + * ks_lock, ks_update, ks_private, and ks_snapshot as necessary. + * Creators of virtual kstats may also reset ks_data. It is + * also up to the caller to initialize the kstat data section, + * if necessary. All initialization must be complete before + * calling kstat_install(). + */ e->e_zone.zoneid = ks_zoneid; e->e_zone.next = NULL; @@ -1159,21 +1150,21 @@ kstat_create_zone(const char *ks_module, int ks_instance, const char *ks_name, mutex_enter(&kstat_chain_lock); /* - * Add our kstat to the AVL trees. - */ + * Add our kstat to the AVL trees. + */ if (avl_find(&kstat_avl_byname, e, &where) != NULL) { mutex_exit(&kstat_chain_lock); cmn_err(CE_WARN, - "kstat_create('%s', %d, '%s'): namespace collision", - ks_module, ks_instance, ks_name); + "kstat_create('%s', %d, '%s'): namespace collision", + ks_module, ks_instance, ks_name); kstat_free(e); return (NULL); } avl_insert(&kstat_avl_byname, e, where); /* - * Loop around until we find an unused KID. - */ + * Loop around until we find an unused KID. + */ do { ksp->ks_kid = kstat_chain_id++; } while (avl_find(&kstat_avl_bykid, e, &where) != NULL); @@ -1185,26 +1176,26 @@ kstat_create_zone(const char *ks_module, int ks_instance, const char *ks_name, } /* -* Activate a fully initialized kstat and make it visible to /dev/kstat. -*/ + * Activate a fully initialized kstat and make it visible to /dev/kstat. + */ void kstat_install(kstat_t *ksp) { zoneid_t zoneid = ((ekstat_t *)ksp)->e_zone.zoneid; /* - * If this is a variable-size kstat, it MUST provide kstat data locking - * to prevent data-size races with kstat readers. - */ + * If this is a variable-size kstat, it MUST provide kstat data locking + * to prevent data-size races with kstat readers. + */ if ((ksp->ks_flags & KSTAT_FLAG_VAR_SIZE) && ksp->ks_lock == NULL) { panic("kstat_install('%s', %d, '%s'): " - "cannot create variable-size kstat without data lock", - ksp->ks_module, ksp->ks_instance, ksp->ks_name); + "cannot create variable-size kstat without data lock", + ksp->ks_module, ksp->ks_instance, ksp->ks_name); } if (kstat_hold_bykid(ksp->ks_kid, zoneid) != ksp) { cmn_err(CE_WARN, "kstat_install(%p): does not exist", - (void *)ksp); + (void *)ksp); return; } @@ -1219,47 +1210,47 @@ kstat_install(kstat_t *ksp) } } /* - * The default snapshot routine does not handle KSTAT_WRITE - * for long strings. - */ + * The default snapshot routine does not handle KSTAT_WRITE + * for long strings. + */ if ((ksp->ks_flags & KSTAT_FLAG_LONGSTRINGS) && - (ksp->ks_flags & KSTAT_FLAG_WRITABLE) && - (ksp->ks_snapshot == default_kstat_snapshot)) { + (ksp->ks_flags & KSTAT_FLAG_WRITABLE) && + (ksp->ks_snapshot == default_kstat_snapshot)) { panic("kstat_install('%s', %d, '%s'): " - "named kstat containing KSTAT_DATA_STRING " - "is writable but uses default snapshot routine", - ksp->ks_module, ksp->ks_instance, ksp->ks_name); + "named kstat containing KSTAT_DATA_STRING " + "is writable but uses default snapshot routine", + ksp->ks_module, ksp->ks_instance, ksp->ks_name); } } if (ksp->ks_flags & KSTAT_FLAG_DORMANT) { /* - * We are reactivating a dormant kstat. Initialize the - * caller's underlying data to the value it had when the - * kstat went dormant, and mark the kstat as active. - * Grab the provider's kstat lock if it's not already held. - */ + * We are reactivating a dormant kstat. Initialize the + * caller's underlying data to the value it had when the + * kstat went dormant, and mark the kstat as active. + * Grab the provider's kstat lock if it's not already held. + */ kmutex_t *lp = ksp->ks_lock; if (lp != NULL && MUTEX_NOT_HELD(lp)) { mutex_enter(lp); - (void)KSTAT_UPDATE(ksp, KSTAT_WRITE); + (void) KSTAT_UPDATE(ksp, KSTAT_WRITE); mutex_exit(lp); } else { - (void)KSTAT_UPDATE(ksp, KSTAT_WRITE); + (void) KSTAT_UPDATE(ksp, KSTAT_WRITE); } ksp->ks_flags &= ~KSTAT_FLAG_DORMANT; } /* - * Now that the kstat is active, make it visible to the kstat driver. - * When copying out kstats the count is determined in - * header_kstat_update() and actually copied into kbuf in - * header_kstat_snapshot(). kstat_chain_lock is held across the two - * calls to ensure that this list doesn't change. Thus, we need to - * also take the lock to ensure that the we don't copy the new kstat - * in the 2nd pass and overrun the buf. - */ + * Now that the kstat is active, make it visible to the kstat driver. + * When copying out kstats the count is determined in + * header_kstat_update() and actually copied into kbuf in + * header_kstat_snapshot(). kstat_chain_lock is held across the two + * calls to ensure that this list doesn't change. Thus, we need to + * also take the lock to ensure that the we don't copy the new kstat + * in the 2nd pass and overrun the buf. + */ mutex_enter(&kstat_chain_lock); ksp->ks_flags &= ~KSTAT_FLAG_INVALID; mutex_exit(&kstat_chain_lock); @@ -1267,9 +1258,9 @@ kstat_install(kstat_t *ksp) } /* -* Remove a kstat from the system. Or, if it's a persistent kstat, -* just update the data and mark it as dormant. -*/ + * Remove a kstat from the system. Or, if it's a persistent kstat, + * just update the data and mark it as dormant. + */ void kstat_delete(kstat_t *ksp) { @@ -1289,29 +1280,29 @@ kstat_delete(kstat_t *ksp) if (lp != NULL && MUTEX_HELD(lp)) { panic("kstat_delete(%p): caller holds data lock %p", - (void *)ksp, (void *)lp); + (void *)ksp, (void *)lp); } if (kstat_hold_bykid(ksp->ks_kid, zoneid) != ksp) { cmn_err(CE_WARN, "kstat_delete(%p): does not exist", - (void *)ksp); + (void *)ksp); return; } if (ksp->ks_flags & KSTAT_FLAG_PERSISTENT) { /* - * Update the data one last time, so that all activity - * prior to going dormant has been accounted for. - */ + * Update the data one last time, so that all activity + * prior to going dormant has been accounted for. + */ KSTAT_ENTER(ksp); - (void)KSTAT_UPDATE(ksp, KSTAT_READ); + (void) KSTAT_UPDATE(ksp, KSTAT_READ); KSTAT_EXIT(ksp); /* - * Mark the kstat as dormant and restore caller-modifiable - * fields to default values, so the kstat is readable during - * the dormant phase. - */ + * Mark the kstat as dormant and restore caller-modifiable + * fields to default values, so the kstat is readable during + * the dormant phase. + */ ksp->ks_flags |= KSTAT_FLAG_DORMANT; ksp->ks_lock = NULL; ksp->ks_update = default_kstat_update; @@ -1322,10 +1313,10 @@ kstat_delete(kstat_t *ksp) } /* - * Remove the kstat from the framework's AVL trees, - * free the allocated memory, and increment kstat_chain_id so - * /dev/kstat clients can detect the event. - */ + * Remove the kstat from the framework's AVL trees, + * free the allocated memory, and increment kstat_chain_id so + * /dev/kstat clients can detect the event. + */ mutex_enter(&kstat_chain_lock); avl_remove(&kstat_avl_bykid, e); avl_remove(&kstat_avl_byname, e); @@ -1337,7 +1328,7 @@ kstat_delete(kstat_t *ksp) kstat_zone_t *t = kz; kz = kz->next; - kmem_free(t, sizeof(*t)); + kmem_free(t, sizeof (*t)); } kstat_rele(ksp); kstat_free(e); @@ -1345,7 +1336,7 @@ kstat_delete(kstat_t *ksp) void kstat_delete_byname_zone(const char *ks_module, int ks_instance, - const char *ks_name, zoneid_t ks_zoneid) + const char *ks_name, zoneid_t ks_zoneid) { kstat_t *ksp; @@ -1363,10 +1354,10 @@ kstat_delete_byname(const char *ks_module, int ks_instance, const char *ks_name) } /* -* The sparc V9 versions of these routines can be much cheaper than -* the poor 32-bit compiler can comprehend, so they're in sparcv9_subr.s. -* For simplicity, however, we always feed the C versions to lint. -*/ + * The sparc V9 versions of these routines can be much cheaper than + * the poor 32-bit compiler can comprehend, so they're in sparcv9_subr.s. + * For simplicity, however, we always feed the C versions to lint. + */ #if !defined(__sparc) || defined(lint) || defined(__lint) void @@ -1516,21 +1507,17 @@ kstat_timer_stop(kstat_timer_t *ktp) #include #include #include -#include #include #include #include #include #include -//#include #include -//#include #include #include #include #include #include -//#include #include #include #include @@ -1550,12 +1537,11 @@ read_kstat_data(int *rvalp, void *user_ksp, int flag) int error = 0; uint_t model; -#define DDI_MODEL_NONE 0 -// switch (model = ddi_model_convert_from(flag & FMODELS)) { +#define DDI_MODEL_NONE 0 switch (model = DDI_MODEL_NONE) { #ifdef _MULTI_DATAMODEL case DDI_MODEL_ILP32: - if (copyin(user_ksp, &user_kstat32, sizeof(kstat32_t)) != 0) + if (copyin(user_ksp, &user_kstat32, sizeof (kstat32_t)) != 0) return (EFAULT); user_kstat.ks_kid = user_kstat32.ks_kid; user_kstat.ks_data = (void *)(uintptr_t)user_kstat32.ks_data; @@ -1564,38 +1550,38 @@ read_kstat_data(int *rvalp, void *user_ksp, int flag) #endif default: case DDI_MODEL_NONE: - if (ddi_copyin(user_ksp, &user_kstat, sizeof(kstat_t), 0) != 0) + if (ddi_copyin(user_ksp, &user_kstat, sizeof (kstat_t), 0) != 0) return (EFAULT); } ksp = kstat_hold_bykid(user_kstat.ks_kid, crgetzoneid()); if (ksp == NULL) { /* - * There is no kstat with the specified KID - */ + * There is no kstat with the specified KID + */ return (ENXIO); } if (ksp->ks_flags & KSTAT_FLAG_INVALID) { /* - * The kstat exists, but is momentarily in some - * indeterminate state (e.g. the data section is not - * yet initialized). Try again in a few milliseconds. - */ + * The kstat exists, but is momentarily in some + * indeterminate state (e.g. the data section is not + * yet initialized). Try again in a few milliseconds. + */ kstat_rele(ksp); return (EAGAIN); } /* - * If it's a fixed-size kstat, allocate the buffer now, so we - * don't have to do it under the kstat's data lock. (If it's a - * var-size kstat or one with long strings, we don't know the size - * until after the update routine is called, so we can't do this - * optimization.) - * The allocator relies on this behavior to prevent recursive - * mutex_enter in its (fixed-size) kstat update routine. - * It's a zalloc to prevent unintentional exposure of random - * juicy morsels of (old) kernel data. - */ + * If it's a fixed-size kstat, allocate the buffer now, so we + * don't have to do it under the kstat's data lock. (If it's a + * var-size kstat or one with long strings, we don't know the size + * until after the update routine is called, so we can't do this + * optimization.) + * The allocator relies on this behavior to prevent recursive + * mutex_enter in its (fixed-size) kstat update routine. + * It's a zalloc to prevent unintentional exposure of random + * juicy morsels of (old) kernel data. + */ if (!(ksp->ks_flags & (KSTAT_FLAG_VAR_SIZE | KSTAT_FLAG_LONGSTRINGS))) { kbufsize = ksp->ks_data_size; allocsize = kbufsize + 1; @@ -1632,11 +1618,11 @@ read_kstat_data(int *rvalp, void *user_ksp, int flag) } /* - * The following info must be returned to user level, - * even if the the update or snapshot failed. This allows - * kstat readers to get a handle on variable-size kstats, - * detect dormant kstats, etc. - */ + * The following info must be returned to user level, + * even if the the update or snapshot failed. This allows + * kstat readers to get a handle on variable-size kstats, + * detect dormant kstats, etc. + */ user_kstat.ks_ndata = ksp->ks_ndata; user_kstat.ks_data_size = kbufsize; user_kstat.ks_flags = ksp->ks_flags; @@ -1644,8 +1630,8 @@ read_kstat_data(int *rvalp, void *user_ksp, int flag) #ifndef _WIN32 *rvalp = kstat_chain_id; #else - // The above doesn't work, as rvalp refers to the userland struct, before copyin() - // and we need to write value to kernel version. + // The above doesn't work, as rvalp refers to the userland struct, + // before copyin() and we need to write value to kernel version. user_kstat.ks_returnvalue = kstat_chain_id; #endif KSTAT_EXIT(ksp); @@ -1655,8 +1641,8 @@ read_kstat_data(int *rvalp, void *user_ksp, int flag) goto out; /* - * Copy the buffer containing the kstat back to userland. - */ + * Copy the buffer containing the kstat back to userland. + */ copysize = kbufsize; switch (model) { @@ -1670,16 +1656,16 @@ read_kstat_data(int *rvalp, void *user_ksp, int flag) if (ksp->ks_type == KSTAT_TYPE_NAMED) { kstat_named_t *kn = kbuf; char *strbuf = (char *)((kstat_named_t *)kn + - ksp->ks_ndata); + ksp->ks_ndata); for (i = 0; i < user_kstat.ks_ndata; kn++, i++) switch (kn->data_type) { - /* - * Named statistics have fields of type 'long'. - * For a 32-bit application looking at a 64-bit - * kernel, forcibly truncate these 64-bit - * quantities to 32-bit values. - */ + /* + * Named statistics have fields of type 'long'. + * For a 32-bit application looking at a 64-bit + * kernel, forcibly truncate these 64-bit + * quantities to 32-bit values. + */ case KSTAT_DATA_LONG: kn->value.i32 = (int32_t)kn->value.l; kn->data_type = KSTAT_DATA_INT32; @@ -1688,62 +1674,62 @@ read_kstat_data(int *rvalp, void *user_ksp, int flag) kn->value.ui32 = (uint32_t)kn->value.ul; kn->data_type = KSTAT_DATA_UINT32; break; - /* - * Long strings must be massaged before being - * copied out to userland. Do that here. - */ + /* + * Long strings must be massaged before being + * copied out to userland. Do that here. + */ case KSTAT_DATA_STRING: if (KSTAT_NAMED_STR_PTR(kn) == NULL) break; /* - * If the string lies outside of kbuf - * copy it there and update the pointer. - */ + * If the string lies outside of kbuf + * copy it there and update the pointer. + */ if (KSTAT_NAMED_STR_PTR(kn) < - (char *)kbuf || - KSTAT_NAMED_STR_PTR(kn) + - KSTAT_NAMED_STR_BUFLEN(kn) > - (char *)kbuf + kbufsize + 1) { + (char *)kbuf || + KSTAT_NAMED_STR_PTR(kn) + + KSTAT_NAMED_STR_BUFLEN(kn) > + (char *)kbuf + kbufsize + 1) { bcopy(KSTAT_NAMED_STR_PTR(kn), - strbuf, - KSTAT_NAMED_STR_BUFLEN(kn)); + strbuf, + KSTAT_NAMED_STR_BUFLEN(kn)); KSTAT_NAMED_STR_PTR(kn) = - strbuf; + strbuf; strbuf += - KSTAT_NAMED_STR_BUFLEN(kn); + KSTAT_NAMED_STR_BUFLEN(kn); ASSERT(strbuf <= - (char *)kbuf + - kbufsize + 1); + (char *)kbuf + + kbufsize + 1); } /* - * The offsets within the buffers are - * the same, so add the offset to the - * beginning of the new buffer to fix - * the pointer. - */ + * The offsets within the buffers are + * the same, so add the offset to the + * beginning of the new buffer to fix + * the pointer. + */ KSTAT_NAMED_STR_PTR(kn) = - (char *)user_kstat.ks_data + - (KSTAT_NAMED_STR_PTR(kn) - - (char *)kbuf); + (char *)user_kstat.ks_data + + (KSTAT_NAMED_STR_PTR(kn) - + (char *)kbuf); /* - * Make sure the string pointer lies - * within the allocated buffer. - */ + * Make sure the string pointer lies + * within the allocated buffer. + */ ASSERT(KSTAT_NAMED_STR_PTR(kn) + - KSTAT_NAMED_STR_BUFLEN(kn) <= - ((char *)user_kstat.ks_data + - ubufsize)); + KSTAT_NAMED_STR_BUFLEN(kn) <= + ((char *)user_kstat.ks_data + + ubufsize)); ASSERT(KSTAT_NAMED_STR_PTR(kn) >= - (char *)((kstat_named_t *) - user_kstat.ks_data + - user_kstat.ks_ndata)); + (char *)((kstat_named_t *) + user_kstat.ks_data + + user_kstat.ks_ndata)); /* - * Cast 64-bit ptr to 32-bit. - */ + * Cast 64-bit ptr to 32-bit. + */ kn->value.str.addr.ptr32 = - (caddr32_t)(uintptr_t) - KSTAT_NAMED_STR_PTR(kn); + (caddr32_t)(uintptr_t) + KSTAT_NAMED_STR_PTR(kn); break; default: break; @@ -1754,22 +1740,22 @@ read_kstat_data(int *rvalp, void *user_ksp, int flag) break; /* - * This is the special case of the kstat header - * list for the entire system. Reshape the - * array in place, then copy it out. - */ + * This is the special case of the kstat header + * list for the entire system. Reshape the + * array in place, then copy it out. + */ k32 = kbuf; k = kbuf; for (i = 0; i < user_kstat.ks_ndata; k32++, k++, i++) { k32->ks_crtime = k->ks_crtime; k32->ks_next = 0; k32->ks_kid = k->ks_kid; - (void)strcpy(k32->ks_module, k->ks_module); + (void) strcpy(k32->ks_module, k->ks_module); k32->ks_resv = k->ks_resv; k32->ks_instance = k->ks_instance; - (void)strcpy(k32->ks_name, k->ks_name); + (void) strcpy(k32->ks_name, k->ks_name); k32->ks_type = k->ks_type; - (void)strcpy(k32->ks_class, k->ks_class); + (void) strcpy(k32->ks_class, k->ks_class); k32->ks_flags = k->ks_flags; k32->ks_data = 0; k32->ks_ndata = k->ks_ndata; @@ -1782,10 +1768,10 @@ read_kstat_data(int *rvalp, void *user_ksp, int flag) } /* - * XXX In this case we copy less data than is - * claimed in the header. - */ - copysize = user_kstat.ks_ndata * sizeof(kstat32_t); + * XXX In this case we copy less data than is + * claimed in the header. + */ + copysize = user_kstat.ks_ndata * sizeof (kstat32_t); break; #endif /* _MULTI_DATAMODEL */ default: @@ -1793,57 +1779,57 @@ read_kstat_data(int *rvalp, void *user_ksp, int flag) if (ksp->ks_type == KSTAT_TYPE_NAMED) { kstat_named_t *kn = kbuf; char *strbuf = (char *)((kstat_named_t *)kn + - ksp->ks_ndata); + ksp->ks_ndata); for (i = 0; i < user_kstat.ks_ndata; kn++, i++) switch (kn->data_type) { #ifdef _LP64 case KSTAT_DATA_LONG: kn->data_type = - KSTAT_DATA_INT64; + KSTAT_DATA_INT64; break; case KSTAT_DATA_ULONG: kn->data_type = - KSTAT_DATA_UINT64; + KSTAT_DATA_UINT64; break; #endif /* _LP64 */ case KSTAT_DATA_STRING: if (KSTAT_NAMED_STR_PTR(kn) == NULL) break; /* - * If the string lies outside of kbuf - * copy it there and update the pointer. - */ + * If the string lies outside of kbuf + * copy it there and update the pointer. + */ if (KSTAT_NAMED_STR_PTR(kn) < - (char *)kbuf || - KSTAT_NAMED_STR_PTR(kn) + - KSTAT_NAMED_STR_BUFLEN(kn) > - (char *)kbuf + kbufsize + 1) { + (char *)kbuf || + KSTAT_NAMED_STR_PTR(kn) + + KSTAT_NAMED_STR_BUFLEN(kn) > + (char *)kbuf + kbufsize + 1) { bcopy(KSTAT_NAMED_STR_PTR(kn), - strbuf, - KSTAT_NAMED_STR_BUFLEN(kn)); + strbuf, + KSTAT_NAMED_STR_BUFLEN(kn)); KSTAT_NAMED_STR_PTR(kn) = - strbuf; + strbuf; strbuf += - KSTAT_NAMED_STR_BUFLEN(kn); + KSTAT_NAMED_STR_BUFLEN(kn); ASSERT(strbuf <= - (char *)kbuf + - kbufsize + 1); + (char *)kbuf + + kbufsize + 1); } KSTAT_NAMED_STR_PTR(kn) = - (char *)user_kstat.ks_data + - (KSTAT_NAMED_STR_PTR(kn) - - (char *)kbuf); + (char *)user_kstat.ks_data + + (KSTAT_NAMED_STR_PTR(kn) - + (char *)kbuf); ASSERT(KSTAT_NAMED_STR_PTR(kn) + - KSTAT_NAMED_STR_BUFLEN(kn) <= - ((char *)user_kstat.ks_data + - ubufsize)); + KSTAT_NAMED_STR_BUFLEN(kn) <= + ((char *)user_kstat.ks_data + + ubufsize)); ASSERT(KSTAT_NAMED_STR_PTR(kn) >= - (char *)((kstat_named_t *) - user_kstat.ks_data + - user_kstat.ks_ndata)); + (char *)((kstat_named_t *) + user_kstat.ks_data + + user_kstat.ks_ndata)); break; default: break; @@ -1853,15 +1839,15 @@ read_kstat_data(int *rvalp, void *user_ksp, int flag) } if (error == 0 && - ddi_copyout(kbuf, user_kstat.ks_data, copysize, 0)) + ddi_copyout(kbuf, user_kstat.ks_data, copysize, 0)) error = EFAULT; kmem_free(kbuf, allocsize); out: /* - * We have modified the ks_ndata, ks_data_size, ks_flags, and - * ks_snaptime fields of the user kstat; now copy it back to userland. - */ + * We have modified the ks_ndata, ks_data_size, ks_flags, and + * ks_snaptime fields of the user kstat; now copy it back to userland. + */ switch (model) { #ifdef _MULTI_DATAMODEL case DDI_MODEL_ILP32: @@ -1873,8 +1859,8 @@ read_kstat_data(int *rvalp, void *user_ksp, int flag) user_kstat32.ks_data_size = (size32_t)kbufsize; user_kstat32.ks_flags = user_kstat.ks_flags; user_kstat32.ks_snaptime = user_kstat.ks_snaptime; - if (copyout(&user_kstat32, user_ksp, sizeof(kstat32_t)) && - error == 0) + if (copyout(&user_kstat32, user_ksp, sizeof (kstat32_t)) && + error == 0) error = EFAULT; break; #endif @@ -1887,9 +1873,9 @@ read_kstat_data(int *rvalp, void *user_ksp, int flag) if (error) { user_kstat.ks_errnovalue = error; user_kstat.ks_returnvalue = -1; - } - if (ddi_copyout(&user_kstat, user_ksp, sizeof(kstat_t), 0) && - error == 0) + } + if (ddi_copyout(&user_kstat, user_ksp, sizeof (kstat_t), 0) && + error == 0) error = EFAULT; break; } @@ -1908,17 +1894,16 @@ write_kstat_data(int *rvalp, void *user_ksp, int flag, cred_t *cred) if (secpolicy_sys_config(cred, B_FALSE) != 0) return (EPERM); -// switch (ddi_model_convert_from(flag & FMODELS)) { switch (DDI_MODEL_NONE) { #ifdef _MULTI_DATAMODEL kstat32_t user_kstat32; case DDI_MODEL_ILP32: - if (copyin(user_ksp, &user_kstat32, sizeof(kstat32_t))) + if (copyin(user_ksp, &user_kstat32, sizeof (kstat32_t))) return (EFAULT); /* - * These are the only fields we actually look at. - */ + * These are the only fields we actually look at. + */ user_kstat.ks_kid = user_kstat32.ks_kid; user_kstat.ks_data = (void *)(uintptr_t)user_kstat32.ks_data; user_kstat.ks_data_size = (size_t)user_kstat32.ks_data_size; @@ -1927,7 +1912,7 @@ write_kstat_data(int *rvalp, void *user_ksp, int flag, cred_t *cred) #endif default: case DDI_MODEL_NONE: - if (ddi_copyin(user_ksp, &user_kstat, sizeof(kstat_t), 0)) + if (ddi_copyin(user_ksp, &user_kstat, sizeof (kstat_t), 0)) return (EFAULT); } @@ -1958,15 +1943,15 @@ write_kstat_data(int *rvalp, void *user_ksp, int flag, cred_t *cred) } /* - * With KSTAT_FLAG_VAR_SIZE, one must call the kstat's update callback - * routine to ensure ks_data_size is up to date. - * In this case it makes sense to do it anyhow, as it will be shortly - * followed by a KSTAT_SNAPSHOT(). - */ + * With KSTAT_FLAG_VAR_SIZE, one must call the kstat's update callback + * routine to ensure ks_data_size is up to date. + * In this case it makes sense to do it anyhow, as it will be shortly + * followed by a KSTAT_SNAPSHOT(). + */ KSTAT_ENTER(ksp); error = KSTAT_UPDATE(ksp, KSTAT_READ); if (error || user_kstat.ks_data_size != ksp->ks_data_size || - user_kstat.ks_ndata != ksp->ks_ndata) { + user_kstat.ks_ndata != ksp->ks_ndata) { KSTAT_EXIT(ksp); kstat_rele(ksp); kmem_free(buf, bufsize + 1); @@ -1974,11 +1959,11 @@ write_kstat_data(int *rvalp, void *user_ksp, int flag, cred_t *cred) } /* - * We have to ensure that we don't accidentally change the type of - * existing kstat_named statistics when writing over them. - * Since read_kstat_data() modifies some of the types on their way - * out, we need to be sure to handle these types seperately. - */ + * We have to ensure that we don't accidentally change the type of + * existing kstat_named statistics when writing over them. + * Since read_kstat_data() modifies some of the types on their way + * out, we need to be sure to handle these types seperately. + */ if (ksp->ks_type == KSTAT_TYPE_NAMED) { void *kbuf; kstat_named_t *kold; @@ -1990,9 +1975,9 @@ write_kstat_data(int *rvalp, void *user_ksp, int flag, cred_t *cred) #endif /* - * Since ksp->ks_data may be NULL, we need to take a snapshot - * of the published data to look at the types. - */ + * Since ksp->ks_data may be NULL, we need to take a snapshot + * of the published data to look at the types. + */ kbuf = kmem_alloc(bufsize + 1, KM_NOSLEEP); if (kbuf == NULL) { KSTAT_EXIT(ksp); @@ -2011,11 +1996,11 @@ write_kstat_data(int *rvalp, void *user_ksp, int flag, cred_t *cred) kold = kbuf; /* - * read_kstat_data() changes the types of - * KSTAT_DATA_LONG / KSTAT_DATA_ULONG, so we need to - * make sure that these (modified) types are considered - * valid. - */ + * read_kstat_data() changes the types of + * KSTAT_DATA_LONG / KSTAT_DATA_ULONG, so we need to + * make sure that these (modified) types are considered + * valid. + */ for (i = 0; i < ksp->ks_ndata; i++, kold++, knew++) { switch (kold->data_type) { #ifdef _MULTI_DATAMODEL @@ -2023,22 +2008,22 @@ write_kstat_data(int *rvalp, void *user_ksp, int flag, cred_t *cred) switch (model) { case DDI_MODEL_ILP32: if (knew->data_type == - KSTAT_DATA_INT32) { + KSTAT_DATA_INT32) { knew->value.l = - (long)knew->value.i32; + (long)knew->value.i32; knew->data_type = - KSTAT_DATA_LONG; + KSTAT_DATA_LONG; } break; default: case DDI_MODEL_NONE: #ifdef _LP64 if (knew->data_type == - KSTAT_DATA_INT64) { + KSTAT_DATA_INT64) { knew->value.l = - (long)knew->value.i64; + (long)knew->value.i64; knew->data_type = - KSTAT_DATA_LONG; + KSTAT_DATA_LONG; } #endif /* _LP64 */ break; @@ -2048,22 +2033,22 @@ write_kstat_data(int *rvalp, void *user_ksp, int flag, cred_t *cred) switch (model) { case DDI_MODEL_ILP32: if (knew->data_type == - KSTAT_DATA_UINT32) { + KSTAT_DATA_UINT32) { knew->value.ul = - (ulong_t)knew->value.ui32; + (ulong_t)knew->value.ui32; knew->data_type = - KSTAT_DATA_ULONG; + KSTAT_DATA_ULONG; } break; default: case DDI_MODEL_NONE: #ifdef _LP64 if (knew->data_type == - KSTAT_DATA_UINT64) { + KSTAT_DATA_UINT64) { knew->value.ul = - (ulong_t)knew->value.ui64; + (ulong_t)knew->value.ui64; knew->data_type = - KSTAT_DATA_ULONG; + KSTAT_DATA_ULONG; } #endif /* _LP64 */ break; @@ -2082,24 +2067,24 @@ write_kstat_data(int *rvalp, void *user_ksp, int flag, cred_t *cred) #ifdef _MULTI_DATAMODEL if (model == DDI_MODEL_ILP32) KSTAT_NAMED_STR_PTR(knew) = - (char *)(uintptr_t) + (char *)(uintptr_t) knew->value.str.addr.ptr32; #endif /* - * Nothing special for NULL - */ + * Nothing special for NULL + */ if (KSTAT_NAMED_STR_PTR(knew) == NULL) break; /* - * Check to see that the pointers all point - * to within the buffer and after the array - * of kstat_named_t's. - */ + * Check to see that the pointers all point + * to within the buffer and after the array + * of kstat_named_t's. + */ if (KSTAT_NAMED_STR_PTR(knew) < - (char *) - ((kstat_named_t *)user_kstat.ks_data + - ksp->ks_ndata)) { + (char *) + ((kstat_named_t *)user_kstat.ks_data + + ksp->ks_ndata)) { KSTAT_EXIT(ksp); kstat_rele(ksp); kmem_free(kbuf, bufsize + 1); @@ -2107,9 +2092,9 @@ write_kstat_data(int *rvalp, void *user_ksp, int flag, cred_t *cred) return (EINVAL); } if (KSTAT_NAMED_STR_PTR(knew) + - KSTAT_NAMED_STR_BUFLEN(knew) > - ((char *)user_kstat.ks_data + - ksp->ks_data_size)) { + KSTAT_NAMED_STR_BUFLEN(knew) > + ((char *)user_kstat.ks_data + + ksp->ks_data_size)) { KSTAT_EXIT(ksp); kstat_rele(ksp); kmem_free(kbuf, bufsize + 1); @@ -2118,12 +2103,12 @@ write_kstat_data(int *rvalp, void *user_ksp, int flag, cred_t *cred) } /* - * Update the pointers within the buffer - */ + * Update the pointers within the buffer + */ KSTAT_NAMED_STR_PTR(knew) = - (char *)buf + - (KSTAT_NAMED_STR_PTR(knew) - - (char *)user_kstat.ks_data); + (char *)buf + + (KSTAT_NAMED_STR_PTR(knew) - + (char *)user_kstat.ks_data); break; default: break; @@ -2134,8 +2119,8 @@ write_kstat_data(int *rvalp, void *user_ksp, int flag, cred_t *cred) knew = buf; /* - * Now make sure the types are what we expected them to be. - */ + * Now make sure the types are what we expected them to be. + */ for (i = 0; i < ksp->ks_ndata; i++, kold++, knew++) if (kold->data_type != knew->data_type) { KSTAT_EXIT(ksp); @@ -2154,8 +2139,8 @@ write_kstat_data(int *rvalp, void *user_ksp, int flag, cred_t *cred) #ifndef _WIN32 *rvalp = kstat_chain_id; #else - // The above doesn't work, as rvalp refers to the userland struct, before copyin() - // and we need to write value to kernel version. + // The above doesn't work, as rvalp refers to the userland struct, + // before copyin() and we need to write value to kernel version. user_kstat.ks_returnvalue = kstat_chain_id; // We need to copyout() so userland will get the return values. #endif @@ -2171,7 +2156,7 @@ write_kstat_data(int *rvalp, void *user_ksp, int flag, cred_t *cred) void spl_kstat_init() { - /* + /* * Create the kstat root OID */ mutex_init(&kstat_chain_lock, NULL, MUTEX_DEFAULT, NULL); @@ -2186,7 +2171,7 @@ spl_kstat_fini() * Done in two passes, first unregisters all * of the oids, second releases all the memory. */ - + vmem_fini(kstat_arena); mutex_destroy(&kstat_chain_lock); } @@ -2213,31 +2198,35 @@ __kstat_set_seq_raw_ops(kstat_t *ksp, ksp->ks_raw_ops.addr = addr; } -int spl_kstat_chain_id(PDEVICE_OBJECT DiskDevice, PIRP Irp, PIO_STACK_LOCATION IrpSp) +int spl_kstat_chain_id(PDEVICE_OBJECT DiskDevice, PIRP Irp, + PIO_STACK_LOCATION IrpSp) { kstat_t ksp = { 0 }; ksp.ks_returnvalue = kstat_chain_id; - ASSERT3U(IrpSp->Parameters.DeviceIoControl.OutputBufferLength, >=, sizeof(ksp)); + ASSERT3U(IrpSp->Parameters.DeviceIoControl.OutputBufferLength, >=, + sizeof (ksp)); ddi_copyout(&ksp, IrpSp->Parameters.DeviceIoControl.Type3InputBuffer, - sizeof(ksp), 0); + sizeof (ksp), 0); dprintf("%s: returning kstat_chain_id %d\n", __func__, kstat_chain_id); - return 0; + return (0); } -int spl_kstat_read(PDEVICE_OBJECT DiskDevice, PIRP Irp, PIO_STACK_LOCATION IrpSp) +int spl_kstat_read(PDEVICE_OBJECT DiskDevice, PIRP Irp, + PIO_STACK_LOCATION IrpSp) { int rc; kstat_t *ksp; ksp = (kstat_t *)IrpSp->Parameters.DeviceIoControl.Type3InputBuffer; rc = read_kstat_data(&ksp->ks_returnvalue, (void *)ksp, 0); - return 0; + return (0); } -int spl_kstat_write(PDEVICE_OBJECT DiskDevice, PIRP Irp, PIO_STACK_LOCATION IrpSp) +int spl_kstat_write(PDEVICE_OBJECT DiskDevice, PIRP Irp, + PIO_STACK_LOCATION IrpSp) { int rc; kstat_t *ksp; ksp = (kstat_t *)IrpSp->Parameters.DeviceIoControl.Type3InputBuffer; rc = write_kstat_data(&ksp->ks_returnvalue, (void *)ksp, 0, NULL); - return 0; + return (0); } diff --git a/module/os/windows/spl/spl-md5.c b/module/os/windows/spl/spl-md5.c index 83df3316731..d03089601a6 100644 --- a/module/os/windows/spl/spl-md5.c +++ b/module/os/windows/spl/spl-md5.c @@ -43,7 +43,6 @@ #include #include #include /* MD5_CONST() optimization */ -//#include "md5_byteswap.h" #if !defined(_KERNEL) || defined(_BOOT) #include #endif /* !_KERNEL || _BOOT */ @@ -521,7 +520,7 @@ MD5Transform(uint32_t a, uint32_t b, uint32_t c, uint32_t d, /* LINTED E_BAD_PTR_CAST_ALIGN */ x_0 = LOAD_LITTLE_32_0(block); #else -#define LOAD_LITTLE_32(addr) (*(uint32_t *)(void *)(addr)) +#define LOAD_LITTLE_32(addr) (*(uint32_t *)(void *)(addr)) x_15 = LOAD_LITTLE_32(block + 60); x_14 = LOAD_LITTLE_32(block + 56); x_13 = LOAD_LITTLE_32(block + 52); @@ -638,7 +637,7 @@ MD5Transform(uint32_t a, uint32_t b, uint32_t c, uint32_t d, */ static void -Encode(uint8_t * output, const uint32_t * input, +Encode(uint8_t *output, const uint32_t *input, size_t input_len) { size_t i, j; diff --git a/module/os/windows/spl/spl-mount.c b/module/os/windows/spl/spl-mount.c index 0c59cd75a33..07176fa0c8d 100644 --- a/module/os/windows/spl/spl-mount.c +++ b/module/os/windows/spl/spl-mount.c @@ -1,100 +1,112 @@ /* -* CDDL HEADER START -* -* The contents of this file are subject to the terms of the -* Common Development and Distribution License (the "License"). -* You may not use this file except in compliance with the License. -* -* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE -* or http://www.opensolaris.org/os/licensing. -* See the License for the specific language governing permissions -* and limitations under the License. -* -* When distributing Covered Code, include this CDDL HEADER in each -* file and include the License file at usr/src/OPENSOLARIS.LICENSE. -* If applicable, add the following below this CDDL HEADER, with the -* fields enclosed by brackets "[]" replaced with your own identifying -* information: Portions Copyright [yyyy] [name of copyright owner] -* -* CDDL HEADER END -*/ + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ /* -* -* Copyright (C) 2017 Jorgen Lundman -* -*/ + * + * Copyright (C) 2017 Jorgen Lundman + * + */ #include #include #include -int vfs_busy(mount_t *mp, int flags) +int +vfs_busy(mount_t *mp, int flags) { - return 0; + return (0); } -void vfs_unbusy(mount_t *mp) +void +vfs_unbusy(mount_t *mp) { } -int vfs_isrdonly(mount_t *mp) +int +vfs_isrdonly(mount_t *mp) { return (mp->mountflags & MNT_RDONLY); } -void *vfs_fsprivate(mount_t *mp) +void * +vfs_fsprivate(mount_t *mp) { - return mp->fsprivate; + return (mp->fsprivate); } -void vfs_setfsprivate(mount_t *mp, void *mntdata) +void +vfs_setfsprivate(mount_t *mp, void *mntdata) { mp->fsprivate = mntdata; } -void vfs_clearflags(mount_t *mp, uint64_t flags) +void +vfs_clearflags(mount_t *mp, uint64_t flags) { mp->mountflags &= ~flags; } -void vfs_setflags(mount_t *mp, uint64_t flags) +void +vfs_setflags(mount_t *mp, uint64_t flags) { mp->mountflags |= flags; } -uint64_t vfs_flags(mount_t *mp) +uint64_t +vfs_flags(mount_t *mp) { - return mp->mountflags; + return (mp->mountflags); } -struct vfsstatfs * vfs_statfs(mount_t *mp) +struct vfsstatfs * +vfs_statfs(mount_t *mp) { - return NULL; + return (NULL); } -void vfs_setlocklocal(mount_t *mp) +void +vfs_setlocklocal(mount_t *mp) { } -int vfs_typenum(mount_t *mp) +int +vfs_typenum(mount_t *mp) { - return 0; + return (0); } -void vfs_getnewfsid(struct mount *mp) +void +vfs_getnewfsid(struct mount *mp) { } -int vfs_isunmount(mount_t *mp) +int +vfs_isunmount(mount_t *mp) { - return 0; + return (0); } int vfs_iswriteupgrade(mount_t *mp) /* ronly && MNTK_WANTRDWR */ { -// return (mp->mnt_flag & MNT_RDONLY) && (mp->mnt_kern_flag & MNTK_WANTRDWR); return (FALSE); } @@ -102,4 +114,3 @@ void vfs_setextendedsecurity(mount_t *mp) { } - diff --git a/module/os/windows/spl/spl-mutex.c b/module/os/windows/spl/spl-mutex.c index 5479ed5164b..6b8b9624f16 100644 --- a/module/os/windows/spl/spl-mutex.c +++ b/module/os/windows/spl/spl-mutex.c @@ -25,17 +25,17 @@ * */ - /* - * Implementation details. - * Using SynchronizationEvent that autoresets. When in 'Signaled' - * state the mutex is considered FREE/Available to be locked. - * Call KeWaitForSingleObject() to wait for it to be made - * 'available' (either blocking, or polling for *Try method) - * Calling KeSetEvent() sets event to Signaled, and wakes 'one' - * waiter, before Clearing it again. - * We attempt to avoid calling KeWaitForSingleObject() by - * using atomic CAS on m_owner, in the simple cases. - */ +/* + * Implementation details. + * Using SynchronizationEvent that autoresets. When in 'Signaled' + * state the mutex is considered FREE/Available to be locked. + * Call KeWaitForSingleObject() to wait for it to be made + * 'available' (either blocking, or polling for *Try method) + * Calling KeSetEvent() sets event to Signaled, and wakes 'one' + * waiter, before Clearing it again. + * We attempt to avoid calling KeWaitForSingleObject() by + * using atomic CAS on m_owner, in the simple cases. + */ #include #include @@ -47,52 +47,57 @@ uint64_t zfs_active_mutex = 0; -#define MUTEX_INITIALISED 0x23456789 -#define MUTEX_DESTROYED 0x98765432 +#define MUTEX_INITIALISED 0x23456789 +#define MUTEX_DESTROYED 0x98765432 -int spl_mutex_subsystem_init(void) +int +spl_mutex_subsystem_init(void) { - return 0; + return (0); } -void spl_mutex_subsystem_fini(void) +void +spl_mutex_subsystem_fini(void) { } -void spl_mutex_init(kmutex_t *mp, char *name, kmutex_type_t type, void *ibc) +void +spl_mutex_init(kmutex_t *mp, char *name, kmutex_type_t type, void *ibc) { - (void)name; + (void) name; ASSERT(type != MUTEX_SPIN); ASSERT(ibc == NULL); - if (mp->initialised == MUTEX_INITIALISED) - panic("%s: mutex already initialised\n", __func__); - mp->initialised = MUTEX_INITIALISED; - mp->set_event_guard = 0; + if (mp->m_initialised == MUTEX_INITIALISED) + panic("%s: mutex already m_initialised\n", __func__); + mp->m_initialised = MUTEX_INITIALISED; + mp->m_set_event_guard = 0; mp->m_owner = NULL; // Initialise it to 'Signaled' as mutex is 'free'. - KeInitializeEvent((PRKEVENT)&mp->m_lock, SynchronizationEvent, TRUE); + KeInitializeEvent((PRKEVENT)&mp->m_lock, SynchronizationEvent, TRUE); atomic_inc_64(&zfs_active_mutex); } -void spl_mutex_destroy(kmutex_t *mp) +void +spl_mutex_destroy(kmutex_t *mp) { - if (!mp) return; + if (!mp) + return; - if (mp->initialised != MUTEX_INITIALISED) - panic("%s: mutex not initialised\n", __func__); + if (mp->m_initialised != MUTEX_INITIALISED) + panic("%s: mutex not m_initialised\n", __func__); // Make sure any call to KeSetEvent() has completed. - while (mp->set_event_guard != 0) { + while (mp->m_set_event_guard != 0) { kpreempt(KPREEMPT_SYNC); } - mp->initialised = MUTEX_DESTROYED; + mp->m_initialised = MUTEX_DESTROYED; - if (mp->m_owner != 0) + if (mp->m_owner != 0) panic("SPL: releasing held mutex"); // There is no FREE member for events @@ -101,34 +106,34 @@ void spl_mutex_destroy(kmutex_t *mp) atomic_dec_64(&zfs_active_mutex); } -void spl_mutex_enter(kmutex_t *mp) +void +spl_mutex_enter(kmutex_t *mp) { NTSTATUS Status; kthread_t *thisthread = current_thread(); - if (mp->initialised != MUTEX_INITIALISED) - panic("%s: mutex not initialised\n", __func__); - + if (mp->m_initialised != MUTEX_INITIALISED) + panic("%s: mutex not m_initialised\n", __func__); + if (mp->m_owner == thisthread) panic("mutex_enter: locking against myself!"); - VERIFY3P(mp->m_owner, != , 0xdeadbeefdeadbeef); + VERIFY3P(mp->m_owner, !=, 0xdeadbeefdeadbeef); // Test if "m_owner" is NULL, if so, set it to "thisthread". // Returns original value, so if NULL, it succeeded. again: - if (InterlockedCompareExchangePointer(&mp->m_owner, - thisthread, NULL) != NULL) { + if (InterlockedCompareExchangePointer(&mp->m_owner, + thisthread, NULL) != NULL) { // Failed to CAS-in 'thisthread', as owner was not NULL // Wait forever for event to be signaled. Status = KeWaitForSingleObject( - (PRKEVENT)&mp->m_lock, - Executive, - KernelMode, - FALSE, - NULL - ); + (PRKEVENT)&mp->m_lock, + Executive, + KernelMode, + FALSE, + NULL); // We waited, but someone else may have beaten us to it // so we need to attempt CAS again @@ -138,32 +143,34 @@ void spl_mutex_enter(kmutex_t *mp) ASSERT(mp->m_owner == thisthread); } -void spl_mutex_exit(kmutex_t *mp) +void +spl_mutex_exit(kmutex_t *mp) { if (mp->m_owner != current_thread()) panic("%s: releasing not held/not our lock?\n", __func__); - VERIFY3P(mp->m_owner, != , 0xdeadbeefdeadbeef); + VERIFY3P(mp->m_owner, !=, 0xdeadbeefdeadbeef); - atomic_inc_32(&mp->set_event_guard); + atomic_inc_32(&mp->m_set_event_guard); mp->m_owner = NULL; - VERIFY3U(KeGetCurrentIrql(), <= , DISPATCH_LEVEL); + VERIFY3U(KeGetCurrentIrql(), <=, DISPATCH_LEVEL); // Wake up one waiter now that it is available. KeSetEvent((PRKEVENT)&mp->m_lock, SEMAPHORE_INCREMENT, FALSE); - atomic_dec_32(&mp->set_event_guard); + atomic_dec_32(&mp->m_set_event_guard); } -int spl_mutex_tryenter(kmutex_t *mp) +int +spl_mutex_tryenter(kmutex_t *mp) { // LARGE_INTEGER timeout; // NTSTATUS Status; kthread_t *thisthread = current_thread(); - if (mp->initialised != MUTEX_INITIALISED) - panic("%s: mutex not initialised\n", __func__); + if (mp->m_initialised != MUTEX_INITIALISED) + panic("%s: mutex not m_initialised\n", __func__); if (mp->m_owner == thisthread) panic("mutex_tryenter: locking against myself!"); @@ -171,8 +178,8 @@ int spl_mutex_tryenter(kmutex_t *mp) // Test if "m_owner" is NULL, if so, set it to "thisthread". // Returns original value, so if NULL, it succeeded. if (InterlockedCompareExchangePointer(&mp->m_owner, - thisthread, NULL) != NULL) { - return 0; // Not held. + thisthread, NULL) != NULL) { + return (0); // Not held. } ASSERT(mp->m_owner == thisthread); @@ -181,12 +188,14 @@ int spl_mutex_tryenter(kmutex_t *mp) return (1); } -int spl_mutex_owned(kmutex_t *mp) +int +spl_mutex_owned(kmutex_t *mp) { return (mp->m_owner == current_thread()); } -struct kthread *spl_mutex_owner(kmutex_t *mp) +struct kthread * +spl_mutex_owner(kmutex_t *mp) { return (mp->m_owner); } diff --git a/module/os/windows/spl/spl-policy.c b/module/os/windows/spl/spl-policy.c index ae36b73bfa1..40e441b121d 100644 --- a/module/os/windows/spl/spl-policy.c +++ b/module/os/windows/spl/spl-policy.c @@ -27,11 +27,6 @@ spl_priv_check_cred(const cred_t *cred, int priv, int flags) { int error = 0; -// apple if (kauth_cred_getuid(cred) == 0) { -// error = 0; -// goto out; -// } - /* * The default is deny, so if no policies have granted it, reject * with a privilege error here. @@ -46,7 +41,7 @@ spl_priv_check_cred(const cred_t *cred, int priv, int flags) // CloseServiceHandle(SCM); // } // error = EPERM; -//out: +// out: return (error); } diff --git a/module/os/windows/spl/spl-proc.c b/module/os/windows/spl/spl-proc.c index 2edde0013e1..28ba36cd346 100644 --- a/module/os/windows/spl/spl-proc.c +++ b/module/os/windows/spl/spl-proc.c @@ -29,7 +29,7 @@ * space, just "an address". It should be a "proc_t *". */ -struct _KPROCESS{ +struct _KPROCESS { void *something; }; diff --git a/module/os/windows/spl/spl-processor.c b/module/os/windows/spl/spl-processor.c index 5c32401f884..19c9987d2c1 100644 --- a/module/os/windows/spl/spl-processor.c +++ b/module/os/windows/spl/spl-processor.c @@ -32,9 +32,7 @@ cpu_number(void) { uint32_t cpuid; cpuid = (uint32_t)KeGetCurrentProcessorIndex(); - return cpuid % max_ncpus; - return 0; - return cpuid >= max_ncpus ? 0 : cpuid; + return (cpuid % max_ncpus); } uint32_t @@ -42,7 +40,5 @@ getcpuid() { uint32_t cpuid; cpuid = (uint32_t)KeGetCurrentProcessorIndex(); - return cpuid % max_ncpus; - return 0; - return cpuid >= max_ncpus ? 0 : cpuid; + return (cpuid % max_ncpus); } diff --git a/module/os/windows/spl/spl-rwlock.c b/module/os/windows/spl/spl-rwlock.c index f5a7346834c..6f518af25cb 100644 --- a/module/os/windows/spl/spl-rwlock.c +++ b/module/os/windows/spl/spl-rwlock.c @@ -26,40 +26,41 @@ */ #include -//#include #include #include uint64_t zfs_active_rwlock = 0; -/* We run rwlock with DEBUG on for now, as it protects against +/* + * We run rwlock with DEBUG on for now, as it protects against * uninitialised access etc, and almost no cost. */ #ifndef DEBUG -#define DEBUG +#define DEBUG #endif #ifdef DEBUG -int rw_isinit(krwlock_t *rwlp) +int +rw_isinit(krwlock_t *rwlp) { if (rwlp->rw_pad != 0x012345678) - return 0; - return 1; + return (0); + return (1); } #endif void -rw_init(krwlock_t *rwlp, char *name, krw_type_t type, /*__unused*/ void *arg) +rw_init(krwlock_t *rwlp, char *name, krw_type_t type, __unused void *arg) { - ASSERT(type != RW_DRIVER); + ASSERT(type != RW_DRIVER); #ifdef DEBUG - VERIFY3U(rwlp->rw_pad, != , 0x012345678); + VERIFY3U(rwlp->rw_pad, !=, 0x012345678); #endif ExInitializeResourceLite(&rwlp->rw_lock); - rwlp->rw_owner = NULL; - rwlp->rw_readers = 0; + rwlp->rw_owner = NULL; + rwlp->rw_readers = 0; #ifdef DEBUG rwlp->rw_pad = 0x012345678; #endif @@ -69,14 +70,16 @@ rw_init(krwlock_t *rwlp, char *name, krw_type_t type, /*__unused*/ void *arg) void rw_destroy(krwlock_t *rwlp) { - // Confirm it was initialised, and is unlocked, and not already destroyed. + // Confirm it was initialised, and is unlocked, + // and not already destroyed. #ifdef DEBUG - VERIFY3U(rwlp->rw_pad, == , 0x012345678); + VERIFY3U(rwlp->rw_pad, ==, 0x012345678); #endif VERIFY3U(rwlp->rw_owner, ==, 0); VERIFY3U(rwlp->rw_readers, ==, 0); - // This has caused panic due to IRQL panic, from taskq->zap_evict->rw_destroy + // This has caused panic due to IRQL panic, from + // taskq->zap_evict->rw_destroy ExDeleteResourceLite(&rwlp->rw_lock); #ifdef DEBUG rwlp->rw_pad = 0x99; @@ -92,18 +95,18 @@ rw_enter(krwlock_t *rwlp, krw_t rw) panic("rwlock %p not initialised\n", rwlp); #endif - if (rw == RW_READER) { + if (rw == RW_READER) { ExAcquireResourceSharedLite(&rwlp->rw_lock, TRUE); - atomic_inc_32((volatile uint32_t *)&rwlp->rw_readers); - ASSERT(rwlp->rw_owner == 0); - } else { - if (rwlp->rw_owner == current_thread()) - panic("rw_enter: locking against myself!"); + atomic_inc_32((volatile uint32_t *)&rwlp->rw_readers); + ASSERT(rwlp->rw_owner == 0); + } else { + if (rwlp->rw_owner == current_thread()) + panic("rw_enter: locking against myself!"); ExAcquireResourceExclusiveLite(&rwlp->rw_lock, TRUE); - ASSERT(rwlp->rw_owner == 0); - ASSERT(rwlp->rw_readers == 0); - rwlp->rw_owner = current_thread(); - } + ASSERT(rwlp->rw_owner == 0); + ASSERT(rwlp->rw_readers == 0); + rwlp->rw_owner = current_thread(); + } } /* @@ -113,31 +116,29 @@ rw_enter(krwlock_t *rwlp, krw_t rw) int rw_tryenter(krwlock_t *rwlp, krw_t rw) { - int held = 0; + int held = 0; #ifdef DEBUG if (rwlp->rw_pad != 0x012345678) panic("rwlock %p not initialised\n", rwlp); #endif - if (rw == RW_READER) { + if (rw == RW_READER) { held = ExAcquireResourceSharedLite(&rwlp->rw_lock, FALSE); - if (held) - atomic_inc_32((volatile uint32_t *)&rwlp->rw_readers); - } else { - if (rwlp->rw_owner == current_thread()) - panic("rw_tryenter: locking against myself!"); + if (held) + atomic_inc_32((volatile uint32_t *)&rwlp->rw_readers); + } else { + if (rwlp->rw_owner == current_thread()) + panic("rw_tryenter: locking against myself!"); held = ExAcquireResourceExclusiveLite(&rwlp->rw_lock, FALSE); - if (held) - rwlp->rw_owner = current_thread(); - } + if (held) + rwlp->rw_owner = current_thread(); + } - return (held); + return (held); } - - /* * It appears a difference between Darwin's * lck_rw_lock_shared_to_exclusive() and Solaris's rw_tryupgrade() and @@ -152,13 +153,14 @@ rw_tryenter(krwlock_t *rwlp, krw_t rw) int rw_tryupgrade(krwlock_t *rwlp) { - int held = 0; + int held = 0; if (rwlp->rw_owner == current_thread()) panic("rw_enter: locking against myself!"); /* More readers than us? give up */ - if (rwlp->rw_readers != 1) return 0; + if (rwlp->rw_readers != 1) + return (0); /* * It is ON. We need to drop our READER lock, and try to @@ -173,8 +175,8 @@ rw_tryupgrade(krwlock_t *rwlp) if (held) { /* Looks like we won */ rwlp->rw_owner = current_thread(); - ASSERT(rwlp->rw_readers == 0); - return 1; + ASSERT(rwlp->rw_readers == 0); + return (1); } /* @@ -184,22 +186,21 @@ rw_tryupgrade(krwlock_t *rwlp) * so we need to grab it. */ rw_enter(rwlp, RW_READER); - return 0; - + return (0); } void rw_exit(krwlock_t *rwlp) { - if (rwlp->rw_owner == current_thread()) { - rwlp->rw_owner = NULL; - ASSERT(rwlp->rw_readers == 0); + if (rwlp->rw_owner == current_thread()) { + rwlp->rw_owner = NULL; + ASSERT(rwlp->rw_readers == 0); ExReleaseResourceLite(&rwlp->rw_lock); - } else { - atomic_dec_32((volatile uint32_t *)&rwlp->rw_readers); - ASSERT(rwlp->rw_owner == 0); + } else { + atomic_dec_32((volatile uint32_t *)&rwlp->rw_readers); + ASSERT(rwlp->rw_owner == 0); ExReleaseResourceLite(&rwlp->rw_lock); - } + } } int @@ -211,16 +212,16 @@ rw_read_held(krwlock_t *rwlp) int rw_lock_held(krwlock_t *rwlp) { - /* - * ### not sure about this one ### - */ - return (rwlp->rw_owner == current_thread() || rwlp->rw_readers > 0); + /* + * ### not sure about this one ### + */ + return (rwlp->rw_owner == current_thread() || rwlp->rw_readers > 0); } int rw_write_held(krwlock_t *rwlp) { - return (rwlp->rw_owner == current_thread()); + return (rwlp->rw_owner == current_thread()); } void @@ -232,12 +233,14 @@ rw_downgrade(krwlock_t *rwlp) rw_enter(rwlp, RW_READER); } -int spl_rwlock_init(void) +int +spl_rwlock_init(void) { - return 0; + return (0); } -void spl_rwlock_fini(void) +void +spl_rwlock_fini(void) { ASSERT(zfs_active_rwlock == 0); } diff --git a/module/os/windows/spl/spl-seg_kmem.c b/module/os/windows/spl/spl-seg_kmem.c index 26481e0e067..9103be7dd06 100644 --- a/module/os/windows/spl/spl-seg_kmem.c +++ b/module/os/windows/spl/spl-seg_kmem.c @@ -26,18 +26,11 @@ #include #include -// ugly: smd -#ifdef kmem_free -#undef kmem_free -#endif -//#include #include #include #include -//#include - /* * seg_kmem is the primary kernel memory segment driver. It * maps the kernel heap [kernelheap, ekernelheap), module text, @@ -92,13 +85,10 @@ #ifdef _KERNEL -#define XNU_KERNEL_PRIVATE -//#include +#define XNU_KERNEL_PRIVATE #include -//extern vm_map_t kernel_map; - /* * These extern prototypes has to be carefully checked against XNU source * in case Apple changes them. They are not defined in the "allowed" parts @@ -111,7 +101,7 @@ typedef uint8_t vm_tag_t; * * (VM_KERN_MEMORY_KEXT - mach_vm_statistics.h) */ -#define SPL_TAG 6 +#define SPL_TAG 6 /* * In kernel lowlevel form of malloc. @@ -128,12 +118,16 @@ typedef int page_t; void *segkmem_alloc(vmem_t *vmp, size_t size, int vmflag); void segkmem_free(vmem_t *vmp, void *inaddr, size_t size); - -uint64_t segkmem_total_mem_allocated = 0; /* Total memory held allocated */ -vmem_t *heap_arena; /* primary kernel heap arena */ -vmem_t *zio_arena_parent; /* qcaches for zio and abd arenas */ -vmem_t *zio_arena; /* arena for allocating file data */ -vmem_t *zio_metadata_arena; /* and for allocation of zfs metadata */ +/* Total memory held allocated */ +uint64_t segkmem_total_mem_allocated = 0; +/* primary kernel heap arena */ +vmem_t *heap_arena; +/* qcaches for zio and abd arenas */ +vmem_t *zio_arena_parent; +/* arena for allocating file data */ +vmem_t *zio_arena; +/* and for allocation of zfs metadata */ +vmem_t *zio_metadata_arena; #ifdef _KERNEL extern uint64_t total_memory; @@ -149,26 +143,25 @@ osif_malloc(uint64_t size) #ifdef _KERNEL void *tr; - //kern_return_t kr = kernel_memory_allocate(kernel_map, - // &tr, size, PAGESIZE, 0, SPL_TAG); tr = ExAllocatePoolWithTag(NonPagedPoolNx, size, '!SFZ'); ASSERT(P2PHASE(tr, PAGE_SIZE) == 0); if (tr != NULL) { atomic_inc_64(&stat_osif_malloc_success); atomic_add_64(&segkmem_total_mem_allocated, size); atomic_add_64(&stat_osif_malloc_bytes, size); - return(tr); + return (tr); } else { - dprintf("%s: ExAllocatePoolWithTag failed (memusage: %llu)\n", __func__, segkmem_total_mem_allocated); + dprintf("%s: ExAllocatePoolWithTag failed (memusage: %llu)\n", + __func__, segkmem_total_mem_allocated); ASSERT(0); extern volatile unsigned int vm_page_free_wanted; extern volatile unsigned int vm_page_free_min; spl_free_set_pressure(vm_page_free_min); vm_page_free_wanted = vm_page_free_min; - return(NULL); + return (NULL); } #else - return(malloc(size)); + return (malloc(size)); #endif } @@ -176,13 +169,12 @@ void osif_free(void* buf, uint64_t size) { #ifdef _KERNEL - //kmem_free(kernel_map, buf, size); ExFreePoolWithTag(buf, '!SFZ'); - atomic_inc_64(&stat_osif_free); - atomic_sub_64(&segkmem_total_mem_allocated, size); - atomic_add_64(&stat_osif_free_bytes, size); + atomic_inc_64(&stat_osif_free); + atomic_sub_64(&segkmem_total_mem_allocated, size); + atomic_add_64(&stat_osif_free_bytes, size); #else - free(buf); + free(buf); #endif /* _KERNEL */ } @@ -190,39 +182,39 @@ osif_free(void* buf, uint64_t size) * Configure vmem, such that the heap arena is fed, * and drains to the kernel low level allocator. */ - extern vmem_t *vmem_init(const char *, void *, uint32_t, uint32_t, - vmem_alloc_t *, vmem_free_t *); +extern vmem_t *vmem_init(const char *, void *, uint32_t, uint32_t, + vmem_alloc_t *, vmem_free_t *); void kernelheap_init() { heap_arena = vmem_init("heap", NULL, 0, PAGESIZE, - (vmem_alloc_t *)segkmem_alloc, (vmem_free_t *)segkmem_free); + (vmem_alloc_t *)segkmem_alloc, (vmem_free_t *)segkmem_free); } - -void kernelheap_fini(void) +void +kernelheap_fini(void) { vmem_fini(heap_arena); } void * -segkmem_alloc(vmem_t * vmp, size_t size, int maybe_unmasked_vmflag) +segkmem_alloc(vmem_t *vmp, size_t size, int maybe_unmasked_vmflag) { - return(osif_malloc(size)); + return (osif_malloc(size)); } void segkmem_free(vmem_t *vmp, void *inaddr, size_t size) { osif_free(inaddr, size); - //since this is mainly called by spl_root_arena and free_arena, - //do we really want to wake up a waiter, just because we have - //transferred from one to the other? - //we already have vmem_add_a_gibibyte waking up waiters - //so specializing here seems wasteful - //(originally included in vmem_experiments) - //cv_signal(&vmp->vm_cv); + // since this is mainly called by spl_root_arena and free_arena, + // do we really want to wake up a waiter, just because we have + // transferred from one to the other? + // we already have vmem_add_a_gibibyte waking up waiters + // so specializing here seems wasteful + // (originally included in vmem_experiments) + // cv_signal(&vmp->vm_cv); } /* @@ -232,7 +224,7 @@ segkmem_free(vmem_t *vmp, void *inaddr, size_t size) * as all the other caches. */ // smd: we nevertheless plumb in an arena with heap as parent, so that -// we can track stats and maintain the VM_ / qc settings differently +// we can track stats and maintain the VM_ / qc settings differently void segkmem_zio_init() { @@ -243,7 +235,7 @@ segkmem_zio_init() // Illumos does not segregate zio_metadata_arena out of heap, // almost exclusively for reasons involving panic dump data - // retention. However, parenting zio_metadata_arena to + // retention. However, parenting zio_metadata_arena to // spl_root_arena and giving it its own qcaches provides better // kstat observability *and* noticeably better performance in // realworld (zfs/dmu) metadata-heavy activity. Additionally, diff --git a/module/os/windows/spl/spl-taskq.c b/module/os/windows/spl/spl-taskq.c index 65a63b17419..4db9db9aae2 100644 --- a/module/os/windows/spl/spl-taskq.c +++ b/module/os/windows/spl/spl-taskq.c @@ -498,8 +498,6 @@ #include #include #include -#include -#include #include #include @@ -753,8 +751,8 @@ uint_t taskq_smtbf = UINT_MAX; /* mean time between injected failures */ tqe->tqent_func = (func); \ tqe->tqent_arg = (arg); \ tq->tq_tasks++; \ - if (tq->tq_tasks - tq->tq_executed > tq->tq_maxtasks) \ - tq->tq_maxtasks = (int)(tq->tq_tasks - tq->tq_executed); \ + if (tq->tq_tasks - tq->tq_executed > tq->tq_maxtasks) \ + tq->tq_maxtasks = (int)(tq->tq_tasks - tq->tq_executed); \ cv_signal(&tq->tq_dispatch_cv); \ DTRACE_PROBE2(taskq__enqueue, taskq_t *, tq, taskq_ent_t *, tqe); \ } @@ -865,8 +863,8 @@ spl_taskq_init(void) mutex_init(&taskq_kstat_lock, NULL, MUTEX_DEFAULT, NULL); mutex_init(&taskq_d_kstat_lock, NULL, MUTEX_DEFAULT, NULL); - - return 0; + + return (0); } void @@ -1031,7 +1029,7 @@ taskq_ent_free(taskq_t *tq, taskq_ent_t *tqe) } else { tq->tq_nalloc--; mutex_exit(&tq->tq_lock); - kmem_cache_free(taskq_ent_cache, tqe); + kmem_cache_free(taskq_ent_cache, tqe); mutex_enter(&tq->tq_lock); } @@ -1122,7 +1120,8 @@ taskq_bucket_dispatch(taskq_bucket_t *b, task_func_t func, void *arg) * dispatch a task. This is useful for debugging. */ static taskqid_t -taskq_dispatch_impl(taskq_t *tq, task_func_t func, void *arg, uint_t flags, clock_t expire_time) +taskq_dispatch_impl(taskq_t *tq, task_func_t func, void *arg, + uint_t flags, clock_t expire_time) { taskq_bucket_t *bucket = NULL; /* Which bucket needs extension */ taskq_ent_t *tqe = NULL; @@ -1152,7 +1151,8 @@ taskq_dispatch_impl(taskq_t *tq, task_func_t func, void *arg, uint_t flags, cloc tqe->tqent_un.tqent_flags = 0; // We could bake this into TQ_ENQUEUE? - tqe->tqent_delay_time = expire_time; // Arm the delay logic, if set + // Arm the delay logic, if set + tqe->tqent_delay_time = expire_time; if (flags & TQ_FRONT) { TQ_ENQUEUE_FRONT(tq, tqe, func, arg); @@ -1183,8 +1183,9 @@ taskq_dispatch_impl(taskq_t *tq, task_func_t func, void *arg, uint_t flags, cloc } else { int loopcount; taskq_bucket_t *b; - //uintptr_t h = ((uintptr_t)CPU + (uintptr_t)arg) >> 3; - uintptr_t h = ((uintptr_t)(cpu_number()<<3) + (uintptr_t)arg) >> 3; + // uintptr_t h = ((uintptr_t)CPU + (uintptr_t)arg) >> 3; + uintptr_t h = + ((uintptr_t)(cpu_number()<<3) + (uintptr_t)arg) >> 3; h = TQ_HASH(h); @@ -1285,7 +1286,7 @@ taskq_dispatch_impl(taskq_t *tq, task_func_t func, void *arg, uint_t flags, cloc taskqid_t taskq_dispatch(taskq_t *tq, task_func_t func, void *arg, uint_t flags) { - return taskq_dispatch_impl(tq, func, arg, flags, 0); + return (taskq_dispatch_impl(tq, func, arg, flags, 0)); } /* @@ -1297,16 +1298,14 @@ taskqid_t taskq_dispatch_delay(taskq_t *tq, task_func_t func, void *arg, uint_t tqflags, clock_t expire_time) { - return taskq_dispatch_impl(tq, func, arg, tqflags, expire_time); + return (taskq_dispatch_impl(tq, func, arg, tqflags, expire_time)); } void taskq_init_ent(taskq_ent_t *t) { VERIFY3P(t->tqent_next, !=, 0xdeadbeefdeadbeef); - memset(t, 0, sizeof(*t)); -// t->tqent_prev = t; -// t->tqent_next = t->tqent_prev; + memset(t, 0, sizeof (*t)); } void @@ -1358,7 +1357,7 @@ taskq_empty_ent(taskq_ent_t *t) if (t->tqent_prev == NULL && t->tqent_next == NULL) - return TRUE; + return (TRUE); return (IS_EMPTY(*t)); } @@ -1463,7 +1462,7 @@ taskq_resume(taskq_t *tq) int taskq_member(taskq_t *tq, struct kthread *thread) { - return (tq == (taskq_t *)tsd_get_by_thread(taskq_tsd, thread)); + return (tq == (taskq_t *)tsd_get_by_thread(taskq_tsd, thread)); } #if 0 @@ -1472,19 +1471,19 @@ taskq_member(taskq_t *tq, struct kthread *thread) { int i; - mutex_enter(&tq->tq_lock); + mutex_enter(&tq->tq_lock); if (tq->tq_thread != NULL) /* nthreads==1 case */ if (tq->tq_thread == (void *)thread) { - mutex_exit(&tq->tq_lock); - return 1; - } + mutex_exit(&tq->tq_lock); + return (1); + } - for (i = 0;i < tq->tq_nthreads; i++) + for (i = 0; i < tq->tq_nthreads; i++) if (tq->tq_threadlist[i] == (void *)thread) { - mutex_exit(&tq->tq_lock); + mutex_exit(&tq->tq_lock); return (1); - } - mutex_exit(&tq->tq_lock); + } + mutex_exit(&tq->tq_lock); return (0); } #endif @@ -1492,7 +1491,7 @@ taskq_member(taskq_t *tq, struct kthread *thread) taskq_t * taskq_of_curthread(void) { - return (tsd_get(taskq_tsd)); + return (tsd_get(taskq_tsd)); } /* @@ -1504,7 +1503,7 @@ taskq_of_curthread(void) int taskq_cancel_id(taskq_t *tq, taskqid_t id) { - taskq_ent_t *task = (taskq_t *) id; + taskq_ent_t *task = (taskq_t *)id; // delay_taskq active? Linux will call with id==0 if (task != NULL) { @@ -1519,11 +1518,11 @@ taskq_cancel_id(taskq_t *tq, taskqid_t id) mutex_exit(&tq->tq_lock); } - /* So we want to tell task to stop, and wait until it does */ - if (!EMPTY_TASKQ(tq)) - taskq_wait(tq); + /* So we want to tell task to stop, and wait until it does */ + if (!EMPTY_TASKQ(tq)) + taskq_wait(tq); - return (0); + return (0); } /* @@ -1628,7 +1627,7 @@ taskq_thread(void *arg) boolean_t freeit; CALLB_CPR_INIT(&cprinfo, &tq->tq_lock, callb_generic_cpr, - tq->tq_name); + tq->tq_name); tsd_set(taskq_tsd, tq); mutex_enter(&tq->tq_lock); thread_id = ++tq->tq_nthreads; @@ -1724,8 +1723,10 @@ taskq_thread(void *arg) // Should we delay? if (tqe->tqent_delay_time > 0) { mutex_enter(&tqe->tqent_delay_lock); - if (tqe->tqent_delay_time > 0) - cv_timedwait(&tqe->tqent_delay_cv, &tqe->tqent_delay_lock, tqe->tqent_delay_time); + if (tqe->tqent_delay_time > 0) + cv_timedwait(&tqe->tqent_delay_cv, + &tqe->tqent_delay_lock, + tqe->tqent_delay_time); mutex_exit(&tqe->tqent_delay_lock); // Did we wake up from being canceled? @@ -2014,7 +2015,7 @@ taskq_create_common(const char *name, int instance, int nthreads, pri_t pri, /* Cannot have DC_BATCH without DUTY_CYCLE */ ASSERT((flags & (TASKQ_DUTY_CYCLE|TASKQ_DC_BATCH)) != TASKQ_DC_BATCH); - //ASSERT(proc != NULL); + // ASSERT(proc != NULL); bsize = 1 << (highbit(ncpus) - 1); ASSERT(bsize >= 1); @@ -2042,7 +2043,7 @@ taskq_create_common(const char *name, int instance, int nthreads, pri_t pri, * we won't be creating LWPs, so new threads will be assigned * to the default processor set. */ - /*ASSERT(curproc == proc || proc == &p0);*/ + /* ASSERT(curproc == proc || proc == &p0); */ tq->tq_threads_ncpus_pct = pct; nthreads = 1; /* corrected in taskq_thread_create() */ max_nthreads = TASKQ_THREADS_PCT(max_ncpus, pct); @@ -2212,7 +2213,7 @@ taskq_destroy(taskq_t *tq) cv_broadcast(&tq->tq_exit_cv); while (tq->tq_nthreads != 0) - cv_wait(&tq->tq_wait_cv, &tq->tq_lock); // this crashes, sometimes. + cv_wait(&tq->tq_wait_cv, &tq->tq_lock); if (tq->tq_nthreads_max != 1) kmem_free(tq->tq_threadlist, sizeof (kthread_t *) * @@ -2335,8 +2336,8 @@ taskq_bucket_extend(void *arg) * for it to be initialized (below). */ tqe->tqent_thread = (kthread_t *)0xCEDEC0DE; - thread = thread_create(NULL, 0, (void (*)(void *))taskq_d_thread, tqe, 0, pp0, TS_RUN, - tq->tq_pri); + thread = thread_create(NULL, 0, (void (*)(void *))taskq_d_thread, + tqe, 0, pp0, TS_RUN, tq->tq_pri); /* * Once the entry is ready, link it to the the bucket free list. diff --git a/module/os/windows/spl/spl-thread.c b/module/os/windows/spl/spl-thread.c index 31108940a64..6ef65414c6d 100644 --- a/module/os/windows/spl/spl-thread.c +++ b/module/os/windows/spl/spl-thread.c @@ -26,7 +26,6 @@ */ #include -//#include #include #include #include @@ -42,84 +41,83 @@ uint64_t zfs_threads = 0; kthread_t * spl_thread_create( - caddr_t stk, - size_t stksize, - void (*proc)(void *), - void *arg, - size_t len, - /*struct proc *pp,*/ - int state, + caddr_t stk, + size_t stksize, + void (*proc)(void *), + void *arg, + size_t len, + int state, #ifdef SPL_DEBUG_THREAD - char *filename, - int line, + char *filename, + int line, #endif - pri_t pri) + pri_t pri) { - NTSTATUS result; - struct _KTHREAD *thread; + NTSTATUS result; + struct _KTHREAD *thread; #ifdef SPL_DEBUG_THREAD - dprintf("Start thread pri %d by '%s':%d\n", pri, - filename, line); + dprintf("Start thread pri %d by '%s':%d\n", pri, + filename, line); #endif - result = PsCreateSystemThread( - (void **)&thread, - 0, // DesiredAccess, - NULL, // ObjectAttributes, - NULL, // ProcessHandle, - 0, // ClientId, - proc, // StartRoutine, - arg // StartContext - ); - - - if (result != STATUS_SUCCESS) - return (NULL); - - /* Improve the priority when asked to do so */ - /* Thread priorities range from 0 to 31, where 0 is the lowest - * priority and 31 is the highest*/ - - if (pri > minclsyspri) { - //thread_precedence_policy_data_t policy; - //policy.importance = pri - minclsyspri; + result = PsCreateSystemThread( + (void **)&thread, + 0, // DesiredAccess, + NULL, // ObjectAttributes, + NULL, // ProcessHandle, + 0, // ClientId, + proc, // StartRoutine, + arg); // StartContext + + if (result != STATUS_SUCCESS) + return (NULL); + + /* + * Improve the priority when asked to do so + * Thread priorities range from 0 to 31, where 0 is the lowest + * priority and 31 is the highest + */ - //thread_policy_set(thread, - // THREAD_PRECEDENCE_POLICY, - // (thread_policy_t)&policy, - // THREAD_PRECEDENCE_POLICY_COUNT); + if (pri > minclsyspri) { + // thread_precedence_policy_data_t policy; + // policy.importance = pri - minclsyspri; + // thread_policy_set(thread, + // THREAD_PRECEDENCE_POLICY, + // (thread_policy_t)&policy, + // THREAD_PRECEDENCE_POLICY_COUNT); - // TODO: Windows thread priority? + // TODO: Windows thread priority? - // why is this call missing? - //KeSetBasePriorityThread(thread, 1); - } - //thread_deallocate(thread); + // why is this call missing? + // KeSetBasePriorityThread(thread, 1); + } - atomic_inc_64(&zfs_threads); + atomic_inc_64(&zfs_threads); // Convert thread handle to pethread, so it matches current_thread() PETHREAD eThread; - ObReferenceObjectByHandle(thread, THREAD_ALL_ACCESS, 0, KernelMode, (void **)&eThread, 0); + ObReferenceObjectByHandle(thread, THREAD_ALL_ACCESS, 0, + KernelMode, (void **)&eThread, 0); ObDereferenceObject(eThread); ZwClose(thread); - return ((kthread_t *)eThread); + return ((kthread_t *)eThread); } kthread_t * spl_current_thread(void) { - thread_t *cur_thread = current_thread(); - return ((kthread_t *)cur_thread); + thread_t *cur_thread = current_thread(); + return ((kthread_t *)cur_thread); } -void spl_thread_exit(void) +void +spl_thread_exit(void) { - atomic_dec_64(&zfs_threads); + atomic_dec_64(&zfs_threads); - tsd_thread_exit(); - (void) PsTerminateSystemThread(0); + tsd_thread_exit(); + (void) PsTerminateSystemThread(0); } @@ -128,14 +126,15 @@ void spl_thread_exit(void) */ callout_id_t timeout_generic(int type, void (*func)(void *), void *arg, - hrtime_t expiration, hrtime_t resolution, int flags) + hrtime_t expiration, hrtime_t resolution, int flags) { -// struct timespec ts; + // struct timespec ts; // hrt2ts(expiration, &ts); - //bsd_timeout(func, arg, &ts); - /* bsd_untimeout() requires func and arg to cancel the timeout, so + // bsd_timeout(func, arg, &ts); + /* + * bsd_untimeout() requires func and arg to cancel the timeout, so * pass it back as the callout_id. If we one day were to implement * untimeout_generic() they would pass it back to us */ - return (callout_id_t)arg; + return ((callout_id_t)arg); } diff --git a/module/os/windows/spl/spl-time.c b/module/os/windows/spl/spl-time.c index a2a42ec5f6b..94c5ed51da9 100644 --- a/module/os/windows/spl/spl-time.c +++ b/module/os/windows/spl/spl-time.c @@ -23,7 +23,7 @@ * * Copyright (C) 2017 Jorgen Lundman * -*/ + */ #define _KERNEL_MODE #include #include @@ -32,20 +32,15 @@ #include #include - -//#include - - /* - * gethrtime() provides high-resolution timestamps with machine-dependent origin -. - * Hence its primary use is to specify intervals. + * gethrtime() provides high-resolution timestamps with machine-dependent + * origin. Hence its primary use is to specify intervals. */ static hrtime_t zfs_abs_to_nano(uint64_t elapsed) { - return elapsed * KeQueryTimeIncrement() * 100; + return (elapsed * KeQueryTimeIncrement() * 100); } /* Open Solaris lbolt is in hz */ @@ -60,9 +55,9 @@ zfs_lbolt(void) return (lbolt_hz); } -hrtime_t gethrtime(void) +hrtime_t +gethrtime(void) { - //static uint64_t start = 0; static LARGE_INTEGER start = { 0 }; LARGE_INTEGER now; if (start.QuadPart == 0) { @@ -71,7 +66,7 @@ hrtime_t gethrtime(void) } KeQueryTickCount(&now); ASSERT((now.QuadPart != start.QuadPart)); - return zfs_abs_to_nano(now.QuadPart - start.QuadPart); + return (zfs_abs_to_nano(now.QuadPart - start.QuadPart)); } /* @@ -81,7 +76,6 @@ hrtime_t gethrtime(void) int random_get_bytes(uint8_t *ptr, uint32_t len) { - //read_random(ptr, len); LARGE_INTEGER TickCount; ULONG r; PULONG b; @@ -91,12 +85,12 @@ random_get_bytes(uint8_t *ptr, uint32_t len) b = (PULONG) ptr; - for (i = 0; i < len / sizeof(ULONG); i++) - b[i] = RtlRandomEx(&TickCount.LowPart); + for (i = 0; i < len / sizeof (ULONG); i++) + b[i] = RtlRandomEx(&TickCount.LowPart); - len &= (sizeof(ULONG) - 1); - if (len > 0) { - r = RtlRandomEx(&TickCount.LowPart); + len &= (sizeof (ULONG) - 1); + if (len > 0) { + r = RtlRandomEx(&TickCount.LowPart); RtlCopyMemory(&b[i], &r, len); } return (0); @@ -113,7 +107,7 @@ gethrestime(struct timespec *ts) #else KeQuerySystemTime(&now); #endif - TIME_WINDOWS_TO_UNIX(now.QuadPart, tv); + TIME_WINDOWS_TO_UNIX(now.QuadPart, tv); // change macro to take 2 dst args, "sec and nsec" to avoid this step? ts->tv_sec = tv[0]; ts->tv_nsec = tv[1]; @@ -131,26 +125,26 @@ gethrestime_sec(void) void hrt2ts(hrtime_t hrt, struct timespec *tsp) { - uint32_t sec, nsec, tmp; - - tmp = (uint32_t)(hrt >> 30); - sec = tmp - (tmp >> 2); - sec = tmp - (sec >> 5); - sec = tmp + (sec >> 1); - sec = tmp - (sec >> 6) + 7; - sec = tmp - (sec >> 3); - sec = tmp + (sec >> 1); - sec = tmp + (sec >> 3); - sec = tmp + (sec >> 4); - tmp = (sec << 7) - sec - sec - sec; - tmp = (tmp << 7) - tmp - tmp - tmp; - tmp = (tmp << 7) - tmp - tmp - tmp; - nsec = (uint32_t)hrt - (tmp << 9); - while (nsec >= NANOSEC) { - nsec -= NANOSEC; - sec++; - } - tsp->tv_sec = (time_t)sec; - tsp->tv_nsec = nsec; + uint32_t sec, nsec, tmp; + + tmp = (uint32_t)(hrt >> 30); + sec = tmp - (tmp >> 2); + sec = tmp - (sec >> 5); + sec = tmp + (sec >> 1); + sec = tmp - (sec >> 6) + 7; + sec = tmp - (sec >> 3); + sec = tmp + (sec >> 1); + sec = tmp + (sec >> 3); + sec = tmp + (sec >> 4); + tmp = (sec << 7) - sec - sec - sec; + tmp = (tmp << 7) - tmp - tmp - tmp; + tmp = (tmp << 7) - tmp - tmp - tmp; + nsec = (uint32_t)hrt - (tmp << 9); + while (nsec >= NANOSEC) { + nsec -= NANOSEC; + sec++; + } + tsp->tv_sec = (time_t)sec; + tsp->tv_nsec = nsec; } #endif diff --git a/module/os/windows/spl/spl-tsd.c b/module/os/windows/spl/spl-tsd.c index 88b94bf50fe..6e30c337ef6 100644 --- a/module/os/windows/spl/spl-tsd.c +++ b/module/os/windows/spl/spl-tsd.c @@ -61,31 +61,30 @@ #include /* Initial size of array, and realloc growth size */ -#define TSD_ALLOC_SIZE 10 +#define TSD_ALLOC_SIZE 10 /* array of dtors, allocated in init */ -static dtor_func_t *tsd_dtor_array = NULL; -static uint32_t tsd_dtor_size = 0; +static dtor_func_t *tsd_dtor_array = NULL; +static uint32_t tsd_dtor_size = 0; -static avl_tree_t tsd_tree; +static avl_tree_t tsd_tree; struct spl_tsd_node_s { /* The index/key */ - uint_t tsd_key; - thread_t *tsd_thread; + uint_t tsd_key; + thread_t *tsd_thread; /* The payload */ - void *tsd_value; + void *tsd_value; /* Internal mumbo */ - avl_node_t tsd_link_node; + avl_node_t tsd_link_node; }; typedef struct spl_tsd_node_s spl_tsd_node_t; static kmutex_t spl_tsd_mutex; - /* * tsd_set - set thread specific data * @key: lookup key @@ -108,13 +107,14 @@ tsd_set(uint_t key, void *value) /* Invalid key values? */ if ((key < 1) || - (key >= tsd_dtor_size)) { - return EINVAL; + (key >= tsd_dtor_size)) { + return (EINVAL); } i = key - 1; - /* First handle the easy case, already has a node/value + /* + * First handle the easy case, already has a node/value * so we just need to find it, update it. */ @@ -133,20 +133,20 @@ tsd_set(uint_t key, void *value) avl_remove(&tsd_tree, entry); mutex_exit(&spl_tsd_mutex); - kmem_free(entry, sizeof(*entry)); - return 0; + kmem_free(entry, sizeof (*entry)); + return (0); } entry->tsd_value = value; - return 0; + return (0); } /* No node, we need to create a new one and insert it. */ /* But if the value is NULL, then why create one eh? */ if (value == NULL) - return 0; + return (0); - entry = kmem_alloc(sizeof(spl_tsd_node_t), KM_SLEEP); + entry = kmem_alloc(sizeof (spl_tsd_node_t), KM_SLEEP); entry->tsd_key = i; entry->tsd_thread = current_thread(); @@ -156,7 +156,7 @@ tsd_set(uint_t key, void *value) avl_add(&tsd_tree, entry); mutex_exit(&spl_tsd_mutex); - return 0; + return (0); } /* @@ -214,7 +214,8 @@ tsd_create(uint_t *keyp, dtor_func_t dtor) { uint_t i; - if (*keyp) return; // Should be 0 + if (*keyp) + return; // Should be 0 // Iterate the dtor_array, looking for first NULL for (i = 0; i < TSD_ALLOC_SIZE; i++) { @@ -246,7 +247,7 @@ tsd_destroy(uint_t *keyp) /* Invalid key values? */ if ((*keyp < 1) || - (*keyp >= tsd_dtor_size)) { + (*keyp >= tsd_dtor_size)) { return; } @@ -269,8 +270,10 @@ tsd_destroy(uint_t *keyp) mutex_enter(&spl_tsd_mutex); entry = avl_find(&tsd_tree, &search, &loc); - /* "entry" should really be NULL here, as we searched for the - * NULL thread */ + /* + * "entry" should really be NULL here, as we searched for the + * NULL thread + */ if (entry == NULL) entry = avl_nearest(&tsd_tree, loc, AVL_AFTER); @@ -284,13 +287,12 @@ tsd_destroy(uint_t *keyp) avl_remove(&tsd_tree, entry); - kmem_free(entry, sizeof(*entry)); + kmem_free(entry, sizeof (*entry)); entry = next; } mutex_exit(&spl_tsd_mutex); - } @@ -298,7 +300,8 @@ tsd_destroy(uint_t *keyp) /* * A thread is exiting, clear out any tsd values it might have. */ -void tsd_thread_exit(void) +void +tsd_thread_exit(void) { spl_tsd_node_t *entry = NULL; spl_tsd_node_t search; @@ -311,7 +314,8 @@ void tsd_thread_exit(void) for (i = 0; i < tsd_dtor_size; i++) { /* If not allocated, skip */ - if (tsd_dtor_array[i] == NULL) continue; + if (tsd_dtor_array[i] == NULL) + continue; /* Find out of this thread has a value */ search.tsd_key = i; @@ -321,52 +325,52 @@ void tsd_thread_exit(void) if (entry) avl_remove(&tsd_tree, entry); mutex_exit(&spl_tsd_mutex); - if (entry == NULL) continue; + if (entry == NULL) + continue; /* If we have a value, call dtor */ if (entry->tsd_value) tsd_dtor_array[i](entry->tsd_value); - kmem_free(entry, sizeof(*entry)); + kmem_free(entry, sizeof (*entry)); } // for all i } - - - -static int tsd_tree_cmp(const void *arg1, const void *arg2) +static int +tsd_tree_cmp(const void *arg1, const void *arg2) { const spl_tsd_node_t *node1 = arg1; const spl_tsd_node_t *node2 = arg2; if (node1->tsd_key > node2->tsd_key) - return 1; + return (1); if (node1->tsd_key < node2->tsd_key) - return -1; + return (-1); if (node1->tsd_thread > node2->tsd_thread) - return 1; + return (1); if (node1->tsd_thread < node2->tsd_thread) - return -1; - return 0; + return (-1); + return (0); } int spl_tsd_init(void) { - tsd_dtor_array = kmem_zalloc(sizeof(dtor_func_t) * TSD_ALLOC_SIZE, - KM_SLEEP); + tsd_dtor_array = kmem_zalloc(sizeof (dtor_func_t) * TSD_ALLOC_SIZE, + KM_SLEEP); tsd_dtor_size = TSD_ALLOC_SIZE; mutex_init(&spl_tsd_mutex, NULL, MUTEX_DEFAULT, NULL); avl_create(&tsd_tree, tsd_tree_cmp, - sizeof (spl_tsd_node_t), - offsetof(spl_tsd_node_t, tsd_link_node)); - return 0; + sizeof (spl_tsd_node_t), + offsetof(spl_tsd_node_t, tsd_link_node)); + return (0); } -uint64_t spl_tsd_size(void) +uint64_t +spl_tsd_size(void) { - return avl_numnodes(&tsd_tree); + return (avl_numnodes(&tsd_tree)); } void @@ -375,18 +379,18 @@ spl_tsd_fini(void) spl_tsd_node_t *entry = NULL; void *cookie = NULL; - dprintf("SPL: tsd unloading %llu\n", spl_tsd_size() ); + dprintf("SPL: tsd unloading %llu\n", spl_tsd_size()); mutex_enter(&spl_tsd_mutex); cookie = NULL; - while((entry = avl_destroy_nodes(&tsd_tree, &cookie))) { - kmem_free(entry, sizeof(*entry)); + while ((entry = avl_destroy_nodes(&tsd_tree, &cookie))) { + kmem_free(entry, sizeof (*entry)); } mutex_exit(&spl_tsd_mutex); avl_destroy(&tsd_tree); mutex_destroy(&spl_tsd_mutex); - kmem_free(tsd_dtor_array, sizeof(dtor_func_t) * tsd_dtor_size); + kmem_free(tsd_dtor_array, sizeof (dtor_func_t) * tsd_dtor_size); tsd_dtor_size = 0; } diff --git a/module/os/windows/spl/spl-uio.c b/module/os/windows/spl/spl-uio.c index 0ae6332e19e..b542a9c4710 100644 --- a/module/os/windows/spl/spl-uio.c +++ b/module/os/windows/spl/spl-uio.c @@ -1,60 +1,61 @@ /* -* CDDL HEADER START -* -* The contents of this file are subject to the terms of the -* Common Development and Distribution License (the "License"). -* You may not use this file except in compliance with the License. -* -* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE -* or http://www.opensolaris.org/os/licensing. -* See the License for the specific language governing permissions -* and limitations under the License. -* -* When distributing Covered Code, include this CDDL HEADER in each -* file and include the License file at usr/src/OPENSOLARIS.LICENSE. -* If applicable, add the following below this CDDL HEADER, with the -* fields enclosed by brackets "[]" replaced with your own identifying -* information: Portions Copyright [yyyy] [name of copyright owner] -* -* CDDL HEADER END -*/ + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ /* -* -* Copyright (C) 2017 Jorgen Lundman -* -*/ + * + * Copyright (C) 2017 Jorgen Lundman + * + */ /* -* Provides an implementation of the union of Illumos and OSX UIO struct -* and API calls. That is to say the OsX API calls are kept, to keep -* the UIO structure as opaque, but the internals are more like Illumos -* to avoid the OsX 32bit vs 64bit logic. -*/ + * Provides an implementation of the union of Illumos and OSX UIO struct + * and API calls. That is to say the OsX API calls are kept, to keep + * the UIO structure as opaque, but the internals are more like Illumos + * to avoid the OsX 32bit vs 64bit logic. + */ #include #include - -uio_t *uio_create(int iovcount, off_t offset, int spacetype, int iodirection) +uio_t * +uio_create(int iovcount, off_t offset, int spacetype, int iodirection) { - // void * my_buf_p; - uint64_t my_size; - uio_t *my_uio; + // void *my_buf_p; + uint64_t my_size; + uio_t *my_uio; - // Future, make sure the uio struct is aligned, and do one alloc for uio and iovec - my_size = sizeof(uio_t); + // Future, make sure the uio struct is aligned, + // and do one alloc for uio and iovec + my_size = sizeof (uio_t); my_uio = kmem_alloc((uint32_t)my_size, KM_SLEEP); memset(my_uio, 0, my_size); - //my_uio->uio_size = my_size; + // my_uio->uio_size = my_size; my_uio->uio_segflg = spacetype; if (iovcount > 0) { - my_uio->uio_iov = kmem_alloc(iovcount * sizeof(iovec_t), KM_SLEEP); - memset(my_uio->uio_iov, 0, iovcount * sizeof(iovec_t)); - } - else { + my_uio->uio_iov = kmem_alloc(iovcount * sizeof (iovec_t), + KM_SLEEP); + memset(my_uio->uio_iov, 0, iovcount * sizeof (iovec_t)); + } else { my_uio->uio_iov = NULL; } my_uio->uio_max_iovs = iovcount; @@ -64,95 +65,100 @@ uio_t *uio_create(int iovcount, off_t offset, int spacetype, int iodirection) return (my_uio); } -void uio_free(uio_t *uio) +void +uio_free(uio_t *uio) { ASSERT(uio != NULL); ASSERT(uio->uio_iov != NULL); - kmem_free(uio->uio_iov, uio->uio_max_iovs * sizeof(iovec_t)); - kmem_free(uio, sizeof(uio_t)); - + kmem_free(uio->uio_iov, uio->uio_max_iovs * sizeof (iovec_t)); + kmem_free(uio, sizeof (uio_t)); } -int uio_addiov(uio_t *uio, user_addr_t baseaddr, user_size_t length) +int +uio_addiov(uio_t *uio, user_addr_t baseaddr, user_size_t length) { ASSERT(uio != NULL); ASSERT(uio->uio_iov != NULL); for (int i = 0; i < uio->uio_max_iovs; i++) { - if (uio->uio_iov[i].iov_len == 0 && uio->uio_iov[i].iov_base == 0) { + if (uio->uio_iov[i].iov_len == 0 && + uio->uio_iov[i].iov_base == 0) { uio->uio_iov[i].iov_len = (uint64_t)length; - uio->uio_iov[i].iov_base = (void *)(user_addr_t)baseaddr; + uio->uio_iov[i].iov_base = + (void *)(user_addr_t)baseaddr; uio->uio_iovcnt++; uio->uio_resid += length; - return(0); + return (0); } } - return(-1); + return (-1); } -int uio_isuserspace(uio_t *uio) +int +uio_isuserspace(uio_t *uio) { ASSERT(uio != NULL); if (uio->uio_segflg == UIO_USERSPACE) - return 1; - return 0; + return (1); + return (0); } -int uio_getiov(uio_t *uio, int index, user_addr_t *baseaddr, user_size_t *length) +int +uio_getiov(uio_t *uio, int index, user_addr_t *baseaddr, user_size_t *length) { ASSERT(uio != NULL); ASSERT(uio->uio_iov != NULL); if (index < 0 || index >= uio->uio_iovcnt) { - return(-1); + return (-1); } if (baseaddr != NULL) { - *baseaddr = (user_addr_t) uio->uio_iov[index].iov_base; + *baseaddr = (user_addr_t)uio->uio_iov[index].iov_base; } if (length != NULL) { *length = uio->uio_iov[index].iov_len; } - return 0; + return (0); } -int uio_iovcnt(uio_t *uio) +int +uio_iovcnt(uio_t *uio) { - if (uio == NULL) { - return(0); - } + if (uio == NULL) + return (0); - return(uio->uio_iovcnt); + return (uio->uio_iovcnt); } -off_t uio_offset(uio_t *uio) +off_t +uio_offset(uio_t *uio) { ASSERT(uio != NULL); ASSERT(uio->uio_iov != NULL); - if (uio == NULL) { - return(0); - } + if (uio == NULL) + return (0); - return(uio->uio_offset); + return (uio->uio_offset); } /* * This function is modelled after OsX, which means you can only pass * in a value between 0 and current "iov_len". Any larger number will * ignore the extra bytes. -*/ -void uio_update(uio_t *uio, user_size_t count) + */ +void +uio_update(uio_t *uio, user_size_t count) { uint32_t ind; - if (uio == NULL || uio->uio_iovcnt < 1) { + if (uio == NULL || uio->uio_iovcnt < 1) return; - } ASSERT(uio->uio_index < uio->uio_iovcnt); @@ -162,16 +168,14 @@ void uio_update(uio_t *uio, user_size_t count) if (count > uio->uio_iov->iov_len) { uio->uio_iov[ind].iov_base += uio->uio_iov[ind].iov_len; uio->uio_iov[ind].iov_len = 0; - } - else { + } else { uio->uio_iov[ind].iov_base += count; uio->uio_iov[ind].iov_len -= count; } if (count > (user_size_t)uio->uio_resid) { uio->uio_offset += uio->uio_resid; uio->uio_resid = 0; - } - else { + } else { uio->uio_offset += count; uio->uio_resid -= count; } @@ -185,98 +189,99 @@ void uio_update(uio_t *uio, user_size_t count) } } - -uint64_t uio_resid(uio_t *uio) +uint64_t +uio_resid(uio_t *uio) { - if (uio == NULL) { - return(0); - } + if (uio == NULL) + return (0); - return(uio->uio_resid); + return (uio->uio_resid); } -user_addr_t uio_curriovbase(uio_t *uio) +user_addr_t +uio_curriovbase(uio_t *uio) { - if (uio == NULL || uio->uio_iovcnt < 1) { - return(0); - } + if (uio == NULL || uio->uio_iovcnt < 1) + return (0); - return((user_addr_t)uio->uio_iov[uio->uio_index].iov_base); + return ((user_addr_t)uio->uio_iov[uio->uio_index].iov_base); } -user_size_t uio_curriovlen(uio_t *a_uio) +user_size_t +uio_curriovlen(uio_t *a_uio) { - if (a_uio == NULL || a_uio->uio_iovcnt < 1) { - return(0); - } + if (a_uio == NULL || a_uio->uio_iovcnt < 1) + return (0); - return((user_size_t)a_uio->uio_iov[a_uio->uio_index].iov_len); + return ((user_size_t)a_uio->uio_iov[a_uio->uio_index].iov_len); } -void uio_setoffset(uio_t *uio, off_t offset) +void +uio_setoffset(uio_t *uio, off_t offset) { - if (uio == NULL) { + if (uio == NULL) return; - } + uio->uio_offset = offset; } -int uio_rw(uio_t *a_uio) +int +uio_rw(uio_t *a_uio) { - if (a_uio == NULL) { - return(-1); - } - return(a_uio->uio_rw); + if (a_uio == NULL) + return (-1); + + return (a_uio->uio_rw); } -void uio_setrw(uio_t *a_uio, int a_value) +void +uio_setrw(uio_t *a_uio, int a_value) { - if (a_uio == NULL) { + if (a_uio == NULL) return; - } if (a_value == UIO_READ || a_value == UIO_WRITE) { a_uio->uio_rw = a_value; } - return; } -int uio_spacetype(uio_t *a_uio) +int +uio_spacetype(uio_t *a_uio) { - if (a_uio == NULL) { - return(-1); - } + if (a_uio == NULL) + return (-1); - return(a_uio->uio_segflg); + return (a_uio->uio_segflg); } -uio_t *uio_duplicate(uio_t *a_uio) +uio_t * +uio_duplicate(uio_t *a_uio) { - uio_t *my_uio; - // int i; + uio_t *my_uio; - if (a_uio == NULL) { - return(NULL); - } + if (a_uio == NULL) + return (NULL); my_uio = uio_create(a_uio->uio_max_iovs, - uio_offset(a_uio), - uio_spacetype(a_uio), - uio_rw(a_uio)); + uio_offset(a_uio), + uio_spacetype(a_uio), + uio_rw(a_uio)); if (my_uio == 0) { panic("%s :%d - allocation failed\n", __FILE__, __LINE__); } - bcopy((void *)a_uio->uio_iov, (void *)my_uio->uio_iov, a_uio->uio_max_iovs * sizeof(iovec_t)); + bcopy((void *)a_uio->uio_iov, (void *)my_uio->uio_iov, + a_uio->uio_max_iovs * sizeof (iovec_t)); my_uio->uio_index = a_uio->uio_index; my_uio->uio_resid = a_uio->uio_resid; my_uio->uio_iovcnt = a_uio->uio_iovcnt; - return(my_uio); + return (my_uio); } -int spl_uiomove(const uint8_t *c_cp, uint32_t n, struct uio *uio) +int +spl_uiomove(const uint8_t *c_cp, uint32_t n, struct uio *uio) { const uint8_t *cp = c_cp; uint64_t acnt; @@ -294,11 +299,11 @@ int spl_uiomove(const uint8_t *c_cp, uint32_t n, struct uio *uio) switch ((int)uio->uio_segflg) { case UIO_SYSSPACE: if (uio->uio_rw == UIO_READ) - /*error =*/ bcopy(cp, uio->uio_iov[uio->uio_index].iov_base, - acnt); + bcopy(cp, uio->uio_iov[uio->uio_index].iov_base, + acnt); else - /*error =*/ bcopy(uio->uio_iov[uio->uio_index].iov_base, (void *)cp, - acnt); + bcopy(uio->uio_iov[uio->uio_index].iov_base, + (void *)cp, acnt); break; default: break; @@ -310,4 +315,3 @@ int spl_uiomove(const uint8_t *c_cp, uint32_t n, struct uio *uio) ASSERT0(n); return (error); } - diff --git a/module/os/windows/spl/spl-vmem.c b/module/os/windows/spl/spl-vmem.c index 8615d7aa054..57871d4a8c3 100644 --- a/module/os/windows/spl/spl-vmem.c +++ b/module/os/windows/spl/spl-vmem.c @@ -222,14 +222,11 @@ #include #include #include -//#include -//#include #include #define VMEM_INITIAL 21 /* early vmem arenas */ -#define VMEM_SEG_INITIAL 800 -//200 //400 /* early segments */ +#define VMEM_SEG_INITIAL 800 /* early segments */ /* * Adding a new span to an arena requires two segment structures: one to @@ -335,15 +332,14 @@ static vmem_t *vmem_hash_arena; static vmem_t *vmem_vmem_arena; vmem_t *spl_default_arena; // The bottom-most arena for SPL static vmem_t *spl_default_arena_parent; // dummy arena as a placeholder -#define VMEM_BUCKETS 13 -#define VMEM_BUCKET_LOWBIT 12 -#define VMEM_BUCKET_HIBIT 24 +#define VMEM_BUCKETS 13 +#define VMEM_BUCKET_LOWBIT 12 +#define VMEM_BUCKET_HIBIT 24 static vmem_t *vmem_bucket_arena[VMEM_BUCKETS]; vmem_t *spl_heap_arena; static void *spl_heap_arena_initial_alloc; static uint32_t spl_heap_arena_initial_alloc_size = 0; -#define NUMBER_OF_ARENAS_IN_VMEM_INIT 21 -//static struct timespec vmem_update_interval = {15, 0}; /* vmem_update() every 15 seconds */ +#define NUMBER_OF_ARENAS_IN_VMEM_INIT 21 uint32_t vmem_mtbf; /* mean time between failures [default: off] */ uint32_t vmem_seg_size = sizeof (vmem_seg_t); @@ -389,7 +385,7 @@ vmem_seg_t *_vnext = (vsp)->vs_##type##next; \ (_vnext)->vs_##type##prev = (_vprev); \ } -/// vmem thread block count +// vmem thread block count uint64_t spl_vmem_threads_waiting = 0; // number of allocations > minalloc @@ -434,12 +430,14 @@ uint64_t spl_bucket_tunable_small_span = 0; // for XAT & XATB visibility into VBA queue static _Atomic uint32_t spl_vba_threads[VMEM_BUCKETS] = { 0 }; -static uint32_t vmem_bucket_id_to_bucket_number[NUMBER_OF_ARENAS_IN_VMEM_INIT] = { 0 }; +static uint32_t + vmem_bucket_id_to_bucket_number[NUMBER_OF_ARENAS_IN_VMEM_INIT] = { 0 }; boolean_t spl_arc_no_grow(uint32_t, boolean_t, kmem_cache_t **); _Atomic uint64_t spl_arc_no_grow_bits = 0; uint64_t spl_arc_no_grow_count = 0; -uint64_t spl_frag_max_walk = 1000; // compare span ages this many steps from the head of the freelist +// compare span ages this many steps from the head of the freelist +uint64_t spl_frag_max_walk = 1000; uint64_t spl_frag_walked_out = 0; uint64_t spl_frag_walk_cnt = 0; @@ -523,10 +521,11 @@ flist_sort_compare(boolean_t newfirst, const vmem_seg_t *nextlist, vmem_seg_t *p, vmem_seg_t *to_insert) { - /* vsp is the segment we are inserting into the freelist + /* + * vsp is the segment we are inserting into the freelist * p is a freelist poniter or an element inside a non-empty freelist * if we return false, then vsp is inserted immedaitely after p, - */ + */ // always enter the for loop if we're at the front of a flist if (p == vhead) @@ -542,7 +541,8 @@ flist_sort_compare(boolean_t newfirst, } if (n->vs_import == B_TRUE && to_insert->vs_import == B_FALSE) { - /* put non-imported segments before imported segments + /* + * put non-imported segments before imported segments * no matter what their respective create times are, * thereby making imported segments more likely "age out" */ @@ -573,33 +573,36 @@ vmem_freelist_insert_sort_by_time(vmem_t *vmp, vmem_seg_t *vsp) const boolean_t newfirst = 0 == (vmp->vm_cflags & VMC_OLDFIRST); const uint64_t abs_max_walk_steps = 1ULL << 30ULL; - uint32_t max_walk_steps = (uint32_t)MIN(spl_frag_max_walk, abs_max_walk_steps); + uint32_t max_walk_steps = + (uint32_t)MIN(spl_frag_max_walk, abs_max_walk_steps); vmem_seg_t *vprev; ASSERT(*VMEM_HASH(vmp, vsp->vs_start) != vsp); - // in vmem_create_common() the freelists are arranged: - // freelist[0].vs_kprev = NULL, freelist[VMEM_FREELISTS].vs_knext = NULL - // freelist[1].vs_kprev = freelist[0], freelist[1].vs_knext = freelist[2] ... - - // from vmem_freelist_insert(): - // VS_SIZE is the segment size (->vs_end - ->vs_start), so say 8k-512 - // highbit is the higest bit set PLUS 1, so in this case would be the 16k list. - // so below, vprev is therefore pointing to the 8k list - - // in vmem_alloc, the unconstrained allocation takes, for a 8k-512 block: - // vsp = flist[8k].vs_knext - // and calls vmem_seg_create() which sends any leftovers from vsp to vmem_freelist_insert - - // vmem_freelist_insert would take the seg (as above, 8k-512 size), vprev points to the - // 16k list, and VMEM_INSERT(vprev, vsp, k) inserts the segment immediately after - - // so vmem_seg_create(...8k-512...) pushes to the head of the 8k list, - // and vmem_alloc(...8-512k...) will pull from the head of the 8k list - - // below we may want to push to the TAIL of the 8k list, which is - // just before flist[16k]. +// in vmem_create_common() the freelists are arranged: +// freelist[0].vs_kprev = NULL, freelist[VMEM_FREELISTS].vs_knext = NULL +// freelist[1].vs_kprev = freelist[0], freelist[1].vs_knext = freelist[2] ... +// +// from vmem_freelist_insert(): +// VS_SIZE is the segment size (->vs_end - ->vs_start), so say 8k-512 +// highbit is the higest bit set PLUS 1, so in this case would be the 16k list. +// so below, vprev is therefore pointing to the 8k list +// +// in vmem_alloc, the unconstrained allocation takes, for a 8k-512 block: +// vsp = flist[8k].vs_knext +// and calls vmem_seg_create() which sends any leftovers from vsp +// to vmem_freelist_insert +// +// vmem_freelist_insert would take the seg (as above, 8k-512 size), +// vprev points to the 16k list, and VMEM_INSERT(vprev, vsp, k) +// inserts the segment immediately after +// +// so vmem_seg_create(...8k-512...) pushes to the head of the 8k list, +// and vmem_alloc(...8-512k...) will pull from the head of the 8k list + +// below we may want to push to the TAIL of the 8k list, which is +// just before flist[16k]. vprev = (vmem_seg_t *)&vmp->vm_freelist[highbit(VS_SIZE(vsp)) - 1]; @@ -610,12 +613,14 @@ vmem_freelist_insert_sort_by_time(vmem_t *vmp, vmem_seg_t *vsp) int next_listnum = my_listnum + 1; - const vmem_seg_t *nextlist = (vmem_seg_t *)&vmp->vm_freelist[next_listnum]; + const vmem_seg_t *nextlist = + (vmem_seg_t *)&vmp->vm_freelist[next_listnum]; ASSERT(vsp->vs_span_createtime != 0); if (vsp->vs_span_createtime == 0) { - TraceEvent(TRACE_WARNING, "SPL: %s: WARNING: vsp->vs_span_createtime == 0 (%s)!\n", - __func__, vmp->vm_name); + TraceEvent(TRACE_WARNING, + "SPL: %s: WARNING: vsp->vs_span_createtime == 0 (%s)!\n", + __func__, vmp->vm_name); } // continuing our example, starts with p at flist[8k] @@ -631,26 +636,19 @@ vmem_freelist_insert_sort_by_time(vmem_t *vmp, vmem_seg_t *vsp) // then insert before that segment. for (uint32_t step = 0; - flist_sort_compare(newfirst, vhead, nextlist, p, vsp) == B_TRUE; - step++) { + flist_sort_compare(newfirst, vhead, nextlist, p, vsp) == B_TRUE; + step++) { // iterating while predecessor pointer p was created // at a later tick than funcarg vsp. // // below we set p to n and update n. ASSERT(n != NULL); if (n == nextlist) { - //dprintf("SPL: %s: at marker (%s)(steps: %u) p->vs_start, end == %lu, %lu\n", - // __func__, vmp->vm_name, step, - // (uintptr_t)p->vs_start, (uintptr_t)p->vs_end); - // IOSleep(1); // the next entry is the next marker (e.g. 16k marker) break; } if (n->vs_start == 0) { // from vmem_freelist_delete, this is a head - //dprintf("SPL: %s: n->vs_start == 0 (%s)(steps: %u) p->vs_start, end == %lu, %lu\n", - // __func__, vmp->vm_name, step, - // (uintptr_t)p->vs_start, (uintptr_t)p->vs_end); // IOSleep(1); break; } @@ -662,14 +660,11 @@ vmem_freelist_insert_sort_by_time(vmem_t *vmp, vmem_seg_t *vsp) n = (vmem_seg_t *)nextlist; p = nextlist->vs_kprev; } - //dprintf("SPL: %s: walked out (%s)\n", __func__, vmp->vm_name); // IOSleep(1); atomic_inc_64(&spl_frag_walked_out); break; } if (n->vs_knext == NULL) { - //dprintf("SPL: %s: n->vs_knext == NULL (my_listnum == %d)\n", - // __func__, my_listnum); // IOSleep(1); break; } @@ -681,7 +676,6 @@ vmem_freelist_insert_sort_by_time(vmem_t *vmp, vmem_seg_t *vsp) ASSERT(p != NULL); // insert segment between p and n - vsp->vs_type = VMEM_FREE; vmp->vm_freemap |= VS_SIZE(vprev); VMEM_INSERT(p, vsp, k); @@ -747,10 +741,9 @@ vmem_hash_insert(vmem_t *vmp, vmem_seg_t *vsp) *bucket = vsp; if (vmem_seg_size == sizeof (vmem_seg_t)) { - // vsp->vs_depth = (uint8_t)getpcstack(vsp->vs_stack, - // VMEM_STACK_DEPTH); - // vsp->vs_thread = curthread; - + // vsp->vs_depth = (uint8_t)getpcstack(vsp->vs_stack, + // VMEM_STACK_DEPTH); + // vsp->vs_thread = curthread; vsp->vs_depth = 0; vsp->vs_thread = 0; vsp->vs_timestamp = gethrtime(); @@ -781,10 +774,12 @@ vmem_hash_delete(vmem_t *vmp, uintptr_t addr, uint32_t size) } if (vsp == NULL) - panic("vmem_hash_delete(%p, %lx, %lu): bad free (name: %s, addr, size)", + panic("vmem_hash_delete(%p, %lx, %lu): bad free " + "(name: %s, addr, size)", (void *)vmp, addr, size, vmp->vm_name); if (VS_SIZE(vsp) != size) - panic("vmem_hash_delete(%p, %lx, %lu): (%s) wrong size (expect %lu)", + panic("vmem_hash_delete(%p, %lx, %lu): (%s) " + "wrong size (expect %lu)", (void *)vmp, addr, size, vmp->vm_name, VS_SIZE(vsp)); vmp->vm_kstat.vk_free.value.ui64++; @@ -871,7 +866,7 @@ static void vmem_span_destroy(vmem_t *vmp, vmem_seg_t *vsp) { vmem_seg_t *span = vsp->vs_aprev; - uint32_t size = (uint32_t) VS_SIZE(vsp); + uint32_t size = (uint32_t)VS_SIZE(vsp); ASSERT(MUTEX_HELD(&vmp->vm_lock)); ASSERT(span->vs_type == VMEM_SPAN); @@ -931,7 +926,8 @@ vmem_seg_alloc(vmem_t *vmp, vmem_seg_t *vsp, uintptr_t addr, uint32_t size) } if (vs_start != addr) { - vmem_seg_t *v = vmem_seg_create(vmp, vsp->vs_aprev, vs_start, addr); + vmem_seg_t *v = + vmem_seg_create(vmp, vsp->vs_aprev, vs_start, addr); v->vs_span_createtime = parent_seg_span_createtime; vmem_freelist_insert(vmp, v); } @@ -953,9 +949,9 @@ int vmem_is_populator() { return (mutex_owner(&vmem_sleep_lock) == curthread || - mutex_owner(&vmem_nosleep_lock) == curthread || - mutex_owner(&vmem_pushpage_lock) == curthread || - mutex_owner(&vmem_panic_lock) == curthread); + mutex_owner(&vmem_nosleep_lock) == curthread || + mutex_owner(&vmem_pushpage_lock) == curthread || + mutex_owner(&vmem_panic_lock) == curthread); } /* @@ -1026,7 +1022,7 @@ vmem_populate(vmem_t *vmp, int vmflag) mutex_enter(&vmem_populator[i]->vm_lock); while (vmem_populator[i]->vm_nsegfree < VMEM_POPULATE_RESERVE) vmem_putseg(vmem_populator[i], - (vmem_seg_t *)(p + --nseg * vmem_seg_size)); + (vmem_seg_t *)(p + --nseg * vmem_seg_size)); mutex_exit(&vmem_populator[i]->vm_lock); } @@ -1072,7 +1068,8 @@ vmem_advance(vmem_t *vmp, vmem_seg_t *walker, vmem_seg_t *afterme) if (vprev->vs_type == VMEM_FREE) { if (vnext->vs_type == VMEM_FREE) { ASSERT(vprev->vs_end == vnext->vs_start); - ASSERT(vprev->vs_span_createtime == vnext->vs_span_createtime); + ASSERT(vprev->vs_span_createtime == + vnext->vs_span_createtime); vmem_freelist_delete(vmp, vnext); vmem_freelist_delete(vmp, vprev); vprev->vs_end = vnext->vs_end; @@ -1089,9 +1086,9 @@ vmem_advance(vmem_t *vmp, vmem_seg_t *walker, vmem_seg_t *afterme) * in which case we must return it to the source. */ if (vsp != NULL && vsp->vs_aprev->vs_import && - vmp->vm_source_free != NULL && - vsp->vs_aprev->vs_type == VMEM_SPAN && - vsp->vs_anext->vs_type == VMEM_SPAN) { + vmp->vm_source_free != NULL && + vsp->vs_aprev->vs_type == VMEM_SPAN && + vsp->vs_anext->vs_type == VMEM_SPAN) { void *vaddr = (void *)vsp->vs_start; uint32_t size = (uint32_t)VS_SIZE(vsp); ASSERT(size == VS_SIZE(vsp->vs_aprev)); @@ -1138,14 +1135,15 @@ vmem_nextfit_alloc(vmem_t *vmp, uint32_t size, int vmflag) */ rotor = &vmp->vm_rotor; vsp = rotor->vs_anext; - if (vsp->vs_type == VMEM_FREE && (vs_size = (uint32_t)VS_SIZE(vsp)) > realsize && - P2SAMEHIGHBIT(vs_size, vs_size - realsize)) { + if (vsp->vs_type == VMEM_FREE && + (vs_size = (uint32_t)VS_SIZE(vsp)) > realsize && + P2SAMEHIGHBIT(vs_size, vs_size - realsize)) { ASSERT(highbit(vs_size) == highbit(vs_size - realsize)); addr = vsp->vs_start; vsp->vs_start = addr + realsize; hrtime_t t = vsp->vs_span_createtime; vmem_hash_insert(vmp, - vmem_seg_create(vmp, rotor->vs_aprev, addr, addr + size)); + vmem_seg_create(vmp, rotor->vs_aprev, addr, addr + size)); vsp->vs_span_createtime = t; mutex_exit(&vmp->vm_lock); return ((void *)addr); @@ -1182,20 +1180,24 @@ vmem_nextfit_alloc(vmem_t *vmp, uint32_t size, int vmflag) (vmflag & VM_NOSLEEP)) { mutex_exit(&vmp->vm_lock); return (vmem_xalloc(vmp, size, vmp->vm_quantum, - 0, 0, NULL, NULL, vmflag & (VM_KMFLAGS | VM_NEXTFIT))); + 0, 0, NULL, NULL, + vmflag & (VM_KMFLAGS | VM_NEXTFIT))); } atomic_inc_64(&vmp->vm_kstat.vk_wait.value.ui64); - atomic_inc_64(&vmp->vm_kstat.vk_threads_waiting.value.ui64); + atomic_inc_64( + &vmp->vm_kstat.vk_threads_waiting.value.ui64); atomic_inc_64(&spl_vmem_threads_waiting); if (spl_vmem_threads_waiting > 1) - dprintf("SPL: %s: waiting for %lu sized alloc after full circle of %s, " - "waiting threads %llu, total threads waiting = %llu.\n", + dprintf("SPL: %s: waiting for %lu sized alloc " + "after full circle of %s, waiting threads " + "%llu, total threads waiting = %llu.\n", __func__, size, vmp->vm_name, vmp->vm_kstat.vk_threads_waiting.value.ui64, spl_vmem_threads_waiting); cv_wait(&vmp->vm_cv, &vmp->vm_lock); atomic_dec_64(&spl_vmem_threads_waiting); - atomic_dec_64(&vmp->vm_kstat.vk_threads_waiting.value.ui64); + atomic_dec_64( + &vmp->vm_kstat.vk_threads_waiting.value.ui64); vsp = rotor->vs_anext; } } @@ -1258,7 +1260,6 @@ vmem_canalloc_atomic(vmem_t *vmp, uint32_t size) int hb; int flist = 0; - //ulong_t freemap = __c11_atomic_load((_Atomic ulong_t *)&vmp->vm_freemap, __ATOMIC_SEQ_CST); ulong_t freemap = InterlockedOr((volatile long *)&vmp->vm_freemap, 0); if (ISP2(size)) @@ -1293,7 +1294,7 @@ spl_vmem_xnu_useful_bytes_free(void) uint64_t vmem_xnu_useful_bytes_free(void) { - return(spl_vmem_xnu_useful_bytes_free()); + return (spl_vmem_xnu_useful_bytes_free()); } @@ -1303,7 +1304,7 @@ spl_vmem_malloc_unconditionally_unlocked(uint32_t size) extern void *osif_malloc(uint64_t); atomic_inc_64(&spl_vmem_unconditional_allocs); atomic_add_64(&spl_vmem_unconditional_alloc_bytes, size); - return(osif_malloc(size)); + return (osif_malloc(size)); } static void * @@ -1321,7 +1322,8 @@ spl_vmem_malloc_if_no_pressure(uint32_t size) // The mutex serializes concurrent callers, providing time for // the variables in spl_vmem_xnu_useful_bytes_free() to be updated. mutex_enter(&vmem_xnu_alloc_lock); - if (spl_vmem_xnu_useful_bytes_free() > (MAX(size,16ULL*1024ULL*1024ULL))) { + if (spl_vmem_xnu_useful_bytes_free() > + (MAX(size, 16ULL*1024ULL*1024ULL))) { extern void *osif_malloc(uint64_t); void *p = osif_malloc(size); if (p != NULL) { @@ -1345,7 +1347,7 @@ spl_vmem_malloc_if_no_pressure(uint32_t size) */ void * vmem_xalloc(vmem_t *vmp, uint32_t size, uint32_t align_arg, uint32_t phase, - uint32_t nocross, void *minaddr, void *maxaddr, int vmflag) + uint32_t nocross, void *minaddr, void *maxaddr, int vmflag) { vmem_seg_t *vsp; vmem_seg_t *vbest = NULL; @@ -1358,34 +1360,34 @@ vmem_xalloc(vmem_t *vmp, uint32_t size, uint32_t align_arg, uint32_t phase, if ((align | phase | nocross) & (vmp->vm_quantum - 1)) panic("vmem_xalloc(%p, %lu, %lu, %lu, %lu, %p, %p, %x): " - "parameters not vm_quantum aligned", - (void *)vmp, size, align_arg, phase, nocross, - minaddr, maxaddr, vmflag); + "parameters not vm_quantum aligned", + (void *)vmp, size, align_arg, phase, nocross, + minaddr, maxaddr, vmflag); if (nocross != 0 && - (align > nocross || P2ROUNDUP(phase + size, align) > nocross)) + (align > nocross || P2ROUNDUP(phase + size, align) > nocross)) panic("vmem_xalloc(%p, %lu, %lu, %lu, %lu, %p, %p, %x): " - "overconstrained allocation", - (void *)vmp, size, align_arg, phase, nocross, - minaddr, maxaddr, vmflag); + "overconstrained allocation", + (void *)vmp, size, align_arg, phase, nocross, + minaddr, maxaddr, vmflag); if (phase >= align || (align & (align - 1)) != 0 || - (nocross & (nocross - 1)) != 0) + (nocross & (nocross - 1)) != 0) panic("vmem_xalloc(%p, %lu, %lu, %lu, %lu, %p, %p, %x): " - "parameters inconsistent or invalid", - (void *)vmp, size, align_arg, phase, nocross, - minaddr, maxaddr, vmflag); + "parameters inconsistent or invalid", + (void *)vmp, size, align_arg, phase, nocross, + minaddr, maxaddr, vmflag); if ((mtbf = vmem_mtbf | vmp->vm_mtbf) != 0 && gethrtime() % mtbf == 0 && - (vmflag & (VM_NOSLEEP | VM_PANIC)) == VM_NOSLEEP) + (vmflag & (VM_NOSLEEP | VM_PANIC)) == VM_NOSLEEP) return (NULL); mutex_enter(&vmp->vm_lock); for (;;) { if (vmp->vm_nsegfree < VMEM_MINFREE && - !vmem_populate(vmp, vmflag)) + !vmem_populate(vmp, vmflag)) break; - do_alloc: +do_alloc: /* * highbit() returns the highest bit + 1, which is exactly * what we want: we want to search the first freelist whose @@ -1409,15 +1411,15 @@ vmem_xalloc(vmem_t *vmp, uint32_t size, uint32_t align_arg, uint32_t phase, } else { hb = highbit(size); if ((vmp->vm_freemap >> hb) == 0 || - hb == VMEM_FREELISTS || - (vmflag & (VM_BESTFIT | VM_FIRSTFIT))) + hb == VMEM_FREELISTS || + (vmflag & (VM_BESTFIT | VM_FIRSTFIT))) hb--; flist = lowbit(P2ALIGN(vmp->vm_freemap, 1UL << hb)); } for (vbest = NULL, vsp = (flist == 0) ? NULL : - vmp->vm_freelist[flist - 1].vs_knext; - vsp != NULL; vsp = vsp->vs_knext) { + vmp->vm_freelist[flist - 1].vs_knext; + vsp != NULL; vsp = vsp->vs_knext) { atomic_inc_64(&vmp->vm_kstat.vk_search.value.ui64); if (vsp->vs_start == 0) { /* @@ -1431,7 +1433,7 @@ vmem_xalloc(vmem_t *vmp, uint32_t size, uint32_t align_arg, uint32_t phase, * Find the next non-empty freelist. */ flist = lowbit(P2ALIGN(vmp->vm_freemap, - VS_SIZE(vsp))); + VS_SIZE(vsp))); if (flist-- == 0) break; vsp = (vmem_seg_t *)&vmp->vm_freelist[flist]; @@ -1447,9 +1449,9 @@ vmem_xalloc(vmem_t *vmp, uint32_t size, uint32_t align_arg, uint32_t phase, taddr = P2PHASEUP(start, align, phase); if (P2BOUNDARY(taddr, size, nocross)) taddr += - P2ROUNDUP(P2NPHASE(taddr, nocross), align); + P2ROUNDUP(P2NPHASE(taddr, nocross), align); if ((taddr - start) + size > end - start || - (vbest != NULL && VS_SIZE(vsp) >= VS_SIZE(vbest))) + (vbest != NULL && VS_SIZE(vsp) >= VS_SIZE(vbest))) continue; vbest = vsp; addr = taddr; @@ -1462,15 +1464,16 @@ vmem_xalloc(vmem_t *vmp, uint32_t size, uint32_t align_arg, uint32_t phase, if (size == 0) panic("vmem_xalloc(): size == 0"); if (vmp->vm_source_alloc != NULL && nocross == 0 && - minaddr == NULL && maxaddr == NULL) { + minaddr == NULL && maxaddr == NULL) { uint32_t aneeded, asize; uint32_t aquantum = MAX(vmp->vm_quantum, - vmp->vm_source->vm_quantum); + vmp->vm_source->vm_quantum); uint32_t aphase = phase; if ((align > aquantum) && - !(vmp->vm_cflags & VMC_XALIGN)) { - aphase = (uint32_t) ((P2PHASE(phase, aquantum) != 0) ? - align - vmp->vm_quantum : align - aquantum); + !(vmp->vm_cflags & VMC_XALIGN)) { + aphase = + (uint32_t)((P2PHASE(phase, aquantum) != 0) ? + align - vmp->vm_quantum : align - aquantum); ASSERT(aphase >= phase); } aneeded = MAX(size + aphase, vmp->vm_min_import); @@ -1483,7 +1486,7 @@ vmem_xalloc(vmem_t *vmp, uint32_t size, uint32_t align_arg, uint32_t phase, * (and explicitly panic if we aren't). */ if ((vmflag & VM_NOSLEEP) && - !(vmflag & VM_PANIC)) { + !(vmflag & VM_PANIC)) { mutex_exit(&vmp->vm_lock); return (NULL); } @@ -1499,11 +1502,11 @@ vmem_xalloc(vmem_t *vmp, uint32_t size, uint32_t align_arg, uint32_t phase, */ if (size == asize && !(vmp->vm_cflags & VMC_XALLOC)) resv = VMEM_SEGS_PER_SPAN_CREATE + - VMEM_SEGS_PER_EXACT_ALLOC; + VMEM_SEGS_PER_EXACT_ALLOC; else if (phase == 0 && - align <= vmp->vm_source->vm_quantum) + align <= vmp->vm_source->vm_quantum) resv = VMEM_SEGS_PER_SPAN_CREATE + - VMEM_SEGS_PER_LEFT_ALLOC; + VMEM_SEGS_PER_LEFT_ALLOC; else resv = VMEM_SEGS_PER_ALLOC_MAX; @@ -1511,17 +1514,19 @@ vmem_xalloc(vmem_t *vmp, uint32_t size, uint32_t align_arg, uint32_t phase, vmp->vm_nsegfree -= resv; /* reserve our segs */ mutex_exit(&vmp->vm_lock); if (vmp->vm_cflags & VMC_XALLOC) { - //uint32_t oasize = asize; + // uint32_t oasize = asize; vaddr = ((vmem_ximport_t *) - vmp->vm_source_alloc)(vmp->vm_source, - &asize, (uint32_t) align, vmflag & VM_KMFLAGS); - //ASSERT(asize >= oasize); + vmp->vm_source_alloc)(vmp->vm_source, + &asize, (uint32_t)align, + vmflag & VM_KMFLAGS); + // ASSERT(asize >= oasize); ASSERT(P2PHASE(asize, - vmp->vm_source->vm_quantum) == 0); + vmp->vm_source->vm_quantum) == 0); ASSERT(!(vmp->vm_cflags & VMC_XALIGN) || IS_P2ALIGNED(vaddr, align)); } else { - atomic_inc_64(&vmp->vm_kstat.vk_parent_alloc.value.ui64); + atomic_inc_64( + &vmp->vm_kstat.vk_parent_alloc.value.ui64); vaddr = vmp->vm_source_alloc(vmp->vm_source, asize, vmflag & (VM_KMFLAGS | VM_NEXTFIT)); } @@ -1542,15 +1547,18 @@ vmem_xalloc(vmem_t *vmp, uint32_t size, uint32_t align_arg, uint32_t phase, // do not return the excess import, rather // wake those threads up so they can use it. if (asize > aneeded && - vmp->vm_source_free != NULL && - vmp->vm_kstat.vk_threads_waiting.value.ui64 == 0 && - vmem_canalloc(vmp, aneeded)) { + vmp->vm_source_free != NULL && + vmp->vm_kstat.vk_threads_waiting.value.ui64 + == 0 && + vmem_canalloc(vmp, aneeded)) { ASSERT(resv >= VMEM_SEGS_PER_MIDDLE_ALLOC); xvaddr = vaddr; xsize = asize; goto do_alloc; - } else if (vmp->vm_kstat.vk_threads_waiting.value.ui64 > 0) { + } else if ( + vmp->vm_kstat.vk_threads_waiting.value.ui64 + > 0) { vmp->vm_kstat.vk_excess.value.ui64++; cv_broadcast(&vmp->vm_cv); } @@ -1589,19 +1597,23 @@ vmem_xalloc(vmem_t *vmp, uint32_t size, uint32_t align_arg, uint32_t phase, atomic_inc_64(&vmp->vm_kstat.vk_threads_waiting.value.ui64); atomic_inc_64(&spl_vmem_threads_waiting); if (spl_vmem_threads_waiting > 0) { - dprintf("SPL: %s: vmem waiting for %lu sized alloc for %s, " - "waiting threads %llu, total threads waiting = %llu\n", + dprintf("SPL: %s: vmem waiting for %lu " + "sized alloc for %s, waiting threads " + "%llu, total threads waiting = %llu\n", __func__, size, vmp->vm_name, vmp->vm_kstat.vk_threads_waiting.value.ui64, spl_vmem_threads_waiting); - extern int64_t spl_free_set_and_wait_pressure(int64_t, boolean_t, clock_t); - extern int64_t spl_free_manual_pressure_wrapper(void); +extern int64_t spl_free_set_and_wait_pressure(int64_t, boolean_t, clock_t); +extern int64_t spl_free_manual_pressure_wrapper(void); mutex_exit(&vmp->vm_lock); - spl_free_set_pressure(0); // release other waiting threads - int64_t target_pressure = size * spl_vmem_threads_waiting; - int64_t delivered_pressure = spl_free_set_and_wait_pressure(target_pressure, + spl_free_set_pressure(0); + int64_t target_pressure = + size * spl_vmem_threads_waiting; + int64_t delivered_pressure = + spl_free_set_and_wait_pressure(target_pressure, TRUE, USEC2NSEC(500)); - dprintf("SPL: %s: pressure %lld targeted, %lld delivered\n", + dprintf( + "SPL: %s: pressure %lld targeted, %lld delivered\n", __func__, target_pressure, delivered_pressure); mutex_enter(&vmp->vm_lock); } @@ -1615,7 +1627,7 @@ vmem_xalloc(vmem_t *vmp, uint32_t size, uint32_t align_arg, uint32_t phase, /* re-position to end of buffer */ if (vmflag & VM_ENDALLOC) { addr += ((vbest->vs_end - (addr + size)) / align) * - align; + align; } (void) vmem_seg_alloc(vmp, vbest, addr, size); mutex_exit(&vmp->vm_lock); @@ -1635,9 +1647,9 @@ vmem_xalloc(vmem_t *vmp, uint32_t size, uint32_t align_arg, uint32_t phase, mutex_exit(&vmp->vm_lock); if (vmflag & VM_PANIC) panic("vmem_xalloc(%p, %lu, %lu, %lu, %lu, %p, %p, %x): " - "cannot satisfy mandatory allocation", - (void *)vmp, size, align_arg, phase, nocross, - minaddr, maxaddr, vmflag); + "cannot satisfy mandatory allocation", + (void *)vmp, size, align_arg, phase, nocross, + minaddr, maxaddr, vmflag); ASSERT(xvaddr == NULL); return (NULL); } @@ -1684,10 +1696,10 @@ vmem_xfree(vmem_t *vmp, void *vaddr, uint32_t size) * If the entire span is free, return it to the source. */ if (vsp->vs_aprev->vs_import && vmp->vm_source_free != NULL && - vsp->vs_aprev->vs_type == VMEM_SPAN && - vsp->vs_anext->vs_type == VMEM_SPAN) { + vsp->vs_aprev->vs_type == VMEM_SPAN && + vsp->vs_anext->vs_type == VMEM_SPAN) { vaddr = (void *)vsp->vs_start; - size = (uint32_t) VS_SIZE(vsp); + size = (uint32_t)VS_SIZE(vsp); ASSERT(size == VS_SIZE(vsp->vs_aprev)); vmem_span_destroy(vmp, vsp); vmp->vm_kstat.vk_parent_free.value.ui64++; @@ -1717,10 +1729,10 @@ vmem_alloc(vmem_t *vmp, uint32_t size, int vmflag) if (size - 1 < vmp->vm_qcache_max) return (kmem_cache_alloc(vmp->vm_qcache[(size - 1) >> - vmp->vm_qshift], vmflag & VM_KMFLAGS)); + vmp->vm_qshift], vmflag & VM_KMFLAGS)); if ((mtbf = vmem_mtbf | vmp->vm_mtbf) != 0 && gethrtime() % mtbf == 0 && - (vmflag & (VM_NOSLEEP | VM_PANIC)) == VM_NOSLEEP) + (vmflag & (VM_NOSLEEP | VM_PANIC)) == VM_NOSLEEP) return (NULL); if (vmflag & VM_NEXTFIT) @@ -1728,7 +1740,7 @@ vmem_alloc(vmem_t *vmp, uint32_t size, int vmflag) if (vmflag & (VM_BESTFIT | VM_FIRSTFIT)) return (vmem_xalloc(vmp, size, vmp->vm_quantum, 0, 0, - NULL, NULL, vmflag)); + NULL, NULL, vmflag)); if (vmp->vm_cflags & VM_NEXTFIT) return (vmem_nextfit_alloc(vmp, size, vmflag)); @@ -1747,7 +1759,7 @@ vmem_alloc(vmem_t *vmp, uint32_t size, int vmflag) if (flist-- == 0) { mutex_exit(&vmp->vm_lock); return (vmem_xalloc(vmp, size, vmp->vm_quantum, - 0, 0, NULL, NULL, vmflag)); + 0, 0, NULL, NULL, vmflag)); } ASSERT(size <= (1UL << flist)); @@ -1805,7 +1817,7 @@ vmem_add(vmem_t *vmp, void *vaddr, uint32_t size, int vmflag) { if (vaddr == NULL || size == 0) panic("vmem_add(%p, %p, %lu): bad arguments", - (void *)vmp, vaddr, size); + (void *)vmp, vaddr, size); ASSERT(!vmem_contains(vmp, vaddr, size)); @@ -1828,7 +1840,7 @@ vmem_add(vmem_t *vmp, void *vaddr, uint32_t size, int vmflag) */ void vmem_walk(vmem_t *vmp, int typemask, - void (*func)(void *, void *, uint32_t), void *arg) + void (*func)(void *, void *, uint32_t), void *arg) { vmem_seg_t *vsp; vmem_seg_t *seg0 = &vmp->vm_seg0; @@ -1845,7 +1857,7 @@ vmem_walk(vmem_t *vmp, int typemask, for (vsp = seg0->vs_anext; vsp != seg0; vsp = vsp->vs_anext) { if (vsp->vs_type & typemask) { void *start = (void *)vsp->vs_start; - uint32_t size = (uint32_t) VS_SIZE(vsp); + uint32_t size = (uint32_t)VS_SIZE(vsp); if (typemask & VMEM_REENTRANT) { vmem_advance(vmp, &walker, vsp); mutex_exit(&vmp->vm_lock); @@ -1904,10 +1916,12 @@ vmem_size_semi_atomic(vmem_t *vmp, int typemask) uint64_t inuse = 0; uint64_t total = 0; - //__sync_swap(&total, vmp->vm_kstat.vk_mem_total.value.ui64); - //__sync_swap(&inuse, vmp->vm_kstat.vk_mem_inuse.value.ui64); - InterlockedExchange64((volatile long long *)&total, vmp->vm_kstat.vk_mem_total.value.ui64); - InterlockedExchange64((volatile long long *)&inuse, vmp->vm_kstat.vk_mem_inuse.value.ui64); + // __sync_swap(&total, vmp->vm_kstat.vk_mem_total.value.ui64); + // __sync_swap(&inuse, vmp->vm_kstat.vk_mem_inuse.value.ui64); + InterlockedExchange64((volatile long long *)&total, + vmp->vm_kstat.vk_mem_total.value.ui64); + InterlockedExchange64((volatile long long *)&inuse, + vmp->vm_kstat.vk_mem_inuse.value.ui64); int64_t inuse_signed = (int64_t)inuse; int64_t total_signed = (int64_t)total; @@ -1920,13 +1934,13 @@ vmem_size_semi_atomic(vmem_t *vmp, int typemask) if (size < 0) size = 0; - return ((uint32_t) size); + return ((uint32_t)size); } uint32_t spl_vmem_size(vmem_t *vmp, int typemask) { - return(vmem_size_locked(vmp, typemask)); + return (vmem_size_locked(vmp, typemask)); } /* @@ -1939,10 +1953,10 @@ spl_vmem_size(vmem_t *vmp, int typemask) * of quantum up to qcache_max. */ static vmem_t * -vmem_create_common(const char *name, void *base, uint32_t size, uint32_t quantum, - void *(*afunc)(vmem_t *, uint32_t, int), - void (*ffunc)(vmem_t *, void *, uint32_t), - vmem_t *source, uint32_t qcache_max, int vmflag) +vmem_create_common(const char *name, void *base, uint32_t size, + uint32_t quantum, void *(*afunc)(vmem_t *, uint32_t, int), + void (*ffunc)(vmem_t *, void *, uint32_t), vmem_t *source, + uint32_t qcache_max, int vmflag) { int i; uint32_t nqcache; @@ -1953,7 +1967,7 @@ vmem_create_common(const char *name, void *base, uint32_t size, uint32_t quantum if (vmem_vmem_arena != NULL) { vmp = vmem_alloc(vmem_vmem_arena, sizeof (vmem_t), - vmflag & VM_KMFLAGS); + vmflag & VM_KMFLAGS); } else { ASSERT(id <= VMEM_INITIAL); vmp = &vmem0[id - 1]; @@ -1961,7 +1975,7 @@ vmem_create_common(const char *name, void *base, uint32_t size, uint32_t quantum /* An identifier arena must inherit from another identifier arena */ ASSERT(source == NULL || ((source->vm_cflags & VMC_IDENTIFIER) == - (vmflag & VMC_IDENTIFIER))); + (vmflag & VMC_IDENTIFIER))); if (vmp == NULL) return (NULL); @@ -2036,17 +2050,17 @@ vmem_create_common(const char *name, void *base, uint32_t size, uint32_t quantum vmp->vm_qcache_max = nqcache << vmp->vm_qshift; for (i = 0; i < (int)nqcache; i++) { char buf[VMEM_NAMELEN + 21]; - (void) snprintf(buf, VMEM_NAMELEN + 20, "%s_%lu", vmp->vm_name, - (i + 1) * quantum); + (void) snprintf(buf, VMEM_NAMELEN + 20, "%s_%lu", + vmp->vm_name, (i + 1) * quantum); vmp->vm_qcache[i] = kmem_cache_create(buf, - (i + 1) * quantum, quantum, NULL, NULL, NULL, - NULL, vmp, KMC_QCACHE | KMC_NOTOUCH); + (i + 1) * quantum, quantum, NULL, NULL, NULL, + NULL, vmp, KMC_QCACHE | KMC_NOTOUCH); } } if ((vmp->vm_ksp = kstat_create("vmem", vmp->vm_id, vmp->vm_name, - "vmem", KSTAT_TYPE_NAMED, sizeof (vmem_kstat_t) / - sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL)) != NULL) { + "vmem", KSTAT_TYPE_NAMED, sizeof (vmem_kstat_t) / + sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL)) != NULL) { vmp->vm_ksp->ks_data = &vmp->vm_kstat; kstat_install(vmp->vm_ksp); } @@ -2083,20 +2097,20 @@ vmem_xcreate(const char *name, void *base, uint32_t size, uint32_t quantum, vmflag &= ~(VMC_POPULATOR | VMC_XALLOC); return (vmem_create_common(name, base, size, quantum, - (vmem_alloc_t *)afunc, ffunc, source, qcache_max, - vmflag | VMC_XALLOC)); + (vmem_alloc_t *)afunc, ffunc, source, qcache_max, + vmflag | VMC_XALLOC)); } vmem_t * vmem_create(const char *name, void *base, uint32_t size, uint32_t quantum, - vmem_alloc_t *afunc, vmem_free_t *ffunc, vmem_t *source, - uint32_t qcache_max, int vmflag) + vmem_alloc_t *afunc, vmem_free_t *ffunc, vmem_t *source, + uint32_t qcache_max, int vmflag) { ASSERT(!(vmflag & (VMC_XALLOC | VMC_XALIGN))); vmflag &= ~(VMC_XALLOC | VMC_XALIGN); return (vmem_create_common(name, base, size, quantum, - afunc, ffunc, source, qcache_max, vmflag)); + afunc, ffunc, source, qcache_max, vmflag)); } /* @@ -2124,9 +2138,9 @@ vmem_destroy(vmem_t *vmp) leaked = vmem_size(vmp, VMEM_ALLOC); if (leaked != 0) - dprintf( "SPL: vmem_destroy('%s'): leaked %lu %s\n", - vmp->vm_name, leaked, (vmp->vm_cflags & VMC_IDENTIFIER) ? - "identifiers" : "bytes"); + dprintf("SPL: vmem_destroy('%s'): leaked %lu %s\n", + vmp->vm_name, leaked, (vmp->vm_cflags & VMC_IDENTIFIER) ? + "identifiers" : "bytes"); if (vmp->vm_hash_table != vmp->vm_hash0) vmem_free(vmem_hash_arena, vmp->vm_hash_table, @@ -2149,7 +2163,7 @@ vmem_destroy(vmem_t *vmp) mutex_destroy(&vmp->vm_lock); cv_destroy(&vmp->vm_cv); - vmem_free(vmem_vmem_arena, vmp, sizeof(vmem_t)); + vmem_free(vmem_vmem_arena, vmp, sizeof (vmem_t)); } @@ -2174,13 +2188,13 @@ vmem_destroy_internal(vmem_t *vmp) leaked = vmem_size(vmp, VMEM_ALLOC); if (leaked != 0) dprintf("SPL: vmem_destroy('%s'): leaked %lu %s\n", - vmp->vm_name, leaked, (vmp->vm_cflags & VMC_IDENTIFIER) ? - "identifiers" : "bytes"); + vmp->vm_name, leaked, (vmp->vm_cflags & VMC_IDENTIFIER) ? + "identifiers" : "bytes"); if (vmp->vm_hash_table != vmp->vm_hash0) - if(vmem_hash_arena != NULL) - vmem_free(vmem_hash_arena, vmp->vm_hash_table, - (vmp->vm_hash_mask + 1) * sizeof (void *)); + if (vmem_hash_arena != NULL) + vmem_free(vmem_hash_arena, vmp->vm_hash_table, + (vmp->vm_hash_mask + 1) * sizeof (void *)); /* * Give back the segment structures for anything that's left in the @@ -2195,9 +2209,11 @@ vmem_destroy_internal(vmem_t *vmp) while (vmp->vm_nsegfree > 0) vmem_putseg_global(vmem_getseg(vmp)); - if (!(vmp->vm_cflags & VMC_IDENTIFIER) && vmem_size(vmp, VMEM_ALLOC) != 0) - dprintf("SPL: vmem_destroy('%s'): STILL %lu bytes at kstat_delete() time\n", - vmp->vm_name, vmem_size(vmp, VMEM_ALLOC)); + if (!(vmp->vm_cflags & VMC_IDENTIFIER) && + vmem_size(vmp, VMEM_ALLOC) != 0) + dprintf("SPL: vmem_destroy('%s'): STILL %lu bytes at " + "kstat_delete() time\n", + vmp->vm_name, vmem_size(vmp, VMEM_ALLOC)); kstat_delete(vmp->vm_ksp); @@ -2206,7 +2222,7 @@ vmem_destroy_internal(vmem_t *vmp) // Alas, to free, requires access to "vmem_vmem_arena" the very thing // we release first. - //vmem_free(vmem_vmem_arena, vmp, sizeof (vmem_t)); + // vmem_free(vmem_vmem_arena, vmp, sizeof (vmem_t)); } /* @@ -2235,7 +2251,7 @@ vmem_hash_rescale(vmem_t *vmp) return; new_table = vmem_alloc(vmem_hash_arena, new_size * sizeof (void *), - VM_NOSLEEP); + VM_NOSLEEP); if (new_table == NULL) return; bzero(new_table, new_size * sizeof (void *)); @@ -2315,21 +2331,22 @@ static inline uint16_t vmem_bucket_number(uint32_t size) { // For VMEM_BUCKET_HIBIT == 12, - // vmem_bucket_arena[n] holds allocations from 2^[n+11]+1 to 2^[n+12], - // so for [n] = 0, 2049-4096, for [n]=5 65537-131072, for [n]=7 (256k+1)-512k + // vmem_bucket_arena[n] holds allocations from 2^[n+11]+1 to 2^[n+12], + // so for [n] = 0, 2049-4096, for [n]=5 65537-131072, + // for [n]=7 (256k+1)-512k - // set hb: 512k == 19, 256k+1 == 19, 256k == 18, ... - const int hb = highbit(size-1); + // set hb: 512k == 19, 256k+1 == 19, 256k == 18, ... + const int hb = highbit(size-1); - int bucket = hb - VMEM_BUCKET_LOWBIT; + int bucket = hb - VMEM_BUCKET_LOWBIT; - // very large allocations go into the 16 MiB bucket - if (hb > VMEM_BUCKET_HIBIT) - bucket = VMEM_BUCKET_HIBIT - VMEM_BUCKET_LOWBIT; + // very large allocations go into the 16 MiB bucket + if (hb > VMEM_BUCKET_HIBIT) + bucket = VMEM_BUCKET_HIBIT - VMEM_BUCKET_LOWBIT; - // very small allocations go into the 4 kiB bucket - if (bucket < 0) - bucket = 0; + // very small allocations go into the 4 kiB bucket + if (bucket < 0) + bucket = 0; return (uint16_t)(bucket); } @@ -2339,13 +2356,13 @@ vmem_bucket_arena_by_size(uint32_t size) { uint16_t bucket = vmem_bucket_number(size); - return(vmem_bucket_arena[bucket]); + return (vmem_bucket_arena[bucket]); } vmem_t * spl_vmem_bucket_arena_by_size(uint32_t size) { - return(vmem_bucket_arena_by_size(size)); + return (vmem_bucket_arena_by_size(size)); } static inline void @@ -2365,12 +2382,11 @@ vmem_bucket_wake_all_waiters(void) */ static inline void * -xnu_alloc_throttled_bail(uint64_t now_ticks, vmem_t *calling_vmp, uint32_t size, int vmflags) +xnu_alloc_throttled_bail(uint64_t now_ticks, vmem_t *calling_vmp, + uint32_t size, int vmflags) { - // spin looking for memory - - const uint64_t bigtarget = MAX(size,16ULL*1024ULL*1024ULL); + const uint64_t bigtarget = MAX(size, 16ULL*1024ULL*1024ULL); static volatile _Atomic uint64_t alloc_lock = FALSE; @@ -2382,7 +2398,8 @@ xnu_alloc_throttled_bail(uint64_t now_ticks, vmem_t *calling_vmp, uint32_t size, uint64_t timeout_time = now_ticks + timeout_ticks; - for (uint32_t suspends = 0, blocked_suspends = 0, try_no_pressure = 0; ; ) { + for (uint32_t suspends = 0, blocked_suspends = 0, try_no_pressure = 0; + /* nothing */; /* nothing */) { if (force_time + timeout_ticks > timeout_time) { // another thread has forced an allocation // by timing out. push our deadline into the future. @@ -2392,16 +2409,18 @@ xnu_alloc_throttled_bail(uint64_t now_ticks, vmem_t *calling_vmp, uint32_t size, blocked_suspends++; IOSleep(1); } else if (spl_vmem_xnu_useful_bytes_free() >= bigtarget) { - // if alloc_lock == f then alloc_lock = TRUE and result is TRUE - // otherwise result is FALSE and f = TRUE - //if ( ! __c11_atomic_compare_exchange_strong(&alloc_lock, &f, TRUE, - // __ATOMIC_SEQ_CST, __ATOMIC_RELAXED)) { - if (InterlockedCompareExchange64((volatile long long *)&alloc_lock, TRUE, FALSE) != FALSE) { - // avoid (highly unlikely) data race on alloc_lock. - // if alloc_lock has become TRUE while we were in the - // else if expression then we effectively optimize away - // the (relaxed) load of alloc_lock (== TRUE) into f and - // continue. +// if alloc_lock == f then alloc_lock = TRUE and result is TRUE +// otherwise result is FALSE and f = TRUE +// if ( ! __c11_atomic_compare_exchange_strong(&alloc_lock, &f, TRUE, +// __ATOMIC_SEQ_CST, __ATOMIC_RELAXED)) { + if (InterlockedCompareExchange64( + (volatile long long *)&alloc_lock, TRUE, FALSE) + != FALSE) { +// avoid (highly unlikely) data race on alloc_lock. +// if alloc_lock has become TRUE while we were in the +// else if expression then we effectively optimize away +// the (relaxed) load of alloc_lock (== TRUE) into f and +// continue. continue; } // alloc_lock is now visible as TRUE to all threads @@ -2414,9 +2433,10 @@ xnu_alloc_throttled_bail(uint64_t now_ticks, vmem_t *calling_vmp, uint32_t size, "%u suspends, %u blocked, %u tries (%s)\n", __func__, (uint64_t)size, ticks, hz, ticks/hz, suspends, - blocked_suspends, try_no_pressure, calling_vmp->vm_name); - alloc_lock = FALSE; // atomic seq cst, so is published to all threads - return(m); + blocked_suspends, try_no_pressure, + calling_vmp->vm_name); + alloc_lock = FALSE; + return (m); } else { alloc_lock = FALSE; spl_free_set_emergency_pressure(bigtarget); @@ -2424,10 +2444,10 @@ xnu_alloc_throttled_bail(uint64_t now_ticks, vmem_t *calling_vmp, uint32_t size, IOSleep(1); } } else if (zfs_lbolt() > timeout_time) { - //if ( ! __c11_atomic_compare_exchange_strong(&alloc_lock, &f, TRUE, - // __ATOMIC_SEQ_CST, __ATOMIC_RELAXED)) { - if (InterlockedCompareExchange64((volatile long long *)&alloc_lock, TRUE, FALSE) != FALSE) { - // avoid (highly unlikely) data race on alloc_lock as above + if (InterlockedCompareExchange64( + (volatile long long *)&alloc_lock, TRUE, FALSE) != + FALSE) { + // avoid (unlikely) data race on alloc_lock continue; } void *mp = spl_vmem_malloc_unconditionally(size); @@ -2439,10 +2459,11 @@ xnu_alloc_throttled_bail(uint64_t now_ticks, vmem_t *calling_vmp, uint32_t size, "%u suspends, %u blocked, %u tries (%s)\n", __func__, (uint64_t)size, ticks, hz, ticks/hz, suspends, - blocked_suspends, try_no_pressure, calling_vmp->vm_name); + blocked_suspends, try_no_pressure, + calling_vmp->vm_name); alloc_lock = FALSE; atomic_inc_64(&spl_xat_forced); - return(mp); + return (mp); } else { spl_free_set_emergency_pressure(bigtarget); suspends++; @@ -2456,7 +2477,8 @@ xnu_alloc_throttled(vmem_t *bvmp, uint32_t size, int vmflag) { // the caller is one of the bucket arenas. - // null_vmp will be spl_default_arena_parent, which is just a placeholder. + // null_vmp will be spl_default_arena_parent, + // which is just a placeholder. uint64_t now = zfs_lbolt(); const uint64_t entry_now = now; @@ -2479,44 +2501,47 @@ xnu_alloc_throttled(vmem_t *bvmp, uint32_t size, int vmflag) spl_xat_lastalloc = gethrtime(); spl_free_set_emergency_pressure(4LL * (int64_t)size); void *p = spl_vmem_malloc_unconditionally(size); - // p cannot be NULL (unconditional kernel malloc always works or panics) - // therefore: success, wake all waiters on alloc|free condvar - // wake up arena waiters to let them know there is memory - // available in the arena; let waiters on other bucket arenas - // continue sleeping. +// p cannot be NULL (unconditional kernel malloc always works or panics) +// therefore: success, wake all waiters on alloc|free condvar +// wake up arena waiters to let them know there is memory +// available in the arena; let waiters on other bucket arenas +// continue sleeping. cv_broadcast(&bvmp->vm_cv); return (p); } if (vmflag & VM_NOSLEEP) { - spl_free_set_emergency_pressure(MAX(2LL * (int64_t)size,16LL*1024LL*1024LL)); - kpreempt(KPREEMPT_SYNC); /* cheating a bit, but not really waiting */ + spl_free_set_emergency_pressure(MAX(2LL * (int64_t)size, + 16LL*1024LL*1024LL)); + /* cheating a bit, but not really waiting */ + kpreempt(KPREEMPT_SYNC); void *p = spl_vmem_malloc_if_no_pressure(size); if (p != NULL) { atomic_inc_64(&spl_xat_late_success_nosleep); cv_broadcast(&bvmp->vm_cv); spl_xat_lastalloc = gethrtime(); } - // if p == NULL, then there will be an increment in the fail kstat + // if p == NULL, then there will increment in the fail kstat return (p); } - /* - * Loop for a while trying to satisfy VM_SLEEP allocations. - * - * If we are able to allocate memory, then return the pointer. - * - * We return NULL if some other thread's activity has caused - * sufficient memory to appear in this arena that we can satisfy - * the allocation. - * - * We call xnu_alloc_throttle_bail() after a few milliseconds of waiting; - * it will either return a pointer to newly allocated memory or NULL. We - * return the result. - * - */ +/* + * Loop for a while trying to satisfy VM_SLEEP allocations. + * + * If we are able to allocate memory, then return the pointer. + * + * We return NULL if some other thread's activity has caused + * sufficient memory to appear in this arena that we can satisfy + * the allocation. + * + * We call xnu_alloc_throttle_bail() after a few milliseconds of waiting; + * it will either return a pointer to newly allocated memory or NULL. We + * return the result. + * + */ - const uint32_t bucket_number = vmem_bucket_id_to_bucket_number[bvmp->vm_id]; + const uint32_t bucket_number = + vmem_bucket_id_to_bucket_number[bvmp->vm_id]; static volatile _Atomic uint32_t waiters = 0; @@ -2529,13 +2554,14 @@ xnu_alloc_throttled(vmem_t *bvmp, uint32_t size, int vmflag) if (waiters > max_waiters_seen) { max_waiters_seen = waiters; - xprintf("SPL: %s: max_waiters_seen increased to %u\n", __func__, max_waiters_seen); + xprintf("SPL: %s: max_waiters_seen increased to %u\n", + __func__, max_waiters_seen); } boolean_t local_xat_pressured = FALSE; - for (; ;) { - clock_t wait_time = USEC2NSEC(500UL * MAX(waiters,1UL)); + for (/* empty */; /* empty */; ) { + clock_t wait_time = USEC2NSEC(500UL * MAX(waiters, 1UL)); mutex_enter(&bvmp->vm_lock); spl_xat_sleep++; if (local_xat_pressured) { @@ -2546,60 +2572,67 @@ xnu_alloc_throttled(vmem_t *bvmp, uint32_t size, int vmflag) wait_time, 0, 0); mutex_exit(&bvmp->vm_lock); now = zfs_lbolt(); - // We may be here because of a broadcast to &vmp->vm_cv, - // causing xnu to schedule all the sleepers in priority-weighted FIFO - // order. Because of the mutex_exit(), the sections below here may - // be entered concurrently. - - // spl_vmem_malloc_if_no_pressure does a mutex, so avoid calling it - // unless there is a chance it will succeed. - if (spl_vmem_xnu_useful_bytes_free() > (MAX(size,16ULL*1024ULL*1024ULL))) { +// We may be here because of a broadcast to &vmp->vm_cv, +// causing xnu to schedule all the sleepers in priority-weighted FIFO +// order. Because of the mutex_exit(), the sections below here may +// be entered concurrently. + +// spl_vmem_malloc_if_no_pressure does a mutex, so avoid calling it +// unless there is a chance it will succeed. + if (spl_vmem_xnu_useful_bytes_free() > (MAX(size, + 16ULL*1024ULL*1024ULL))) { void *a = spl_vmem_malloc_if_no_pressure(size); if (a != NULL) { atomic_inc_64(&spl_xat_late_success); spl_xat_lastalloc = gethrtime(); waiters--; atomic_dec_32(&waiters); - // Wake up all waiters on the bucket arena locks, - // since the system apparently has memory again. +// Wake up all waiters on the bucket arena locks, +// since the system apparently has memory again. vmem_bucket_wake_all_waiters(); return (a); } else { - // Probably vm_page_free_count changed while we were - // in the mutex queue in spl_vmem_malloc_if_no_pressure(). - // There is therefore no point in doing the bail-out check - // below, so go back to the top of the for loop. +// Probably vm_page_free_count changed while we were +// in the mutex queue in spl_vmem_malloc_if_no_pressure(). +// There is therefore no point in doing the bail-out check +// below, so go back to the top of the for loop. atomic_inc_64(&spl_xat_late_deny); continue; } } - if (now > entry_now + hz / 4 || spl_vba_threads[bucket_number] > 1UL) { - // If there are other threads waiting for us in vba() - // then when we satisfy this allocation, we satisfy more than one - // thread, so invoke XATB(). - // Otherwise, if we have had no luck for 250 ms, then - // switch to XATB() which is much more aggressive. + if (now > entry_now + hz / 4 || + spl_vba_threads[bucket_number] > 1UL) { +// If there are other threads waiting for us in vba() +// then when we satisfy this allocation, we satisfy more than one +// thread, so invoke XATB(). +// Otherwise, if we have had no luck for 250 ms, then +// switch to XATB() which is much more aggressive. if (spl_vba_threads[bucket_number] > 1UL) atomic_inc_64(&spl_xat_bailed_contended); atomic_inc_64(&spl_xat_bailed); - static _Atomic uint32_t bailing_threads = 0, max_bailers_seen = 0; + static _Atomic uint32_t bailing_threads = 0, + max_bailers_seen = 0; atomic_inc_32(&bailing_threads); if (bailing_threads > max_bailers_seen) { max_bailers_seen = bailing_threads; - xprintf("SPL: %s: max_bailers_seen increased to %u\n", + xprintf("SPL: %s: max_bailers_seen " + "increased to %u\n", __func__, max_bailers_seen); } - void *b = xnu_alloc_throttled_bail(now, bvmp, size, vmflag); + void *b = + xnu_alloc_throttled_bail(now, bvmp, size, vmflag); atomic_dec_32(&bailing_threads); spl_xat_lastalloc = gethrtime(); - // wake up waiters on the arena lock, - // since they now have memory they can use. +// wake up waiters on the arena lock, +// since they now have memory they can use. cv_broadcast(&bvmp->vm_cv); - // open turnstile after having bailed, rather than before +// open turnstile after having bailed, rather than before atomic_dec_32(&waiters); return (b); - } else if (now - entry_now > 0 && ((now - entry_now) % (hz/10))) { - spl_free_set_emergency_pressure(MAX(size,16LL*1024LL*1024LL)); + } else if (now - entry_now > 0 && + ((now - entry_now) % (hz/10))) { + spl_free_set_emergency_pressure(MAX(size, + 16LL*1024LL*1024LL)); local_xat_pressured = TRUE; } } @@ -2641,23 +2674,24 @@ xnu_free_throttled(vmem_t *vmp, void *vaddr, uint32_t size) if (a_waiters > max_waiters_seen) { max_waiters_seen = a_waiters; - dprintf("SPL: %s: max_waiters_seen increased to %u\n", __func__, max_waiters_seen); + dprintf("SPL: %s: max_waiters_seen increased to %u\n", + __func__, max_waiters_seen); } for (uint32_t iter = 0; a_waiters > 1UL; iter++) { - // there is more than one thread here, so suspend and sleep for 1 ms +// there is more than one thread here, so suspend and sleep for 1 ms atomic_inc_64(&spl_xft_wait); IOSleep(1); - // If are growing old in this loop, then see if - // anyone else is still in osif_free. If not, we can exit. +// If are growing old in this loop, then see if +// anyone else is still in osif_free. If not, we can exit. if (iter >= a_waiters) { - // if is_freeing == f, then set is_freeing to TRUE with - // release semantics (i.e. "push" it to other cores) then break; - // otherwise, set f to TRUE relaxedly (i.e., optimize it out) - //uint64_t f = FALSE; - //if (__c11_atomic_compare_exchange_weak(&is_freeing, &f, TRUE, - // __ATOMIC_RELEASE, __ATOMIC_RELAXED)) { - if (InterlockedCompareExchange64((volatile long long *)&is_freeing, TRUE, FALSE) != FALSE) { +// if is_freeing == f, then set is_freeing to TRUE with +// release semantics (i.e. "push" it to other cores) then break; +// otherwise, set f to TRUE relaxedly (i.e., optimize it out) +// uint64_t f = FALSE; + if (InterlockedCompareExchange64( + (volatile long long *)&is_freeing, TRUE, FALSE) != + FALSE) { break; } } @@ -2689,7 +2723,6 @@ vba_atomic_lock_bucket(volatile _Atomic uint16_t *bbap, uint16_t bucket_bit) // the return from __c11_atomic_fetch_or() is the // previous value of buckets_busy_allocating. - //uint16_t prev = __c11_atomic_fetch_or(bbap, bucket_bit, __ATOMIC_SEQ_CST); uint16_t prev = InterlockedOr16((volatile short *)bbap, bucket_bit); if (prev & bucket_bit) return (FALSE); // we did not acquire the bit lock here @@ -2704,8 +2737,8 @@ vmem_bucket_alloc(vmem_t *null_vmp, uint32_t size, const int vmflags) if (vmflags & VM_NO_VBA) return (NULL); - // caller is spl_heap_arena looking for memory. - // null_vmp will be spl_default_arena_parent, and so is just a placeholder. +// caller is spl_heap_arena looking for memory. +// null_vmp will be spl_default_arena_parent, and so is just a placeholder. vmem_t *calling_arena = spl_heap_arena; @@ -2714,7 +2747,6 @@ vmem_bucket_alloc(vmem_t *null_vmp, uint32_t size, const int vmflags) if (0 != (vmflags & (VM_PUSHPAGE | VM_NOSLEEP | VM_PANIC | VM_ABORT))) { local_hipriority_allocator = TRUE; - //hipriority_allocators++; atomic_inc_32(&hipriority_allocators); } @@ -2723,56 +2755,56 @@ vmem_bucket_alloc(vmem_t *null_vmp, uint32_t size, const int vmflags) vmem_t *bvmp = vmem_bucket_arena_by_size(size); - // there are 13 buckets, so use a 16-bit scalar to hold - // a set of bits, where each bit corresponds to an in-progress - // vmem_alloc(bucket, ...) below. +// there are 13 buckets, so use a 16-bit scalar to hold +// a set of bits, where each bit corresponds to an in-progress +// vmem_alloc(bucket, ...) below. static volatile _Atomic uint16_t buckets_busy_allocating = 0; const uint16_t bucket_number = vmem_bucket_number(size); const uint16_t bucket_bit = (uint16_t)1 << bucket_number; - //spl_vba_threads[bucket_number]++; atomic_inc_32(&spl_vba_threads[bucket_number]); static volatile _Atomic uint32_t waiters = 0; - // First, if we are VM_SLEEP, check for memory, try some pressure, - // and if that doesn't work, force entry into the loop below. +// First, if we are VM_SLEEP, check for memory, try some pressure, +// and if that doesn't work, force entry into the loop below. boolean_t loop_once = FALSE; if ((vmflags & (VM_NOSLEEP | VM_PANIC | VM_ABORT)) == 0 && ! vmem_canalloc_atomic(bvmp, size)) { - if (spl_vmem_xnu_useful_bytes_free() < (MAX(size,16ULL*1024ULL*1024ULL))) { + if (spl_vmem_xnu_useful_bytes_free() < (MAX(size, + 16ULL*1024ULL*1024ULL))) { spl_free_set_emergency_pressure(size); IOSleep(1); if (! vmem_canalloc_atomic(bvmp, size) && - (spl_vmem_xnu_useful_bytes_free() < (MAX(size,16ULL*1024ULL*1024ULL)))) { + (spl_vmem_xnu_useful_bytes_free() < (MAX(size, + 16ULL*1024ULL*1024ULL)))) { loop_once = TRUE; } } } - // spin-sleep: if we would need to go to the xnu allocator. - // - // We want to avoid a burst of allocs from bucket_heap's children - // successively hitting a low-memory condition, or alternatively - // each successfully importing memory from xnu when they can share - // a single import. - // - // We also want to take advantage of any memory that becomes available - // in bucket_heap. - // - // If there is more than one thread in this function (~ few percent) - // then the subsequent threads are put into the loop below. They - // can escape the loop if they are [1]non-waiting allocations, or - // [2]if they become the only waiting thread, or - // [3]if the cv_timedwait_hires returns -1 (which represents EWOULDBLOCK - // from msleep() which gets it from _sleep()'s THREAD_TIMED_OUT) - // allocating in the bucket, or [4]if this thread has (rare condition) spent - // a quarter of a second in the loop. - - //if (waiters++ > 1 || loop_once) { +// spin-sleep: if we would need to go to the xnu allocator. +// +// We want to avoid a burst of allocs from bucket_heap's children +// successively hitting a low-memory condition, or alternatively +// each successfully importing memory from xnu when they can share +// a single import. +// +// We also want to take advantage of any memory that becomes available +// in bucket_heap. +// +// If there is more than one thread in this function (~ few percent) +// then the subsequent threads are put into the loop below. They +// can escape the loop if they are [1]non-waiting allocations, or +// [2]if they become the only waiting thread, or +// [3]if the cv_timedwait_hires returns -1 (which represents EWOULDBLOCK +// from msleep() which gets it from _sleep()'s THREAD_TIMED_OUT) +// allocating in the bucket, or [4]if this thread has (rare condition) spent +// a quarter of a second in the loop. + if (atomic_inc_32_nv(&waiters) > 1 || loop_once) { atomic_inc_64(&spl_vba_loop_entries); } @@ -2781,54 +2813,58 @@ vmem_bucket_alloc(vmem_t *null_vmp, uint32_t size, const int vmflags) if (waiters > max_waiters_seen) { max_waiters_seen = waiters; - dprintf("SPL: %s: max_waiters_seen increased to %u\n", __func__, max_waiters_seen); + dprintf("SPL: %s: max_waiters_seen increased to %u\n", + __func__, max_waiters_seen); } // local counters, to be added atomically to global kstat variables - uint64_t local_memory_blocked = 0, local_cv_timeout = 0, local_loop_timeout = 0; + uint64_t local_memory_blocked = 0, local_cv_timeout = 0, + local_loop_timeout = 0; uint64_t local_cv_timeout_blocked = 0, local_loop_timeout_blocked = 0; uint64_t local_sleep = 0, local_hipriority_blocked = 0; const uint64_t loop_ticks = 25; // a tick is 10 msec, so 250 msec const uint64_t hiprio_loop_ticks = 4; // 40 msec int crutch = 0; - for (uint64_t entry_time = zfs_lbolt(), loop_timeout = entry_time + loop_ticks, - hiprio_timeout = entry_time + hiprio_loop_ticks, timedout = 0; - waiters > 1UL || loop_once; ) { + for (uint64_t entry_time = zfs_lbolt(), + loop_timeout = entry_time + loop_ticks, + hiprio_timeout = entry_time + hiprio_loop_ticks, timedout = 0; + waiters > 1UL || loop_once; /* empty */) { loop_once = FALSE; - // non-waiting allocations should proceeed to vmem_alloc() immediately +// non-waiting allocations should proceeed to vmem_alloc() immediately if (vmflags & (VM_NOSLEEP | VM_PANIC | VM_ABORT)) { break; } if (crutch++ > 25) break; if (vmem_canalloc_atomic(bvmp, size)) { - // We can probably vmem_alloc(bvmp, size, vmflags). - // At worst case it will give us a NULL and we will - // end up on the vmp's cv_wait. - // - // We can have threads with different bvmp - // taking this exit, and will proceed concurrently. - // - // However, we should protect against a burst of - // callers hitting the same bvmp before the allocation - // results are reflected in vmem_canalloc_atomic(bvmp, ...) +// We can probably vmem_alloc(bvmp, size, vmflags). +// At worst case it will give us a NULL and we will +// end up on the vmp's cv_wait. +// +// We can have threads with different bvmp +// taking this exit, and will proceed concurrently. +// +// However, we should protect against a burst of +// callers hitting the same bvmp before the allocation +// results are reflected in vmem_canalloc_atomic(bvmp, ...) if (local_hipriority_allocator == FALSE && hipriority_allocators > 0) { - // more high priority allocations are wanted, - // so this thread stays here +// more high priority allocations are wanted, +// so this thread stays here local_hipriority_blocked++; - } else if (vba_atomic_lock_bucket(&buckets_busy_allocating, bucket_bit)) { - // we are not being blocked by another allocator - // to the same bucket, or any higher priority allocator + } else if (vba_atomic_lock_bucket( + &buckets_busy_allocating, bucket_bit)) { +// we are not being blocked by another allocator +// to the same bucket, or any higher priority allocator atomic_inc_64(&spl_vba_parent_memory_appeared); break; - // The vmem_alloc() should return extremely quickly from - // an INSTANTFIT allocation that canalloc predicts will succeed. +// The vmem_alloc() should return extremely quickly from +// an INSTANTFIT allocation that canalloc predicts will succeed. } else { - // another thread is trying to use the free memory in the - // bucket_## arena; there might still be free memory there after - // its allocation is completed, and there might be excess in the - // bucket_heap arena, so stick around in this loop. +// another thread is trying to use the free memory in the +// bucket_## arena; there might still be free memory there after +// its allocation is completed, and there might be excess in the +// bucket_heap arena, so stick around in this loop. local_memory_blocked++; cv_broadcast(&bvmp->vm_cv); } @@ -2837,7 +2873,8 @@ vmem_bucket_alloc(vmem_t *null_vmp, uint32_t size, const int vmflags) if (local_hipriority_allocator == FALSE && hipriority_allocators > 0) { local_hipriority_blocked++; - } else if (vba_atomic_lock_bucket(&buckets_busy_allocating, bucket_bit)) { + } else if (vba_atomic_lock_bucket( + &buckets_busy_allocating, bucket_bit)) { if (timedout & 1) local_cv_timeout++; if (timedout & 6 || zfs_lbolt() >= loop_timeout) @@ -2857,25 +2894,29 @@ vmem_bucket_alloc(vmem_t *null_vmp, uint32_t size, const int vmflags) cv_broadcast(&bvmp->vm_cv); } } - // The bucket is already allocating, or the bucket needs - // more memory to satisfy vmem_allocat(bvmp, size, VM_NOSLEEP), or - // we want to give the bucket some time to acquire more memory. - // - // substitute for the vmp arena's cv_wait in vmem_xalloc() - // (vmp is the bucket_heap AKA spl_heap_arena) +// The bucket is already allocating, or the bucket needs +// more memory to satisfy vmem_allocat(bvmp, size, VM_NOSLEEP), or +// we want to give the bucket some time to acquire more memory. +// +// substitute for the vmp arena's cv_wait in vmem_xalloc() +// (vmp is the bucket_heap AKA spl_heap_arena) mutex_enter(&calling_arena->vm_lock); local_sleep++; if (local_sleep >= 1000ULL) { atomic_add_64(&spl_vba_sleep, local_sleep - 1ULL); local_sleep = 1ULL; - atomic_add_64(&spl_vba_cv_timeout_blocked, local_cv_timeout_blocked); + atomic_add_64(&spl_vba_cv_timeout_blocked, + local_cv_timeout_blocked); local_cv_timeout_blocked = 0; - atomic_add_64(&spl_vba_loop_timeout_blocked, local_loop_timeout_blocked); + atomic_add_64(&spl_vba_loop_timeout_blocked, + local_loop_timeout_blocked); local_loop_timeout_blocked = 0; - atomic_add_64(&spl_vba_hiprio_blocked, local_hipriority_blocked); + atomic_add_64(&spl_vba_hiprio_blocked, + local_hipriority_blocked); local_hipriority_blocked = 0; if (local_memory_blocked > 1ULL) { - atomic_add_64(&spl_vba_parent_memory_blocked, local_memory_blocked - 1ULL); + atomic_add_64(&spl_vba_parent_memory_blocked, + local_memory_blocked - 1ULL); local_memory_blocked = 1ULL; } } @@ -2883,10 +2924,11 @@ vmem_bucket_alloc(vmem_t *null_vmp, uint32_t size, const int vmflags) if (timedout > 0 || local_memory_blocked > 0) { wait_time = MSEC2NSEC(1); } - int ret = (int) cv_timedwait_hires(&calling_arena->vm_cv, &calling_arena->vm_lock, + int ret = (int)cv_timedwait_hires(&calling_arena->vm_cv, + &calling_arena->vm_lock, wait_time, 0, 0); - // We almost certainly have exited because of a signal/broadcast, - // but maybe just timed out. Either way, recheck memory. +// We almost certainly have exited because of a signal/broadcast, +// but maybe just timed out. Either way, recheck memory. mutex_exit(&calling_arena->vm_lock); if (ret == -1) { // cv_timedwait_hires timer expired @@ -2899,112 +2941,117 @@ vmem_bucket_alloc(vmem_t *null_vmp, uint32_t size, const int vmflags) if (n > loop_timeout) { timedout |= 2; extern uint64_t real_total_memory; - spl_free_set_emergency_pressure(real_total_memory / 64LL); + spl_free_set_emergency_pressure( + real_total_memory / 64LL); // flush the current thread in xat() out of // xat()'s for() loop and into xat_bail() cv_broadcast(&bvmp->vm_cv); - } else if (local_hipriority_allocator && n > hiprio_timeout && waiters > 1UL) { + } else if (local_hipriority_allocator && + n > hiprio_timeout && waiters > 1UL) { timedout |= 4; } } } - /* - * Turn on the exclusion bit in buckets_busy_allocating, to - * prevent multiple threads from calling vmem_alloc() on the - * same bucket arena concurrently rather than serially. - * - * This principally reduces the liklihood of asking xnu for - * more memory when other memory is or becomes available. - * - * This exclusion only applies to VM_SLEEP allocations; - * others (VM_PANIC, VM_NOSLEEP, VM_ABORT) will go to - * vmem_alloc() concurrently with any other threads. - * - * Since we aren't doing a test-and-set operation like above, - * we can just use |= and &= below and get correct atomic - * results, instead of using: - * - * __c11_atomic_fetch_or(&buckets_busy_allocating, - * bucket_bit, __ATOMIC_SEQ_CST); - * with the &= down below being written as - * __c11_atomic_fetch_and(&buckets_busy_allocating, - * ~bucket_bit, __ATOMIC_SEQ_CST); - * - * and this makes a difference with no optimization either - * compiling the whole file or with __attribute((optnone)) - * in front of the function decl. In particular, the non- - * optimized version that uses the builtin __c11_atomic_fetch_{and,or} - * preserves the C program order in the machine language output, - * inersting cmpxchgws, while all optimized versions, and the - * non-optimized version using the plainly-written version, reorder - * the "orw regr, memory" and "andw register, memory" (these are atomic - * RMW operations in x86-64 when the memory is naturally aligned) so that - * the strong memory model x86-64 promise that later loads see the - * results of earlier stores. - * - * clang+llvm simply are good at optimizing _Atomics and - * the optimized code differs only in line numbers and - * among all three approaches (as plainly written, using - * the __c11_atomic_fetch_{or,and} with sequential consistency, - * or when compiling with at least -O optimization so an - * atomic_or_16(&buckets_busy_allocating) built with GCC intrinsics - * is actually inlined rather than a function call). - * - */ +/* + * Turn on the exclusion bit in buckets_busy_allocating, to + * prevent multiple threads from calling vmem_alloc() on the + * same bucket arena concurrently rather than serially. + * + * This principally reduces the liklihood of asking xnu for + * more memory when other memory is or becomes available. + * + * This exclusion only applies to VM_SLEEP allocations; + * others (VM_PANIC, VM_NOSLEEP, VM_ABORT) will go to + * vmem_alloc() concurrently with any other threads. + * + * Since we aren't doing a test-and-set operation like above, + * we can just use |= and &= below and get correct atomic + * results, instead of using: + * + * __c11_atomic_fetch_or(&buckets_busy_allocating, + * bucket_bit, __ATOMIC_SEQ_CST); + * with the &= down below being written as + * __c11_atomic_fetch_and(&buckets_busy_allocating, + * ~bucket_bit, __ATOMIC_SEQ_CST); + * + * and this makes a difference with no optimization either + * compiling the whole file or with __attribute((optnone)) + * in front of the function decl. In particular, the non- + * optimized version that uses the builtin __c11_atomic_fetch_{and,or} + * preserves the C program order in the machine language output, + * inersting cmpxchgws, while all optimized versions, and the + * non-optimized version using the plainly-written version, reorder + * the "orw regr, memory" and "andw register, memory" (these are atomic + * RMW operations in x86-64 when the memory is naturally aligned) so that + * the strong memory model x86-64 promise that later loads see the + * results of earlier stores. + * + * clang+llvm simply are good at optimizing _Atomics and + * the optimized code differs only in line numbers and + * among all three approaches (as plainly written, using + * the __c11_atomic_fetch_{or,and} with sequential consistency, + * or when compiling with at least -O optimization so an + * atomic_or_16(&buckets_busy_allocating) built with GCC intrinsics + * is actually inlined rather than a function call). + * + */ // in case we left the loop by being the only waiter, stop the // next thread arriving from leaving the for loop because // vmem_canalloc(bvmp, that_thread's_size) is TRUE. - //buckets_busy_allocating |= bucket_bit; InterlockedOr16((volatile short *)&buckets_busy_allocating, bucket_bit); // update counters if (local_sleep > 0) atomic_add_64(&spl_vba_sleep, local_sleep); if (local_memory_blocked > 0) - atomic_add_64(&spl_vba_parent_memory_blocked, local_memory_blocked); + atomic_add_64(&spl_vba_parent_memory_blocked, + local_memory_blocked); if (local_cv_timeout > 0) atomic_add_64(&spl_vba_cv_timeout, local_cv_timeout); if (local_cv_timeout_blocked > 0) - atomic_add_64(&spl_vba_cv_timeout_blocked, local_cv_timeout_blocked); + atomic_add_64(&spl_vba_cv_timeout_blocked, + local_cv_timeout_blocked); if (local_loop_timeout > 0) atomic_add_64(&spl_vba_loop_timeout, local_loop_timeout); if (local_loop_timeout_blocked > 0) - atomic_add_64(&spl_vba_loop_timeout_blocked, local_loop_timeout_blocked); + atomic_add_64(&spl_vba_loop_timeout_blocked, + local_loop_timeout_blocked); if (local_hipriority_blocked > 0) - atomic_add_64(&spl_vba_hiprio_blocked, local_hipriority_blocked); - - // There is memory in this bucket, or there are no other waiters, - // or we aren't a VM_SLEEP allocation, or we iterated out of the for loop. - // - // vmem_alloc() and vmem_xalloc() do their own mutex serializing - // on bvmp->vm_lock, so we don't have to here. - // - // vmem_alloc may take some time to return (especially for VM_SLEEP - // allocations where we did not take the vm_canalloc(bvmp...) break out - // of the for loop). Therefore, if we didn't enter the for loop at all - // because waiters was 0 when we entered this function, - // subsequent callers will enter the for loop. + atomic_add_64(&spl_vba_hiprio_blocked, + local_hipriority_blocked); + +// There is memory in this bucket, or there are no other waiters, +// or we aren't a VM_SLEEP allocation, or we iterated out of the for loop. +// +// vmem_alloc() and vmem_xalloc() do their own mutex serializing +// on bvmp->vm_lock, so we don't have to here. +// +// vmem_alloc may take some time to return (especially for VM_SLEEP +// allocations where we did not take the vm_canalloc(bvmp...) break out +// of the for loop). Therefore, if we didn't enter the for loop at all +// because waiters was 0 when we entered this function, +// subsequent callers will enter the for loop. void *m = vmem_alloc(bvmp, size, vmflags); - // allow another vmem_canalloc() through for this bucket - // by atomically turning off the appropriate bit +// allow another vmem_canalloc() through for this bucket +// by atomically turning off the appropriate bit - /* - * Except clang+llvm DTRT because of _Atomic, could be written as: - *__c11_atomic_fetch_and(&buckets_busy_allocating, - *~bucket_bit, __ATOMIC_SEQ_CST); - * - * On processors with more relaxed memory models, it might be - * more efficient to do so with release semantics here, and - * in the atomic |= above, with acquire semantics in the bit tests, - * but on the other hand it may be hard to do better than clang+llvm. - */ +/* + * Except clang+llvm DTRT because of _Atomic, could be written as: + * __c11_atomic_fetch_and(&buckets_busy_allocating, + * ~bucket_bit, __ATOMIC_SEQ_CST); + * + * On processors with more relaxed memory models, it might be + * more efficient to do so with release semantics here, and + * in the atomic |= above, with acquire semantics in the bit tests, + * but on the other hand it may be hard to do better than clang+llvm. + */ - //buckets_busy_allocating &= ~bucket_bit; - InterlockedAnd16((volatile short *)&buckets_busy_allocating, ~bucket_bit); + InterlockedAnd16((volatile short *)&buckets_busy_allocating, + ~bucket_bit); if (local_hipriority_allocator) atomic_dec_32(&hipriority_allocators); @@ -3018,7 +3065,6 @@ vmem_bucket_alloc(vmem_t *null_vmp, uint32_t size, const int vmflags) } atomic_dec_32(&waiters); - //spl_vba_threads[bucket_number]--; atomic_dec_32(&spl_vba_threads[bucket_number]); return (m); } @@ -3038,14 +3084,16 @@ static inline int64_t vmem_bucket_arena_free(uint16_t bucket) { VERIFY(bucket < VMEM_BUCKETS); - return((int64_t)vmem_size_semi_atomic(vmem_bucket_arena[bucket], VMEM_FREE)); + return ((int64_t)vmem_size_semi_atomic(vmem_bucket_arena[bucket], + VMEM_FREE)); } static inline int64_t vmem_bucket_arena_used(int bucket) { VERIFY(bucket < VMEM_BUCKETS); - return((int64_t)vmem_size_semi_atomic(vmem_bucket_arena[bucket], VMEM_ALLOC)); + return ((int64_t)vmem_size_semi_atomic(vmem_bucket_arena[bucket], + VMEM_ALLOC)); } @@ -3065,20 +3113,22 @@ vmem_buckets_size(int typemask) if (total_size < 0) total_size = 0; - return((uint32_t) total_size); + return ((uint32_t)total_size); } static uint64_t spl_validate_bucket_span_size(uint64_t val) { if (!ISP2(val)) { - TraceEvent(TRACE_WARNING, "SPL: %s: WARNING %llu is not a power of two, not changing.\n", - __func__, val); + TraceEvent(TRACE_WARNING, + "SPL: %s: WARNING %llu is not a power of two, " + "not changing.\n", __func__, val); return (0); } if (val < 128ULL*1024ULL || val > 16ULL*1024ULL*1024ULL) { - TraceEvent(TRACE_WARNING, "SPL: %s: WARNING %llu is out of range [128k - 16M], not changing.\n", - __func__, val); + TraceEvent(TRACE_WARNING, + "SPL: %s: WARNING %llu is out of range [128k - 16M], " + "not changing.\n", __func__, val); return (0); } return (val); @@ -3090,7 +3140,7 @@ spl_modify_bucket_span_size(int bucket, uint64_t size) vmem_t *bvmp = vmem_bucket_arena[bucket]; mutex_enter(&bvmp->vm_lock); - bvmp->vm_min_import = (uint32_t) size; + bvmp->vm_min_import = (uint32_t)size; mutex_exit(&bvmp->vm_lock); } @@ -3103,18 +3153,21 @@ spl_modify_bucket_array() // asking xnu for a non-power-of-two size. const int bucket = i - VMEM_BUCKET_LOWBIT; const uint32_t bucket_alloc_minimum_size = 1UL << (uint32_t)i; - const uint32_t bucket_parent_alloc_minimum_size = bucket_alloc_minimum_size * 2UL; + const uint32_t bucket_parent_alloc_minimum_size = + bucket_alloc_minimum_size * 2UL; - switch(i) { + switch (i) { // see vmem_init() below for details case 16: case 17: spl_modify_bucket_span_size(bucket, - MAX(spl_bucket_tunable_small_span, bucket_parent_alloc_minimum_size)); + MAX(spl_bucket_tunable_small_span, + bucket_parent_alloc_minimum_size)); break; default: spl_modify_bucket_span_size(bucket, - MAX(spl_bucket_tunable_large_span, bucket_parent_alloc_minimum_size)); + MAX(spl_bucket_tunable_large_span, + bucket_parent_alloc_minimum_size)); break; } } @@ -3172,7 +3225,7 @@ static void * spl_vmem_default_alloc(vmem_t *vmp, uint32_t size, int vmflags) { extern void *osif_malloc(uint64_t); - return(osif_malloc(size)); + return (osif_malloc(size)); } static void @@ -3184,23 +3237,28 @@ spl_vmem_default_free(vmem_t *vmp, void *vaddr, uint32_t size) vmem_t * vmem_init(const char *heap_name, - void *heap_start, uint32_t heap_size, uint32_t heap_quantum, - void *(*heap_alloc)(vmem_t *, uint32_t, int), - void (*heap_free)(vmem_t *, void *, uint32_t)) + void *heap_start, uint32_t heap_size, uint32_t heap_quantum, + void *(*heap_alloc)(vmem_t *, uint32_t, int), + void (*heap_free)(vmem_t *, void *, uint32_t)) { uint32_t id; int nseg = VMEM_SEG_INITIAL; vmem_t *heap; - // XNU mutexes need initialisation - mutex_init(&vmem_list_lock, "vmem_list_lock", MUTEX_DEFAULT, NULL); - mutex_init(&vmem_segfree_lock, "vmem_segfree_lock", MUTEX_DEFAULT, NULL); - mutex_init(&vmem_sleep_lock, "vmem_sleep_lock", MUTEX_DEFAULT, NULL); - mutex_init(&vmem_nosleep_lock, "vmem_nosleep_lock", MUTEX_DEFAULT, NULL); - mutex_init(&vmem_pushpage_lock, "vmem_pushpage_lock", MUTEX_DEFAULT, NULL); - mutex_init(&vmem_panic_lock, "vmem_panic_lock", MUTEX_DEFAULT, NULL); - - mutex_init(&vmem_xnu_alloc_lock, "vmem_xnu_alloc_lock", MUTEX_DEFAULT, NULL); + mutex_init(&vmem_list_lock, "vmem_list_lock", MUTEX_DEFAULT, + NULL); + mutex_init(&vmem_segfree_lock, "vmem_segfree_lock", MUTEX_DEFAULT, + NULL); + mutex_init(&vmem_sleep_lock, "vmem_sleep_lock", MUTEX_DEFAULT, + NULL); + mutex_init(&vmem_nosleep_lock, "vmem_nosleep_lock", MUTEX_DEFAULT, + NULL); + mutex_init(&vmem_pushpage_lock, "vmem_pushpage_lock", MUTEX_DEFAULT, + NULL); + mutex_init(&vmem_panic_lock, "vmem_panic_lock", MUTEX_DEFAULT, + NULL); + mutex_init(&vmem_xnu_alloc_lock, "vmem_xnu_alloc_lock", MUTEX_DEFAULT, + NULL); while (--nseg >= 0) vmem_putseg_global(&vmem_seg0[nseg]); @@ -3216,49 +3274,50 @@ vmem_init(const char *heap_name, * serves no other purpose; its stats will always be zero. * */ - spl_default_arena_parent = vmem_create("spl_default_arena_parent", // id 0 - NULL, 0, heap_quantum, NULL, NULL, NULL, 0, VM_SLEEP); + spl_default_arena_parent = vmem_create("spl_default_arena_parent", + NULL, 0, heap_quantum, NULL, NULL, NULL, 0, VM_SLEEP); // id 0 - // illumos/openzfs has a gigantic pile of memory that it can use for its first arena; - // o3x is not so lucky, so we start with this +// illumos/openzfs has a gigantic pile of memory that it can use +// for its first arena; Win is not so lucky, so we start with this + __declspec(align(PAGE_SIZE)) static char + initial_default_block[16ULL * 1024ULL * 1024ULL] = { 0 }; - //static char initial_default_block[16ULL*1024ULL*1024ULL] __attribute__((aligned(4096))) = { 0 }; - __declspec(align(PAGE_SIZE)) static char initial_default_block[16ULL * 1024ULL * 1024ULL] = { 0 }; - - // The default arena is very low-bandwidth; it supplies the initial large - // allocation for the heap arena below, and it serves as the parent of the - // vmem_metadata arena. It will typically do only 2 or 3 parent_alloc calls - // (to spl_vmem_default_alloc) in total. +// The default arena is very low-bandwidth; it supplies the initial large +// allocation for the heap arena below, and it serves as the parent of the +// vmem_metadata arena. It will typically do only 2 or 3 parent_alloc calls +// (to spl_vmem_default_alloc) in total. spl_default_arena = vmem_create("spl_default_arena", // id 1 initial_default_block, 16ULL*1024ULL*1024ULL, heap_quantum, spl_vmem_default_alloc, spl_vmem_default_free, - spl_default_arena_parent, 16ULL*1024ULL*1024ULL, VM_SLEEP | VMC_POPULATOR | VMC_NO_QCACHE); + spl_default_arena_parent, 16ULL*1024ULL*1024ULL, + VM_SLEEP | VMC_POPULATOR | VMC_NO_QCACHE); VERIFY(spl_default_arena != NULL); - // The bucket arenas satisfy allocations & frees from the bucket heap - // that are dispatched to the bucket whose power-of-two label is the - // smallest allocation that vmem_bucket_allocate will ask for. - // - // The bucket arenas in turn exchange memory with XNU's allocator/freer in - // large spans (~ 1 MiB is stable on all systems but creates bucket fragmentation) - // - // Segregating by size constrains internal fragmentation within the bucket and - // provides kstat.vmem visiblity and span-size policy to be applied to particular - // buckets (notably the sources of most allocations, see the comments below) - // - // For VMEM_BUCKET_HIBIT == 12, - // vmem_bucket_arena[n] holds allocations from 2^[n+11]+1 to 2^[n+12], - // so for [n] = 0, 2049-4096, for [n]=5 65537-131072, for [n]=7 (256k+1)-512k - // - // so "kstat.vmvm.vmem.bucket_1048576" should be read as the bucket arena containing - // allocations 1 MiB and smaller, but larger than 512 kiB. - - // create arenas for the VMEM_BUCKETS, id 2 - id 14 +// The bucket arenas satisfy allocations & frees from the bucket heap +// that are dispatched to the bucket whose power-of-two label is the +// smallest allocation that vmem_bucket_allocate will ask for. +// +// The bucket arenas in turn exchange memory with XNU's allocator/freer in +// large spans (~ 1 MiB is stable on all systems but creates bucket +// fragmentatin) +// +// Segregating by size constrains internal fragmentation within the bucket and +// provides kstat.vmem visiblity and span-size policy to be applied to +// particular buckets (notably the sources of most allocations, +// see the comments below) +// +// For VMEM_BUCKET_HIBIT == 12, +// vmem_bucket_arena[n] holds allocations from 2^[n+11]+1 to 2^[n+12], +// so for [n] = 0, 2049-4096, for [n]=5 65537-131072, for [n]=7 (256k+1)-512k +// +// so "kstat.vmvm.vmem.bucket_1048576" should be read as the bucket +// arena contaning allocations 1 MiB and smaller, but larger than 512 kiB. +// create arenas for the VMEM_BUCKETS, id 2 - id 14 extern uint64_t real_total_memory; - VERIFY3U(real_total_memory,>=,1024ULL*1024ULL*1024ULL); + VERIFY3U(real_total_memory, >=, 1024ULL*1024ULL*1024ULL); // adjust minimum bucket span size for memory size // see comments in the switch below @@ -3271,10 +3330,11 @@ vmem_init(const char *heap_name, const uint64_t small = MAX(real_total_memory / (k * 128ULL), qm); spl_bucket_tunable_large_span = MIN(big, 16ULL * m); spl_bucket_tunable_small_span = small; - dprintf("SPL: %s: real_total_memory %llu, large spans %llu, small spans %llu\n", + dprintf("SPL: %s: real_total_memory %llu, large spans %llu, " + "small spans %llu\n", __func__, real_total_memory, spl_bucket_tunable_large_span, spl_bucket_tunable_small_span); - char* buf = vmem_alloc(spl_default_arena, VMEM_NAMELEN + 21, VM_SLEEP); + char *buf = vmem_alloc(spl_default_arena, VMEM_NAMELEN + 21, VM_SLEEP); for (int32_t i = VMEM_BUCKET_LOWBIT; i <= VMEM_BUCKET_HIBIT; i++) { size_t minimum_allocsize = 0; const uint64_t bucket_largest_size = (1ULL << (uint64_t)i); @@ -3285,66 +3345,67 @@ vmem_init(const char *heap_name, switch (i) { case 15: case 16: - /* - * With the arrival of abd, the 2^15 (== 32768) and 2^16 - * buckets are by far the most busy, holding respectively - * the qcache spans of kmem_va (the kmem_alloc et al. heap) - * and zfs_qcache (notably the source for the abd_chunk arena) - * - * The lifetime of early (i.e., after import and mount) - * allocations can be highly variable, leading - * to persisting fragmentation from the first eviction after - * arc has grown large. This can happen if, for example, - * there substantial import and mounting (and mds/mdworker and - * backupd scanning) activity before a user logs in and starts - * demanding memory in userland (e.g. by firing up a browser or - * mail app). - * - * Crucially, this makes it difficult to give back memory to xnu - * without holding the ARC size down for long periods of time. - * - * We can mitigate this by exchanging smaller - * amounts of memory with xnu for these buckets. - * There are two downsides: xnu's memory - * freelist will be prone to greater - * fragmentation, which will affect all - * allocation and free activity using xnu's - * allocator including kexts other than our; and - * we are likely to have more waits in the throttled - * alloc function, as more threads are likely to require - * slab importing into the kmem layer and fewer threads - * can be satisfied by a small allocation vs a large one. - * - * The import sizes are sysadmin-tunable by setting - * kstat.spl.misc.spl_misc.spl_tunable_small_span - * to a power-of-two number of bytes in zsysctl.conf - * should a sysadmin prefer non-early allocations to - * be larger or smaller depending on system performance - * and workload. - * - * However, a zfs booting system must use the defaults - * here for the earliest allocations, therefore they. - * should be only large enough to protect system performance - * if the sysadmin never changes the tunable span sizes. - */ +/* + * With the arrival of abd, the 2^15 (== 32768) and 2^16 + * buckets are by far the most busy, holding respectively + * the qcache spans of kmem_va (the kmem_alloc et al. heap) + * and zfs_qcache (notably the source for the abd_chunk arena) + * + * The lifetime of early (i.e., after import and mount) + * allocations can be highly variable, leading + * to persisting fragmentation from the first eviction after + * arc has grown large. This can happen if, for example, + * there substantial import and mounting (and mds/mdworker and + * backupd scanning) activity before a user logs in and starts + * demanding memory in userland (e.g. by firing up a browser or + * mail app). + * + * Crucially, this makes it difficult to give back memory to xnu + * without holding the ARC size down for long periods of time. + * + * We can mitigate this by exchanging smaller + * amounts of memory with xnu for these buckets. + * There are two downsides: xnu's memory + * freelist will be prone to greater + * fragmentation, which will affect all + * allocation and free activity using xnu's + * allocator including kexts other than our; and + * we are likely to have more waits in the throttled + * alloc function, as more threads are likely to require + * slab importing into the kmem layer and fewer threads + * can be satisfied by a small allocation vs a large one. + * + * The import sizes are sysadmin-tunable by setting + * kstat.spl.misc.spl_misc.spl_tunable_small_span + * to a power-of-two number of bytes in zsysctl.conf + * should a sysadmin prefer non-early allocations to + * be larger or smaller depending on system performance + * and workload. + * + * However, a zfs booting system must use the defaults + * here for the earliest allocations, therefore they. + * should be only large enough to protect system performance + * if the sysadmin never changes the tunable span sizes. + */ minimum_allocsize = MAX(spl_bucket_tunable_small_span, bucket_largest_size * 4); break; default: - /* - * These buckets are all relatively low bandwidth and - * with relatively uniform lifespans for most allocations - * (borrowed arc buffers dominate). They should be large - * enough that they do not pester xnu. - */ +/* + * These buckets are all relatively low bandwidth and + * with relatively uniform lifespans for most allocations + * (borrowed arc buffers dominate). They should be large + * enough that they do not pester xnu. + */ minimum_allocsize = MAX(spl_bucket_tunable_large_span, bucket_largest_size * 4); break; } const int bucket_number = i - VMEM_BUCKET_LOWBIT; vmem_t *b = vmem_create(buf, NULL, 0, heap_quantum, - xnu_alloc_throttled, xnu_free_throttled, spl_default_arena_parent, - minimum_allocsize, VM_SLEEP | VMC_POPULATOR | VMC_NO_QCACHE | VMC_TIMEFREE); + xnu_alloc_throttled, xnu_free_throttled, + spl_default_arena_parent, minimum_allocsize, + VM_SLEEP | VMC_POPULATOR | VMC_NO_QCACHE | VMC_TIMEFREE); VERIFY(b != NULL); b->vm_min_import = minimum_allocsize; b->vm_source = b; @@ -3352,9 +3413,8 @@ vmem_init(const char *heap_name, vmem_bucket_id_to_bucket_number[b->vm_id] = bucket_number; } vmem_free(spl_default_arena, buf, VMEM_NAMELEN + 21); - // spl_heap_arena, the bucket heap, is the primary interface to the vmem system - - // all arenas not rooted to vmem_metadata will be rooted to spl_heap arena. +// spl_heap_arena, the bucket heap, is the primary interface to the vmem system +// all arenas not rooted to vmem_metadata will be rooted to spl_heap arena. spl_heap_arena = vmem_create("bucket_heap", // id 15 NULL, 0, heap_quantum, @@ -3413,31 +3473,32 @@ vmem_init(const char *heap_name, VERIFY(vmem_metadata_arena != NULL); vmem_seg_arena = vmem_create("vmem_seg", // id 18 - NULL, 0, heap_quantum, - vmem_alloc, vmem_free, vmem_metadata_arena, 0, - VM_SLEEP | VMC_POPULATOR); + NULL, 0, heap_quantum, + vmem_alloc, vmem_free, vmem_metadata_arena, 0, + VM_SLEEP | VMC_POPULATOR); VERIFY(vmem_seg_arena != NULL); vmem_hash_arena = vmem_create("vmem_hash", // id 19 - NULL, 0, 8, - vmem_alloc, vmem_free, vmem_metadata_arena, 0, - VM_SLEEP); + NULL, 0, 8, + vmem_alloc, vmem_free, vmem_metadata_arena, 0, + VM_SLEEP); VERIFY(vmem_hash_arena != NULL); vmem_vmem_arena = vmem_create("vmem_vmem", // id 20 - vmem0, sizeof (vmem0), 1, - vmem_alloc, vmem_free, vmem_metadata_arena, 0, - VM_SLEEP); + vmem0, sizeof (vmem0), 1, + vmem_alloc, vmem_free, vmem_metadata_arena, 0, + VM_SLEEP); VERIFY(vmem_vmem_arena != NULL); - // 21 (0-based) vmem_create before this line. - macroized NUMBER_OF_ARENAS_IN_VMEM_INIT + // 21 (0-based) vmem_create before this line. - + // macroized NUMBER_OF_ARENAS_IN_VMEM_INIT for (id = 0; id < vmem_id; id++) { - (void) vmem_xalloc(vmem_vmem_arena, sizeof (vmem_t), - 1, 0, 0, &vmem0[id], &vmem0[id + 1], - VM_NOSLEEP | VM_BESTFIT | VM_PANIC); + (void) vmem_xalloc(vmem_vmem_arena, sizeof (vmem_t), + 1, 0, 0, &vmem0[id], &vmem0[id + 1], + VM_NOSLEEP | VM_BESTFIT | VM_PANIC); } dprintf("SPL: starting vmem_update() thread\n"); @@ -3454,11 +3515,13 @@ struct free_slab { }; static list_t freelist; -static void vmem_fini_freelist(void *vmp, void *start, uint32_t size) +static void +vmem_fini_freelist(void *vmp, void *start, uint32_t size) { struct free_slab *fs; - MALLOC(fs, struct free_slab *, sizeof(struct free_slab), M_TEMP, M_WAITOK); + MALLOC(fs, struct free_slab *, sizeof (struct free_slab), + M_TEMP, M_WAITOK); fs->vmp = vmp; fs->slabsize = size; fs->slab = start; @@ -3467,39 +3530,38 @@ static void vmem_fini_freelist(void *vmp, void *start, uint32_t size) } -void vmem_free_span_list() +void +vmem_free_span_list(void) { - int total = 0; + int total = 0; int total_count = 0; - struct free_slab* fs; + struct free_slab *fs; // int release = 1; while ((fs = list_head(&freelist))) { total_count++; total += fs->slabsize; list_remove(&freelist, fs); - /* - Commenting out due to BSOD during uninstallation, will revisit later. - - for (int id = 0; id < VMEM_INITIAL; id++) { - if (&vmem0[id] == fs->slab) { - release = 0; - break; - } - } - - if (release) - fs->vmp->vm_source_free(fs->vmp, fs->slab, fs->slabsize); - release = 1; - - */ +/* + * Commenting out due to BSOD during uninstallation, will revisit later. + * + * for (int id = 0; id < VMEM_INITIAL; id++) { + * if (&vmem0[id] == fs->slab) { + * release = 0; + * break; + * } + * } + * + * if (release) + * fs->vmp->vm_source_free(fs->vmp, fs->slab, fs->slabsize); + * release = 1; + */ FREE(fs, M_TEMP); } } static void vmem_fini_void(void *vmp, void *start, uint32_t size) { - return; } void @@ -3510,26 +3572,31 @@ vmem_fini(vmem_t *heap) // bsd_untimeout(vmem_update, NULL); - dprintf("SPL: %s: stopped vmem_update. Creating list and walking arenas.\n", __func__); + dprintf("SPL: %s: stopped vmem_update. " + "Creating list and walking arenas.\n", __func__); /* Create a list of slabs to free by walking the list of allocs */ list_create(&freelist, sizeof (struct free_slab), - offsetof(struct free_slab, next)); + offsetof(struct free_slab, next)); /* Walk to list of allocations */ - // walking with VMEM_REENTRANT causes segment consolidation and freeing of spans + // walking with VMEM_REENTRANT causes segment consolidation + // and freeing of spans // the freelist contains a list of segments that are still allocated - // at the time of the walk; unfortunately the lists cannot be exact without - // complex multiple passes, locking, and a more complex vmem_fini_freelist(). + // at the time of the walk; unfortunately the lists cannot be exact + // without complex multiple passes, locking, and a more complex + // vmem_fini_freelist(). // - // Walking withoutu VMEM_REENTRANT can produce a nearly-exact list of unfreed - // spans, which Illumos would then free directly after the list is complete. + // Walking without VMEM_REENTRANT can produce a nearly-exact list + // of unfreed spans, which Illumos would then free directly after + // the list is complete. // // Unfortunately in O3X, that lack of exactness can lead to a panic - // caused by attempting to free to xnu memory that we already freed to xnu. - // Fortunately, we can get a sense of what would have been destroyed - // after the (non-reentrant) walking, and we dprintf that at the end of this function. + // caused by attempting to free to xnu memory that we already freed to + // xnu. Fortunately, we can get a sense of what would have been + // destroyed after the (non-reentrant) walking, and we dprintf that + // at the end of this function. // Walk all still-alive arenas from leaves to the root @@ -3538,34 +3605,39 @@ vmem_fini(vmem_t *heap) vmem_walk(heap, VMEM_ALLOC, vmem_fini_freelist, heap); vmem_free_span_list(); dprintf("\nSPL: %s destroying heap\n", __func__); - vmem_destroy(heap); // PARENT: spl_heap_arena + vmem_destroy(heap); // PARENT: spl_heap_arena - dprintf("SPL: %s: walking spl_heap_arena, aka bucket_heap (pass 1)\n", __func__); + dprintf("SPL: %s: walking spl_heap_arena, aka bucket_heap (pass 1)\n", + __func__); - vmem_walk(spl_heap_arena, VMEM_ALLOC | VMEM_REENTRANT, vmem_fini_void, spl_heap_arena); + vmem_walk(spl_heap_arena, VMEM_ALLOC | VMEM_REENTRANT, + vmem_fini_void, spl_heap_arena); dprintf("SPL: %s: calling vmem_xfree(spl_default_arena, ptr, %llu);\n", __func__, (uint64_t)spl_heap_arena_initial_alloc_size); - // forcibly remove the initial alloc from spl_heap_arena arena, whether - // or not it is empty. below this point, any activity on spl_default_arena - // other than a non-reentrant(!) walk and a destroy is unsafe (UAF or MAF). +// forcibly remove the initial alloc from spl_heap_arena arena, whether +// or not it is empty. below this point, any activity on spl_default_arena +// other than a non-reentrant(!) walk and a destroy is unsafe (UAF or MAF). - // However, all the children of spl_heap_arena should now be destroyed. +// However, all the children of spl_heap_arena should now be destroyed. vmem_xfree(spl_default_arena, spl_heap_arena_initial_alloc, spl_heap_arena_initial_alloc_size); - dprintf("SPL: %s: walking spl_heap_arena, aka bucket_heap (pass 2)\n", __func__); + dprintf("SPL: %s: walking spl_heap_arena, aka bucket_heap (pass 2)\n", + __func__); - vmem_walk(spl_heap_arena, VMEM_ALLOC, vmem_fini_freelist, spl_heap_arena); + vmem_walk(spl_heap_arena, VMEM_ALLOC, + vmem_fini_freelist, spl_heap_arena); vmem_free_span_list(); dprintf("SPL: %s: walking bucket arenas...\n", __func__); for (int i = VMEM_BUCKET_LOWBIT; i <= VMEM_BUCKET_HIBIT; i++) { const int bucket = i - VMEM_BUCKET_LOWBIT; - vmem_walk(vmem_bucket_arena[bucket], VMEM_ALLOC | VMEM_REENTRANT, + vmem_walk(vmem_bucket_arena[bucket], + VMEM_ALLOC | VMEM_REENTRANT, vmem_fini_void, vmem_bucket_arena[bucket]); vmem_walk(vmem_bucket_arena[bucket], VMEM_ALLOC, @@ -3575,7 +3647,7 @@ vmem_fini(vmem_t *heap) dprintf("SPL: %s destroying spl_bucket_arenas...", __func__); for (int32_t i = VMEM_BUCKET_LOWBIT; i <= VMEM_BUCKET_HIBIT; i++) { - vmem_t* vmpt = vmem_bucket_arena[i - VMEM_BUCKET_LOWBIT]; + vmem_t *vmpt = vmem_bucket_arena[i - VMEM_BUCKET_LOWBIT]; dprintf(" %llu", (1ULL << i)); vmem_destroy(vmpt); // parent: spl_default_arena_parent } @@ -3591,23 +3663,25 @@ vmem_fini(vmem_t *heap) vmem_free_span_list(); - // We should not do VMEM_REENTRANT on vmem_seg_arena or vmem_hash_arena or below - // to avoid causing work in vmem_seg_arena and vmem_hash_arena. +// We should not do VMEM_REENTRANT on vmem_seg_arena or +// vmem_hash_arena or below to avoid causing work in vmem_seg_arena +// and vmem_hash_arena. vmem_walk(vmem_seg_arena, VMEM_ALLOC, - vmem_fini_freelist, vmem_seg_arena); + vmem_fini_freelist, vmem_seg_arena); vmem_free_span_list(); vmem_walk(vmem_hash_arena, VMEM_ALLOC, - vmem_fini_freelist, vmem_hash_arena); + vmem_fini_freelist, vmem_hash_arena); vmem_free_span_list(); vmem_walk(vmem_metadata_arena, VMEM_ALLOC, vmem_fini_freelist, vmem_metadata_arena); vmem_free_span_list(); - dprintf("SPL: %s walking the root arena (spl_default_arena)...\n", __func__); + dprintf("SPL: %s walking the root arena (spl_default_arena)...\n", + __func__); vmem_walk(spl_default_arena, VMEM_ALLOC, vmem_fini_freelist, spl_default_arena); @@ -3615,30 +3689,32 @@ vmem_fini(vmem_t *heap) vmem_free_span_list(); dprintf("SPL: %s destroying bucket heap\n", __func__); - vmem_destroy(spl_heap_arena); // PARENT: spl_default_arena_parent (but depends on buckets) + // PARENT: spl_default_arena_parent (but depends on buckets) + vmem_destroy(spl_heap_arena); // destroying the vmem_vmem arena and any arena afterwards // requires the use of vmem_destroy_internal(), which does // not talk to vmem_vmem_arena like vmem_destroy() does. - //dprintf("SPL: %s destroying vmem_vmem_arena\n", __func__); - //vmem_destroy_internal(vmem_vmem_arena); // parent: vmem_metadata_arena + // dprintf("SPL: %s destroying vmem_vmem_arena\n", __func__); + // parent: vmem_metadata_arena + // vmem_destroy_internal(vmem_vmem_arena); // destroying the seg arena means we must no longer // talk to vmem_populate() dprintf("SPL: %s destroying vmem_seg_arena\n", __func__); vmem_destroy(vmem_seg_arena); - // vmem_hash_arena may be freed-to in vmem_destroy_internal() + // vmem_hash_arena may be freed-to in vmem_destroy_internal() // so it should be just before the vmem_metadata_arena. dprintf("SPL: %s destroying vmem_hash_arena\n", __func__); vmem_destroy(vmem_hash_arena); // parent: vmem_metadata_arena vmem_hash_arena = NULL; - // XXX: if we panic on unload below here due to destroyed mutex, vmem_init() - // will need some reworking (e.g. have vmem_metadata_arena talk directly - // to xnu), or alternatively a vmem_destroy_internal_internal() - // function that does not touch vmem_hash_arena will need writing. +// XXX: if we panic on unload below here due to destroyed mutex, vmem_init() +// will need some reworking (e.g. have vmem_metadata_arena talk directly +// to xnu), or alternatively a vmem_destroy_internal_internal() +// function that does not touch vmem_hash_arena will need writing. dprintf("SPL: %s destroying vmem_metadata_arena\n", __func__); vmem_destroy(vmem_metadata_arena); // parent: spl_default_arena @@ -3669,7 +3745,7 @@ vmem_fini(vmem_t *heap) mutex_destroy(&vmem_list_lock); dprintf("\nSPL: %s: walking list of live slabs at time of call to %s\n", - __func__, __func__); + __func__, __func__); // annoyingly, some of these should be returned to xnu, but // we have no idea which have already been freed to xnu, and @@ -3678,16 +3754,14 @@ vmem_fini(vmem_t *heap) /* Now release the list of allocs to built above */ total = 0; uint64_t total_count = 0; - while((fs = list_head(&freelist))) { - total_count++; - total+=fs->slabsize; + while ((fs = list_head(&freelist))) { + total_count++; + total += fs->slabsize; list_remove(&freelist, fs); - //extern void segkmem_free(vmem_t *, void *, uint32_t); - //segkmem_free(fs->vmp, fs->slab, fs->slabsize); FREE(fs, M_TEMP); } - dprintf("SPL: WOULD HAVE released %llu bytes (%llu spans) from arenas\n", - total, total_count); + dprintf("SPL: WOULD HAVE released %llu bytes (%llu spans) " + "from arenas\n", total, total_count); list_destroy(&freelist); dprintf("SPL: %s: Brief delay for readability...\n", __func__); delay(hz); @@ -3716,14 +3790,15 @@ bucket_fragmented(const uint16_t bn, const uint64_t now) const vmem_t *vmp = vmem_bucket_arena[bn]; - const int64_t imported = (int64_t)vmp->vm_kstat.vk_mem_import.value.ui64; + const int64_t imported = + (int64_t)vmp->vm_kstat.vk_mem_import.value.ui64; const int64_t inuse = (int64_t)vmp->vm_kstat.vk_mem_inuse.value.ui64; const int64_t tiny = 64LL*1024LL*1024LL; - const int64_t small = tiny * 2LL; // 128 M - const int64_t medium = small * 2LL; // 256 - const int64_t large = medium * 2LL; // 512 - const int64_t huge = large * 2LL; // 1 G - const int64_t super_huge = huge * 2LL; // 2 + const int64_t small = tiny * 2LL; // 128 M + const int64_t medium = small * 2LL; // 256 + const int64_t large = medium * 2LL; // 512 + const int64_t huge = large * 2LL; // 1 G + const int64_t super_huge = huge * 2LL; // 2 const int64_t amount_free = imported - inuse; @@ -3749,12 +3824,11 @@ bucket_fragmented(const uint16_t bn, const uint64_t now) /* * return TRUE if the bucket for size is fragmented - * */ + */ static inline boolean_t -spl_arc_no_grow_impl(const uint16_t b, const uint32_t size, const boolean_t buf_is_metadata, - kmem_cache_t **kc) +spl_arc_no_grow_impl(const uint16_t b, const uint32_t size, + const boolean_t buf_is_metadata, kmem_cache_t **kc) { - static _Atomic uint8_t frag_suppression_counter[VMEM_BUCKETS] = { 0 }; const uint64_t now = zfs_lbolt(); @@ -3771,12 +3845,13 @@ spl_arc_no_grow_impl(const uint16_t b, const uint32_t size, const boolean_t buf_ return (FALSE); } const uint32_t b_bit = (uint32_t)1 << (uint32_t)b; - //spl_arc_no_grow_bits |= b_bit; - InterlockedOr64((volatile long long *)&spl_arc_no_grow_bits, b_bit); + InterlockedOr64((volatile long long *)&spl_arc_no_grow_bits, + b_bit); const uint32_t sup_at_least_every = MIN(b_bit, 255); const uint32_t sup_at_most_every = MAX(b_bit, 16); - const uint32_t sup_every = MIN(sup_at_least_every,sup_at_most_every); + const uint32_t sup_every = MIN(sup_at_least_every, + sup_at_most_every); if (frag_suppression_counter[b] >= sup_every) { frag_suppression_counter[b] = 0; return (TRUE); @@ -3786,12 +3861,12 @@ spl_arc_no_grow_impl(const uint16_t b, const uint32_t size, const boolean_t buf_ } } else { const uint32_t b_bit = (uint32_t)1 << (uint32_t)b; - //spl_arc_no_grow_bits &= ~b_bit; - InterlockedAnd64((volatile long long *)&spl_arc_no_grow_bits, ~b_bit); + InterlockedAnd64((volatile long long *)&spl_arc_no_grow_bits, + ~b_bit); } - extern boolean_t spl_zio_is_suppressed(const uint32_t, const uint64_t, const boolean_t, - kmem_cache_t **); + extern boolean_t spl_zio_is_suppressed(const uint32_t, const uint64_t, + const boolean_t, kmem_cache_t **); return (spl_zio_is_suppressed(size, now, buf_is_metadata, kc)); } @@ -3801,9 +3876,9 @@ vmem_bucket_number_arc_no_grow(const uint32_t size) { // qcaching on arc if (size < 128*1024) - return(vmem_bucket_number(262144)); + return (vmem_bucket_number(262144)); else - return(vmem_bucket_number(size)); + return (vmem_bucket_number(size)); } boolean_t @@ -3817,5 +3892,5 @@ spl_arc_no_grow(uint32_t size, boolean_t buf_is_metadata, kmem_cache_t **zp) atomic_inc_64(&spl_arc_no_grow_count); } - return((boolean_t)rv); + return ((boolean_t)rv); } diff --git a/module/os/windows/spl/spl-vnode.c b/module/os/windows/spl/spl-vnode.c index 3e72519699d..b0c3d19a87f 100644 --- a/module/os/windows/spl/spl-vnode.c +++ b/module/os/windows/spl/spl-vnode.c @@ -27,10 +27,8 @@ #include #include -//#include #include #include -//#include #include @@ -43,7 +41,7 @@ #include -//#define FIND_MAF +// #define FIND_MAF /* Counter for unique vnode ID */ @@ -67,60 +65,50 @@ enum vtype iftovt_tab[16] = { VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON, VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VBAD, }; -int vttoif_tab[9] = { +int vttoif_tab[9] = { 0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK, S_IFSOCK, S_IFIFO, S_IFMT, }; -/* +/* * In a real VFS the filesystem would register the callbacks for - * VNOP_ACTIVE and VNOP_RECLAIM - but here we just call them direct + * VNOP_ACTIVE and VNOP_RECLAIM - but here we just call them direct */ -//extern int zfs_zinactive(struct vnode *), void *, void*); extern int zfs_vnop_reclaim(struct vnode *); int vnode_recycle_int(vnode_t *vp, int flags); - int vn_open(char *pnamep, enum uio_seg seg, int filemode, int createmode, - struct vnode **vpp, enum create crwhy, mode_t umask) + struct vnode **vpp, enum create crwhy, mode_t umask) { - // vfs_context_t *vctx; - int fmode; - int error=0; + // vfs_context_t *vctx; + int fmode; + int error = 0; - fmode = filemode; - if (crwhy) - fmode |= O_CREAT; - // TODO I think this should be 'fmode' instead of 'filemode' - // vctx = vfs_context_create((vfs_context_t)0); - //error = vnode_open(pnamep, filemode, createmode, 0, vpp, vctx); - //(void) vfs_context_rele(vctx); - //printf("vn_open '%s' -> %d (vp %p)\n", pnamep, error, *vpp); - return (error); + fmode = filemode; + if (crwhy) + fmode |= O_CREAT; + + return (error); } int vn_openat(char *pnamep, enum uio_seg seg, int filemode, int createmode, - struct vnode **vpp, enum create crwhy, - mode_t umask, struct vnode *startvp) + struct vnode **vpp, enum create crwhy, + mode_t umask, struct vnode *startvp) { - char *path; - // int pathlen = MAXPATHLEN; - int error=0; + char *path; + // int pathlen = MAXPATHLEN; + int error = 0; - path = (char *)kmem_zalloc(MAXPATHLEN, KM_SLEEP); + path = (char *)kmem_zalloc(MAXPATHLEN, KM_SLEEP); - //error = vn_getpath(startvp, path, &pathlen); - if (error == 0) { - // strlcat(path, pnamep, MAXPATHLEN); - // error = vn_open(path, seg, filemode, createmode, vpp, crwhy, - // umask); - } + if (error == 0) { + } - kmem_free(path, MAXPATHLEN); - return (error); + kmem_free(path, MAXPATHLEN); + return (error); } extern errno_t vnode_rename(const char *, const char *, int, vfs_context_t *); @@ -128,26 +116,26 @@ extern errno_t vnode_rename(const char *, const char *, int, vfs_context_t *); errno_t vnode_rename(const char *from, const char *to, int flags, vfs_context_t *vctx) { - /* - * We need proper KPI changes to be able to safely update - * the zpool.cache file. For now, we return EPERM. - */ - return (EPERM); + /* + * We need proper KPI changes to be able to safely update + * the zpool.cache file. For now, we return EPERM. + */ + return (EPERM); } int vn_rename(char *from, char *to, enum uio_seg seg) { - // vfs_context_t *vctx; - int error=0; + // vfs_context_t *vctx; + int error = 0; - //vctx = vfs_context_create((vfs_context_t)0); + // vctx = vfs_context_create((vfs_context_t)0); - //error = vnode_rename(from, to, 0, vctx); + // error = vnode_rename(from, to, 0, vctx); - //(void) vfs_context_rele(vctx); + // (void) vfs_context_rele(vctx); - return (error); + return (error); } extern errno_t vnode_remove(const char *, int, enum vtype, vfs_context_t *); @@ -155,76 +143,52 @@ extern errno_t vnode_remove(const char *, int, enum vtype, vfs_context_t *); errno_t vnode_remove(const char *name, int flag, enum vtype type, vfs_context_t *vctx) { - /* - * Now that zed ZFS Event Daemon can handle the rename of zpool.cache - * we will silence this limitation, and look in zed.d/config.sync.sh - */ - /* - IOLog("vnode_remove: \"%s\"\n", name); - IOLog("zfs: vnode_remove not yet supported\n"); - */ - return (EPERM); + /* + * Now that zed ZFS Event Daemon can handle the rename of zpool.cache + * we will silence this limitation, and look in zed.d/config.sync.sh + */ + return (EPERM); } int vn_remove(char *fnamep, enum uio_seg seg, enum rm dirflag) { - // vfs_context_t *vctx; - // enum vtype type; - int error=0; - - //type = dirflag == RMDIRECTORY ? VDIR : VREG; - - //vctx = vfs_context_create((vfs_context_t)0); - - //error = vnode_remove(fnamep, 0, type, vctx); - - //(void) vfs_context_rele(vctx); - - return (error); + // vfs_context_t *vctx; + // enum vtype type; + int error = 0; + return (error); } int zfs_vn_rdwr(enum uio_rw rw, struct vnode *vp, caddr_t base, ssize_t len, - offset_t offset, enum uio_seg seg, int ioflag, rlim64_t ulimit, - cred_t *cr, ssize_t *residp) + offset_t offset, enum uio_seg seg, int ioflag, rlim64_t ulimit, + cred_t *cr, ssize_t *residp) { - // uio_t *auio; - // int spacetype; - int error=0; - // vfs_context_t *vctx; - - //spacetype = UIO_SEG_IS_USER_SPACE(seg) ? UIO_USERSPACE32 : UIO_SYSSPACE; - - //vctx = vfs_context_create((vfs_context_t)0); - //auio = uio_create(1, 0, spacetype, rw); - //uio_reset(auio, offset, spacetype, rw); - //uio_addiov(auio, (uint64_t)(uintptr_t)base, len); - - if (rw == UIO_READ) { - // error = VNOP_READ(vp, auio, ioflag, vctx); - } else { - // error = VNOP_WRITE(vp, auio, ioflag, vctx); - } + int error = 0; - if (residp) { - // *residp = uio_resid(auio); - } else { - // if (uio_resid(auio) && error == 0) - error = EIO; - } + if (rw == UIO_READ) { + // error = VNOP_READ(vp, auio, ioflag, vctx); + } else { + // error = VNOP_WRITE(vp, auio, ioflag, vctx); + } -// uio_free(auio); - // vfs_context_rele(vctx); + if (residp) { + // *residp = uio_resid(auio); + } else { + // if (uio_resid(auio) && error == 0) + error = EIO; + } - return (error); + return (error); } -int kernel_ioctl(PDEVICE_OBJECT DeviceObject, FILE_OBJECT *FileObject, long cmd, void *inbuf, uint32_t inlen, - void *outbuf, uint32_t outlen) +int +kernel_ioctl(PDEVICE_OBJECT DeviceObject, FILE_OBJECT *FileObject, + long cmd, void *inbuf, uint32_t inlen, + void *outbuf, uint32_t outlen) { // NTSTATUS status; - // PFILE_OBJECT FileObject; + // PFILE_OBJECT FileObject; dprintf("%s: trying to send kernel ioctl %x\n", __func__, cmd); @@ -238,15 +202,16 @@ int kernel_ioctl(PDEVICE_OBJECT DeviceObject, FILE_OBJECT *FileObject, long cmd, /* Build the information IRP */ KeInitializeEvent(&Event, SynchronizationEvent, FALSE); Irp = IoBuildDeviceIoControlRequest(cmd, - DeviceObject, - inbuf, - inlen, - outbuf, - outlen, - FALSE, - &Event, - &IoStatusBlock); - if (!Irp) return STATUS_NO_MEMORY; + DeviceObject, + inbuf, + inlen, + outbuf, + outlen, + FALSE, + &Event, + &IoStatusBlock); + if (!Irp) + return (STATUS_NO_MEMORY); /* Override verification */ IoGetNextIrpStackLocation(Irp)->Flags |= SL_OVERRIDE_VERIFY_VOLUME; @@ -259,18 +224,19 @@ int kernel_ioctl(PDEVICE_OBJECT DeviceObject, FILE_OBJECT *FileObject, long cmd, if (Status == STATUS_PENDING) { /* Wait for completion */ KeWaitForSingleObject(&Event, - Executive, - KernelMode, - FALSE, - NULL); + Executive, + KernelMode, + FALSE, + NULL); Status = IoStatusBlock.Status; } - return Status; + return (Status); } /* Linux TRIM API */ -int blk_queue_discard(PDEVICE_OBJECT dev) +int +blk_queue_discard(PDEVICE_OBJECT dev) { STORAGE_PROPERTY_QUERY spqTrim; spqTrim.PropertyId = (STORAGE_PROPERTY_ID)StorageDeviceTrimProperty; @@ -280,32 +246,37 @@ int blk_queue_discard(PDEVICE_OBJECT dev) DEVICE_TRIM_DESCRIPTOR dtd = { 0 }; if (kernel_ioctl(dev, NULL, IOCTL_STORAGE_QUERY_PROPERTY, - &spqTrim, sizeof(spqTrim), &dtd, sizeof(dtd)) == 0) { - return dtd.TrimEnabled; + &spqTrim, sizeof (spqTrim), &dtd, sizeof (dtd)) == 0) { + return (dtd.TrimEnabled); } - return 0; // No trim + return (0); // No trim } -int blk_queue_discard_secure(PDEVICE_OBJECT dev) +int +blk_queue_discard_secure(PDEVICE_OBJECT dev) { - return 0; // No secure trim + return (0); // No secure trim } -int blk_queue_nonrot(PDEVICE_OBJECT dev) +int +blk_queue_nonrot(PDEVICE_OBJECT dev) { STORAGE_PROPERTY_QUERY spqSeekP; - spqSeekP.PropertyId = (STORAGE_PROPERTY_ID)StorageDeviceSeekPenaltyProperty; + spqSeekP.PropertyId = + (STORAGE_PROPERTY_ID)StorageDeviceSeekPenaltyProperty; spqSeekP.QueryType = PropertyStandardQuery; // DWORD bytesReturned = 0; DEVICE_SEEK_PENALTY_DESCRIPTOR dspd = { 0 }; if (kernel_ioctl(dev, NULL, IOCTL_STORAGE_QUERY_PROPERTY, - &spqSeekP, sizeof(spqSeekP), &dspd, sizeof(dspd)) == 0) { - return !dspd.IncursSeekPenalty; + &spqSeekP, sizeof (spqSeekP), &dspd, sizeof (dspd)) == 0) { + return (!dspd.IncursSeekPenalty); } - return 0; // Not SSD; + return (0); // Not SSD; } -int blkdev_issue_discard_bytes(PDEVICE_OBJECT dev, uint64_t offset, uint64_t size, uint32_t flags) +int +blkdev_issue_discard_bytes(PDEVICE_OBJECT dev, uint64_t offset, + uint64_t size, uint32_t flags) { int Status = 0; struct setAttrAndRange { @@ -313,32 +284,33 @@ int blkdev_issue_discard_bytes(PDEVICE_OBJECT dev, uint64_t offset, uint64_t siz DEVICE_DATA_SET_RANGE range; } set; - set.dmdsa.Size = sizeof(DEVICE_MANAGE_DATA_SET_ATTRIBUTES); + set.dmdsa.Size = sizeof (DEVICE_MANAGE_DATA_SET_ATTRIBUTES); set.dmdsa.Action = DeviceDsmAction_Trim; set.dmdsa.Flags = DEVICE_DSM_FLAG_TRIM_NOT_FS_ALLOCATED; set.dmdsa.ParameterBlockOffset = 0; set.dmdsa.ParameterBlockLength = 0; - set.dmdsa.DataSetRangesOffset = FIELD_OFFSET(struct setAttrAndRange, range); - set.dmdsa.DataSetRangesLength = 1 * sizeof(DEVICE_DATA_SET_RANGE); + set.dmdsa.DataSetRangesOffset = + FIELD_OFFSET(struct setAttrAndRange, range); + set.dmdsa.DataSetRangesLength = 1 * sizeof (DEVICE_DATA_SET_RANGE); set.range.LengthInBytes = size; set.range.StartingOffset = offset; - Status = kernel_ioctl(dev, NULL, IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES, - &set, sizeof(set), NULL, 0); + Status = kernel_ioctl(dev, NULL, + IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES, + &set, sizeof (set), NULL, 0); - if (Status == 0) { - return 0; // TRIM OK - } + if (Status == 0) + return (0); // TRIM OK // Linux returncodes are negative - return -Status; + return (-Status); } int VOP_SPACE(HANDLE h, int cmd, struct flock *fl, int flags, offset_t off, - cred_t *cr, void *ctx) + cred_t *cr, void *ctx) { if (cmd == F_FREESP) { NTSTATUS Status; @@ -348,16 +320,15 @@ VOP_SPACE(HANDLE h, int cmd, struct flock *fl, int flags, offset_t off, fzdi.BeyondFinalZero.QuadPart = fl->l_start + fl->l_len; Status = ZwFsControlFile( - h, - NULL, - NULL, - NULL, - NULL, - FSCTL_SET_ZERO_DATA, - &fzdi, sizeof(fzdi), - NULL, - 0 - ); + h, + NULL, + NULL, + NULL, + NULL, + FSCTL_SET_ZERO_DATA, + &fzdi, sizeof (fzdi), + NULL, + 0); return (Status); } @@ -366,122 +337,92 @@ VOP_SPACE(HANDLE h, int cmd, struct flock *fl, int flags, offset_t off, } int -VOP_CLOSE(struct vnode *vp, int flag, int count, offset_t off, void *cr, void *k) +VOP_CLOSE(struct vnode *vp, int flag, int count, offset_t off, + void *cr, void *k) { - // vfs_context_t vctx; - int error=0; + int error = 0; - //vctx = vfs_context_create((vfs_context_t)0); - //error = vnode_close(vp, flag & FWRITE, vctx); - //(void) vfs_context_rele(vctx); - return (error); + return (error); } int VOP_FSYNC(struct vnode *vp, int flags, void* unused, void *uused2) { -// vfs_context_t vctx; - int error=0; + int error = 0; - //vctx = vfs_context_create((vfs_context_t)0); - //error = VNOP_FSYNC(vp, (flags == FSYNC), vctx); - //(void) vfs_context_rele(vctx); - return (error); + return (error); } -int VOP_GETATTR(struct vnode *vp, vattr_t *vap, int flags, void *x3, void *x4) +int +VOP_GETATTR(struct vnode *vp, vattr_t *vap, int flags, void *x3, void *x4) { -// vfs_context_t vctx; - int error=0; - - //vap->va_size = 134217728; - //return 0; - - // panic("take this"); - //printf("VOP_GETATTR(%p, %p, %d)\n", vp, vap, flags); - //vctx = vfs_context_create((vfs_context_t)0); - //error= vnode_getattr(vp, vap, vctx); - //(void) vfs_context_rele(vctx); - return error; + int error = 0; + return (error); } #if 1 -errno_t VNOP_LOOKUP(struct vnode *, struct vnode **, struct componentname *, vfs_context_t *); +errno_t VNOP_LOOKUP(struct vnode *, struct vnode **, struct componentname *, + vfs_context_t *); -errno_t VOP_LOOKUP(struct vnode *vp, struct vnode **vpp, struct componentname *cn, vfs_context_t *ct) +errno_t +VOP_LOOKUP(struct vnode *vp, struct vnode **vpp, struct componentname *cn, + vfs_context_t *ct) { - //return VNOP_LOOKUP(vp,vpp,cn,ct); - return ENOTSUP; + return (ENOTSUP); } #endif -#if 0 -extern errno_t VNOP_MKDIR (struct vnode *, struct vnode **, - struct componentname *, struct vnode_attr *, - vfs_context_t); -errno_t VOP_MKDIR(struct vnode *vp, struct vnode **vpp, - struct componentname *cn, struct vnode_attr *vattr, - vfs_context_t ct) -{ - return VNOP_MKDIR(vp, vpp, cn, vattr, ct); -} -extern errno_t VNOP_REMOVE (struct vnode *, struct vnode *, - struct componentname *, int, vfs_context_t); -errno_t VOP_REMOVE (struct vnode *vp, struct vnode *dp, - struct componentname *cn, int flags, - vfs_context_t ct) +#if 0 +extern errno_t VNOP_REMOVE(struct vnode *, struct vnode *, + struct componentname *, int, vfs_context_t); +errno_t +VOP_REMOVE(struct vnode *vp, struct vnode *dp, + struct componentname *cn, int flags, + vfs_context_t ct) { - return VNOP_REMOVE(vp, dp, cn, flags, ct); + return (VNOP_REMOVE(vp, dp, cn, flags, ct)); } -extern errno_t VNOP_SYMLINK (struct vnode *, struct vnode **, - struct componentname *, struct vnode_attr *, - char *, vfs_context_t); -errno_t VOP_SYMLINK (struct vnode *vp, struct vnode **vpp, - struct componentname *cn, struct vnode_attr *attr, - char *name, vfs_context_t ct) +extern errno_t VNOP_SYMLINK(struct vnode *, struct vnode **, + struct componentname *, struct vnode_attr *, + char *, vfs_context_t); +errno_t +VOP_SYMLINK(struct vnode *vp, struct vnode **vpp, + struct componentname *cn, struct vnode_attr *attr, + char *name, vfs_context_t ct) { - return VNOP_SYMLINK(vp, vpp, cn, attr, name, ct); + return (VNOP_SYMLINK(vp, vpp, cn, attr, name, ct)); } #endif - #undef VFS_ROOT extern int VFS_ROOT(mount_t *, struct vnode **, vfs_context_t); -int spl_vfs_root(mount_t *mount, struct vnode **vp) +int +spl_vfs_root(mount_t *mount, struct vnode **vp) { - // return VFS_ROOT(mount, vp, vfs_context_current() ); *vp = NULL; - return -1; + return (-1); } - - -void vfs_mountedfrom(struct mount *vfsp, char *osname) +void +vfs_mountedfrom(struct mount *vfsp, char *osname) { -// (void) copystr(osname, vfs_statfs(vfsp)->f_mntfromname, MNAMELEN - 1, 0); } - /* * DNLC Name Cache Support */ struct vnode * dnlc_lookup(struct vnode *dvp, char *name) { - struct componentname cn; + struct componentname cn; struct vnode *vp = NULL; - //return DNLC_NO_VNODE; bzero(&cn, sizeof (cn)); - //cn.cn_nameiop = LOOKUP; - //cn.cn_flags = ISLASTCN; - //cn.cn_nameptr = (char *)name; - //cn.cn_namelen = strlen(name); - switch(0/*cache_lookup(dvp, &vp, &cn)*/) { + switch (0 /* cache_lookup(dvp, &vp, &cn) */) { case -1: break; case ENOENT: @@ -493,53 +434,36 @@ dnlc_lookup(struct vnode *dvp, char *name) return (vp); } -int dnlc_purge_vfsp(struct mount *mp, int flags) +int +dnlc_purge_vfsp(struct mount *mp, int flags) { - // cache_purgevfs(mp); - return 0; + return (0); } -void dnlc_remove(struct vnode *vp, char *name) +void +dnlc_remove(struct vnode *vp, char *name) { - // cache_purge(vp); - return; } - /* * * */ -void dnlc_update(struct vnode *vp, char *name, struct vnode *tp) +void +dnlc_update(struct vnode *vp, char *name, struct vnode *tp) { - -#if 0 - // If tp is NULL, it is a negative-cache entry - struct componentname cn; - - // OSX panics if you give empty(non-NULL) name - if (!name || !*name || !strlen(name)) return; - - bzero(&cn, sizeof(cn)); - cn.cn_nameiop = CREATE; - cn.cn_flags = ISLASTCN; - cn.cn_nameptr = (char *)name; - cn.cn_namelen = strlen(name); - - cache_enter(vp, tp == DNLC_NO_VNODE ? NULL : tp, &cn); -#endif - return; } -static int vnode_fileobject_compare(const void *arg1, const void *arg2) +static int +vnode_fileobject_compare(const void *arg1, const void *arg2) { const vnode_fileobjects_t *node1 = arg1; const vnode_fileobjects_t *node2 = arg2; if (node1->fileobject > node2->fileobject) - return 1; + return (1); if (node1->fileobject < node2->fileobject) - return -1; - return 0; + return (-1); + return (0); } static int @@ -549,17 +473,18 @@ zfs_vnode_cache_constructor(void *buf, void *arg, int kmflags) // So the Windows structs have to be zerod, even though we call // their setup functions. - memset(vp, 0, sizeof(*vp)); + memset(vp, 0, sizeof (*vp)); mutex_init(&vp->v_mutex, NULL, MUTEX_DEFAULT, NULL); avl_create(&vp->v_fileobjects, vnode_fileobject_compare, - sizeof(vnode_fileobjects_t), offsetof(vnode_fileobjects_t, avlnode)); + sizeof (vnode_fileobjects_t), offsetof(vnode_fileobjects_t, + avlnode)); ExInitializeResourceLite(&vp->resource); ExInitializeResourceLite(&vp->pageio_resource); ExInitializeFastMutex(&vp->AdvancedFcbHeaderMutex); - return 0; + return (0); } static void @@ -567,34 +492,34 @@ zfs_vnode_cache_destructor(void *buf, void *arg) { vnode_t *vp = buf; - //ExDeleteFastMutex(&vp->AdvancedFcbHeaderMutex); ExDeleteResourceLite(&vp->pageio_resource); ExDeleteResourceLite(&vp->resource); avl_destroy(&vp->v_fileobjects); mutex_destroy(&vp->v_mutex); - } -int spl_vnode_init(void) +int +spl_vnode_init(void) { mutex_init(&spl_getf_lock, NULL, MUTEX_DEFAULT, NULL); - list_create(&spl_getf_list, sizeof(struct spl_fileproc), - offsetof(struct spl_fileproc, f_next)); + list_create(&spl_getf_list, sizeof (struct spl_fileproc), + offsetof(struct spl_fileproc, f_next)); mutex_init(&vnode_all_list_lock, NULL, MUTEX_DEFAULT, NULL); - list_create(&vnode_all_list, sizeof(struct vnode), - offsetof(struct vnode, v_list)); + list_create(&vnode_all_list, sizeof (struct vnode), + offsetof(struct vnode, v_list)); vnode_cache = kmem_cache_create("zfs_vnode_cache", - sizeof(vnode_t), 0, - zfs_vnode_cache_constructor, - zfs_vnode_cache_destructor, NULL, NULL, - NULL, 0); + sizeof (vnode_t), 0, + zfs_vnode_cache_constructor, + zfs_vnode_cache_destructor, NULL, NULL, + NULL, 0); - return 0; + return (0); } -void spl_vnode_fini(void) +void +spl_vnode_fini(void) { mutex_destroy(&vnode_all_list_lock); list_destroy(&vnode_all_list); @@ -607,41 +532,26 @@ void spl_vnode_fini(void) } #include -struct fileproc; - -extern int fp_drop(struct proc *p, int fd, struct fileproc *fp, int locked); -extern int fp_drop_written(struct proc *p, int fd, struct fileproc *fp, - int locked); -extern int fp_lookup(struct proc *p, int fd, struct fileproc **resultfp, int locked); -extern int fo_read(struct fileproc *fp, struct uio *uio, int flags, - vfs_context_t ctx); -extern int fo_write(struct fileproc *fp, struct uio *uio, int flags, - vfs_context_t ctx); -extern int file_vnode_withvid(int, struct vnode **, uint64_t *); -extern int file_drop(int); - -void cache_purgevfs(mount_t *mp) +void +cache_purgevfs(mount_t *mp) { } dev_t vnode_specrdev(vnode_t *vp) { -// return vp->v_rdev; return (0); } void cache_purge(vnode_t *vp) { - } void cache_purge_negatives(vnode_t *vp) { - } int @@ -655,235 +565,217 @@ vnode_removefsref(vnode_t *vp) * releasef(). On OSX we will also look up the vnode of the fd for calls * to spl_vn_rdwr(). */ -void *getf(uint64_t fd) +void * +getf(uint64_t fd) { struct spl_fileproc *sfp = NULL; // HANDLE h; #if 1 - struct fileproc *fp = NULL; + struct fileproc *fp = NULL; // struct vnode *vp; // uint64_t vid; /* - * We keep the "fp" pointer as well, both for unlocking in releasef() and - * used in vn_rdwr(). + * We keep the "fp" pointer as well, both for unlocking in releasef() + * and used in vn_rdwr(). */ - sfp = kmem_alloc(sizeof(*sfp), KM_SLEEP); - if (!sfp) return NULL; - - // if (fp_lookup(current_proc(), fd, &fp, 0/*!locked*/)) { - // kmem_free(sfp, sizeof(*sfp)); - // return (NULL); - // } + sfp = kmem_alloc(sizeof (*sfp), KM_SLEEP); + if (!sfp) + return (NULL); /* - * The f_vnode ptr is used to point back to the "sfp" node itself, as it is - * the only information passed to vn_rdwr. - */ - if (ObReferenceObjectByHandle((HANDLE)fd, 0, 0, KernelMode, (void **)&fp, 0) != STATUS_SUCCESS) { + * The f_vnode ptr is used to point back to the "sfp" node itself, + * as it is the only information passed to vn_rdwr. + */ + if (ObReferenceObjectByHandle((HANDLE)fd, 0, 0, KernelMode, + (void **)&fp, 0) != STATUS_SUCCESS) { dprintf("%s: failed to get fd %d fp 0x\n", __func__, fd); } - sfp->f_vnode = sfp; + sfp->f_vnode = sfp; - sfp->f_fd = fd; - sfp->f_offset = 0; - sfp->f_proc = current_proc(); - sfp->f_fp = (void *)fp; - sfp->f_file = (uint64_t) fp; + sfp->f_fd = fd; + sfp->f_offset = 0; + sfp->f_proc = current_proc(); + sfp->f_fp = (void *)fp; + sfp->f_file = (uint64_t)fp; mutex_enter(&spl_getf_lock); list_insert_tail(&spl_getf_list, sfp); mutex_exit(&spl_getf_lock); - //printf("SPL: new getf(%d) ret %p fp is %p so vnode set to %p\n", - // fd, sfp, fp, sfp->f_vnode); + // printf("SPL: new getf(%d) ret %p fp is %p so vnode set to %p\n", + // fd, sfp, fp, sfp->f_vnode); #endif - return sfp; + return (sfp); } -struct vnode *getf_vnode(void *fp) +struct vnode * +getf_vnode(void *fp) { struct vnode *vp = NULL; #if 0 - struct spl_fileproc *sfp = (struct spl_fileproc *) fp; + struct spl_fileproc *sfp = (struct spl_fileproc *)fp; uint32_t vid; if (!file_vnode_withvid(sfp->f_fd, &vp, &vid)) { file_drop(sfp->f_fd); } #endif - return vp; + return (vp); } -void releasef(uint64_t fd) +void +releasef(uint64_t fd) { #if 1 - struct spl_fileproc *fp = NULL; - struct proc *p = NULL; + struct spl_fileproc *fp = NULL; + struct proc *p = NULL; - //printf("SPL: releasef(%d)\n", fd); + // printf("SPL: releasef(%d)\n", fd); - p = (void *)current_proc(); + p = (void *)current_proc(); mutex_enter(&spl_getf_lock); for (fp = list_head(&spl_getf_list); fp != NULL; - fp = list_next(&spl_getf_list, fp)) { - if ((fp->f_proc == p) && fp->f_fd == fd) break; - } + fp = list_next(&spl_getf_list, fp)) { + if ((fp->f_proc == p) && fp->f_fd == fd) + break; + } mutex_exit(&spl_getf_lock); - if (!fp) return; // Not found + if (!fp) + return; // Not found - //printf("SPL: releasing %p\n", fp); + // printf("SPL: releasing %p\n", fp); - // Release the hold from getf(). -// if (fp->f_writes) -// fp_drop_written(p, fd, fp->f_fp, 0/*!locked*/); -// else -// fp_drop(p, fd, fp->f_fp, 0/*!locked*/); + // Release the hold from getf(). if (fp->f_fp) ObDereferenceObject(fp->f_fp); - // Remove node from the list + // Remove node from the list mutex_enter(&spl_getf_lock); list_remove(&spl_getf_list, fp); mutex_exit(&spl_getf_lock); - // Free the node - kmem_free(fp, sizeof(*fp)); + // Free the node + kmem_free(fp, sizeof (*fp)); #endif } - - /* * Our version of vn_rdwr, here "vp" is not actually a vnode, but a ptr * to the node allocated in getf(). We use the "fp" part of the node to * be able to issue IO. * You must call getf() before calling spl_vn_rdwr(). */ -int spl_vn_rdwr(enum uio_rw rw, - struct vnode *vp, - caddr_t base, - ssize_t len, - offset_t offset, - enum uio_seg seg, - int ioflag, - rlim64_t ulimit, /* meaningful only if rw is UIO_WRITE */ - cred_t *cr, - ssize_t *residp) -{ - struct spl_fileproc *sfp = (struct spl_fileproc*)vp; - // uio_t *auio; - // int spacetype; - int error=0; - // vfs_context_t *vctx; - - //spacetype = UIO_SEG_IS_USER_SPACE(seg) ? UIO_USERSPACE32 : UIO_SYSSPACE; - - //vctx = vfs_context_create((vfs_context_t)0); - //auio = uio_create(1, 0, spacetype, rw); - ///uio_reset(auio, offset, spacetype, rw); - - //uio_addiov(auio, (uint64_t)(uintptr_t)base, len); - //LARGE_INTEGER Offset; - //Offset.QuadPart = offset; +int +spl_vn_rdwr(enum uio_rw rw, + struct vnode *vp, + caddr_t base, + ssize_t len, + offset_t offset, + enum uio_seg seg, + int ioflag, + rlim64_t ulimit, /* meaningful only if rw is UIO_WRITE */ + cred_t *cr, + ssize_t *residp) +{ + struct spl_fileproc *sfp = (struct spl_fileproc *)vp; + int error = 0; IO_STATUS_BLOCK iob; LARGE_INTEGER off; off.QuadPart = offset; if (rw == UIO_READ) { - error = ZwReadFile((HANDLE)sfp->f_fd, NULL, NULL, NULL, &iob, base, (ULONG)len, &off, NULL); - // error = fo_read(sfp->f_fp, auio, ioflag, vctx); - } else { - // error = fo_write(sfp->f_fp, auio, ioflag, vctx); - error = ZwWriteFile((HANDLE)sfp->f_fd, NULL, NULL, NULL, &iob, base, (ULONG)len, &off, NULL); + error = ZwReadFile((HANDLE)sfp->f_fd, NULL, NULL, NULL, &iob, + base, (ULONG)len, &off, NULL); + } else { + error = ZwWriteFile((HANDLE)sfp->f_fd, NULL, NULL, NULL, &iob, + base, (ULONG)len, &off, NULL); sfp->f_writes = 1; - } - - if (residp) { - *residp = len - iob.Information; - } else { - if ((iob.Information < len) && error == 0) - error = EIO; - } + } - //uio_free(auio); - //vfs_context_rele(vctx); + if (residp) { + *residp = len - iob.Information; + } else { + if ((iob.Information < len) && error == 0) + error = EIO; + } - return (error); + return (error); } -void spl_rele_async(void *arg) +void +spl_rele_async(void *arg) { - struct vnode *vp = (struct vnode *)arg; + struct vnode *vp = (struct vnode *)arg; #ifdef DEBUG_IOCOUNT if (vp) { znode_t *zp = VTOZ(vp); - if (zp) dprintf("%s: Dec iocount from %u for '%s' \n", __func__, - &vp->v_iocount, - zp->z_name_cache); + if (zp) + dprintf("%s: Dec iocount from %u for '%s' \n", __func__, + &vp->v_iocount, + zp->z_name_cache); } #endif if (vp) VN_RELE(vp); } -void vn_rele_async(struct vnode *vp, void *taskq) +void +vn_rele_async(struct vnode *vp, void *taskq) { #ifdef DEBUG_IOCOUNT if (vp) { znode_t *zp = VTOZ(vp); - if (zp) dprintf("%s: Dec iocount in future, now %u for '%s' \n", __func__, - vp->v_iocount, - zp->z_name_cache); + if (zp) + dprintf("%s: Dec iocount in future, now %u for '%s' \n", + __func__, vp->v_iocount, zp->z_name_cache); } #endif VERIFY(taskq_dispatch((taskq_t *)taskq, - (task_func_t *)spl_rele_async, vp, TQ_SLEEP) != 0); + (task_func_t *)spl_rele_async, vp, TQ_SLEEP) != 0); } - - -vfs_context_t *spl_vfs_context_kernel(void) +vfs_context_t * +spl_vfs_context_kernel(void) { -// return vfs_context_kernel(); - return NULL; + return (NULL); } -#undef build_path extern int build_path(struct vnode *vp, char *buff, int buflen, int *outlen, - int flags, vfs_context_t *ctx); + int flags, vfs_context_t *ctx); -int spl_build_path(struct vnode *vp, char *buff, int buflen, int *outlen, - int flags, vfs_context_t *ctx) +int +spl_build_path(struct vnode *vp, char *buff, int buflen, int *outlen, + int flags, vfs_context_t *ctx) { - //return build_path(vp, buff, buflen, outlen, flags, ctx); - return 0; + return (0); } /* * vnode_notify was moved from KERNEL_PRIVATE to KERNEL in 10.11, but to be * backward compatible, we keep the wrapper for now. */ -extern int vnode_notify(struct vnode *, uint32_t, struct vnode_attr*); -int spl_vnode_notify(struct vnode *vp, uint32_t type, struct vnode_attr *vap) +extern int vnode_notify(struct vnode *, uint32_t, struct vnode_attr *); +int +spl_vnode_notify(struct vnode *vp, uint32_t type, struct vnode_attr *vap) { - //return vnode_notify(vp, type, vap); - return 0; + return (0); } -extern int vfs_get_notify_attributes(struct vnode_attr *vap); -int spl_vfs_get_notify_attributes(struct vnode_attr *vap) +extern intvfs_get_notify_attributes(struct vnode_attr *vap); +int +spl_vfs_get_notify_attributes(struct vnode_attr *vap) { - //return vfs_get_notify_attributes(vap); - return 0; + return (0); } /* Root directory vnode for the system a.k.a. '/' */ -/* Must use vfs_rootvnode() to acquire a reference, and +/* + * Must use vfs_rootvnode() to acquire a reference, and * vnode_put() to release it */ @@ -900,107 +792,125 @@ struct vnode * getrootdir(void) { struct vnode *rvnode = NULL; - if (spl_skip_getrootdir) return NULL; + if (spl_skip_getrootdir) + return (NULL); -// rvnode = vfs_rootvnode(); -// if (rvnode) -// vnode_put(rvnode); - return rvnode; + return (rvnode); } -void spl_vfs_start() +void +spl_vfs_start() { spl_skip_getrootdir = 0; } -int vnode_vfsisrdonly(vnode_t *vp) +int +vnode_vfsisrdonly(vnode_t *vp) { - return 0; + return (0); } -uint64_t vnode_vid(vnode_t *vp) +uint64_t +vnode_vid(vnode_t *vp) { - return vp->v_id; + return (vp->v_id); } -int vnode_isreg(vnode_t *vp) +int +vnode_isreg(vnode_t *vp) { - return vp->v_type == VREG; + return (vp->v_type == VREG); } -int vnode_isdir(vnode_t *vp) +int +vnode_isdir(vnode_t *vp) { - return vp->v_type == VDIR; + return (vp->v_type == VDIR); } -void *vnode_fsnode(struct vnode *dvp) +void * +vnode_fsnode(struct vnode *dvp) { - return dvp->v_data; + return (dvp->v_data); } -enum vtype vnode_vtype(vnode_t *vp) +enum vtype +vnode_vtype(vnode_t *vp) { - return vp->v_type; + return (vp->v_type); } -int vnode_isblk(vnode_t *vp) +int +vnode_isblk(vnode_t *vp) { - return vp->v_type == VBLK; + return (vp->v_type == VBLK); } -int vnode_ischr(vnode_t *vp) +int +vnode_ischr(vnode_t *vp) { - return vp->v_type == VCHR; + return (vp->v_type == VCHR); } -int vnode_isswap(vnode_t *vp) +int +vnode_isswap(vnode_t *vp) { - return 0; + return (0); } -int vnode_isfifo(vnode_t *vp) +int +vnode_isfifo(vnode_t *vp) { - return 0; + return (0); } -int vnode_islnk(vnode_t *vp) +int +vnode_islnk(vnode_t *vp) { - return 0; + return (0); } -mount_t *vnode_mountedhere(vnode_t *vp) +mount_t * +vnode_mountedhere(vnode_t *vp) { - return NULL; + return (NULL); } -void ubc_setsize(struct vnode *vp, uint64_t size) +void +ubc_setsize(struct vnode *vp, uint64_t size) { } -int vnode_isinuse(vnode_t *vp, uint64_t refcnt) +int +vnode_isinuse(vnode_t *vp, uint64_t refcnt) { - if (((vp->v_usecount /*+ vp->v_iocount*/) > refcnt)) // xnu uses usecount +kusecount, not iocount - return 1; - return 0; + // xnu uses usecount +kusecount, not iocount + if (((vp->v_usecount /* + vp->v_iocount */) > refcnt)) + return (1); + return (0); } -int vnode_isidle(vnode_t *vp) +int +vnode_isidle(vnode_t *vp) { if ((vp->v_usecount == 0) && (vp->v_iocount <= 1)) - return 1; - return 0; + return (1); + return (0); } -int vnode_iocount(vnode_t *vp) +int +vnode_iocount(vnode_t *vp) { return (vp->v_iocount); } #ifdef DEBUG_IOCOUNT -int vnode_getwithref(vnode_t *vp, char *file, int line) +int +vnode_getwithref(vnode_t *vp, char *file, int line) #else -int vnode_getwithref(vnode_t *vp) +int +vnode_getwithref(vnode_t *vp) #endif { // KIRQL OldIrql; @@ -1018,10 +928,12 @@ int vnode_getwithref(vnode_t *vp) #ifdef DEBUG_IOCOUNT if (vp) { znode_t *zp = VTOZ(vp); - if (zp) dprintf("%s: Inc iocount now %u for '%s' (%s:%d) thread %p \n", __func__, - atomic_inc_32_nv(&vp->v_iocount), - zp->z_name_cache, - file, line, current_thread()); + if (zp) + dprintf("%s: Inc iocount now %u for '%s' " + "(%s:%d) thread %p \n", __func__, + atomic_inc_32_nv(&vp->v_iocount), + zp->z_name_cache, + file, line, current_thread()); } #else atomic_inc_32(&vp->v_iocount); @@ -1029,13 +941,15 @@ int vnode_getwithref(vnode_t *vp) } mutex_exit(&vp->v_mutex); - return error; + return (error); } #ifdef DEBUG_IOCOUNT -int vnode_debug_getwithvid(vnode_t *vp, uint64_t id, char *file, int line) +int +vnode_debug_getwithvid(vnode_t *vp, uint64_t id, char *file, int line) #else -int vnode_getwithvid(vnode_t *vp, uint64_t id) +int +vnode_getwithvid(vnode_t *vp, uint64_t id) #endif { // KIRQL OldIrql; @@ -1048,17 +962,20 @@ int vnode_getwithvid(vnode_t *vp, uint64_t id) mutex_enter(&vp->v_mutex); if ((vp->v_flags & VNODE_DEAD)) { error = ENOENT; - } else if (id != vp->v_id) { + } else if (id != vp->v_id) { error = ENOENT; // } else if (vnode_deleted(vp)) { // error = ENOENT; - } else { + } else { #ifdef DEBUG_IOCOUNT if (vp) { znode_t *zp = VTOZ(vp); - if (zp) dprintf("%s: Inc iocount now %u for '%s' (%s:%d) thread %p\n", __func__, - atomic_inc_32_nv(&vp->v_iocount), - zp->z_name_cache, file, line, current_thread()); + if (zp) + dprintf("%s: Inc iocount now %u for '%s' " + "(%s:%d) thread %p\n", __func__, + atomic_inc_32_nv(&vp->v_iocount), + zp->z_name_cache, file, line, + current_thread()); } #else atomic_inc_32(&vp->v_iocount); @@ -1066,15 +983,17 @@ int vnode_getwithvid(vnode_t *vp, uint64_t id) } mutex_exit(&vp->v_mutex); - return error; + return (error); } extern void zfs_inactive(vnode_t *vp, cred_t *cr, caller_context_t *ct); #ifdef DEBUG_IOCOUNT -int vnode_put(vnode_t *vp, char *file, int line) +int +vnode_put(vnode_t *vp, char *file, int line) #else -int vnode_put(vnode_t *vp) +int +vnode_put(vnode_t *vp) #endif { // KIRQL OldIrql; @@ -1085,9 +1004,11 @@ int vnode_put(vnode_t *vp) #ifdef DEBUG_IOCOUNT if (vp) { znode_t *zp = VTOZ(vp); - if (zp) dprintf("%s: Dec iocount now %u for '%s' (%s:%d) thread %p \n", __func__, - atomic_dec_32_nv(&vp->v_iocount), - zp->z_name_cache, file, line, current_thread()); + if (zp) + dprintf("%s: Dec iocount now %u for '%s' (%s:%d) " + "thread %p \n", __func__, + atomic_dec_32_nv(&vp->v_iocount), + zp->z_name_cache, file, line, current_thread()); } #else atomic_dec_32(&vp->v_iocount); @@ -1097,7 +1018,7 @@ int vnode_put(vnode_t *vp) if (vp->v_iocount == 0) { - if (vp->v_usecount == 0) + if (vp->v_usecount == 0) calldrain = 1; if (vp->v_flags & VNODE_NEEDINACTIVE) { @@ -1113,12 +1034,11 @@ int vnode_put(vnode_t *vp) #if 0 // Re-test for idle, as we may have dropped lock for inactive if ((vp->v_usecount == 0) && (vp->v_iocount == 0)) { - // Was it marked TERM, but we were waiting for last ref to leave. + // Was it marked TERM, but we were waiting for last ref if ((vp->v_flags & VNODE_MARKTERM)) { - //vnode_recycle_int(vp, VNODE_LOCKED); //OldIrql is lost! KeReleaseSpinLock(&vp->v_spinlock, OldIrql); - vnode_recycle_int(vp, 0); //OldIrql is lost! - return 0; + vnode_recycle_int(vp, 0); // OldIrql is lost! + return (0); } } #endif @@ -1128,17 +1048,18 @@ int vnode_put(vnode_t *vp) // if (calldrain) // vnode_drain_delayclose(0); - return 0; + return (0); } -int vnode_recycle_int(vnode_t *vp, int flags) +int +vnode_recycle_int(vnode_t *vp, int flags) { // KIRQL OldIrql; ASSERT((vp->v_flags & VNODE_DEAD) == 0); // Mark it for recycle, if we are not ROOT. if (!(vp->v_flags&VNODE_MARKROOT)) { - if (vp->v_flags & VNODE_MARKTERM) + if (vp->v_flags & VNODE_MARKTERM) dprintf("already marked\n"); vp->v_flags |= VNODE_MARKTERM; // Mark it terminating dprintf("%s: marking %p VNODE_MARKTERM\n", __func__, vp); @@ -1153,29 +1074,30 @@ int vnode_recycle_int(vnode_t *vp, int flags) // If it hasn't quite let go yet, let the node linger on deadlist. #if 1 if (vp->SectionObjectPointers.DataSectionObject != NULL || - vp->SectionObjectPointers.ImageSectionObject != NULL || - vp->SectionObjectPointers.SharedCacheMap != NULL) { - dprintf("%s: %p still has CcMgr, lingering on dead list.\n", __func__, vp); + vp->SectionObjectPointers.ImageSectionObject != NULL || + vp->SectionObjectPointers.SharedCacheMap != NULL) { + dprintf("%s: %p still has CcMgr, lingering on dead list.\n", + __func__, vp); mutex_exit(&vp->v_mutex); - return -1; + return (-1); } #endif // We will only reclaim idle nodes, and not mountpoints(ROOT) if ((flags & FORCECLOSE) || + ((vp->v_usecount == 0) && + (vp->v_iocount <= 1) && + avl_is_empty(&vp->v_fileobjects) && + ((vp->v_flags&VNODE_MARKROOT) == 0))) { - ((vp->v_usecount == 0) && - (vp->v_iocount <= 1) && - avl_is_empty(&vp->v_fileobjects) && - ((vp->v_flags&VNODE_MARKROOT) == 0))) { - - ASSERT3P(vp->SectionObjectPointers.DataSectionObject, == , NULL); - ASSERT3P(vp->SectionObjectPointers.ImageSectionObject, == , NULL); - ASSERT3P(vp->SectionObjectPointers.SharedCacheMap, == , NULL); + ASSERT3P(vp->SectionObjectPointers.DataSectionObject, ==, NULL); + ASSERT3P(vp->SectionObjectPointers.ImageSectionObject, ==, + NULL); + ASSERT3P(vp->SectionObjectPointers.SharedCacheMap, ==, NULL); vp->v_flags |= VNODE_DEAD; // Mark it dead - // Since we might get swapped out (noticably FsRtlTeardownPerStreamContexts) - // we hold a look until the very end. +// Since we might get swapped out (noticably FsRtlTeardownPerStreamContexts) +// we hold a look until the very end. vp->v_iocount = 1; mutex_exit(&vp->v_mutex); @@ -1184,7 +1106,7 @@ int vnode_recycle_int(vnode_t *vp, int flags) FsRtlUninitializeFileLock(&vp->lock); // Call sync? If vnode_write - //zfs_fsync(vp, 0, NULL, NULL); + // zfs_fsync(vp, 0, NULL, NULL); // Call inactive? if (vp->v_flags & VNODE_NEEDINACTIVE) { @@ -1193,9 +1115,9 @@ int vnode_recycle_int(vnode_t *vp, int flags) } - // Tell FS to release node. + // Tell FS to release node. if (zfs_vnop_reclaim(vp)) - panic("vnode_recycle: cannot reclaim\n"); // My fav panic from OSX + panic("vnode_recycle: cannot reclaim\n"); // KIRQL OldIrql; mutex_enter(&vp->v_mutex); @@ -1208,33 +1130,36 @@ int vnode_recycle_int(vnode_t *vp, int flags) vp->v_flags |= 0x8000; #endif - /* - * Windows has a habit of copying FsContext (vp) without our knowledge and attempt - * To call fsDispatcher. We notice in vnode_getwithref(), which calls mutex_enter - * so we can not free the vp right here like we want to, or that would be a MAF. - * So we let it linger and age, there is no great way to know for sure that it - * has finished trying. - */ +/* + * Windows has a habit of copying FsContext (vp) without our knowledge and + * attempt to call fsDispatcher. We notice in vnode_getwithref(), which + * calls mutex_enter so we can not free the vp right here like we want to, + * or that would be a MAF. + * So we let it linger and age, there is no great way to know for sure that it + * has finished trying. + */ dprintf("vp %p left on DEAD list\n", vp); vp->v_age = gethrtime(); - return 0; + return (0); } mutex_exit(&vp->v_mutex); - - return -1; + return (-1); } -int vnode_recycle(vnode_t *vp) +int +vnode_recycle(vnode_t *vp) { if (vp->v_flags & VNODE_FLUSHING) - return -1; - return vnode_recycle_int(vp, 0); + return (-1); + return (vnode_recycle_int(vp, 0)); } -void vnode_create(mount_t *mp, void *v_data, int type, int flags, struct vnode **vpp) +void +vnode_create(mount_t *mp, void *v_data, int type, int flags, + struct vnode **vpp) { struct vnode *vp; // cache_alloc does not zero the struct, we need to @@ -1253,14 +1178,15 @@ void vnode_create(mount_t *mp, void *v_data, int type, int flags, struct vnode * atomic_inc_64(&vnode_active); list_link_init(&vp->v_list); - ASSERT(vnode_fileobject_empty(vp, 1)); // lying about locked is ok. + ASSERT(vnode_fileobject_empty(vp, 1)); // lying about locked is ok. if (flags & VNODE_MARKROOT) vp->v_flags |= VNODE_MARKROOT; // Initialise the Windows specific data. - memset(&vp->SectionObjectPointers, 0, sizeof(vp->SectionObjectPointers)); + memset(&vp->SectionObjectPointers, 0, + sizeof (vp->SectionObjectPointers)); FsRtlSetupAdvancedHeader(&vp->FileHeader, &vp->AdvancedFcbHeaderMutex); @@ -1274,24 +1200,28 @@ void vnode_create(mount_t *mp, void *v_data, int type, int flags, struct vnode * mutex_exit(&vnode_all_list_lock); } -int vnode_isvroot(vnode_t *vp) +int +vnode_isvroot(vnode_t *vp) { return (vp->v_flags & VNODE_MARKROOT); } -mount_t *vnode_mount(vnode_t *vp) +mount_t * +vnode_mount(vnode_t *vp) { - return vp->v_mount; + return (vp->v_mount); } -void vnode_clearfsnode(vnode_t *vp) +void +vnode_clearfsnode(vnode_t *vp) { vp->v_data = NULL; } -void *vnode_sectionpointer(vnode_t *vp) +void * +vnode_sectionpointer(vnode_t *vp) { - return &vp->SectionObjectPointers; + return (&vp->SectionObjectPointers); } int @@ -1300,7 +1230,7 @@ vnode_ref(vnode_t *vp) ASSERT(vp->v_iocount > 0); ASSERT(!(vp->v_flags & VNODE_DEAD)); atomic_inc_32(&vp->v_usecount); - return 0; + return (0); } void @@ -1331,7 +1261,9 @@ vnode_rele(vnode_t *vp) #ifdef DEBUG_VERBOSE if (vp) { znode_t *zp = VTOZ(vp); - if (zp) dprintf("%s: Inc iocount to %u for %s \n", __func__, vp->v_iocount, zp->z_name_cache); + if (zp) + dprintf("%s: Inc iocount to %u for %s \n", + __func__, vp->v_iocount, zp->z_name_cache); } #endif atomic_dec_32(&vp->v_iocount); @@ -1339,7 +1271,7 @@ vnode_rele(vnode_t *vp) // we can reclaim now mutex_enter(&vp->v_mutex); if ((vp->v_iocount == 0) && (vp->v_usecount == 0) && - ((vp->v_flags & (VNODE_MARKTERM)))) { + ((vp->v_flags & (VNODE_MARKTERM)))) { mutex_exit(&vp->v_mutex); vnode_recycle_int(vp, 0); return; @@ -1354,7 +1286,8 @@ vnode_rele(vnode_t *vp) * Set force=1 to perform check now. * Will return number of vnodes with delete set, but not yet reclaimed. */ -int vnode_drain_delayclose(int force) +int +vnode_drain_delayclose(int force) { struct vnode *vp, *next = NULL; int ret = 0; @@ -1364,18 +1297,18 @@ int vnode_drain_delayclose(int force) const hrtime_t curtime = gethrtime(); mutex_enter(&vnode_all_list_lock); - // This should probably be its own thread, but for now, run once every 2s + // This should probably be its own thread, but for now, run every 2s if (!force && curtime - last < interval) { mutex_exit(&vnode_all_list_lock); - return 0; + return (0); } last = curtime; dprintf("%s: scanning\n", __func__); for (vp = list_head(&vnode_all_list); - vp; - vp = next) { + vp; + vp = next) { next = list_next(&vnode_all_list, vp); @@ -1389,40 +1322,45 @@ int vnode_drain_delayclose(int force) candidate = 0; if ((vp->v_flags & VNODE_MARKTERM) && - !(vp->v_flags & VNODE_DEAD) && - (vp->v_iocount == 0) && - (vp->v_usecount == 0) && - vnode_fileobject_empty(vp, /* locked */ 1) && - !vnode_isvroot(vp) && - (vp->SectionObjectPointers.ImageSectionObject == NULL) && - (vp->SectionObjectPointers.DataSectionObject == NULL)) { + !(vp->v_flags & VNODE_DEAD) && + (vp->v_iocount == 0) && + (vp->v_usecount == 0) && + vnode_fileobject_empty(vp, /* locked */ 1) && + !vnode_isvroot(vp) && + (vp->SectionObjectPointers.ImageSectionObject == NULL) && + (vp->SectionObjectPointers.DataSectionObject == NULL)) { // We are ready to let go dprintf("%s: drain %p\n", __func__, vp); - // Pass VNODELOCKED as we hold vp, recycle will unlock. - // We have to give up all_list due to recycle -> reclaim -> rmnode -> purgedir -> zget -> vnode_create +// Pass VNODELOCKED as we hold vp, recycle will unlock. +// We have to give up all_list due to +// recycle -> reclaim -> rmnode -> purgedir -> zget -> vnode_create mutex_exit(&vnode_all_list_lock); if (vnode_recycle_int(vp, VNODELOCKED) == 0) - candidate = 0; // If recycle was ok, this isnt a node we wait for + candidate = 0; +// If recycle was ok, this isnt a node we wait for + mutex_enter(&vnode_all_list_lock); // If successful, vp is freed. Do not use vp from here: } else if ((vp->v_flags & VNODE_DEAD) && - (vp->v_age != 0) && - (curtime - vp->v_age > SEC2NSEC(5))) { - // Arbitrary time! fixme? It would be nice to know when Windows really wont try this vp again. - // fastfat seems to clear up the cache of the parent directory, perhaps this is the missing - // bit. It is non-trivial to get parent from here though. - - //dprintf("age is %llu %d\n", (curtime - vp->v_age), NSEC2SEC(curtime - vp->v_age)); + (vp->v_age != 0) && + (curtime - vp->v_age > SEC2NSEC(5))) { +// Arbitrary time! fixme? It would be nice to know when Windows really +// wont try this vp again. fastfat seems to clear up the cache of the +// parent directory, perhaps this is the missing bit. It is non-trivial +// to get parent from here though. + + // dprintf("age is %llu %d\n", (curtime - vp->v_age), + // NSEC2SEC(curtime - vp->v_age)); // Finally free vp. list_remove(&vnode_all_list, vp); vnode_unlock(vp); dprintf("%s: freeing DEAD vp %p\n", __func__, vp); - kmem_cache_free(vnode_cache, vp); // Holding all_list_lock, that OK? + kmem_cache_free(vnode_cache, vp); atomic_dec_64(&vnode_active); } else { @@ -1433,19 +1371,20 @@ int vnode_drain_delayclose(int force) } mutex_exit(&vnode_all_list_lock); - return ret; + return (ret); } -int mount_count_nodes(struct mount *mp, int flags) +int +mount_count_nodes(struct mount *mp, int flags) { int count = 0; struct vnode *rvp; mutex_enter(&vnode_all_list_lock); for (rvp = list_head(&vnode_all_list); - rvp; - rvp = list_next(&vnode_all_list, rvp)) { - if (rvp->v_mount != mp) + rvp; + rvp = list_next(&vnode_all_list, rvp)) { + if (rvp->v_mount != mp) continue; if ((flags&SKIPROOT) && vnode_isvroot(rvp)) continue; @@ -1456,10 +1395,11 @@ int mount_count_nodes(struct mount *mp, int flags) count++; } mutex_exit(&vnode_all_list_lock); - return count; + return (count); } -int vflush(struct mount *mp, struct vnode *skipvp, int flags) +int +vflush(struct mount *mp, struct vnode *skipvp, int flags) { // Iterate the vnode list and call reclaim // flags: @@ -1479,27 +1419,27 @@ int vflush(struct mount *mp, struct vnode *skipvp, int flags) mutex_enter(&vnode_all_list_lock); while (1) { for (rvp = list_head(&vnode_all_list); - rvp; - rvp = list_next(&vnode_all_list, rvp)) { + rvp; + rvp = list_next(&vnode_all_list, rvp)) { // skip vnodes not belonging to this mount if (mp && rvp->v_mount != mp) continue; - // If we aren't FORCE and asked to SKIPROOT, and node + // If we aren't FORCE and asked to SKIPROOT, and node // is MARKROOT, then go to next. if (!(flags & FORCECLOSE)) if ((flags & SKIPROOT)) if (rvp->v_flags & VNODE_MARKROOT) continue; - + // We are to remove this node, even if ROOT - unmark it. mutex_exit(&vnode_all_list_lock); // Release the AVL tree // KIRQL OldIrql; - // Attempt to flush out any caches; + // Attempt to flush out any caches; mutex_enter(&rvp->v_mutex); // Make sure we don't call vnode_cacheflush() again // from IRP_MJ_CLOSE. @@ -1510,22 +1450,24 @@ int vflush(struct mount *mp, struct vnode *skipvp, int flags) node = AVL_NEXT(&rvp->v_fileobjects, node)) { FILE_OBJECT *fileobject = node->fileobject; - // Because the CC* calls can re-enter ZFS, we need to - // release the lock, and because we release the lock the - // while has to start from the top each time. We release - // the node at end of this while. + // Because the CC* calls can re-enter ZFS, we need to + // release the lock, and because we release the lock the + // while has to start from the top each time. We release + // the node at end of this while. - // Try to lock fileobject before we use it. + // Try to lock fileobject before we use it. if (NT_SUCCESS(ObReferenceObjectByPointer( - fileobject, // fixme, keep this in dvd - 0, - *IoFileObjectType, - KernelMode))) { + fileobject, // fixme, keep this in dvd + 0, + *IoFileObjectType, + KernelMode))) { int ok; - // Let go of mutex, as flushcache will re-enter (IRP_MJ_CLEANUP) + // Let go of mutex, as flushcache will re-enter + // (IRP_MJ_CLEANUP) mutex_exit(&rvp->v_mutex); - node->remove = vnode_flushcache(rvp, fileobject, TRUE); + node->remove = vnode_flushcache(rvp, + fileobject, TRUE); ObDereferenceObject(fileobject); @@ -1541,7 +1483,7 @@ int vflush(struct mount *mp, struct vnode *skipvp, int flags) node = AVL_NEXT(&rvp->v_fileobjects, node)) { if (node->remove) { avl_remove(&rvp->v_fileobjects, node); - kmem_free(node, sizeof(*node)); + kmem_free(node, sizeof (*node)); goto restart; } } @@ -1549,11 +1491,12 @@ int vflush(struct mount *mp, struct vnode *skipvp, int flags) dprintf("vp %p has %d fileobject(s) remaining\n", rvp, avl_numnodes(&rvp->v_fileobjects)); - // vnode_recycle_int() will call mutex_exit(&rvp->v_mutex); - // re-check flags, due to releasing locks + // vnode_recycle_int() will call mutex_exit(&rvp->v_mutex); + // re-check flags, due to releasing locks isbusy = 1; if (!(rvp->v_flags & VNODE_DEAD)) - isbusy = vnode_recycle_int(rvp, (flags & FORCECLOSE) | VNODELOCKED); + isbusy = vnode_recycle_int(rvp, + (flags & FORCECLOSE) | VNODELOCKED); else mutex_exit(&rvp->v_mutex); @@ -1566,7 +1509,8 @@ int vflush(struct mount *mp, struct vnode *skipvp, int flags) } // If the end of the list was reached, stop entirely - if (!rvp) break; + if (!rvp) + break; } mutex_exit(&vnode_all_list_lock); @@ -1600,18 +1544,17 @@ int vflush(struct mount *mp, struct vnode *skipvp, int flags) // GROSS HACK mutex_enter(&vnode_all_list_lock); for (rvp = list_head(&vnode_all_list); - rvp; - rvp = list_next(&vnode_all_list, rvp)) { + rvp; + rvp = list_next(&vnode_all_list, rvp)) { if (rvp->v_data && rvp->v_mount == mp) { - //mutex_exit(&vnode_all_list_lock); + // mutex_exit(&vnode_all_list_lock); zfs_vnop_reclaim(rvp); - //mutex_enter(&vnode_all_list_lock); + // mutex_enter(&vnode_all_list_lock); // Also empty fileobjects while (node = avl_first(&rvp->v_fileobjects)) { avl_remove(&rvp->v_fileobjects, node); - kmem_free(node, sizeof(*node)); + kmem_free(node, sizeof (*node)); } - } } mutex_exit(&vnode_all_list_lock); @@ -1619,33 +1562,38 @@ int vflush(struct mount *mp, struct vnode *skipvp, int flags) dprintf("vflush end\n"); - return 0; + return (0); } /* - * Set the Windows SecurityPolicy + * Set the Windows SecurityPolicy */ -void vnode_setsecurity(vnode_t *vp, void *sd) +void +vnode_setsecurity(vnode_t *vp, void *sd) { vp->security_descriptor = sd; } -void *vnode_security(vnode_t *vp) +void * +vnode_security(vnode_t *vp) { - return vp->security_descriptor; + return (vp->security_descriptor); } extern CACHE_MANAGER_CALLBACKS CacheManagerCallbacks; -void vnode_couplefileobject(vnode_t *vp, FILE_OBJECT *fileobject, uint64_t size) +void +vnode_couplefileobject(vnode_t *vp, FILE_OBJECT *fileobject, uint64_t size) { if (fileobject) { fileobject->FsContext = vp; // Make sure it is pointing to the right vp. - if (fileobject->SectionObjectPointer != vnode_sectionpointer(vp)) { - fileobject->SectionObjectPointer = vnode_sectionpointer(vp); + if (fileobject->SectionObjectPointer != + vnode_sectionpointer(vp)) { + fileobject->SectionObjectPointer = + vnode_sectionpointer(vp); } // If this fo's CcMgr hasn't been initialised, do so now @@ -1657,16 +1605,18 @@ void vnode_couplefileobject(vnode_t *vp, FILE_OBJECT *fileobject, uint64_t size) // Add this fileobject to the list of known ones. vnode_fileobject_add(vp, fileobject); - if (vnode_isvroot(vp)) return; + if (vnode_isvroot(vp)) + return; vnode_pager_setsize(vp, size); - vnode_setsizechange(vp, 0); // We are updating now, clear sizechange + vnode_setsizechange(vp, 0); } } // Attempt to boot CcMgr out of the fileobject, return // true if we could -int vnode_flushcache(vnode_t *vp, FILE_OBJECT *fileobject, boolean_t hard) +int +vnode_flushcache(vnode_t *vp, FILE_OBJECT *fileobject, boolean_t hard) { CACHE_UNINITIALIZE_EVENT UninitializeCompleteEvent; // NTSTATUS WaitStatus; @@ -1674,14 +1624,14 @@ int vnode_flushcache(vnode_t *vp, FILE_OBJECT *fileobject, boolean_t hard) int ret = 1; if (vp == NULL) - return 1; + return (1); if (fileobject == NULL) - return 1; + return (1); - // Have CcMgr already released it? + // Have CcMgr already released it? if (fileobject->SectionObjectPointer == NULL) - return 1; + return (1); if (FlagOn(fileobject->Flags, FO_CLEANUP_COMPLETE)) { // return 1; @@ -1689,7 +1639,7 @@ int vnode_flushcache(vnode_t *vp, FILE_OBJECT *fileobject, boolean_t hard) if (avl_numnodes(&vp->v_fileobjects) > 1) { dprintf("warning, has other fileobjects: %d\n", - avl_numnodes(&vp->v_fileobjects)); + avl_numnodes(&vp->v_fileobjects)); } int lastclose = 0; @@ -1697,67 +1647,74 @@ int vnode_flushcache(vnode_t *vp, FILE_OBJECT *fileobject, boolean_t hard) if (vp->v_iocount <= 1 && vp->v_usecount == 0) lastclose = 1; - // Because CcUninitializeCacheMap() can call MJ_CLOSE immediately, and we - // don't want to free anything in *that* call, take a usecount++ here, that - // way we skip the vnode_isinuse() test +// Because CcUninitializeCacheMap() can call MJ_CLOSE immediately, and we +// don't want to free anything in *that* call, take a usecount++ here, that +// way we skip the vnode_isinuse() test atomic_inc_32(&vp->v_usecount); if (fileobject->SectionObjectPointer->ImageSectionObject) { - if (hard) - (VOID)MmForceSectionClosed(fileobject->SectionObjectPointer, TRUE); + if (hard) + (void) MmForceSectionClosed( + fileobject->SectionObjectPointer, TRUE); else - (VOID)MmFlushImageSection(fileobject->SectionObjectPointer, MmFlushForWrite); + (void) MmFlushImageSection( + fileobject->SectionObjectPointer, MmFlushForWrite); } if (lastclose && FlagOn(fileobject->Flags, FO_CACHE_SUPPORTED)) { // DataSection next if (fileobject->SectionObjectPointer->DataSectionObject) { - CcFlushCache(fileobject->SectionObjectPointer, NULL, 0, NULL); - ExAcquireResourceExclusiveLite(vp->FileHeader.PagingIoResource, TRUE); + CcFlushCache(fileobject->SectionObjectPointer, NULL, 0, + NULL); + ExAcquireResourceExclusiveLite( + vp->FileHeader.PagingIoResource, TRUE); ExReleaseResourceLite(vp->FileHeader.PagingIoResource); } - CcPurgeCacheSection(fileobject->SectionObjectPointer, NULL, 0, hard); + CcPurgeCacheSection(fileobject->SectionObjectPointer, NULL, + 0, hard); #if 0 if (vp->has_uninit > 3) { NTSTATUS ntstatus; IO_STATUS_BLOCK IoStatus; - ntstatus = ZwDeviceIoControlFile(fileobject, - 0,0,0, &IoStatus, FSCTL_DISMOUNT_VOLUME, 0,0,0,0); + ntstatus = ZwDeviceIoControlFile(fileobject, 0, 0, 0, + &IoStatus, FSCTL_DISMOUNT_VOLUME, 0, 0, 0, 0); dprintf("Said 0x%x\n", ntstatus); - ntstatus = ZwDeviceIoControlFile(fileobject, - 0,0,0, &IoStatus, IRP_MN_REMOVE_DEVICE, 0,0,0,0); + ntstatus = ZwDeviceIoControlFile(fileobject, 0, 0, 0, + &IoStatus, IRP_MN_REMOVE_DEVICE, 0, 0, 0, 0); dprintf("Said 0x%x\n", ntstatus); } #endif - } if (!hard && avl_numnodes(&vp->v_fileobjects) > 1) { - //dprintf("leaving early due to v_fileobjects > 1 - flush only\n"); - //ret = 0; - //goto out; + // dprintf("leaving early due to v_fileobjects > 1 - flush only\n"); + // ret = 0; + // goto out; } KeInitializeEvent(&UninitializeCompleteEvent.Event, - SynchronizationEvent, - FALSE); + SynchronizationEvent, + FALSE); // Try to release cache dprintf("calling CcUninit: fo %p\n", fileobject); CcUninitializeCacheMap(fileobject, - hard ? &Zero : NULL, - NULL); + hard ? &Zero : NULL, + NULL); dprintf("complete CcUninit\n"); ret = 1; if (fileobject && fileobject->SectionObjectPointer) - if ((fileobject->SectionObjectPointer->ImageSectionObject != NULL) || - (fileobject->SectionObjectPointer->DataSectionObject != NULL) || - (fileobject->SectionObjectPointer->SharedCacheMap != NULL)) { + if ((fileobject->SectionObjectPointer->ImageSectionObject != + NULL) || + (fileobject->SectionObjectPointer->DataSectionObject != + NULL) || + (fileobject->SectionObjectPointer->SharedCacheMap != + NULL)) { ret = 0; dprintf("vp %p: Non^NULL entires so saying failed\n", vp); } @@ -1769,13 +1726,14 @@ int vnode_flushcache(vnode_t *vp, FILE_OBJECT *fileobject, boolean_t hard) // Unable to fully release CcMgr dprintf("%s: ret %d : vp %p fo %p\n", __func__, ret, - vp, fileobject); + vp, fileobject); - return ret; + return (ret); } -void vnode_decouplefileobject(vnode_t *vp, FILE_OBJECT *fileobject) +void +vnode_decouplefileobject(vnode_t *vp, FILE_OBJECT *fileobject) { if (fileobject && fileobject->FsContext) { dprintf("%s: fo %p -X-> %p\n", __func__, fileobject, vp); @@ -1793,7 +1751,8 @@ void vnode_decouplefileobject(vnode_t *vp, FILE_OBJECT *fileobject) } } -void vnode_setsizechange(vnode_t *vp, int set) +void +vnode_setsizechange(vnode_t *vp, int set) { if (set) vp->v_flags |= VNODE_SIZECHANGE; @@ -1801,35 +1760,37 @@ void vnode_setsizechange(vnode_t *vp, int set) vp->v_flags &= ~VNODE_SIZECHANGE; } -int vnode_sizechange(vnode_t *vp) +int +vnode_sizechange(vnode_t *vp) { return (vp->v_flags & VNODE_SIZECHANGE); } -int vnode_isrecycled(vnode_t *vp) +int +vnode_isrecycled(vnode_t *vp) { return (vp->v_flags&(VNODE_MARKTERM | VNODE_DEAD)); } -void vnode_lock(vnode_t *vp) +void +vnode_lock(vnode_t *vp) { mutex_enter(&vp->v_mutex); } -//int vnode_trylock(vnode_t *vp); - -void vnode_unlock(vnode_t *vp) +void +vnode_unlock(vnode_t *vp) { mutex_exit(&vp->v_mutex); } - /* * Add a FileObject to the list of FO in the vnode. * Return 1 if we actually added it * Return 0 if it was already in the list. */ -int vnode_fileobject_add(vnode_t *vp, void *fo) +int +vnode_fileobject_add(vnode_t *vp, void *fo) { vnode_fileobjects_t *node; avl_index_t idx; @@ -1840,11 +1801,11 @@ int vnode_fileobject_add(vnode_t *vp, void *fo) search.fileobject = fo; if (avl_find(&vp->v_fileobjects, &search, &idx) != NULL) { mutex_exit(&vp->v_mutex); - return 0; + return (0); } mutex_exit(&vp->v_mutex); - node = kmem_alloc(sizeof(*node), KM_SLEEP); + node = kmem_alloc(sizeof (*node), KM_SLEEP); node->fileobject = fo; node->remove = 0; @@ -1853,15 +1814,15 @@ int vnode_fileobject_add(vnode_t *vp, void *fo) avl_insert(&vp->v_fileobjects, node, idx); mutex_exit(&vp->v_mutex); dprintf("%s: added FO %p to vp %p\n", __func__, fo, vp); - return 1; + return (1); } else { mutex_exit(&vp->v_mutex); - kmem_free(node, sizeof(*node)); - return 0; + kmem_free(node, sizeof (*node)); + return (0); } // not reached. mutex_exit(&vp->v_mutex); - return 0; + return (0); } /* @@ -1869,7 +1830,8 @@ int vnode_fileobject_add(vnode_t *vp, void *fo) * Return 1 if we actually removed it * Return 0 if it was not in the list. */ -int vnode_fileobject_remove(vnode_t *vp, void *fo) +int +vnode_fileobject_remove(vnode_t *vp, void *fo) { vnode_fileobjects_t search, *node; // KIRQL OldIrql; @@ -1878,25 +1840,26 @@ int vnode_fileobject_remove(vnode_t *vp, void *fo) node = avl_find(&vp->v_fileobjects, &search, NULL); if (node == NULL) { mutex_exit(&vp->v_mutex); - - return 0; + return (0); } avl_remove(&vp->v_fileobjects, node); mutex_exit(&vp->v_mutex); - kmem_free(node, sizeof(*node)); + kmem_free(node, sizeof (*node)); dprintf("%s: remed FO %p fm vp %p\n", __func__, fo, vp); if (avl_numnodes(&vp->v_fileobjects) == 0) - dprintf("vp %p has no more fileobjects, it should be released\n", vp); + dprintf("vp %p no more fileobjects, it should be released\n", + vp); - return 1; + return (1); } /* * Check and make sure the list of FileObjects is empty */ -int vnode_fileobject_empty(vnode_t *vp, int locked) +int +vnode_fileobject_empty(vnode_t *vp, int locked) { // KIRQL OldIrql; @@ -1906,44 +1869,45 @@ int vnode_fileobject_empty(vnode_t *vp, int locked) if (!locked) mutex_exit(&vp->v_mutex); - return ret; + return (ret); } // Get cached EA size, returns 1 is it is cached, 0 if not. -int vnode_easize(struct vnode *vp, uint64_t *size) +int +vnode_easize(struct vnode *vp, uint64_t *size) { if (vp->v_flags & VNODE_EASIZE) { *size = vp->v_easize; - return 1; + return (1); } - return 0; + return (0); } -void vnode_set_easize(struct vnode *vp, uint64_t size) +void +vnode_set_easize(struct vnode *vp, uint64_t size) { vp->v_easize = size; vp->v_flags |= VNODE_EASIZE; } -void vnode_clear_easize(struct vnode *vp) +void +vnode_clear_easize(struct vnode *vp) { vp->v_flags &= ~VNODE_EASIZE; } #ifdef DEBUG_IOCOUNT -void vnode_check_iocount(void) +void +vnode_check_iocount(void) { /* Iterate all vnodes, checking that iocount is zero. */ struct vnode *rvp; mutex_enter(&vnode_all_list_lock); for (rvp = list_head(&vnode_all_list); - rvp; - rvp = list_next(&vnode_all_list, rvp)) { + rvp; + rvp = list_next(&vnode_all_list, rvp)) { ASSERT0(rvp->v_iocount); } mutex_exit(&vnode_all_list_lock); } #endif - - - diff --git a/module/os/windows/spl/spl-windows.c b/module/os/windows/spl/spl-windows.c index 5f2e7a7dc33..61231c94d47 100644 --- a/module/os/windows/spl/spl-windows.c +++ b/module/os/windows/spl/spl-windows.c @@ -29,27 +29,18 @@ #include #include -//#include -//#include #include #include #include -//#include #include #include #include -//#define MACH_KERNEL_PRIVATE - -//#include - -#define DEBUG 1 // for backtrace debugging info +#define DEBUG 1 // for backtrace debugging info static utsname_t utsname_static = { { 0 } }; -//extern struct machine_info machine_info; - unsigned int max_ncpus = 0; uint64_t total_memory = 0; uint64_t real_total_memory = 0; @@ -62,19 +53,11 @@ volatile unsigned int vm_page_speculative_count = 5500; uint64_t spl_GetPhysMem(void); #include -//#include -/* protect against: - * /System/Library/Frameworks/Kernel.framework/Headers/mach/task.h:197: error: conflicting types for ‘spl_thread_create’ - * ../../include/sys/thread.h:72: error: previous declaration of ‘spl_thread_create’ was here - */ -#define _task_user_ -//#include - #include // Size in bytes of the memory allocated in seg_kmem -extern uint64_t segkmem_total_mem_allocated; -#define MAXHOSTNAMELEN 64 +extern uint64_t segkmem_total_mem_allocated; +#define MAXHOSTNAMELEN 64 extern char hostname[MAXHOSTNAMELEN]; uint32_t spl_hostid = 0; @@ -84,22 +67,23 @@ uint32_t spl_hostid = 0; * Try to figure out why we fail linking with these two missing * Appears to come from including intrin.h - except we don't. */ -uint64_t __readcr8(void) +uint64_t +__readcr8(void) { - return 0ULL; + return (0ULL); } -unsigned long _byteswap_ulong(unsigned long b) +unsigned long +_byteswap_ulong(unsigned long b) { - return __builtin_bswap32(b); + return (__builtin_bswap32(b)); } #endif - utsname_t * utsname(void) { - return (&utsname_static); + return (&utsname_static); } /* @@ -115,19 +99,22 @@ windows_delay(int ticks) KeDelayExecutionThread(KernelMode, FALSE, &interval); } -uint32_t zone_get_hostid(void *zone) +uint32_t +zone_get_hostid(void *zone) { - return spl_hostid; + return (spl_hostid); } -const char *spl_panicstr(void) +const char * +spl_panicstr(void) { - return ""; + return (""); } -int spl_system_inshutdown(void) +int +spl_system_inshutdown(void) { - return 0; + return (0); } void @@ -138,12 +125,14 @@ hrt2ts(hrtime_t hrt, timespec_t *tsp) } // If we want to implement this on Windows, we could probably use -// https://stackoverflow.com/questions/590160/how-to-log-stack-frames-with-windows-x64 +// https:/ /stackoverflow.com/questions/590160/how-to-log- +// stack-frames-with-windows-x64 // which calls RtlCaptureStackBackTrace(); int getpcstack(uintptr_t *pcstack, int pcstack_limit) { - return RtlCaptureStackBackTrace(1, pcstack_limit, (PVOID *)pcstack, NULL); + return (RtlCaptureStackBackTrace(1, pcstack_limit, (PVOID *)pcstack, + NULL)); } /* @@ -157,7 +146,7 @@ getpcstack(uintptr_t *pcstack, int pcstack_limit) * 32 bit hash as a static hash type * * NOTE: To use the recommended 32 bit FNV-1a hash, use FNV1_32A_INIT as the - * hval arg on the first call to either fnv_32a_buf() or fnv_32a_str(). + * hval arg on the first call to either fnv_32a_buf() or fnv_32a_str(). */ uint32_t fnv_32a_str(const char *str, uint32_t hval) @@ -176,24 +165,25 @@ fnv_32a_str(const char *str, uint32_t hval) #if defined(NO_FNV_GCC_OPTIMIZATION) hval *= FNV_32_PRIME; #else - hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24); + hval += (hval << 1) + (hval << 4) + (hval << 7) + + (hval << 8) + (hval << 24); #endif } /* return our new hash value */ - return hval; + return (hval); } /* * fnv_32a_buf - perform a 32 bit Fowler/Noll/Vo FNV-1a hash on a buffer * * input: - *buf- start of buffer to hash - *len- length of buffer in octets - *hval- previous hash value or 0 if first call + * buf- start of buffer to hash + * len- length of buffer in octets + * hval- previous hash value or 0 if first call * * returns: - *32 bit hash as a static hash type + * 32 bit hash as a static hash type * * NOTE: To use the recommended 32 bit FNV-1a hash, use FNV1_32A_INIT as the * hval arg on the first call to either fnv_32a_buf() or fnv_32a_str(). @@ -201,8 +191,8 @@ fnv_32a_str(const char *str, uint32_t hval) uint32_t fnv_32a_buf(void *buf, size_t len, uint32_t hval) { - unsigned char *bp = (unsigned char *)buf;/* start of buffer */ - unsigned char *be = bp + len;/* beyond end of buffer */ + unsigned char *bp = (unsigned char *)buf; /* start of buffer */ + unsigned char *be = bp + len; /* beyond end of buffer */ /* * FNV-1a hash each octet in the buffer @@ -216,26 +206,26 @@ fnv_32a_buf(void *buf, size_t len, uint32_t hval) #if defined(NO_FNV_GCC_OPTIMIZATION) hval *= FNV_32_PRIME; #else - hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24); + hval += (hval << 1) + (hval << 4) + (hval << 7) + + (hval << 8) + (hval << 24); #endif } /* return our new hash value */ - return hval; + return (hval); } /* * Function to free a MDL chain */ -void UnlockAndFreeMdl(PMDL Mdl) +void +UnlockAndFreeMdl(PMDL Mdl) { PMDL currentMdl, nextMdl; - for (currentMdl = Mdl; currentMdl != NULL; currentMdl = nextMdl) - { + for (currentMdl = Mdl; currentMdl != NULL; currentMdl = nextMdl) { nextMdl = currentMdl->Next; - if (currentMdl->MdlFlags & MDL_PAGES_LOCKED) - { + if (currentMdl->MdlFlags & MDL_PAGES_LOCKED) { MmUnlockPages(currentMdl); } IoFreeMdl(currentMdl); @@ -250,32 +240,31 @@ ddi_copyin(const void *from, void *to, size_t len, int flags) PCHAR buffer = NULL; if (from == NULL || - to == NULL || - len == 0) - return 0; + to == NULL || + len == 0) + return (0); - /* Fake ioctl() issued by kernel, so we just need to bcopy */ + /* Fake ioctl() issued by kernel, so we just need to bcopy */ if (flags & FKIOCTL) { - if (flags & FCOPYSTR) + if (flags & FCOPYSTR) strlcpy(to, from, len); else bcopy(from, to, len); - return 0; + return (0); } - //ret = copyin((user_addr_t)from, (void *)to, len); // Lets try reading from the input nvlist dprintf("SPL: trying windows copyin: %p:%d\n", from, len); try { - ProbeForRead((void *)from, len, sizeof(UCHAR)); + ProbeForRead((void *)from, len, sizeof (UCHAR)); } - except(EXCEPTION_EXECUTE_HANDLER) - { + except(EXCEPTION_EXECUTE_HANDLER) { error = GetExceptionCode(); } if (error) { - TraceEvent(TRACE_ERROR, "SPL: Exception while accessing inBuf 0X%08X\n", error); + TraceEvent(TRACE_ERROR, + "SPL: Exception while accessing inBuf 0X%08X\n", error); goto out; } @@ -288,16 +277,17 @@ ddi_copyin(const void *from, void *to, size_t len, int flags) try { MmProbeAndLockPages(mdl, UserMode, IoReadAccess); } - except(EXCEPTION_EXECUTE_HANDLER) - { + except(EXCEPTION_EXECUTE_HANDLER) { error = GetExceptionCode(); } if (error) { - TraceEvent(TRACE_ERROR, "SPL: Exception while locking inBuf 0X%08X\n", error); + TraceEvent(TRACE_ERROR, + "SPL: Exception while locking inBuf 0X%08X\n", error); goto out; } - buffer = MmGetSystemAddressForMdlSafe(mdl, NormalPagePriority | MdlMappingNoExecute); + buffer = MmGetSystemAddressForMdlSafe(mdl, + NormalPagePriority | MdlMappingNoExecute); if (!buffer) { error = STATUS_INSUFFICIENT_RESOURCES; @@ -316,10 +306,9 @@ ddi_copyin(const void *from, void *to, size_t len, int flags) UnlockAndFreeMdl(mdl); } - return error; + return (error); } - int ddi_copyout(const void *from, void *to, size_t len, int flags) { @@ -328,39 +317,41 @@ ddi_copyout(const void *from, void *to, size_t len, int flags) PCHAR buffer = NULL; if (from == NULL || - to == NULL || - len == 0) - return 0; + to == NULL || + len == 0) + return (0); /* Fake ioctl() issued by kernel, 'from' is a kernel address */ if (flags & FKIOCTL) { bcopy(from, to, len); - return 0; + return (0); } - //dprintf("SPL: trying windows copyout: %p:%d\n", to, len); + // dprintf("SPL: trying windows copyout: %p:%d\n", to, len); mdl = IoAllocateMdl(to, len, FALSE, FALSE, NULL); if (!mdl) { error = STATUS_INSUFFICIENT_RESOURCES; - TraceEvent(TRACE_ERROR, "SPL: copyout failed to allocate mdl\n"); + TraceEvent(TRACE_ERROR, + "SPL: copyout failed to allocate mdl\n"); goto out; } try { MmProbeAndLockPages(mdl, UserMode, IoWriteAccess); } - except(EXCEPTION_EXECUTE_HANDLER) - { + except(EXCEPTION_EXECUTE_HANDLER) { error = GetExceptionCode(); } if (error != 0) { - TraceEvent(TRACE_ERROR, "SPL: Exception while locking outBuf 0X%08X\n", - error); + TraceEvent(TRACE_ERROR, + "SPL: Exception while locking outBuf 0X%08X\n", + error); goto out; } - buffer = MmGetSystemAddressForMdlSafe(mdl, NormalPagePriority | MdlMappingNoExecute); + buffer = MmGetSystemAddressForMdlSafe(mdl, + NormalPagePriority | MdlMappingNoExecute); if (!buffer) { error = STATUS_INSUFFICIENT_RESOURCES; @@ -369,13 +360,13 @@ ddi_copyout(const void *from, void *to, size_t len, int flags) // Success, copy over the data. bcopy(from, buffer, len); } - //dprintf("SPL: copyout return %d (%d bytes)\n", error, len); + // dprintf("SPL: copyout return %d (%d bytes)\n", error, len); out: if (mdl) { UnlockAndFreeMdl(mdl); } - return error; + return (error); } int @@ -386,59 +377,61 @@ ddi_copysetup(void *to, size_t len, void **out_buffer, PMDL *out_mdl) PCHAR buffer = NULL; if (to == NULL || - out_buffer == NULL || - out_mdl == NULL || - len == 0) - return 0; + out_buffer == NULL || + out_mdl == NULL || + len == 0) + return (0); - //dprintf("SPL: trying windows copyout_ex: %p:%d\n", to, len); + // dprintf("SPL: trying windows copyout_ex: %p:%d\n", to, len); // Do we have to call both? Or is calling ProbeForWrite enough? try { - ProbeForRead(to, len, sizeof(UCHAR)); + ProbeForRead(to, len, sizeof (UCHAR)); } - except(EXCEPTION_EXECUTE_HANDLER) - { + except(EXCEPTION_EXECUTE_HANDLER) { error = GetExceptionCode(); } if (error) { - TraceEvent(TRACE_ERROR, "SPL: Exception while accessing inBuf 0X%08X\n", error); + TraceEvent(TRACE_ERROR, + "SPL: Exception while accessing inBuf 0X%08X\n", error); goto out; } try { - ProbeForWrite(to, len, sizeof(UCHAR)); + ProbeForWrite(to, len, sizeof (UCHAR)); } - except(EXCEPTION_EXECUTE_HANDLER) - { + except(EXCEPTION_EXECUTE_HANDLER) { error = GetExceptionCode(); } if (error) { - TraceEvent(TRACE_ERROR, "SPL: Exception while accessing inBuf 0X%08X\n", error); + TraceEvent(TRACE_ERROR, + "SPL: Exception while accessing inBuf 0X%08X\n", error); goto out; } mdl = IoAllocateMdl(to, len, FALSE, FALSE, NULL); if (!mdl) { error = STATUS_INSUFFICIENT_RESOURCES; - TraceEvent(TRACE_ERROR, "SPL: copyout failed to allocate mdl\n"); + TraceEvent(TRACE_ERROR, + "SPL: copyout failed to allocate mdl\n"); goto out; } try { MmProbeAndLockPages(mdl, UserMode, IoWriteAccess); } - except(EXCEPTION_EXECUTE_HANDLER) - { + except(EXCEPTION_EXECUTE_HANDLER) { error = GetExceptionCode(); } if (error != 0) { - TraceEvent(TRACE_ERROR, "SPL: Exception while locking outBuf 0X%08X\n", - error); + TraceEvent(TRACE_ERROR, + "SPL: Exception while locking outBuf 0X%08X\n", + error); goto out; } - buffer = MmGetSystemAddressForMdlSafe(mdl, NormalPagePriority | MdlMappingNoExecute); + buffer = MmGetSystemAddressForMdlSafe(mdl, + NormalPagePriority | MdlMappingNoExecute); if (!buffer) { error = STATUS_INSUFFICIENT_RESOURCES; @@ -447,21 +440,23 @@ ddi_copysetup(void *to, size_t len, void **out_buffer, PMDL *out_mdl) *out_buffer = buffer; *out_mdl = mdl; - return 0; + return (0); out: if (mdl) { UnlockAndFreeMdl(mdl); } - return error; + return (error); } -/* Technically, this call does not exist in IllumOS, but we use it for +/* + * Technically, this call does not exist in IllumOS, but we use it for * consistency. */ -int ddi_copyinstr(const void *uaddr, void *kaddr, size_t len, size_t *done) +int +ddi_copyinstr(const void *uaddr, void *kaddr, size_t len, size_t *done) { int ret = 0; @@ -469,20 +464,14 @@ int ddi_copyinstr(const void *uaddr, void *kaddr, size_t len, size_t *done) if ((ret == STATUS_SUCCESS) && done) { *done = strlen(kaddr) + 1; // copyinstr includes the NULL byte } - return ret; + return (ret); } - - - -int spl_start (void) +int +spl_start(void) { - //max_ncpus = processor_avail_count; - // int ncpus; - // size_t len = sizeof(ncpus); - dprintf("SPL: start\n"); - max_ncpus = KeQueryActiveProcessorCountEx(ALL_PROCESSOR_GROUPS); + max_ncpus = KeQueryActiveProcessorCountEx(ALL_PROCESSOR_GROUPS); if (!max_ncpus) max_ncpus = 1; dprintf("SPL: total ncpu %d\n", max_ncpus); @@ -501,9 +490,9 @@ int spl_start (void) * not in charge of all memory and we need to leave some room for * the OS X allocator. We internally add pressure if we step over it */ - real_total_memory = total_memory; - total_memory = total_memory * 50ULL / 100ULL; // smd: experiment with 50%, 8GiB - physmem = total_memory / PAGE_SIZE; + real_total_memory = total_memory; + total_memory = total_memory * 50ULL / 100ULL; + physmem = total_memory / PAGE_SIZE; // We need to set these to some non-zero values // so we don't think there is permanent memory @@ -511,73 +500,55 @@ int spl_start (void) vm_page_free_count = (unsigned int)(physmem/2ULL); vm_page_speculative_count = vm_page_free_count; - /* - * For some reason, (CTLFLAG_KERN is not set) looking up hostname - * returns 1. So we set it to uuid just to give it *something*. - * As it happens, ZFS sets the nodename on init. - */ - //len = sizeof(utsname.nodename); - //sysctlbyname("kern.uuid", &utsname.nodename, &len, NULL, 0); - - //len = sizeof(utsname.release); - //sysctlbyname("kern.osrelease", &utsname.release, &len, NULL, 0); - - //len = sizeof(utsname.version); - //sysctlbyname("kern.version", &utsname.version, &len, NULL, 0); - - //strlcpy(utsname.nodename, hostname, sizeof(utsname.nodename)); - strlcpy(utsname_static.nodename, "Windows", sizeof(utsname_static.nodename)); - spl_mutex_subsystem_init(); - //DbgBreakPoint(); + /* + * For some reason, (CTLFLAG_KERN is not set) looking up hostname + * returns 1. So we set it to uuid just to give it *something*. + * As it happens, ZFS sets the nodename on init. + */ + strlcpy(utsname_static.nodename, "Windows", + sizeof (utsname_static.nodename)); + spl_mutex_subsystem_init(); spl_kmem_init(total_memory); spl_tsd_init(); spl_rwlock_init(); spl_taskq_init(); - spl_vnode_init(); + spl_vnode_init(); spl_kmem_thread_init(); spl_kmem_mp_init(); - IOLog("SPL: Loaded module v%s-%s%s, " - "(ncpu %d, memsize %llu, pages %llu)\n", - SPL_META_VERSION, SPL_META_RELEASE, SPL_DEBUG_STR, - max_ncpus, total_memory, physmem); - return STATUS_SUCCESS; + IOLog("SPL: Loaded module v%s-%s%s, " + "(ncpu %d, memsize %llu, pages %llu)\n", + SPL_META_VERSION, SPL_META_RELEASE, SPL_DEBUG_STR, + max_ncpus, total_memory, physmem); + return (STATUS_SUCCESS); } extern uint64_t zfs_threads; -int spl_stop (void) +int +spl_stop(void) { spl_kmem_thread_fini(); - spl_vnode_fini(); - spl_taskq_fini(); - spl_rwlock_fini(); + spl_vnode_fini(); + spl_taskq_fini(); + spl_rwlock_fini(); spl_tsd_fini(); - spl_kmem_fini(); - // XXX: we run into a bunch of problems with this kstat_fini stuff, as it calls vmem_fini a second time - // after spl_kmem_fini()->kernelheap_fini()->vmem_fini(heap_arena) got called - // and therefore destroys global structures twice - // so skip that for the moment - // - // spl_kstat_fini(); - spl_mutex_subsystem_fini(); - IOLog("SPL: Unloaded module v%s-%s " - "(os_mem_alloc: %llu)\n", - SPL_META_VERSION, SPL_META_RELEASE, - segkmem_total_mem_allocated); + spl_kmem_fini(); + spl_mutex_subsystem_fini(); + IOLog("SPL: Unloaded module v%s-%s " + "(os_mem_alloc: %llu)\n", + SPL_META_VERSION, SPL_META_RELEASE, + segkmem_total_mem_allocated); while (zfs_threads >= 1) { IOLog("SPL: active threads %d\n", zfs_threads); delay(hz << 2); } - return STATUS_SUCCESS; + return (STATUS_SUCCESS); } - - - -#define UNICODE +#define UNICODE #pragma pack(push, 4) typedef struct { @@ -590,13 +561,15 @@ typedef struct { #pragma pack(pop) /* TimoVJL */ -LONGLONG GetMemResources(char *pData) +LONGLONG +GetMemResources(char *pData) { LONGLONG llMem = 0; char *pPtr; uint32_t *pDW; pDW = (uint32_t *)pData; - if (*pDW != 1) return 0; + if (*pDW != 1) + return (0); DWORD nCnt = *(uint32_t *)(pData + 0x10); // Count pPtr = pData + 0x14; DWORD nRLen = 0; @@ -606,28 +579,28 @@ LONGLONG GetMemResources(char *pData) for (DWORD nIdx = 0; nRLen && nIdx < nCnt; nIdx++) { pMem = (PMEMORY)(pPtr + nRLen * nIdx); if (pMem->Type == 3) llMem += pMem->Length; - if (pMem->Type == 7 && pMem->Flags == 0x200) llMem += ((LONGLONG)pMem->Length) << 8; + if (pMem->Type == 7 && pMem->Flags == 0x200) + llMem += ((LONGLONG)pMem->Length) << 8; pMem += nRLen; } - return llMem; + return (llMem); } NTSTATUS spl_query_memsize( - IN PWSTR ValueName, - IN ULONG ValueType, - IN PVOID ValueData, - IN ULONG ValueLength, - IN PVOID Context, - IN PVOID EntryContext -) + IN PWSTR ValueName, + IN ULONG ValueType, + IN PVOID ValueData, + IN ULONG ValueLength, + IN PVOID Context, + IN PVOID EntryContext) { dprintf("%s: '%S' type 0x%x len 0x%x\n", __func__, - ValueName, ValueType, ValueLength); + ValueName, ValueType, ValueLength); if ((ValueType == REG_RESOURCE_LIST) && - (_wcsicmp(L".Translated", ValueName) == 0)) { + (_wcsicmp(L".Translated", ValueName) == 0)) { uint64_t *value; value = EntryContext; if (value) @@ -635,37 +608,37 @@ spl_query_memsize( dprintf("%s: memsize is %llu\n", __func__, value ? *value : 0); } - return STATUS_SUCCESS; + return (STATUS_SUCCESS); } - -uint64_t spl_GetPhysMem(void) +uint64_t +spl_GetPhysMem(void) { uint64_t memory; NTSTATUS status; - static RTL_QUERY_REGISTRY_TABLE query[2] = - { + static RTL_QUERY_REGISTRY_TABLE query[2] = + { { .Flags = RTL_QUERY_REGISTRY_REQUIRED - /*| RTL_QUERY_REGISTRY_DIRECT*/ - | RTL_QUERY_REGISTRY_NOEXPAND - | RTL_QUERY_REGISTRY_TYPECHECK, + /* | RTL_QUERY_REGISTRY_DIRECT */ + | RTL_QUERY_REGISTRY_NOEXPAND + | RTL_QUERY_REGISTRY_TYPECHECK, .QueryRoutine = spl_query_memsize, - } + } }; query[0].EntryContext = &memory; status = RtlQueryRegistryValues( - RTL_REGISTRY_ABSOLUTE, - L"\\REGISTRY\\MACHINE\\HARDWARE\\RESOURCEMAP\\System Resources\\Physical Memory", - query, NULL, NULL); + RTL_REGISTRY_ABSOLUTE, + L"\\REGISTRY\\MACHINE\\HARDWARE\\RESOURCEMAP\\" + "System Resources\\Physical Memory", + query, NULL, NULL); if (status != STATUS_SUCCESS) { - TraceEvent(TRACE_ERROR, "%s: size query failed: 0x%x\n", __func__, status); - return 0ULL; + TraceEvent(TRACE_ERROR, + "%s: size query failed: 0x%x\n", __func__, status); + return (0ULL); } - return memory; + return (memory); } - - diff --git a/module/os/windows/spl/spl-xdr.c b/module/os/windows/spl/spl-xdr.c index 1317826fec8..1a02711485f 100644 --- a/module/os/windows/spl/spl-xdr.c +++ b/module/os/windows/spl/spl-xdr.c @@ -149,7 +149,8 @@ xdrmem_create(XDR *xdrs, const caddr_t addr, const uint_t size, xdrs->x_ops = &xdrmem_decode_ops; break; default: - TraceEvent(TRACE_ERROR, "SPL: Invalid op value: %d\n", op); + TraceEvent(TRACE_ERROR, + "SPL: Invalid op value: %d\n", op); xdrs->x_ops = NULL; /* Let the caller know we failed */ return; } @@ -159,7 +160,9 @@ xdrmem_create(XDR *xdrs, const caddr_t addr, const uint_t size, xdrs->x_addr_end = addr + size; if (xdrs->x_addr_end < xdrs->x_addr) { - TraceEvent(TRACE_ERROR, "SPL: Overflow while creating xdrmem: %p, %u\n", addr, size); + TraceEvent(TRACE_ERROR, + "SPL: Overflow while creating xdrmem: %p, %u\n", + addr, size); xdrs->x_ops = NULL; } } @@ -168,17 +171,18 @@ EXPORT_SYMBOL(xdrmem_create); static bool_t xdrmem_control(XDR *xdrs, int req, void *info) { - struct xdr_bytesrec *rec = (struct xdr_bytesrec *) info; + struct xdr_bytesrec *rec = (struct xdr_bytesrec *)info; if (req != XDR_GET_BYTES_AVAIL) { - TraceEvent(TRACE_ERROR, "SPL: Called with unknown request: %d\n", req); - return FALSE; + TraceEvent(TRACE_ERROR, + "SPL: Called with unknown request: %d\n", req); + return (FALSE); } rec->xc_is_last_record = TRUE; /* always TRUE in xdrmem streams */ rec->xc_num_avail = (size_t)(xdrs->x_addr_end - xdrs->x_addr); - return TRUE; + return (TRUE); } static bool_t @@ -188,13 +192,13 @@ xdrmem_enc_bytes(XDR *xdrs, caddr_t cp, const uint_t cnt) uint_t pad; if (size < cnt) - return FALSE; /* Integer overflow */ + return (FALSE); /* Integer overflow */ if (xdrs->x_addr > xdrs->x_addr_end) - return FALSE; + return (FALSE); if (xdrs->x_addr_end - xdrs->x_addr < size) - return FALSE; + return (FALSE); memcpy(xdrs->x_addr, cp, cnt); @@ -206,7 +210,7 @@ xdrmem_enc_bytes(XDR *xdrs, caddr_t cp, const uint_t cnt) xdrs->x_addr += pad; } - return TRUE; + return (TRUE); } static bool_t @@ -217,13 +221,13 @@ xdrmem_dec_bytes(XDR *xdrs, caddr_t cp, const uint_t cnt) uint_t pad; if (size < cnt) - return FALSE; /* Integer overflow */ + return (FALSE); /* Integer overflow */ if (xdrs->x_addr > xdrs->x_addr_end) - return FALSE; + return (FALSE); if (xdrs->x_addr_end - xdrs->x_addr < size) - return FALSE; + return (FALSE); memcpy(cp, xdrs->x_addr, cnt); xdrs->x_addr += cnt; @@ -232,38 +236,38 @@ xdrmem_dec_bytes(XDR *xdrs, caddr_t cp, const uint_t cnt) if (pad > 0) { /* An inverted memchr() would be useful here... */ if (memcmp(&zero, xdrs->x_addr, pad) != 0) - return FALSE; + return (FALSE); xdrs->x_addr += pad; } - return TRUE; + return (TRUE); } static bool_t xdrmem_enc_uint32(XDR *xdrs, uint32_t val) { - if (xdrs->x_addr + sizeof(uint32_t) > xdrs->x_addr_end) - return FALSE; + if (xdrs->x_addr + sizeof (uint32_t) > xdrs->x_addr_end) + return (FALSE); - *((uint32_t *) xdrs->x_addr) = BE_32(val); + *((uint32_t *)xdrs->x_addr) = BE_32(val); - xdrs->x_addr += sizeof(uint32_t); + xdrs->x_addr += sizeof (uint32_t); - return TRUE; + return (TRUE); } static bool_t xdrmem_dec_uint32(XDR *xdrs, uint32_t *val) { - if (xdrs->x_addr + sizeof(uint32_t) > xdrs->x_addr_end) - return FALSE; + if (xdrs->x_addr + sizeof (uint32_t) > xdrs->x_addr_end) + return (FALSE); - *val = BE_32(*((uint32_t *) xdrs->x_addr)); + *val = BE_32(*((uint32_t *)xdrs->x_addr)); - xdrs->x_addr += sizeof(uint32_t); + xdrs->x_addr += sizeof (uint32_t); - return TRUE; + return (TRUE); } static bool_t @@ -271,10 +275,10 @@ xdrmem_enc_char(XDR *xdrs, char *cp) { uint32_t val; - //BUILD_BUG_ON(sizeof(char) != 1); + // BUILD_BUG_ON(sizeof(char) != 1); val = *((unsigned char *) cp); - return xdrmem_enc_uint32(xdrs, val); + return (xdrmem_enc_uint32(xdrs, val)); } static bool_t @@ -282,10 +286,10 @@ xdrmem_dec_char(XDR *xdrs, char *cp) { uint32_t val; - //BUILD_BUG_ON(sizeof(char) != 1); + // BUILD_BUG_ON(sizeof(char) != 1); if (!xdrmem_dec_uint32(xdrs, &val)) - return FALSE; + return (FALSE); /* * If any of the 3 other bytes are non-zero then val will be greater @@ -293,19 +297,19 @@ xdrmem_dec_char(XDR *xdrs, char *cp) * not have a char encoded in it. */ if (val > 0xff) - return FALSE; + return (FALSE); *((unsigned char *) cp) = (uint8_t)val; - return TRUE; + return (TRUE); } static bool_t xdrmem_enc_ushort(XDR *xdrs, unsigned short *usp) { - //BUILD_BUG_ON(sizeof(unsigned short) != 2); + // BUILD_BUG_ON(sizeof(unsigned short) != 2); - return xdrmem_enc_uint32(xdrs, *usp); + return (xdrmem_enc_uint32(xdrs, *usp)); } static bool_t @@ -313,48 +317,48 @@ xdrmem_dec_ushort(XDR *xdrs, unsigned short *usp) { uint32_t val; - //BUILD_BUG_ON(sizeof(unsigned short) != 2); + // BUILD_BUG_ON(sizeof(unsigned short) != 2); if (!xdrmem_dec_uint32(xdrs, &val)) - return FALSE; + return (FALSE); /* * Short ints are not in the RFC, but we assume similar logic as in * xdrmem_dec_char(). */ if (val > 0xffff) - return FALSE; + return (FALSE); *usp = (uint16_t)val; - return TRUE; + return (TRUE); } static bool_t xdrmem_enc_uint(XDR *xdrs, unsigned *up) { - //BUILD_BUG_ON(sizeof(unsigned) != 4); + // BUILD_BUG_ON(sizeof(unsigned) != 4); - return xdrmem_enc_uint32(xdrs, *up); + return (xdrmem_enc_uint32(xdrs, *up)); } static bool_t xdrmem_dec_uint(XDR *xdrs, unsigned *up) { - //BUILD_BUG_ON(sizeof(unsigned) != 4); + // BUILD_BUG_ON(sizeof(unsigned) != 4); - return xdrmem_dec_uint32(xdrs, (uint32_t *) up); + return (xdrmem_dec_uint32(xdrs, (uint32_t *)up)); } static bool_t xdrmem_enc_ulonglong(XDR *xdrs, u_longlong_t *ullp) { - //BUILD_BUG_ON(sizeof(u_longlong_t) != 8); + // BUILD_BUG_ON(sizeof(u_longlong_t) != 8); if (!xdrmem_enc_uint32(xdrs, *ullp >> 32)) - return FALSE; + return (FALSE); - return xdrmem_enc_uint32(xdrs, *ullp & 0xffffffff); + return (xdrmem_enc_uint32(xdrs, *ullp & 0xffffffff)); } static bool_t @@ -362,16 +366,16 @@ xdrmem_dec_ulonglong(XDR *xdrs, u_longlong_t *ullp) { uint32_t low, high; - //BUILD_BUG_ON(sizeof(u_longlong_t) != 8); + // BUILD_BUG_ON(sizeof(u_longlong_t) != 8); if (!xdrmem_dec_uint32(xdrs, &high)) - return FALSE; + return (FALSE); if (!xdrmem_dec_uint32(xdrs, &low)) - return FALSE; + return (FALSE); - *ullp = ((u_longlong_t) high << 32) | low; + *ullp = ((u_longlong_t)high << 32) | low; - return TRUE; + return (TRUE); } static bool_t @@ -382,18 +386,18 @@ xdr_enc_array(XDR *xdrs, caddr_t *arrp, uint_t *sizep, const uint_t maxsize, caddr_t addr = *arrp; if (*sizep > maxsize || *sizep > UINT_MAX / elsize) - return FALSE; + return (FALSE); if (!xdrmem_enc_uint(xdrs, sizep)) - return FALSE; + return (FALSE); for (i = 0; i < *sizep; i++) { if (!elproc(xdrs, addr)) - return FALSE; + return (FALSE); addr += elsize; } - return TRUE; + return (TRUE); } static bool_t @@ -405,23 +409,23 @@ xdr_dec_array(XDR *xdrs, caddr_t *arrp, uint_t *sizep, const uint_t maxsize, caddr_t addr; if (!xdrmem_dec_uint(xdrs, sizep)) - return FALSE; + return (FALSE); size = *sizep; if (size > maxsize || size > UINT_MAX / elsize) - return FALSE; + return (FALSE); /* * The Solaris man page says: "If *arrp is NULL when decoding, * xdr_array() allocates memory and *arrp points to it". */ if (*arrp == NULL) { - //BUILD_BUG_ON(sizeof(uint_t) > sizeof(size_t)); + // BUILD_BUG_ON(sizeof(uint_t) > sizeof(size_t)); *arrp = kmem_alloc(size * elsize, KM_NOSLEEP); if (*arrp == NULL) - return FALSE; + return (FALSE); alloc = TRUE; } @@ -432,12 +436,12 @@ xdr_dec_array(XDR *xdrs, caddr_t *arrp, uint_t *sizep, const uint_t maxsize, if (!elproc(xdrs, addr)) { if (alloc) kmem_free(*arrp, size * elsize); - return FALSE; + return (FALSE); } addr += elsize; } - return TRUE; + return (TRUE); } static bool_t @@ -447,14 +451,14 @@ xdr_enc_string(XDR *xdrs, char **sp, const uint_t maxsize) uint_t len; if (slen > maxsize) - return FALSE; + return (FALSE); len = slen; if (!xdrmem_enc_uint(xdrs, &len)) - return FALSE; + return (FALSE); - return xdrmem_enc_bytes(xdrs, *sp, len); + return (xdrmem_enc_bytes(xdrs, *sp, len)); } static bool_t @@ -464,21 +468,21 @@ xdr_dec_string(XDR *xdrs, char **sp, const uint_t maxsize) bool_t alloc = FALSE; if (!xdrmem_dec_uint(xdrs, &size)) - return FALSE; + return (FALSE); if (size > maxsize || size > UINT_MAX - 1) - return FALSE; + return (FALSE); /* * Solaris man page: "If *sp is NULL when decoding, xdr_string() * allocates memory and *sp points to it". */ if (*sp == NULL) { - //BUILD_BUG_ON(sizeof(uint_t) > sizeof(size_t)); + // BUILD_BUG_ON(sizeof(uint_t) > sizeof(size_t)); *sp = kmem_alloc(size + 1, KM_NOSLEEP); if (*sp == NULL) - return FALSE; + return (FALSE); alloc = TRUE; } @@ -491,33 +495,33 @@ xdr_dec_string(XDR *xdrs, char **sp, const uint_t maxsize) (*sp)[size] = '\0'; - return TRUE; + return (TRUE); fail: if (alloc) kmem_free(*sp, size + 1); - return FALSE; + return (FALSE); } static struct xdr_ops xdrmem_encode_ops = { - .xdr_control = xdrmem_control, - .xdr_char = xdrmem_enc_char, - .xdr_u_short = xdrmem_enc_ushort, - .xdr_u_int = xdrmem_enc_uint, - .xdr_u_longlong_t = xdrmem_enc_ulonglong, - .xdr_opaque = xdrmem_enc_bytes, - .xdr_string = xdr_enc_string, - .xdr_array = xdr_enc_array + .xdr_control = xdrmem_control, + .xdr_char = xdrmem_enc_char, + .xdr_u_short = xdrmem_enc_ushort, + .xdr_u_int = xdrmem_enc_uint, + .xdr_u_longlong_t = xdrmem_enc_ulonglong, + .xdr_opaque = xdrmem_enc_bytes, + .xdr_string = xdr_enc_string, + .xdr_array = xdr_enc_array }; static struct xdr_ops xdrmem_decode_ops = { - .xdr_control = xdrmem_control, - .xdr_char = xdrmem_dec_char, - .xdr_u_short = xdrmem_dec_ushort, - .xdr_u_int = xdrmem_dec_uint, - .xdr_u_longlong_t = xdrmem_dec_ulonglong, - .xdr_opaque = xdrmem_dec_bytes, - .xdr_string = xdr_dec_string, - .xdr_array = xdr_dec_array + .xdr_control = xdrmem_control, + .xdr_char = xdrmem_dec_char, + .xdr_u_short = xdrmem_dec_ushort, + .xdr_u_int = xdrmem_dec_uint, + .xdr_u_longlong_t = xdrmem_dec_ulonglong, + .xdr_opaque = xdrmem_dec_bytes, + .xdr_string = xdr_dec_string, + .xdr_array = xdr_dec_array }; diff --git a/module/os/windows/spl/spl-zlib.c b/module/os/windows/spl/spl-zlib.c index a758198f425..d066bbd2822 100644 --- a/module/os/windows/spl/spl-zlib.c +++ b/module/os/windows/spl/spl-zlib.c @@ -1,4 +1,4 @@ -/*****************************************************************************\ +/* * * zlib.h -- interface of the 'zlib' general purpose compression library * version 1.2.5, April 19th, 2010 @@ -23,8 +23,7 @@ * * Jean-loup Gailly * Mark Adler -\*****************************************************************************/ - + */ #include #include @@ -35,7 +34,7 @@ #undef DEBUG_SUBSYSTEM #endif -#define DEBUG_SUBSYSTEM SS_ZLIB +#define DEBUG_SUBSYSTEM SS_ZLIB static spl_kmem_cache_t *zlib_workspace_cache; @@ -51,7 +50,7 @@ static spl_kmem_cache_t *zlib_workspace_cache; static void * zlib_workspace_alloc(int flags) { - return kmem_cache_alloc(zlib_workspace_cache, flags & ~(__GFP_FS)); + return (kmem_cache_alloc(zlib_workspace_cache, flags & ~(__GFP_FS))); } static void @@ -73,7 +72,7 @@ zlib_workspace_free(void *workspace) */ int z_compress_level(void *dest, size_t *destLen, const void *source, - size_t sourceLen, int level) + size_t sourceLen, int level) { z_stream stream; int err; @@ -84,30 +83,30 @@ z_compress_level(void *dest, size_t *destLen, const void *source, stream.avail_out = (uInt)*destLen; if ((size_t)stream.avail_out != *destLen) - return Z_BUF_ERROR; + return (Z_BUF_ERROR); stream.workspace = zlib_workspace_alloc(KM_SLEEP); if (!stream.workspace) - return Z_MEM_ERROR; + return (Z_MEM_ERROR); err = zlib_deflateInit(&stream, level); if (err != Z_OK) { zlib_workspace_free(stream.workspace); - return err; + return (err); } err = zlib_deflate(&stream, Z_FINISH); if (err != Z_STREAM_END) { zlib_deflateEnd(&stream); zlib_workspace_free(stream.workspace); - return err == Z_OK ? Z_BUF_ERROR : err; + return (err == Z_OK ? Z_BUF_ERROR : err); } *destLen = stream.total_out; err = zlib_deflateEnd(&stream); zlib_workspace_free(stream.workspace); - return err; + return (err); } EXPORT_SYMBOL(z_compress_level); @@ -138,16 +137,16 @@ z_uncompress(void *dest, size_t *destLen, const void *source, size_t sourceLen) stream.avail_out = (uInt)*destLen; if ((size_t)stream.avail_out != *destLen) - return Z_BUF_ERROR; + return (Z_BUF_ERROR); stream.workspace = zlib_workspace_alloc(KM_SLEEP); if (!stream.workspace) - return Z_MEM_ERROR; + return (Z_MEM_ERROR); err = zlib_inflateInit(&stream); if (err != Z_OK) { zlib_workspace_free(stream.workspace); - return err; + return (err); } err = zlib_inflate(&stream, Z_FINISH); @@ -156,17 +155,17 @@ z_uncompress(void *dest, size_t *destLen, const void *source, size_t sourceLen) zlib_workspace_free(stream.workspace); if (err == Z_NEED_DICT || - (err == Z_BUF_ERROR && stream.avail_in == 0)) - return Z_DATA_ERROR; + (err == Z_BUF_ERROR && stream.avail_in == 0)) + return (Z_DATA_ERROR); - return err; + return (err); } *destLen = stream.total_out; err = zlib_inflateEnd(&stream); zlib_workspace_free(stream.workspace); - return err; + return (err); } EXPORT_SYMBOL(z_uncompress); @@ -174,7 +173,7 @@ int spl_zlib_init(void) { int size; - SENTRY; + SENTRY; size = MAX(spl_zlib_deflate_workspacesize(MAX_WBITS, MAX_MEM_LEVEL), zlib_inflate_workspacesize()); @@ -183,17 +182,17 @@ spl_zlib_init(void) "spl_zlib_workspace_cache", size, 0, NULL, NULL, NULL, NULL, NULL, KMC_VMEM | KMC_NOEMERGENCY); - if (!zlib_workspace_cache) + if (!zlib_workspace_cache) SRETURN(1); - SRETURN(0); + SRETURN(0); } void spl_zlib_fini(void) { - SENTRY; + SENTRY; kmem_cache_destroy(zlib_workspace_cache); - zlib_workspace_cache = NULL; - SEXIT; + zlib_workspace_cache = NULL; + SEXIT; } diff --git a/module/os/windows/zfs/arc_os.c b/module/os/windows/zfs/arc_os.c index 79b48008bec..cf3bfc4b301 100644 --- a/module/os/windows/zfs/arc_os.c +++ b/module/os/windows/zfs/arc_os.c @@ -879,4 +879,3 @@ arc_prune_async(int64_t adjust) } mutex_exit(&arc_prune_mtx); } - diff --git a/module/os/windows/zfs/spa_misc_os.c b/module/os/windows/zfs/spa_misc_os.c index db5dd630752..d75e3cd29fa 100644 --- a/module/os/windows/zfs/spa_misc_os.c +++ b/module/os/windows/zfs/spa_misc_os.c @@ -66,7 +66,7 @@ spa_export_os(void *arg) void spa_activate_os(void *arg) { - atomic_inc_64(&zfs_module_busy); + atomic_inc_64(&zfs_module_busy); } void diff --git a/module/os/windows/zfs/vdev_disk.c b/module/os/windows/zfs/vdev_disk.c index 83ee6004927..2f6d3c4697c 100644 --- a/module/os/windows/zfs/vdev_disk.c +++ b/module/os/windows/zfs/vdev_disk.c @@ -18,7 +18,7 @@ * * CDDL HEADER END */ - /* +/* * Copyright (c) 2017 Jorgen Lundman */ @@ -76,19 +76,22 @@ static void disk_exclusive(DEVICE_OBJECT *device, boolean_t excl) DWORD returnedSize; // Set disk attributes. - diskAttrs.Version = sizeof(diskAttrs); - diskAttrs.AttributesMask = DISK_ATTRIBUTE_OFFLINE | DISK_ATTRIBUTE_READ_ONLY; - diskAttrs.Attributes = excl ? DISK_ATTRIBUTE_OFFLINE | DISK_ATTRIBUTE_READ_ONLY : 0; + diskAttrs.Version = sizeof (diskAttrs); + diskAttrs.AttributesMask = + DISK_ATTRIBUTE_OFFLINE | DISK_ATTRIBUTE_READ_ONLY; + diskAttrs.Attributes = + excl ? DISK_ATTRIBUTE_OFFLINE | DISK_ATTRIBUTE_READ_ONLY : 0; diskAttrs.Persist = FALSE; if (kernel_ioctl(device, NULL, IOCTL_DISK_SET_DISK_ATTRIBUTES, - &diskAttrs, sizeof(diskAttrs), NULL, 0) != 0) { + &diskAttrs, sizeof (diskAttrs), NULL, 0) != 0) { dprintf("IOCTL_DISK_SET_DISK_ATTRIBUTES"); return; } // Tell the system that the disk was changed. - if (kernel_ioctl(device, NULL, IOCTL_DISK_UPDATE_PROPERTIES, NULL, 0, NULL, 0) != 0) + if (kernel_ioctl(device, NULL, IOCTL_DISK_UPDATE_PROPERTIES, NULL, + 0, NULL, 0) != 0) dprintf("IOCTL_DISK_UPDATE_PROPERTIES"); } @@ -99,14 +102,14 @@ static void disk_exclusive(DEVICE_OBJECT *device, boolean_t excl) * even a fallback to DKIOCGMEDIAINFO fails. */ #ifdef DEBUG -#define VDEV_DEBUG(...) cmn_err(CE_NOTE, __VA_ARGS__) +#define VDEV_DEBUG(...) cmn_err(CE_NOTE, __VA_ARGS__) #else -#define VDEV_DEBUG(...) /* Nothing... */ +#define VDEV_DEBUG(...) /* Nothing... */ #endif static int vdev_disk_open(vdev_t *vd, uint64_t *psize, uint64_t *max_psize, - uint64_t *ashift, uint64_t *physical_ashif) + uint64_t *ashift, uint64_t *physical_ashif) { spa_t *spa = vd->vdev_spa; vdev_disk_t *dvd = vd->vdev_tsd; @@ -117,12 +120,14 @@ vdev_disk_open(vdev_t *vd, uint64_t *psize, uint64_t *max_psize, PAGED_CODE(); - dprintf("%s: open of '%s' (physpath '%s')\n", __func__, vd->vdev_path, vd->vdev_physpath ? vd->vdev_physpath : ""); + dprintf("%s: open of '%s' (physpath '%s')\n", __func__, + vd->vdev_path, vd->vdev_physpath ? vd->vdev_physpath : ""); /* * We must have a pathname, and it must be absolute. * It can also start with # for partition encoded paths */ - if (vd->vdev_path == NULL || (vd->vdev_path[0] != '/' && vd->vdev_path[0] != '#' && + if (vd->vdev_path == NULL || + (vd->vdev_path[0] != '/' && vd->vdev_path[0] != '#' && vd->vdev_path[0] != '\\')) { vd->vdev_stat.vs_aux = VDEV_AUX_BAD_LABEL; return (SET_ERROR(EINVAL)); @@ -140,16 +145,15 @@ vdev_disk_open(vdev_t *vd, uint64_t *psize, uint64_t *max_psize, * up the LDI event callbacks and free vd->vdev_tsd. */ vdev_disk_free(vd); - } - else { + } else { ASSERT(vd->vdev_reopening); goto skip_open; } } /* - * Create vd->vdev_tsd. - */ + * Create vd->vdev_tsd. + */ vdev_disk_alloc(vd); dvd = vd->vdev_tsd; @@ -163,7 +167,7 @@ vdev_disk_open(vdev_t *vd, uint64_t *psize, uint64_t *max_psize, // Use vd->vdev_physpath first, if set, otherwise // usual vd->vdev_path - if (vd->vdev_physpath) + if (vd->vdev_physpath) vdev_path = spa_strdup(vd->vdev_physpath); else vdev_path = spa_strdup(vd->vdev_path); @@ -179,13 +183,12 @@ vdev_disk_open(vdev_t *vd, uint64_t *psize, uint64_t *max_psize, while (end && end[0] == '#') end++; FileName = end; - } - else { + } else { FileName = vdev_path; // Sometimes only vdev_path is set, with "/dev/physicaldrive" // make it be " \??\physicaldrive" space skipped over. - if (!strncmp("/dev/", FileName, 5)) { + if (strncmp("/dev/", FileName, 5) == 0) { FileName[0] = ' '; FileName[1] = '\\'; FileName[2] = '?'; @@ -197,22 +200,22 @@ vdev_disk_open(vdev_t *vd, uint64_t *psize, uint64_t *max_psize, // Apparently in Userland it is "\\?\" but in // kernel has to be "\??\" - is there not a name that works in both? - if (!strncmp("\\\\?\\", FileName, 4)) { + if (strncmp("\\\\?\\", FileName, 4) == 0) { FileName[1] = '?'; } dprintf("%s: opening '%s'\n", __func__, FileName); - ANSI_STRING AnsiFilespec; - UNICODE_STRING UnicodeFilespec; - OBJECT_ATTRIBUTES ObjectAttributes; + ANSI_STRING AnsiFilespec; + UNICODE_STRING UnicodeFilespec; + OBJECT_ATTRIBUTES ObjectAttributes; - SHORT UnicodeName[PATH_MAX]; - CHAR AnsiName[PATH_MAX]; - USHORT NameLength = 0; + SHORT UnicodeName[PATH_MAX]; + CHAR AnsiName[PATH_MAX]; + USHORT NameLength = 0; - memset(UnicodeName, 0, sizeof(SHORT) * PATH_MAX); - memset(AnsiName, 0, sizeof(UCHAR) * PATH_MAX); + memset(UnicodeName, 0, sizeof (SHORT) * PATH_MAX); + memset(AnsiName, 0, sizeof (UCHAR) * PATH_MAX); NameLength = strlen(FileName); ASSERT(NameLength < PATH_MAX); @@ -228,25 +231,28 @@ vdev_disk_open(vdev_t *vd, uint64_t *psize, uint64_t *max_psize, RtlAnsiStringToUnicodeString(&UnicodeFilespec, &AnsiFilespec, FALSE); - ObjectAttributes.Length = sizeof(OBJECT_ATTRIBUTES); + ObjectAttributes.Length = sizeof (OBJECT_ATTRIBUTES); ObjectAttributes.RootDirectory = NULL; - ObjectAttributes.Attributes = /*OBJ_CASE_INSENSITIVE |*/ OBJ_KERNEL_HANDLE; + ObjectAttributes.Attributes = OBJ_KERNEL_HANDLE; ObjectAttributes.ObjectName = &UnicodeFilespec; ObjectAttributes.SecurityDescriptor = NULL; ObjectAttributes.SecurityQualityOfService = NULL; IO_STATUS_BLOCK iostatus; ntstatus = ZwCreateFile(&dvd->vd_lh, - spa_mode(spa) == SPA_MODE_READ ? GENERIC_READ | SYNCHRONIZE : GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE, - &ObjectAttributes, - &iostatus, - 0, - FILE_ATTRIBUTE_NORMAL, - /* FILE_SHARE_WRITE | */ FILE_SHARE_READ, - FILE_OPEN, - FILE_SYNCHRONOUS_IO_NONALERT | (spa_mode(spa) == SPA_MODE_READ ? 0 : FILE_NO_INTERMEDIATE_BUFFERING), - NULL, - 0); + spa_mode(spa) == SPA_MODE_READ ? GENERIC_READ | SYNCHRONIZE : + GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE, + &ObjectAttributes, + &iostatus, + 0, + FILE_ATTRIBUTE_NORMAL, + /* FILE_SHARE_WRITE | */ FILE_SHARE_READ, + FILE_OPEN, + FILE_SYNCHRONOUS_IO_NONALERT | + (spa_mode(spa) == SPA_MODE_READ ? 0 : + FILE_NO_INTERMEDIATE_BUFFERING), + NULL, + 0); if (ntstatus == STATUS_SUCCESS) { error = 0; @@ -256,9 +262,9 @@ vdev_disk_open(vdev_t *vd, uint64_t *psize, uint64_t *max_psize, } /* - * If we succeeded in opening the device, but 'vdev_wholedisk' - * is not yet set, then this must be a slice. - */ + * If we succeeded in opening the device, but 'vdev_wholedisk' + * is not yet set, then this must be a slice. + */ if (error == 0 && vd->vdev_wholedisk == -1ULL) vd->vdev_wholedisk = 0; @@ -271,25 +277,24 @@ vdev_disk_open(vdev_t *vd, uint64_t *psize, uint64_t *max_psize, // Since we will use DeviceObject and FileObject to do ioctl and IO // we grab them now and lock them in place. // Convert HANDLE to FileObject - PFILE_OBJECT FileObject; - PDEVICE_OBJECT DeviceObject; + PFILE_OBJECT FileObject; + PDEVICE_OBJECT DeviceObject; NTSTATUS status; // This adds a reference to FileObject status = ObReferenceObjectByHandle( - dvd->vd_lh, // fixme, keep this in dvd - 0, - *IoFileObjectType, - KernelMode, - &FileObject, - NULL - ); + dvd->vd_lh, // fixme, keep this in dvd + 0, + *IoFileObjectType, + KernelMode, + &FileObject, + NULL); if (status != STATUS_SUCCESS) { ZwClose(dvd->vd_lh); dvd->vd_lh = NULL; vd->vdev_stat.vs_aux = VDEV_AUX_OPEN_FAILED; spa_strfree(vdev_path); - return EIO; + return (EIO); } @@ -297,19 +302,20 @@ vdev_disk_open(vdev_t *vd, uint64_t *psize, uint64_t *max_psize, PDEVICE_OBJECT pTopDevice = IoGetRelatedDeviceObject(FileObject); PDEVICE_OBJECT pSendToDevice = pTopDevice; // default - /* - Move to the top of the device stack or until we find the protection filter driver. - We need to stay under that driver so we can still access the disk - after protecting it. - The custom protection filter is optional: if none set we stay under the default "partmgr" driver; - otherwise we will stay under the first one found. - By default the disk gets minimal protection being set offline and read only through "partmgr". - A custom filter driver can provide enhanced protection for the vdev disk. - */ +/* + * Move to the top of the device stack or until we find the protection + * filter driver. We need to stay under that driver so we can still + * access the disk after protecting it. + * The custom protection filter is optional: if none set we stay under + * the default "partmgr" driver; otherwise we will stay under the first + * one found. By default the disk gets minimal protection being set offline + * and read only through "partmgr". A custom filter driver can provide + * enhanced protection for the vdev disk. + */ UNICODE_STRING customFilterName; UNICODE_STRING defaultFilterName; RtlInitUnicodeString(&customFilterName, zfs_vdev_protection_filter); - RtlInitUnicodeString(&defaultFilterName, L"\\Driver\\partmgr"); // default + RtlInitUnicodeString(&defaultFilterName, L"\\Driver\\partmgr"); DeviceObject = FileObject->DeviceObject; // bottom of stack ObReferenceObject(DeviceObject); @@ -323,28 +329,32 @@ vdev_disk_open(vdev_t *vd, uint64_t *psize, uint64_t *max_psize, capacity = dvd->vdev_win_length; // STORAGE_DEVICE_NUMBER sdn = { 0 }; - // kernel_ioctl(DeviceObject, FileObject, IOCTL_STORAGE_GET_DEVICE_NUMBER, - // NULL, 0, &sdn, sizeof(sdn)); + // kernel_ioctl(DeviceObject, FileObject, + // IOCTL_STORAGE_GET_DEVICE_NUMBER, + // NULL, 0, &sdn, sizeof(sdn)); if (capacity == 0ULL) { PARTITION_INFORMATION_EX pix = {0}; - if (kernel_ioctl(DeviceObject, FileObject, IOCTL_DISK_GET_PARTITION_INFO_EX, - NULL, 0, &pix, sizeof(pix)) == 0) + if (kernel_ioctl(DeviceObject, FileObject, + IOCTL_DISK_GET_PARTITION_INFO_EX, + NULL, 0, &pix, sizeof (pix)) == 0) capacity = pix.PartitionLength.QuadPart; } if (capacity == 0ULL) { PARTITION_INFORMATION pi = {0}; - if (kernel_ioctl(DeviceObject, FileObject, IOCTL_DISK_GET_PARTITION_INFO, - NULL, 0, &pi, sizeof(pi)) == 0) + if (kernel_ioctl(DeviceObject, FileObject, + IOCTL_DISK_GET_PARTITION_INFO, + NULL, 0, &pi, sizeof (pi)) == 0) capacity = pi.PartitionLength.QuadPart; } if (capacity == 0ULL) { GET_LENGTH_INFORMATION len; - if (kernel_ioctl(DeviceObject, FileObject, IOCTL_DISK_GET_LENGTH_INFO, - NULL, 0, &len, sizeof(len)) == 0) + if (kernel_ioctl(DeviceObject, FileObject, + IOCTL_DISK_GET_LENGTH_INFO, + NULL, 0, &len, sizeof (len)) == 0) capacity = len.Length.QuadPart; } @@ -352,29 +362,37 @@ vdev_disk_open(vdev_t *vd, uint64_t *psize, uint64_t *max_psize, DISK_GEOMETRY_EX geometry_ex = {0}; DWORD len; - if (kernel_ioctl(DeviceObject, FileObject, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, - NULL, 0, &geometry_ex, sizeof(geometry_ex)) == 0) + if (kernel_ioctl(DeviceObject, FileObject, + IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, + NULL, 0, &geometry_ex, sizeof (geometry_ex)) == 0) capacity = geometry_ex.DiskSize.QuadPart; } if (capacity == 0ULL && vd->vdev_wholedisk) { STORAGE_READ_CAPACITY cap = {0}; - cap.Version = sizeof(STORAGE_READ_CAPACITY); - if (kernel_ioctl(DeviceObject, FileObject, IOCTL_STORAGE_READ_CAPACITY, - NULL, 0, &cap, sizeof(cap)) == 0) + cap.Version = sizeof (STORAGE_READ_CAPACITY); + if (kernel_ioctl(DeviceObject, FileObject, + IOCTL_STORAGE_READ_CAPACITY, + NULL, 0, &cap, sizeof (cap)) == 0) capacity = cap.DiskLength.QuadPart; } // Remember the size for when we skip_open dvd->vdev_win_length = capacity; - // Now walk up the stack locating the device to lock while (DeviceObject) { - if ((zfs_vdev_protection_filter[0] != L'\0' ? !RtlCompareUnicodeString(&DeviceObject->DriverObject->DriverName, &customFilterName, TRUE) : FALSE) || - !RtlCompareUnicodeString(&DeviceObject->DriverObject->DriverName, &defaultFilterName, TRUE)) { - dprintf("%s: disk %s : vdev protection filter set to %S\n", __func__, - FileName, DeviceObject->DriverObject->DriverName.Buffer); + if ((zfs_vdev_protection_filter[0] != L'\0' ? + !RtlCompareUnicodeString( + &DeviceObject->DriverObject->DriverName, + &customFilterName, TRUE) : FALSE) || + !RtlCompareUnicodeString( + &DeviceObject->DriverObject->DriverName, + &defaultFilterName, TRUE)) { + dprintf("%s: disk %s : vdev protection " + "filter set to %S\n", + __func__, FileName, + DeviceObject->DriverObject->DriverName.Buffer); break; } pSendToDevice = DeviceObject; @@ -388,7 +406,8 @@ vdev_disk_open(vdev_t *vd, uint64_t *psize, uint64_t *max_psize, dvd->vd_FileObject = FileObject; dvd->vd_ExclusiveObject = DeviceObject; - // Make disk readonly and offline, so that users can't partition/format it. + // Make disk readonly and offline, so that users can't + // partition/format it. if (vd->vdev_wholedisk) disk_exclusive(dvd->vd_ExclusiveObject, TRUE); spa_strfree(vdev_path); @@ -398,22 +417,23 @@ vdev_disk_open(vdev_t *vd, uint64_t *psize, uint64_t *max_psize, capacity = dvd->vdev_win_length; /* - * Determine the device's minimum transfer size. - * If the ioctl isn't supported, assume DEV_BSIZE. - */ + * Determine the device's minimum transfer size. + * If the ioctl isn't supported, assume DEV_BSIZE. + */ // fill in capacity, blksz, pbsize STORAGE_PROPERTY_QUERY storageQuery; - memset(&storageQuery, 0, sizeof(STORAGE_PROPERTY_QUERY)); + memset(&storageQuery, 0, sizeof (STORAGE_PROPERTY_QUERY)); storageQuery.PropertyId = StorageAccessAlignmentProperty; storageQuery.QueryType = PropertyStandardQuery; STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR diskAlignment = { 0 }; - memset(&diskAlignment, 0, sizeof(STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR)); + memset(&diskAlignment, 0, sizeof (STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR)); DWORD outsize; - error = kernel_ioctl(dvd->vd_DeviceObject, dvd->vd_FileObject, IOCTL_STORAGE_QUERY_PROPERTY, - &storageQuery, sizeof(STORAGE_PROPERTY_QUERY), - &diskAlignment, sizeof(STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR)); + error = kernel_ioctl(dvd->vd_DeviceObject, dvd->vd_FileObject, + IOCTL_STORAGE_QUERY_PROPERTY, + &storageQuery, sizeof (STORAGE_PROPERTY_QUERY), + &diskAlignment, sizeof (STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR)); if (error == 0) { blksz = diskAlignment.BytesPerLogicalSector; @@ -436,23 +456,25 @@ vdev_disk_open(vdev_t *vd, uint64_t *psize, uint64_t *max_psize, dprintf("%s: picked ashift %llu for device\n", __func__, *ashift); /* - * Clear the nowritecache bit, so that on a vdev_reopen() we will - * try again. - */ + * Clear the nowritecache bit, so that on a vdev_reopen() we will + * try again. + */ vd->vdev_nowritecache = B_FALSE; /* Set when device reports it supports TRIM. */ vd->vdev_has_trim = !!blk_queue_discard(dvd->vd_DeviceObject); /* Set when device reports it supports secure TRIM. */ - vd->vdev_has_securetrim = !!blk_queue_discard_secure(dvd->vd_DeviceObject); + vd->vdev_has_securetrim = + !!blk_queue_discard_secure(dvd->vd_DeviceObject); /* Inform the ZIO pipeline that we are non-rotational */ /* Best choice seems to be either TRIM, or SeekPenalty */ - vd->vdev_nonrot = vd->vdev_has_trim || blk_queue_nonrot(dvd->vd_DeviceObject); + vd->vdev_nonrot = + vd->vdev_has_trim || blk_queue_nonrot(dvd->vd_DeviceObject); dprintf("%s: nonrot %d, trim %d, securetrim %d\n", __func__, - vd->vdev_nonrot, vd->vdev_has_trim, vd->vdev_has_securetrim); + vd->vdev_nonrot, vd->vdev_has_trim, vd->vdev_has_securetrim); return (0); } @@ -515,7 +537,7 @@ vdev_disk_physio(vdev_t *vd, caddr_t data, ASSERT(vd->vdev_ops == &vdev_disk_ops); - return EIO; + return (EIO); } static void @@ -555,13 +577,13 @@ vdev_disk_io_start_done(__in PVOID pDummy, __in PVOID pWkParms) // Return abd buf if (zio->io_type == ZIO_TYPE_READ) { - VERIFY3S(zio->io_abd->abd_size, >= , zio->io_size); + VERIFY3S(zio->io_abd->abd_size, >=, zio->io_size); abd_return_buf_copy(zio->io_abd, zio->windows.b_addr, - zio->io_size); + zio->io_size); } else { - VERIFY3S(zio->io_abd->abd_size, >= , zio->io_size); + VERIFY3S(zio->io_abd->abd_size, >=, zio->io_size); abd_return_buf(zio->io_abd, zio->windows.b_addr, - zio->io_size); + zio->io_size); } UnlockAndFreeMdl(zio->windows.irp->MdlAddress); @@ -583,25 +605,26 @@ vdev_disk_io_intr(PDEVICE_OBJECT DeviceObject, PIRP irp, PVOID Context) ASSERT(zio != NULL); - /* - * Unfortunately: - * Whatever thread happened to be running is "borrowed" to handle - * the completion. - * As about DPCs - in Windows, they are not bound to a thread, KeGetCurrentThread - * is just nonsense in them. - * - * So, the whole Windows kernel framework just does not support the notion of - * "current thread" in DPCs and thus completion routines. - * - * This means our call to "mutex_enter()" will "panic: lock against myself" if that - * thread it "borrowed" is the actual owner thread. - * - * So schedule IoQueueWorkItem() to call the done function in a real context. - */ +/* + * Unfortunately: + * Whatever thread happened to be running is "borrowed" to handle + * the completion. + * As about DPCs - in Windows, they are not bound to a thread, + * KeGetCurrentThread is just nonsense in them. + * + * So, the whole Windows kernel framework just does not support the notion of + * "current thread" in DPCs and thus completion routines. + * + * This means our call to "mutex_enter()" will "panic: lock against myself" + * if that thread it "borrowed" is the actual owner thread. + * + * So schedule IoQueueWorkItem() to call the done function in a real context. + */ VERIFY3P(zio->windows.work_item, !=, NULL); - IoQueueWorkItem(zio->windows.work_item, vdev_disk_io_start_done, DelayedWorkQueue, zio); - return STATUS_MORE_PROCESSING_REQUIRED; + IoQueueWorkItem(zio->windows.work_item, vdev_disk_io_start_done, + DelayedWorkQueue, zio); + return (STATUS_MORE_PROCESSING_REQUIRED); } static void @@ -614,7 +637,8 @@ vdev_disk_io_start(zio_t *zio) unsigned long trim_flags = 0; int flags, error = 0; - // dprintf("%s: type 0x%x offset 0x%llx len 0x%llx \n", __func__, zio->io_type, zio->io_offset, zio->io_size); + // dprintf("%s: type 0x%x offset 0x%llx len 0x%llx \n", + // __func__, zio->io_type, zio->io_offset, zio->io_size); /* * If the vdev is closed, it's likely in the REMOVED or FAULTED state. @@ -693,8 +717,9 @@ vdev_disk_io_start(zio_t *zio) if (zio->io_trim_flags & ZIO_TRIM_SECURE) trim_flags |= BLKDEV_DISCARD_SECURE; #endif - zio->io_error = -blkdev_issue_discard_bytes(dvd->vd_DeviceObject, - zio->io_offset, zio->io_size, trim_flags); + zio->io_error = -blkdev_issue_discard_bytes( + dvd->vd_DeviceObject, + zio->io_offset, zio->io_size, trim_flags); zio_interrupt(zio); return; @@ -717,7 +742,7 @@ vdev_disk_io_start(zio_t *zio) offset.QuadPart = zio->io_offset + dvd->vdev_win_offset; /* - * Start IO -> IOCompletion callback 'vdev_disk_io_intr()' + * Start IO -> IOCompletion callback 'vdev_disk_io_intr()' * -> IoQueueWorkItem(DelayedWorkQueue) -> callback vdev_disk_io_done() */ @@ -731,27 +756,27 @@ vdev_disk_io_start(zio_t *zio) if (zio->io_type == ZIO_TYPE_READ) { zio->windows.b_addr = - abd_borrow_buf(zio->io_abd, zio->io_size); + abd_borrow_buf(zio->io_abd, zio->io_size); irp = IoBuildAsynchronousFsdRequest(IRP_MJ_READ, - dvd->vd_DeviceObject, - zio->windows.b_addr, - (ULONG)zio->io_size, - &offset, - &zio->windows.IoStatus); + dvd->vd_DeviceObject, + zio->windows.b_addr, + (ULONG)zio->io_size, + &offset, + &zio->windows.IoStatus); } else { zio->windows.b_addr = - abd_borrow_buf_copy(zio->io_abd, zio->io_size); + abd_borrow_buf_copy(zio->io_abd, zio->io_size); irp = IoBuildAsynchronousFsdRequest(IRP_MJ_WRITE, - dvd->vd_DeviceObject, - zio->windows.b_addr, - (ULONG)zio->io_size, - &offset, - &zio->windows.IoStatus); + dvd->vd_DeviceObject, + zio->windows.b_addr, + (ULONG)zio->io_size, + &offset, + &zio->windows.IoStatus); } - + if (!irp) { if (zio->io_type == ZIO_TYPE_READ) { @@ -776,15 +801,14 @@ vdev_disk_io_start(zio_t *zio) irpStack->FileObject = dvd->vd_FileObject; IoSetCompletionRoutine(irp, - vdev_disk_io_intr, - zio, // "Context" in vdev_disk_io_intr() - TRUE, // On Success - TRUE, // On Error - TRUE);// On Cancel + vdev_disk_io_intr, + zio, // "Context" in vdev_disk_io_intr() + TRUE, // On Success + TRUE, // On Error + TRUE); // On Cancel IoCallDriver(dvd->vd_DeviceObject, irp); - return; } static void @@ -828,7 +852,7 @@ static void vdev_disk_rele(vdev_t *vd) { ASSERT(spa_config_held(vd->vdev_spa, SCL_STATE, RW_WRITER)); - + /* XXX: Implement me as a vnode rele for the device */ } @@ -855,5 +879,5 @@ vdev_ops_t vdev_disk_ops = { int vdev_disk_read_rootlabel(char *devpath, char *devid, nvlist_t **config) { - return -1; + return (-1); } diff --git a/module/os/windows/zfs/vdev_file.c b/module/os/windows/zfs/vdev_file.c index 28afc25921c..a532a059139 100644 --- a/module/os/windows/zfs/vdev_file.c +++ b/module/os/windows/zfs/vdev_file.c @@ -59,23 +59,23 @@ vdev_file_rele(vdev_t *vd) } #ifdef _KERNEL -extern int VOP_GETATTR(struct vnode *vp, vattr_t *vap, int flags, void *x3, void *x4); +extern int VOP_GETATTR(struct vnode *vp, vattr_t *vap, int flags, + void *x3, void *x4); #endif -static mode_t vdev_file_open_mode(spa_mode_t spa_mode) +static mode_t +vdev_file_open_mode(spa_mode_t spa_mode) { mode_t mode = 0; // TODO :- Add flags if ((spa_mode & SPA_MODE_READ) && (spa_mode & SPA_MODE_WRITE)) { mode = O_RDWR; - } - else if (spa_mode & SPA_MODE_READ) { + } else if (spa_mode & SPA_MODE_READ) { mode = O_RDONLY; - } - else if (spa_mode & SPA_MODE_WRITE) { + } else if (spa_mode & SPA_MODE_WRITE) { mode = O_WRONLY; } - return mode; + return (mode); } static int @@ -108,7 +108,7 @@ vdev_file_open(vdev_t *vd, uint64_t *psize, uint64_t *max_psize, * We must have a pathname, and it must be absolute. */ if (vd->vdev_path == NULL || (vd->vdev_path[0] != '/' && - vd->vdev_path[0] != '\\')) { + vd->vdev_path[0] != '\\')) { vd->vdev_stat.vs_aux = VDEV_AUX_BAD_LABEL; return (SET_ERROR(EINVAL)); } @@ -125,9 +125,9 @@ vdev_file_open(vdev_t *vd, uint64_t *psize, uint64_t *max_psize, } #endif - vf = vd->vdev_tsd = kmem_zalloc(sizeof(vdev_file_t), KM_SLEEP); + vf = vd->vdev_tsd = kmem_zalloc(sizeof (vdev_file_t), KM_SLEEP); - /* Make sure to change //?/ into kernel /??/ */ + /* Make sure to change / /?/ into kernel /??/ */ if (vd->vdev_path[0] == '\\' && vd->vdev_path[1] == '\\' && vd->vdev_path[2] == '?' && @@ -154,17 +154,16 @@ vdev_file_open(vdev_t *vd, uint64_t *psize, uint64_t *max_psize, #ifdef _KERNEL // Change it to SPARSE, so TRIM might work error = ZwFsControlFile( - fp->f_handle, - NULL, - NULL, - NULL, - NULL, - FSCTL_SET_SPARSE, - NULL, - 0, - NULL, - 0 - ); + fp->f_handle, + NULL, + NULL, + NULL, + NULL, + FSCTL_SET_SPARSE, + NULL, + 0, + NULL, + 0); dprintf("%s: set Sparse 0x%x.\n", __func__, error); #else // Userland? @@ -230,24 +229,22 @@ vdev_file_io_start_done(void *param) // Return abd buf if (zio->io_type == ZIO_TYPE_READ) { abd_return_buf_copy(zio->io_abd, vb->b_data, - zio->io_size); + zio->io_size); } else { abd_return_buf(zio->io_abd, vb->b_data, - zio->io_size); + zio->io_size); } UnlockAndFreeMdl(vb->irp->MdlAddress); IoFreeIrp(vb->irp); - kmem_free(vb, sizeof(vf_callback_t) + IoSizeofWorkItem()); + kmem_free(vb, sizeof (vf_callback_t) + IoSizeofWorkItem()); vb = NULL; zio_delay_interrupt(zio); } -static VOID -FileIoWkRtn( - __in PVOID pDummy, // Not used. - __in PVOID pWkParms // Parm list pointer. -) +static void +FileIoWkRtn(__in PVOID pDummy, + __in PVOID pWkParms) { vf_callback_t *vb = (vf_callback_t *)pWkParms; @@ -263,19 +260,22 @@ vdev_file_io_intr(PDEVICE_OBJECT DeviceObject, PIRP irp, PVOID Context) ASSERT(vb != NULL); - /* If IRQL is below DIPATCH_LEVEL then there is no issue in calling + /* + * If IRQL is below DIPATCH_LEVEL then there is no issue in calling * vdev_file_io_start_done() directly; otherwise queue a new Work Item - */ - if (KeGetCurrentIrql() < DISPATCH_LEVEL) + */ + if (KeGetCurrentIrql() < DISPATCH_LEVEL) { vdev_file_io_start_done(vb); - else { + } else { vdev_file_t *vf = vb->zio->io_vd->vdev_tsd; zfs_file_t *fp = vf->vf_file; - IoInitializeWorkItem(fp->f_deviceobject, (PIO_WORKITEM)vb->work_item); - IoQueueWorkItem((PIO_WORKITEM)vb->work_item, FileIoWkRtn, DelayedWorkQueue, vb); + IoInitializeWorkItem(fp->f_deviceobject, + (PIO_WORKITEM)vb->work_item); + IoQueueWorkItem((PIO_WORKITEM)vb->work_item, FileIoWkRtn, + DelayedWorkQueue, vb); } - return STATUS_MORE_PROCESSING_REQUIRED; + return (STATUS_MORE_PROCESSING_REQUIRED); } #endif @@ -321,7 +321,7 @@ vdev_file_io_start(zio_t *zio) { vdev_t *vd = zio->io_vd; ssize_t resid = 0; - vdev_file_t* vf = vd->vdev_tsd; + vdev_file_t *vf = vd->vdev_tsd; zfs_file_t *fp = vf->vf_file; if (zio->io_type == ZIO_TYPE_IOCTL) { @@ -330,18 +330,18 @@ vdev_file_io_start(zio_t *zio) zio->io_error = SET_ERROR(ENXIO); zio_interrupt(zio); return; - } - - switch (zio->io_cmd) { - case DKIOCFLUSHWRITECACHE: - zio->io_error = zfs_file_fsync(fp, 0); - break; - default: - zio->io_error = SET_ERROR(ENOTSUP); + } + + switch (zio->io_cmd) { + case DKIOCFLUSHWRITECACHE: + zio->io_error = zfs_file_fsync(fp, 0); + break; + default: + zio->io_error = SET_ERROR(ENOTSUP); } zio_execute(zio); - return; + return; } else if (zio->io_type == ZIO_TYPE_TRIM) { int mode = 0; @@ -357,7 +357,7 @@ vdev_file_io_start(zio_t *zio) ASSERT(zio->io_size != 0); LARGE_INTEGER offset; - offset.QuadPart = zio->io_offset /*+ vd->vdev_win_offset */; + offset.QuadPart = zio->io_offset; /* + vd->vdev_win_offset */ VERIFY3U(taskq_dispatch(system_taskq, vdev_file_io_strategy, zio, TQ_SLEEP), !=, 0); diff --git a/module/os/windows/zfs/zfs_acl.c b/module/os/windows/zfs/zfs_acl.c index 3f4f82f7cc3..374fd50e575 100644 --- a/module/os/windows/zfs/zfs_acl.c +++ b/module/os/windows/zfs/zfs_acl.c @@ -38,7 +38,6 @@ #include #include #include -#include #include #include #include @@ -51,7 +50,6 @@ #include #include #include -//#include #define ALLOW ACE_ACCESS_ALLOWED_ACE_TYPE #define DENY ACE_ACCESS_DENIED_ACE_TYPE @@ -683,7 +681,7 @@ zfs_copy_ace_2_fuid(zfsvfs_t *zfsvfs, umode_t obj_mode, zfs_acl_t *aclp, * Make sure ACE is valid */ if (zfs_ace_valid(obj_mode, aclp, aceptr->z_hdr.z_type, - aceptr->z_hdr.z_flags) != B_TRUE) + aceptr->z_hdr.z_flags) != B_TRUE) return (SET_ERROR(EINVAL)); switch (acep->a_type) { @@ -733,7 +731,7 @@ zfs_copy_fuid_2_ace(zfsvfs_t *zfsvfs, zfs_acl_t *aclp, cred_t *cr, uint16_t entry_type; while ((zacep = zfs_acl_next_ace(aclp, zacep, - &who, &access_mask, &iflags, &type))) { + &who, &access_mask, &iflags, &type))) { switch (type) { case ACE_ACCESS_ALLOWED_OBJECT_ACE_TYPE: @@ -825,7 +823,7 @@ zfs_acl_xform(znode_t *zp, zfs_acl_t *aclp, cred_t *cr) KM_SLEEP); i = 0; while ((cookie = zfs_acl_next_ace(aclp, cookie, &who, - &access_mask, &iflags, &type))) { + &access_mask, &iflags, &type))) { oldaclp[i].z_flags = iflags; oldaclp[i].z_type = type; oldaclp[i].z_fuid = who; @@ -906,7 +904,7 @@ zfs_mode_compute(uint64_t fmode, zfs_acl_t *aclp, mode = (fmode & (S_IFMT | S_ISUID | S_ISGID | S_ISVTX)); while ((acep = zfs_acl_next_ace(aclp, acep, &who, - &access_mask, &iflags, &type))) { + &access_mask, &iflags, &type))) { if (!zfs_acl_valid_ace_type(type, iflags)) continue; @@ -920,20 +918,21 @@ zfs_mode_compute(uint64_t fmode, zfs_acl_t *aclp, continue; - /* - * Apple has unusual expectations to emulate hfs in that the mode is not - * updated: - * -rw-r--r-- 1 root wheel 0 Nov 12 12:39 file.txt - * chmod +a "root allow execute" file.txt - * ZFS: -rwxr--r--+ 1 root wheel 0 Nov 12 12:39 file.txt - * HFS: -rw-r--r--+ 1 root wheel 0 Nov 12 12:39 file.txt - * 0: user:root allow execute - */ - if (entry_type == ACE_OWNER + /* + * Apple has unusual expectations to emulate hfs in that the mode is not + * updated: + * -rw-r--r-- 1 root wheel 0 Nov 12 12:39 file.txt + * chmod +a "root allow execute" file.txt + * ZFS: -rwxr--r--+ 1 root wheel 0 Nov 12 12:39 file.txt + * HFS: -rw-r--r--+ 1 root wheel 0 Nov 12 12:39 file.txt + * 0: user:root allow execute + */ #ifndef _WIN32 - || (entry_type == 0 && who == fuid) + if (entry_type == ACE_OWNER || + (entry_type == 0 && who == fuid)) { +#else + if (entry_type == ACE_OWNER) { #endif - ) { if ((access_mask & ACE_READ_DATA) && (!(seen & S_IRUSR))) { seen |= S_IRUSR; @@ -955,11 +954,13 @@ zfs_mode_compute(uint64_t fmode, zfs_acl_t *aclp, mode |= S_IXUSR; } } - } else if (entry_type == OWNING_GROUP #ifndef _WIN32 - || (entry_type == ACE_IDENTIFIER_GROUP && who == fgid) + } else if (entry_type == OWNING_GROUP || + (entry_type == ACE_IDENTIFIER_GROUP && who == fgid)) { +#else + } else if (entry_type == OWNING_GROUP) { + #endif - ) { if ((access_mask & ACE_READ_DATA) && (!(seen & S_IRGRP))) { seen |= S_IRGRP; @@ -1365,7 +1366,7 @@ zfs_aclset_common(znode_t *zp, zfs_acl_t *aclp, cred_t *cr, dmu_tx_t *tx) static void zfs_acl_chmod(umode_t umode, uint64_t mode, boolean_t split, boolean_t trim, - zfs_acl_t *aclp) + zfs_acl_t *aclp) { void *acep = NULL; uint64_t who; @@ -1408,7 +1409,7 @@ zfs_acl_chmod(umode_t umode, uint64_t mode, boolean_t split, boolean_t trim, } while ((acep = zfs_acl_next_ace(aclp, acep, &who, &access_mask, - &iflags, &type))) { + &iflags, &type))) { entry_type = (iflags & ACE_TYPE_FLAGS); /* * ACEs used to represent the file mode may be divided @@ -1417,10 +1418,10 @@ zfs_acl_chmod(umode_t umode, uint64_t mode, boolean_t split, boolean_t trim, * Skip regular ACEs, which are replaced by the new mode. */ if (split && (entry_type == ACE_OWNER || - entry_type == OWNING_GROUP || - entry_type == ACE_EVERYONE)) { + entry_type == OWNING_GROUP || + entry_type == ACE_EVERYONE)) { if (!isdir || !(iflags & - (ACE_FILE_INHERIT_ACE|ACE_DIRECTORY_INHERIT_ACE))) + (ACE_FILE_INHERIT_ACE|ACE_DIRECTORY_INHERIT_ACE))) continue; /* * We preserve owner@, group@, or @everyone @@ -1428,7 +1429,7 @@ zfs_acl_chmod(umode_t umode, uint64_t mode, boolean_t split, boolean_t trim, * copying them to inherit_only ACEs. This * prevents inheritable permissions from being * altered along with the file mode. - */ + */ iflags |= ACE_INHERIT_ONLY_ACE; } @@ -1540,10 +1541,10 @@ zfs_acl_inherit(zfsvfs_t *zfsvfs, zfs_acl_t *paclp, size_t ace_size; void *data1, *data2 = NULL; size_t data1sz, data2sz = 0; - uint_t aclinherit; - boolean_t isdir = S_ISDIR(umode); - boolean_t islnk = S_ISLNK(umode); - boolean_t isreg = S_ISREG(umode); + uint_t aclinherit; + boolean_t isdir = S_ISDIR(umode); + boolean_t islnk = S_ISLNK(umode); + boolean_t isreg = S_ISREG(umode); *need_chmod = B_TRUE; @@ -1553,7 +1554,7 @@ zfs_acl_inherit(zfsvfs_t *zfsvfs, zfs_acl_t *paclp, return (aclp); while ((pacep = zfs_acl_next_ace(paclp, pacep, &who, - &access_mask, &iflags, &type))) { + &access_mask, &iflags, &type))) { /* * don't inherit bogus ACEs @@ -1565,7 +1566,7 @@ zfs_acl_inherit(zfsvfs_t *zfsvfs, zfs_acl_t *paclp, * Check if ACE is inheritable by this vnode */ if ((aclinherit == ZFS_ACL_NOALLOW && type == ALLOW) || - !zfs_ace_can_use(umode, iflags)) + !zfs_ace_can_use(umode, iflags)) continue; /* @@ -1584,7 +1585,7 @@ zfs_acl_inherit(zfsvfs_t *zfsvfs, zfs_acl_t *paclp, * not in mode */ if (aclinherit == ZFS_ACL_PASSTHROUGH_X && type == ALLOW && - !isdir && ((umode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0)) { + !isdir && ((umode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0)) { access_mask &= ~ACE_EXECUTE; } @@ -1823,78 +1824,78 @@ zfs_acl_ids_overquota(zfsvfs_t *zv, zfs_acl_ids_t *acl_ids, uint64_t projid) */ int zfs_getacl(znode_t *zp, vsecattr_t *aclpp, boolean_t skipaclcheck, - cred_t *cr) -{ - zfs_acl_t *aclp; - kauth_acl_t *k_acl; - uint32_t ace_flags = 0; - kauth_ace_rights_t *rights = 0; - guid_t *guidp; - uint64_t who; - uint32_t access_mask; - uint16_t flags; - uint16_t type; - int i; - int error; - void *zacep = NULL; - - mutex_enter(&zp->z_acl_lock); - - error = zfs_acl_node_read(zp, B_FALSE, &aclp, B_TRUE); - if (error != 0) { - mutex_exit(&zp->z_acl_lock); - return (error); - } -// if ((k_acl = kauth_acl_alloc(aclp->z_acl_count)) == NULL) { -// mutex_exit(&zp->z_acl_lock); -// *aclpp = (kauth_acl_t *) KAUTH_FILESEC_NONE; -// return (ENOMEM); -// } - - dprintf("acl_count %d\n",aclp->z_acl_count); + cred_t *cr) +{ + zfs_acl_t *aclp; + kauth_acl_t *k_acl; + uint32_t ace_flags = 0; + kauth_ace_rights_t *rights = 0; + guid_t *guidp; + uint64_t who; + uint32_t access_mask; + uint16_t flags; + uint16_t type; + int i; + int error; + void *zacep = NULL; + + mutex_enter(&zp->z_acl_lock); + + error = zfs_acl_node_read(zp, B_FALSE, &aclp, B_TRUE); + if (error != 0) { + mutex_exit(&zp->z_acl_lock); + return (error); + } +// if ((k_acl = kauth_acl_alloc(aclp->z_acl_count)) == NULL) { +// mutex_exit(&zp->z_acl_lock); +// *aclpp = (kauth_acl_t *) KAUTH_FILESEC_NONE; +// return (ENOMEM); +// } + + dprintf("acl_count %d\n", aclp->z_acl_count); // k_acl->acl_entrycount = aclp->z_acl_count; // k_acl->acl_flags = 0; #if 0 *aclpp = k_acl; - /* - * Translate Open Solaris ACEs to Mac OS X ACLs - */ - i = 0; - while ((zacep = zfs_acl_next_ace(aclp, zacep, - &who, &access_mask, &flags, &type))) { - rights = 0; - ace_flags = 0; + /* + * Translate Open Solaris ACEs to Mac OS X ACLs + */ + i = 0; + while ((zacep = zfs_acl_next_ace(aclp, zacep, + &who, &access_mask, &flags, &type))) { + rights = 0; + ace_flags = 0; -// guidp = &k_acl->acl_ace[i].ace_applicable; +// guidp = &k_acl->acl_ace[i].ace_applicable; - if (flags & ACE_OWNER) { + if (flags & ACE_OWNER) { #if HIDE_TRIVIAL_ACL continue; #endif - who = -1; -// nfsacl_set_wellknown(KAUTH_WKG_OWNER, guidp); - } else if ((flags & OWNING_GROUP) == OWNING_GROUP) { + who = -1; +// nfsacl_set_wellknown(KAUTH_WKG_OWNER, guidp); + } else if ((flags & OWNING_GROUP) == OWNING_GROUP) { #if HIDE_TRIVIAL_ACL continue; #endif - who = -1; - // nfsacl_set_wellknown(KAUTH_WKG_GROUP, guidp); - } else if (flags & ACE_EVERYONE) { + who = -1; +// nfsacl_set_wellknown(KAUTH_WKG_GROUP, guidp); + } else if (flags & ACE_EVERYONE) { #if HIDE_TRIVIAL_ACL continue; #endif - who = -1; - // nfsacl_set_wellknown(KAUTH_WKG_EVERYBODY, guidp); - /* Try to get a guid from our uid */ - } else { + who = -1; +// nfsacl_set_wellknown(KAUTH_WKG_EVERYBODY, guidp); + /* Try to get a guid from our uid */ + } else { - dprintf("ZFS: trying to map uid %d flags %x type %x\n", who, flags, - type); + dprintf("ZFS: trying to map uid %d flags %x type %x\n", + who, flags, type); if (flags & OWNING_GROUP) { -// if (kauth_cred_gid2guid(who, guidp) == 0) { +// if (kauth_cred_gid2guid(who, guidp) == 0) { // dprintf("ZFS: appears to be a group\n"); // } // } else if (kauth_cred_uid2guid(who, guidp) == 0) { @@ -1903,126 +1904,125 @@ zfs_getacl(znode_t *zp, vsecattr_t *aclpp, boolean_t skipaclcheck, dprintf("ZFS: Unable to map\n"); bzero(guidp, sizeof (guid_t)); } - } + } - //access_mask = aclp->z_acl[i].a_access_mask; + // access_mask = aclp->z_acl[i].a_access_mask; if (access_mask & ACE_READ_DATA) - rights |= KAUTH_VNODE_READ_DATA; - if (access_mask & ACE_WRITE_DATA) - rights |= KAUTH_VNODE_WRITE_DATA; - if (access_mask & ACE_APPEND_DATA) - rights |= KAUTH_VNODE_APPEND_DATA; - if (access_mask & ACE_READ_NAMED_ATTRS) - rights |= KAUTH_VNODE_READ_EXTATTRIBUTES; - if (access_mask & ACE_WRITE_NAMED_ATTRS) - rights |= KAUTH_VNODE_WRITE_EXTATTRIBUTES; - if (access_mask & ACE_EXECUTE) - rights |= KAUTH_VNODE_EXECUTE; - if (access_mask & ACE_DELETE_CHILD) - rights |= KAUTH_VNODE_DELETE_CHILD; - if (access_mask & ACE_READ_ATTRIBUTES) - rights |= KAUTH_VNODE_READ_ATTRIBUTES; - if (access_mask & ACE_WRITE_ATTRIBUTES) - rights |= KAUTH_VNODE_WRITE_ATTRIBUTES; - if (access_mask & ACE_DELETE) - rights |= KAUTH_VNODE_DELETE; - if (access_mask & ACE_READ_ACL) - rights |= KAUTH_VNODE_READ_SECURITY; - if (access_mask & ACE_WRITE_ACL) - rights |= KAUTH_VNODE_WRITE_SECURITY; - if (access_mask & ACE_WRITE_OWNER) - rights |= KAUTH_VNODE_TAKE_OWNERSHIP; - if (access_mask & ACE_SYNCHRONIZE) - rights |= KAUTH_VNODE_SYNCHRONIZE; - k_acl->acl_ace[i].ace_rights = rights; - - //flags = aclp->z_acl[i].a_flags; - if (flags & ACE_FILE_INHERIT_ACE) - ace_flags |= KAUTH_ACE_FILE_INHERIT; - if (flags & ACE_DIRECTORY_INHERIT_ACE) - ace_flags |= KAUTH_ACE_DIRECTORY_INHERIT; - if (flags & ACE_NO_PROPAGATE_INHERIT_ACE) - ace_flags |= KAUTH_ACE_LIMIT_INHERIT; - if (flags & ACE_INHERIT_ONLY_ACE) - ace_flags |= KAUTH_ACE_ONLY_INHERIT; - - //type = aclp->z_acl[i].a_type; - switch(type) { - case ACE_ACCESS_ALLOWED_ACE_TYPE: - ace_flags |= KAUTH_ACE_PERMIT; - break; - case ACE_ACCESS_DENIED_ACE_TYPE: - ace_flags |= KAUTH_ACE_DENY; - break; - case ACE_SYSTEM_AUDIT_ACE_TYPE: - ace_flags |= KAUTH_ACE_AUDIT; - break; - case ACE_SYSTEM_ALARM_ACE_TYPE: - ace_flags |= KAUTH_ACE_ALARM; - break; - } - k_acl->acl_ace[i].ace_flags = ace_flags; - i++; - } - k_acl->acl_entrycount = i; + rights |= KAUTH_VNODE_READ_DATA; + if (access_mask & ACE_WRITE_DATA) + rights |= KAUTH_VNODE_WRITE_DATA; + if (access_mask & ACE_APPEND_DATA) + rights |= KAUTH_VNODE_APPEND_DATA; + if (access_mask & ACE_READ_NAMED_ATTRS) + rights |= KAUTH_VNODE_READ_EXTATTRIBUTES; + if (access_mask & ACE_WRITE_NAMED_ATTRS) + rights |= KAUTH_VNODE_WRITE_EXTATTRIBUTES; + if (access_mask & ACE_EXECUTE) + rights |= KAUTH_VNODE_EXECUTE; + if (access_mask & ACE_DELETE_CHILD) + rights |= KAUTH_VNODE_DELETE_CHILD; + if (access_mask & ACE_READ_ATTRIBUTES) + rights |= KAUTH_VNODE_READ_ATTRIBUTES; + if (access_mask & ACE_WRITE_ATTRIBUTES) + rights |= KAUTH_VNODE_WRITE_ATTRIBUTES; + if (access_mask & ACE_DELETE) + rights |= KAUTH_VNODE_DELETE; + if (access_mask & ACE_READ_ACL) + rights |= KAUTH_VNODE_READ_SECURITY; + if (access_mask & ACE_WRITE_ACL) + rights |= KAUTH_VNODE_WRITE_SECURITY; + if (access_mask & ACE_WRITE_OWNER) + rights |= KAUTH_VNODE_TAKE_OWNERSHIP; + if (access_mask & ACE_SYNCHRONIZE) + rights |= KAUTH_VNODE_SYNCHRONIZE; + k_acl->acl_ace[i].ace_rights = rights; + + // flags = aclp->z_acl[i].a_flags; + if (flags & ACE_FILE_INHERIT_ACE) + ace_flags |= KAUTH_ACE_FILE_INHERIT; + if (flags & ACE_DIRECTORY_INHERIT_ACE) + ace_flags |= KAUTH_ACE_DIRECTORY_INHERIT; + if (flags & ACE_NO_PROPAGATE_INHERIT_ACE) + ace_flags |= KAUTH_ACE_LIMIT_INHERIT; + if (flags & ACE_INHERIT_ONLY_ACE) + ace_flags |= KAUTH_ACE_ONLY_INHERIT; + + // type = aclp->z_acl[i].a_type; + switch (type) { + case ACE_ACCESS_ALLOWED_ACE_TYPE: + ace_flags |= KAUTH_ACE_PERMIT; + break; + case ACE_ACCESS_DENIED_ACE_TYPE: + ace_flags |= KAUTH_ACE_DENY; + break; + case ACE_SYSTEM_AUDIT_ACE_TYPE: + ace_flags |= KAUTH_ACE_AUDIT; + break; + case ACE_SYSTEM_ALARM_ACE_TYPE: + ace_flags |= KAUTH_ACE_ALARM; + break; + } + k_acl->acl_ace[i].ace_flags = ace_flags; + i++; + } + k_acl->acl_entrycount = i; #endif mutex_exit(&zp->z_acl_lock); - zfs_acl_free(aclp); + zfs_acl_free(aclp); - return (0); + return (0); } int zfs_addacl_trivial(znode_t *zp, ace_t *aces, int *nentries, int seen_type) { - zfs_acl_t *aclp; - uint64_t who; - uint32_t access_mask; - uint16_t flags; - uint16_t type; - int i; - int error; - void *zacep = NULL; + zfs_acl_t *aclp; + uint64_t who; + uint32_t access_mask; + uint16_t flags; + uint16_t type; + int i; + int error; + void *zacep = NULL; - mutex_enter(&zp->z_acl_lock); + mutex_enter(&zp->z_acl_lock); - error = zfs_acl_node_read(zp, B_FALSE, &aclp, B_TRUE); - if (error != 0) { - mutex_exit(&zp->z_acl_lock); - return (error); - } + error = zfs_acl_node_read(zp, B_FALSE, &aclp, B_TRUE); + if (error != 0) { + mutex_exit(&zp->z_acl_lock); + return (error); + } - dprintf("ondisk acl_count %d\n",aclp->z_acl_count); + dprintf("ondisk acl_count %d\n", aclp->z_acl_count); // Start at the end i = *nentries; - /* - * Translate Open Solaris ACEs to Mac OS X ACLs - */ - while ((zacep = zfs_acl_next_ace(aclp, zacep, - &who, &access_mask, &flags, &type))) { + /* + * Translate Open Solaris ACEs to Mac OS X ACLs + */ + while ((zacep = zfs_acl_next_ace(aclp, zacep, + &who, &access_mask, &flags, &type))) { - if (flags & ACE_OWNER) { + if (flags & ACE_OWNER) { if (seen_type & ACE_OWNER) continue; seen_type |= ACE_OWNER; - who = -1; - } else if ((flags & OWNING_GROUP) == OWNING_GROUP) { + who = -1; + } else if ((flags & OWNING_GROUP) == OWNING_GROUP) { if (seen_type & ACE_GROUP) continue; seen_type |= ACE_GROUP; - who = -1; - } else if (flags & ACE_EVERYONE) { + who = -1; + } else if (flags & ACE_EVERYONE) { if (seen_type & ACE_EVERYONE) continue; seen_type |= ACE_EVERYONE; - who = -1; - /* Try to get a guid from our uid */ - } else { + who = -1; + /* Try to get a guid from our uid */ + } else { // Only deal with the trivials continue; - } aces[i].a_who = who; @@ -2031,16 +2031,16 @@ zfs_addacl_trivial(znode_t *zp, ace_t *aces, int *nentries, int seen_type) aces[i].a_type = type; dprintf("zfs: adding entry %d for type %x sizeof %d\n", i, type, - sizeof(aces[i])); - i++; - } + sizeof (aces[i])); + i++; + } - *nentries=i; - mutex_exit(&zp->z_acl_lock); + *nentries = i; + mutex_exit(&zp->z_acl_lock); - zfs_acl_free(aclp); + zfs_acl_free(aclp); - return (0); + return (0); } @@ -2109,7 +2109,7 @@ zfs_setacl(znode_t *zp, vsecattr_t *vsecp, boolean_t skipaclchk, cred_t *cr) { zfsvfs_t *zfsvfs = zp->z_zfsvfs; zilog_t *zilog = zfsvfs->z_log; - //ulong_t mask = vsecp->vsa_mask & (VSA_ACE | VSA_ACECNT); + // ulong_t mask = vsecp->vsa_mask & (VSA_ACE | VSA_ACECNT); dmu_tx_t *tx; int error; zfs_acl_t *aclp; @@ -2117,8 +2117,8 @@ zfs_setacl(znode_t *zp, vsecattr_t *vsecp, boolean_t skipaclchk, cred_t *cr) boolean_t fuid_dirtied; uint64_t acl_obj; - // Anyone remember why we commented this out? - //if (mask == 0) + // Anyone remember why we commented this out? + // if (mask == 0) // return (ENOSYS); if (zp->z_pflags & ZFS_IMMUTABLE) @@ -2127,8 +2127,8 @@ zfs_setacl(znode_t *zp, vsecattr_t *vsecp, boolean_t skipaclchk, cred_t *cr) if ((error = zfs_zaccess(zp, ACE_WRITE_ACL, 0, skipaclchk, cr))) return (error); - error = zfs_vsec_2_aclp(zfsvfs, vnode_vtype(ZTOV(zp)), vsecp, cr, &fuidp, - &aclp); + error = zfs_vsec_2_aclp(zfsvfs, vnode_vtype(ZTOV(zp)), vsecp, cr, + &fuidp, &aclp); if (error) return (error); @@ -2136,10 +2136,10 @@ zfs_setacl(znode_t *zp, vsecattr_t *vsecp, boolean_t skipaclchk, cred_t *cr) * If ACL wide flags aren't being set then preserve any * existing flags. */ - //if (!(vsecp->vsa_mask & VSA_ACE_ACLFLAGS)) { + // if (!(vsecp->vsa_mask & VSA_ACE_ACLFLAGS)) { // aclp->z_hints |= // (zp->z_pflags & V4_ACL_WIDE_FLAGS); - //} + // } top: mutex_enter(&zp->z_acl_lock); mutex_enter(&zp->z_lock); @@ -2227,14 +2227,14 @@ zfs_zaccess_dataset_check(znode_t *zp, uint32_t v4_mode) * Intentionally allow ZFS_READONLY through here. * See zfs_zaccess_common(). */ - if ((v4_mode & WRITE_MASK_DATA) && + if ((v4_mode & WRITE_MASK_DATA) && (zp->z_pflags & ZFS_IMMUTABLE)) { return (EPERM); } #ifdef sun - if ((v4_mode & (ACE_DELETE | ACE_DELETE_CHILD)) && - (zp->z_pflags & ZFS_NOUNLINK)) { - return (EPERM); + if ((v4_mode & (ACE_DELETE | ACE_DELETE_CHILD)) && + (zp->z_pflags & ZFS_NOUNLINK)) { + return (EPERM); #else /* * In FreeBSD we allow to modify directory's content is ZFS_NOUNLINK @@ -2311,7 +2311,7 @@ zfs_zaccess_aces_check(znode_t *zp, uint32_t *working_mode, ASSERT(zp->z_acl_cached); while ((acep = zfs_acl_next_ace(aclp, acep, &who, &access_mask, - &iflags, &type))) { + &iflags, &type))) { uint32_t mask_matched; if (!zfs_acl_valid_ace_type(type, iflags)) @@ -2463,7 +2463,7 @@ zfs_zaccess_common(znode_t *zp, uint32_t v4_mode, uint32_t *working_mode, * Also note: DOS R/O is ignored for directories. */ if ((v4_mode & WRITE_MASK_DATA) && - !vnode_isdir(ZTOV(zp)) && + !vnode_isdir(ZTOV(zp)) && (zp->z_pflags & ZFS_READONLY)) { return (SET_ERROR(EPERM)); } @@ -2495,7 +2495,7 @@ zfs_fastaccesschk_execute(znode_t *zdp, cred_t *cr) return (SET_ERROR(EACCES)); is_attr = ((zdp->z_pflags & ZFS_XATTR) && - (vnode_isdir(ZTOV(zdp)))); + (vnode_isdir(ZTOV(zdp)))); if (is_attr) goto slow; @@ -2694,16 +2694,19 @@ zfs_zaccess(znode_t *zp, int mode, int flags, boolean_t skipaclchk, cred_t *cr) needed_bits & ~checkmode, needed_bits); if (error == 0 && (working_mode & ACE_WRITE_OWNER)) - error = secpolicy_vnode_chown(ZTOV(check_zp), cr, owner); + error = secpolicy_vnode_chown(ZTOV(check_zp), cr, + owner); if (error == 0 && (working_mode & ACE_WRITE_ACL)) - error = secpolicy_vnode_setdac(ZTOV(check_zp), cr, owner); + error = secpolicy_vnode_setdac(ZTOV(check_zp), cr, + owner); if (error == 0 && (working_mode & (ACE_DELETE|ACE_DELETE_CHILD))) error = secpolicy_vnode_remove(ZTOV(check_zp), cr); if (error == 0 && (working_mode & ACE_SYNCHRONIZE)) { - error = secpolicy_vnode_chown(ZTOV(check_zp), cr, owner); + error = secpolicy_vnode_chown(ZTOV(check_zp), cr, + owner); } if (error == 0) { /* @@ -2848,7 +2851,7 @@ zfs_zaccess_delete(znode_t *dzp, znode_t *zp, cred_t *cr) * (This is part of why we're checking the target first.) */ zp_error = zfs_zaccess_common(zp, ACE_DELETE, &zp_working_mode, - &zpcheck_privs, B_FALSE, cr); + &zpcheck_privs, B_FALSE, cr); if (zp_error == EACCES) { /* We hit a DENY ACE. */ if (!zpcheck_privs) @@ -2870,7 +2873,7 @@ zfs_zaccess_delete(znode_t *dzp, znode_t *zp, cred_t *cr) if (zfs_write_implies_delete_child) wanted_dirperms |= ACE_WRITE_DATA; dzp_error = zfs_zaccess_common(dzp, wanted_dirperms, - &dzp_working_mode, &dzpcheck_privs, B_FALSE, cr); + &dzp_working_mode, &dzpcheck_privs, B_FALSE, cr); if (dzp_error == EACCES) { /* We hit a DENY ACE. */ if (!dzpcheck_privs) @@ -2915,15 +2918,15 @@ zfs_zaccess_delete(znode_t *dzp, znode_t *zp, cred_t *cr) * the VWRITE flag in the current access mode. */ owner = zfs_fuid_map_id(dzp->z_zfsvfs, dzp->z_uid, cr, - ZFS_OWNER); + ZFS_OWNER); dzp_error = secpolicy_vnode_access2(cr, ZTOV(dzp), - owner, VEXEC, VWRITE|VEXEC); + owner, VEXEC, VWRITE|VEXEC); } if (dzp_error != 0) { /* * Note: We may have dzp_error = -1 here (from * zfs_zacess_common). Don't return that. - */ + */ return (SET_ERROR(EACCES)); } diff --git a/module/os/windows/zfs/zfs_ctldir.c b/module/os/windows/zfs/zfs_ctldir.c index 3470d8bdbaa..1f977654c01 100644 --- a/module/os/windows/zfs/zfs_ctldir.c +++ b/module/os/windows/zfs/zfs_ctldir.c @@ -100,7 +100,6 @@ extern uint64_t vnop_num_vnodes; * * We don't have 'shares' directory, so only 'snapshot' is relevant. * - * // perhaps we can in windows: We can not issue mount from kernel, so involve zed. * - see zfs_ctldir_snapdir.c * * All vnodes point to znode_t, no special case nodes. @@ -227,8 +226,9 @@ zfsctl_vnode_alloc(zfsvfs_t *zfsvfs, uint64_t id, zp->z_vid = vnode_vid(vp); zp->z_vnode = vp; - // Build a fullpath string here, for Notifications and set_name_information - if (zfs_build_path(zp, NULL, &zp->z_name_cache, &zp->z_name_len, &zp->z_name_offset) == -1) + // Build fullpath string here, for Notifications & set_name_information + if (zfs_build_path(zp, NULL, &zp->z_name_cache, + &zp->z_name_len, &zp->z_name_offset) == -1) dprintf("%s: failed to build fullpath\n", __func__); zfs_set_security(vp, NULL); @@ -940,7 +940,6 @@ zfsctl_vnop_open(struct vnop_open_args *ap) if (flags & FWRITE) return (EACCES); return (zfsctl_snapshot_mount(ap->a_vp, 0)); - return -1; } int diff --git a/module/os/windows/zfs/zfs_file_os.c b/module/os/windows/zfs/zfs_file_os.c index 113897f62e1..b97900edc2f 100644 --- a/module/os/windows/zfs/zfs_file_os.c +++ b/module/os/windows/zfs/zfs_file_os.c @@ -65,7 +65,8 @@ zfs_file_open(const char *path, int flags, int mode, zfs_file_t **fpp) dwCreationDisposition = FILE_SUPERSEDE; break; case (O_CREAT | O_EXCL): - case (O_CREAT | O_EXCL | O_TRUNC): // Only creating new implies starting from 0 + // Only creating new implies starting from 0 + case (O_CREAT | O_EXCL | O_TRUNC): dwCreationDisposition = FILE_CREATE; break; case (O_CREAT | O_TRUNC): @@ -85,44 +86,42 @@ zfs_file_open(const char *path, int flags, int mode, zfs_file_t **fpp) RtlInitUnicodeString(&uniName, buf); InitializeObjectAttributes(&objAttr, &uniName, - OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, - NULL, NULL); + OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, + NULL, NULL); - if(KeGetCurrentIrql() != PASSIVE_LEVEL) - return -1; + if (KeGetCurrentIrql() != PASSIVE_LEVEL) + return (-1); ntstatus = ZwCreateFile(&handle, - desiredAccess, - &objAttr, &ioStatusBlock, NULL, - FILE_ATTRIBUTE_NORMAL, - 0, - dwCreationDisposition, - FILE_SYNCHRONOUS_IO_NONALERT, - NULL, 0); - - if (ntstatus != STATUS_SUCCESS) { - return -1; - } + desiredAccess, + &objAttr, &ioStatusBlock, NULL, + FILE_ATTRIBUTE_NORMAL, + 0, + dwCreationDisposition, + FILE_SYNCHRONOUS_IO_NONALERT, + NULL, 0); + + if (ntstatus != STATUS_SUCCESS) + return (-1); // Since we will use DeviceObject and FileObject to do ioctl and IO // we grab them now and lock them in place. // Convert HANDLE to FileObject - PFILE_OBJECT FileObject; - PDEVICE_OBJECT DeviceObject; + PFILE_OBJECT FileObject; + PDEVICE_OBJECT DeviceObject; NTSTATUS status; // This adds a reference to FileObject status = ObReferenceObjectByHandle( - handle, - 0, - *IoFileObjectType, - KernelMode, - &FileObject, - NULL - ); + handle, + 0, + *IoFileObjectType, + KernelMode, + &FileObject, + NULL); if (status != STATUS_SUCCESS) { ZwClose(handle); - return (EIO); + return (EIO); } // Convert FileObject to DeviceObject @@ -140,7 +139,7 @@ zfs_file_open(const char *path, int flags, int mode, zfs_file_t **fpp) *fpp = fp; - return 0; + return (0); } void @@ -174,7 +173,7 @@ zfs_file_write(zfs_file_t *fp, const void *buf, size_t count, ssize_t *resid) IO_STATUS_BLOCK ioStatusBlock; ntstatus = ZwWriteFile(fp->f_handle, NULL, NULL, NULL, - &ioStatusBlock, buf, count, NULL, NULL); + &ioStatusBlock, buf, count, NULL, NULL); if (resid) *resid = 0; @@ -195,11 +194,13 @@ zfs_file_write(zfs_file_t *fp, const void *buf, size_t count, ssize_t *resid) * * Returns 0 on success errno on failure. */ -int zfs_file_read(zfs_file_t *fp, /* const */void *buf, size_t count, ssize_t *resid) +int +zfs_file_read(zfs_file_t *fp, void *buf, size_t count, ssize_t *resid) { NTSTATUS ntstatus; IO_STATUS_BLOCK ioStatusBlock; - ntstatus = ZwReadFile(fp->f_handle, NULL, NULL, NULL, &ioStatusBlock, buf, count, NULL, NULL); + ntstatus = ZwReadFile(fp->f_handle, NULL, NULL, NULL, + &ioStatusBlock, buf, count, NULL, NULL); if (STATUS_SUCCESS != ntstatus) return (EIO); if (resid) @@ -220,13 +221,14 @@ int zfs_file_read(zfs_file_t *fp, /* const */void *buf, size_t count, ssize_t *r */ int zfs_file_pwrite(zfs_file_t *fp, const void *buf, size_t count, loff_t off, - ssize_t *resid) + ssize_t *resid) { NTSTATUS ntstatus; IO_STATUS_BLOCK ioStatusBlock; LARGE_INTEGER offset = { 0 }; offset.QuadPart = off; - ntstatus = ZwWriteFile(fp->f_handle, NULL, NULL, NULL, &ioStatusBlock, buf, count, &offset, NULL); + ntstatus = ZwWriteFile(fp->f_handle, NULL, NULL, NULL, + &ioStatusBlock, buf, count, &offset, NULL); // reset fp to its original position if (STATUS_SUCCESS != ntstatus) return (EIO); @@ -254,7 +256,8 @@ zfs_file_pread(zfs_file_t *fp, void *buf, size_t count, loff_t off, IO_STATUS_BLOCK ioStatusBlock; LARGE_INTEGER offset = { 0 }; offset.QuadPart = off; - ntstatus = ZwReadFile(fp->f_handle, NULL, NULL, NULL, &ioStatusBlock, buf, count, &offset, NULL); + ntstatus = ZwReadFile(fp->f_handle, NULL, NULL, NULL, + &ioStatusBlock, buf, count, &offset, NULL); if (STATUS_SUCCESS != ntstatus) return (EIO); if (resid) @@ -273,17 +276,16 @@ int zfs_file_fsync(zfs_file_t *fp, int flags) { if (KeGetCurrentIrql() != PASSIVE_LEVEL) - return -1; + return (-1); IO_STATUS_BLOCK ioStatusBlock; NTSTATUS ntStatus; ntStatus = ZwFlushBuffersFile( - fp->f_handle, - &ioStatusBlock - ); + fp->f_handle, + &ioStatusBlock); if (ntStatus != STATUS_SUCCESS) { - return -1; + return (-1); } - return 0; + return (0); } /* * fallocate - allocate or free space on disk @@ -301,7 +303,7 @@ zfs_file_fallocate(zfs_file_t *fp, int mode, loff_t offset, loff_t len) int error; struct flock flck; - bzero(&flck, sizeof(flck)); + bzero(&flck, sizeof (flck)); flck.l_type = F_FREESP; flck.l_start = offset; flck.l_len = len; @@ -330,12 +332,11 @@ zfs_file_getattr(zfs_file_t *fp, zfs_file_attr_t *zfattr) IO_STATUS_BLOCK ioStatusBlock; NTSTATUS ntStatus; ntStatus = ZwQueryInformationFile( - fp->f_handle, - &ioStatusBlock, - &fileInfo, - sizeof(fileInfo), - FileStandardInformation - ); + fp->f_handle, + &ioStatusBlock, + &fileInfo, + sizeof (fileInfo), + FileStandardInformation); if (ntStatus != STATUS_SUCCESS) { return (-1); } @@ -395,7 +396,7 @@ zfs_file_private(zfs_file_t *fp) * OPTIONAL */ int -zfs_file_unlink(const char* path) +zfs_file_unlink(const char *path) { return (EOPNOTSUPP); } diff --git a/module/os/windows/zfs/zfs_ioctl_os.c b/module/os/windows/zfs/zfs_ioctl_os.c index 9da99e5b429..5f5da128f90 100644 --- a/module/os/windows/zfs/zfs_ioctl_os.c +++ b/module/os/windows/zfs/zfs_ioctl_os.c @@ -217,7 +217,7 @@ zfsdev_ioctl(PDEVICE_OBJECT DeviceObject, PIRP Irp, int flag) zfs_cmd_t *zc; int error, rc; user_addr_t uaddr; - u_long cmd = 0; + ulong_t cmd = 0; caddr_t arg = NULL; PIO_STACK_LOCATION irpSp; @@ -227,7 +227,8 @@ zfsdev_ioctl(PDEVICE_OBJECT DeviceObject, PIRP Irp, int flag) cmd = irpSp->Parameters.DeviceIoControl.IoControlCode; arg = irpSp->Parameters.DeviceIoControl.Type3InputBuffer; - // vecnum = cmd - CTL_CODE(ZFSIOCTL_TYPE, ZFSIOCTL_BASE, METHOD_NEITHER, FILE_ANY_ACCESS); + // vecnum = cmd - CTL_CODE(ZFSIOCTL_TYPE, ZFSIOCTL_BASE, + // METHOD_NEITHER, FILE_ANY_ACCESS); vecnum = DEVICE_FUNCTION_FROM_CTL_CODE(cmd); ASSERT3U(vecnum, >=, ZFSIOCTL_BASE + ZFS_IOC_FIRST); @@ -242,11 +243,11 @@ zfsdev_ioctl(PDEVICE_OBJECT DeviceObject, PIRP Irp, int flag) return (EINVAL); } - // Copy in the wrapper, which contains real zfs_cmd_t addr, len, and compat version + // Copy in the wrapper, which contains real zfs_cmd_t addr, len, + // and compat version error = ddi_copyin((void *)arg, &zit, len, 0); - if (error != 0) { + if (error != 0) return (EINVAL); - } uaddr = (user_addr_t)zit.zfs_cmd; @@ -267,7 +268,7 @@ zfsdev_ioctl(PDEVICE_OBJECT DeviceObject, PIRP Irp, int flag) // Set the real return code in struct. // XNU only calls copyout if error=0, but - // presumably we can skip that in Windows and just return? + // presumably we can skip that in Windows and just return? zit.zfs_ioc_error = error; error = ddi_copyout(&zit, (void *)arg, len, 0); error = 0; @@ -279,48 +280,48 @@ zfsdev_ioctl(PDEVICE_OBJECT DeviceObject, PIRP Irp, int flag) } /* -* inputs: -* zc_name dataset name to mount -* zc_value path location to mount -* -* outputs: -* return code -*/ + * inputs: + * zc_name dataset name to mount + * zc_value path location to mount + * + * outputs: + * return code + */ int zfs_windows_mount(zfs_cmd_t *zc); // move me to headers static int zfs_ioc_mount(zfs_cmd_t *zc) { - return zfs_windows_mount(zc); + return (zfs_windows_mount(zc)); } /* -* inputs: -* zc_name dataset name to unmount -* zc_value path location to unmount -* -* outputs: -* return code -*/ + * inputs: + * zc_name dataset name to unmount + * zc_value path location to unmount + * + * outputs: + * return code + */ int zfs_windows_unmount(zfs_cmd_t *zc); // move me to headers static int zfs_ioc_unmount(zfs_cmd_t *zc) { dprintf("%s: enter\n", __func__); - return zfs_windows_unmount(zc); + return (zfs_windows_unmount(zc)); } void zfs_ioctl_init_os(void) { /* - * Windows functions - */ + * Windows functions + */ zfs_ioctl_register_legacy(ZFS_IOC_MOUNT, zfs_ioc_mount, - zfs_secpolicy_config, NO_NAME, B_FALSE, POOL_CHECK_NONE); + zfs_secpolicy_config, NO_NAME, B_FALSE, POOL_CHECK_NONE); zfs_ioctl_register_legacy(ZFS_IOC_UNMOUNT, zfs_ioc_unmount, - zfs_secpolicy_config, NO_NAME, B_FALSE, POOL_CHECK_NONE); + zfs_secpolicy_config, NO_NAME, B_FALSE, POOL_CHECK_NONE); } @@ -334,33 +335,38 @@ zfsdev_bioctl(dev_t dev, ulong_t cmd, caddr_t data, } // Callback to print registered filesystems. Not needed -VOID DriverNotificationRoutine(_In_ struct _DEVICE_OBJECT *DeviceObject, - _In_ BOOLEAN FsActive) +void +DriverNotificationRoutine(_In_ struct _DEVICE_OBJECT *DeviceObject, + _In_ BOOLEAN FsActive) { - CHAR nibuf[512]; // buffer that receives name information and name + CHAR nibuf[512]; // buffer that receives name information and name POBJECT_NAME_INFORMATION name_info = (POBJECT_NAME_INFORMATION)nibuf; ULONG ret_len; NTSTATUS status; - status = ObQueryNameString(DeviceObject, name_info, sizeof(nibuf), &ret_len); + status = ObQueryNameString(DeviceObject, name_info, + sizeof (nibuf), &ret_len); if (NT_SUCCESS(status)) { dprintf("Filesystem %p: '%wZ'\n", DeviceObject, name_info); } else { - dprintf("Filesystem %p: '%wZ'\n", DeviceObject, DeviceObject->DriverObject->DriverName); + dprintf("Filesystem %p: '%wZ'\n", DeviceObject, + DeviceObject->DriverObject->DriverName); } } // extern PDRIVER_UNLOAD STOR_DriverUnload; uint64_t -zfs_ioc_unregister_fs(void) +zfs_ioc_unregister_fs(void) { dprintf("%s\n", __func__); if (zfs_module_busy != 0) { - dprintf("%s: datasets still busy: %llu pool(s)\n", __func__, zfs_module_busy); - return zfs_module_busy; + dprintf("%s: datasets still busy: %llu pool(s)\n", + __func__, zfs_module_busy); + return (zfs_module_busy); } if (fsDiskDeviceObject != NULL) { - IoUnregisterFsRegistrationChange(WIN_DriverObject, DriverNotificationRoutine); + IoUnregisterFsRegistrationChange(WIN_DriverObject, + DriverNotificationRoutine); IoUnregisterFileSystem(fsDiskDeviceObject); ObDereferenceObject(fsDiskDeviceObject); UNICODE_STRING ntWin32NameString; @@ -380,7 +386,7 @@ zfs_ioc_unregister_fs(void) STOR_DriverUnload = NULL; } #endif - return 0; + return (0); } @@ -389,59 +395,61 @@ zfsdev_attach(void) { NTSTATUS ntStatus; UNICODE_STRING ntUnicodeString; // NT Device Name - UNICODE_STRING ntWin32NameString; // Win32 Name + UNICODE_STRING ntWin32NameString; // Win32 Name static UNICODE_STRING sddl = RTL_CONSTANT_STRING( - L"D:P(A;;GA;;;SY)(A;;GRGWGX;;;BA)(A;;GRGWGX;;;WD)(A;;GRGX;;;RC)"); + L"D:P(A;;GA;;;SY)(A;;GRGWGX;;;BA)" + "(A;;GRGWGX;;;WD)(A;;GRGX;;;RC)"); // Or use &SDDL_DEVOBJ_SYS_ALL_ADM_RWX_WORLD_RW_RES_R RtlInitUnicodeString(&ntUnicodeString, ZFS_DEV_KERNEL); ntStatus = IoCreateDeviceSecure( - WIN_DriverObject, // Our Driver Object - sizeof(mount_t), - &ntUnicodeString, // Device name "\Device\SIOCTL" - FILE_DEVICE_UNKNOWN, // Device type - /*FILE_DEVICE_SECURE_OPEN*/ 0, // Device characteristics - FALSE, // Not an exclusive device - &sddl, - NULL, - &ioctlDeviceObject); // Returned ptr to Device Object + WIN_DriverObject, + sizeof (mount_t), + &ntUnicodeString, // Device name "\Device\SIOCTL" + FILE_DEVICE_UNKNOWN, // Device type + /* FILE_DEVICE_SECURE_OPEN */ 0, // Device characteristics + FALSE, // Not an exclusive device + &sddl, + NULL, + &ioctlDeviceObject); // Returned ptr to Device Object if (!NT_SUCCESS(ntStatus)) { - dprintf("ZFS: Couldn't create the device object /dev/zfs (%S)\n", ZFS_DEV_KERNEL); - return ntStatus; + dprintf("ZFS: Couldn't create the device object " + "/dev/zfs (%S)\n", ZFS_DEV_KERNEL); + return (ntStatus); } - dprintf("ZFS: created kernel device node: %p: name %S\n", ioctlDeviceObject, ZFS_DEV_KERNEL); - + dprintf("ZFS: created kernel device node: %p: name %S\n", + ioctlDeviceObject, ZFS_DEV_KERNEL); UNICODE_STRING fsDiskDeviceName; RtlInitUnicodeString(&fsDiskDeviceName, ZFS_GLOBAL_FS_DISK_DEVICE_NAME); - ntStatus = IoCreateDeviceSecure(WIN_DriverObject, // DriverObject - sizeof(mount_t), // DeviceExtensionSize - &fsDiskDeviceName, // DeviceName - FILE_DEVICE_DISK_FILE_SYSTEM, // DeviceType - 0, // DeviceCharacteristics - FALSE, // Not Exclusive - &sddl, // Default SDDL String - NULL, // Device Class GUID - &fsDiskDeviceObject); // DeviceObject - + ntStatus = IoCreateDeviceSecure(WIN_DriverObject, // DriverObject + sizeof (mount_t), // DeviceExtensionSize + &fsDiskDeviceName, // DeviceName + FILE_DEVICE_DISK_FILE_SYSTEM, // DeviceType + 0, + FALSE, + &sddl, + NULL, + &fsDiskDeviceObject); // DeviceObject ObReferenceObject(ioctlDeviceObject); mount_t *dgl; dgl = ioctlDeviceObject->DeviceExtension; dgl->type = MOUNT_TYPE_DGL; - dgl->size = sizeof(mount_t); + dgl->size = sizeof (mount_t); mount_t *vcb; vcb = fsDiskDeviceObject->DeviceExtension; vcb->type = MOUNT_TYPE_VCB; - vcb->size = sizeof(mount_t); + vcb->size = sizeof (mount_t); if (ntStatus == STATUS_SUCCESS) { - dprintf("DiskFileSystemDevice: 0x%0x %wZ created\n", ntStatus, &fsDiskDeviceName); + dprintf("DiskFileSystemDevice: 0x%0x %wZ created\n", + ntStatus, &fsDiskDeviceName); } // Initialize a Unicode String containing the Win32 name @@ -450,13 +458,14 @@ zfsdev_attach(void) // Create a symbolic link between our device name and the Win32 name ntStatus = IoCreateSymbolicLink( - &ntWin32NameString, &ntUnicodeString); + &ntWin32NameString, &ntUnicodeString); if (!NT_SUCCESS(ntStatus)) { - dprintf("ZFS: Couldn't create userland symbolic link to /dev/zfs (%wZ)\n", ZFS_DEV); + dprintf("ZFS: Couldn't create userland symbolic link to " + "/dev/zfs (%wZ)\n", ZFS_DEV); ObDereferenceObject(ioctlDeviceObject); IoDeleteDevice(ioctlDeviceObject); - return -1; + return (-1); } dprintf("ZFS: created userland device symlink\n"); @@ -466,32 +475,56 @@ zfsdev_attach(void) ObReferenceObject(fsDiskDeviceObject); // Set all the callbacks to "dispatch()" - WIN_DriverObject->MajorFunction[IRP_MJ_CREATE] = (PDRIVER_DISPATCH)dispatcher; // zfs_ioctl.c - WIN_DriverObject->MajorFunction[IRP_MJ_CLOSE] = (PDRIVER_DISPATCH)dispatcher; // zfs_ioctl.c - WIN_DriverObject->MajorFunction[IRP_MJ_READ] = (PDRIVER_DISPATCH)dispatcher; - WIN_DriverObject->MajorFunction[IRP_MJ_WRITE] = (PDRIVER_DISPATCH)dispatcher; - WIN_DriverObject->MajorFunction[IRP_MJ_QUERY_INFORMATION] = (PDRIVER_DISPATCH)dispatcher; - WIN_DriverObject->MajorFunction[IRP_MJ_SET_INFORMATION] = (PDRIVER_DISPATCH)dispatcher; - WIN_DriverObject->MajorFunction[IRP_MJ_QUERY_EA] = (PDRIVER_DISPATCH)dispatcher; - WIN_DriverObject->MajorFunction[IRP_MJ_SET_EA] = (PDRIVER_DISPATCH)dispatcher; - WIN_DriverObject->MajorFunction[IRP_MJ_FLUSH_BUFFERS] = (PDRIVER_DISPATCH)dispatcher; - WIN_DriverObject->MajorFunction[IRP_MJ_QUERY_VOLUME_INFORMATION] = (PDRIVER_DISPATCH)dispatcher; - WIN_DriverObject->MajorFunction[IRP_MJ_SET_VOLUME_INFORMATION] = (PDRIVER_DISPATCH)dispatcher; - WIN_DriverObject->MajorFunction[IRP_MJ_DIRECTORY_CONTROL] = (PDRIVER_DISPATCH)dispatcher; - WIN_DriverObject->MajorFunction[IRP_MJ_FILE_SYSTEM_CONTROL] = (PDRIVER_DISPATCH)dispatcher; - WIN_DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = (PDRIVER_DISPATCH)dispatcher; // zfs_ioctl.c - WIN_DriverObject->MajorFunction[IRP_MJ_INTERNAL_DEVICE_CONTROL] = (PDRIVER_DISPATCH)dispatcher; // zfs_ioctl.c - WIN_DriverObject->MajorFunction[IRP_MJ_SHUTDOWN] = (PDRIVER_DISPATCH)dispatcher; - WIN_DriverObject->MajorFunction[IRP_MJ_LOCK_CONTROL] = (PDRIVER_DISPATCH)dispatcher; - WIN_DriverObject->MajorFunction[IRP_MJ_CLEANUP] = (PDRIVER_DISPATCH)dispatcher; - WIN_DriverObject->MajorFunction[IRP_MJ_SYSTEM_CONTROL] = (PDRIVER_DISPATCH)dispatcher; - WIN_DriverObject->MajorFunction[IRP_MJ_DEVICE_CHANGE] = (PDRIVER_DISPATCH)dispatcher; - WIN_DriverObject->MajorFunction[IRP_MJ_PNP] = (PDRIVER_DISPATCH)dispatcher; - WIN_DriverObject->MajorFunction[IRP_MJ_QUERY_SECURITY] = (PDRIVER_DISPATCH)dispatcher; - WIN_DriverObject->MajorFunction[IRP_MJ_SET_SECURITY] = (PDRIVER_DISPATCH)dispatcher; + WIN_DriverObject->MajorFunction[IRP_MJ_CREATE] = + (PDRIVER_DISPATCH)dispatcher; // zfs_ioctl.c + WIN_DriverObject->MajorFunction[IRP_MJ_CLOSE] = + (PDRIVER_DISPATCH)dispatcher; // zfs_ioctl.c + WIN_DriverObject->MajorFunction[IRP_MJ_READ] = + (PDRIVER_DISPATCH)dispatcher; + WIN_DriverObject->MajorFunction[IRP_MJ_WRITE] = + (PDRIVER_DISPATCH)dispatcher; + WIN_DriverObject->MajorFunction[IRP_MJ_QUERY_INFORMATION] = + (PDRIVER_DISPATCH)dispatcher; + WIN_DriverObject->MajorFunction[IRP_MJ_SET_INFORMATION] = + (PDRIVER_DISPATCH)dispatcher; + WIN_DriverObject->MajorFunction[IRP_MJ_QUERY_EA] = + (PDRIVER_DISPATCH)dispatcher; + WIN_DriverObject->MajorFunction[IRP_MJ_SET_EA] = + (PDRIVER_DISPATCH)dispatcher; + WIN_DriverObject->MajorFunction[IRP_MJ_FLUSH_BUFFERS] = + (PDRIVER_DISPATCH)dispatcher; + WIN_DriverObject->MajorFunction[IRP_MJ_QUERY_VOLUME_INFORMATION] = + (PDRIVER_DISPATCH)dispatcher; + WIN_DriverObject->MajorFunction[IRP_MJ_SET_VOLUME_INFORMATION] = + (PDRIVER_DISPATCH)dispatcher; + WIN_DriverObject->MajorFunction[IRP_MJ_DIRECTORY_CONTROL] = + (PDRIVER_DISPATCH)dispatcher; + WIN_DriverObject->MajorFunction[IRP_MJ_FILE_SYSTEM_CONTROL] = + (PDRIVER_DISPATCH)dispatcher; + WIN_DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = + (PDRIVER_DISPATCH)dispatcher; // zfs_ioctl.c + WIN_DriverObject->MajorFunction[IRP_MJ_INTERNAL_DEVICE_CONTROL] = + (PDRIVER_DISPATCH)dispatcher; // zfs_ioctl.c + WIN_DriverObject->MajorFunction[IRP_MJ_SHUTDOWN] = + (PDRIVER_DISPATCH)dispatcher; + WIN_DriverObject->MajorFunction[IRP_MJ_LOCK_CONTROL] = + (PDRIVER_DISPATCH)dispatcher; + WIN_DriverObject->MajorFunction[IRP_MJ_CLEANUP] = + (PDRIVER_DISPATCH)dispatcher; + WIN_DriverObject->MajorFunction[IRP_MJ_SYSTEM_CONTROL] = + (PDRIVER_DISPATCH)dispatcher; + WIN_DriverObject->MajorFunction[IRP_MJ_DEVICE_CHANGE] = + (PDRIVER_DISPATCH)dispatcher; + WIN_DriverObject->MajorFunction[IRP_MJ_PNP] = + (PDRIVER_DISPATCH)dispatcher; + WIN_DriverObject->MajorFunction[IRP_MJ_QUERY_SECURITY] = + (PDRIVER_DISPATCH)dispatcher; + WIN_DriverObject->MajorFunction[IRP_MJ_SET_SECURITY] = + (PDRIVER_DISPATCH)dispatcher; // Dump all registered filesystems - ntStatus = IoRegisterFsRegistrationChange(WIN_DriverObject, DriverNotificationRoutine); + ntStatus = IoRegisterFsRegistrationChange(WIN_DriverObject, + DriverNotificationRoutine); wrap_avl_init(); wrap_unicode_init(); @@ -504,9 +537,9 @@ zfsdev_attach(void) DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "ZFS: Loaded module %s, " - "ZFS pool version %s, ZFS filesystem version %s\n", - ZFS_META_GITREV, - SPA_VERSION_STRING, ZPL_VERSION_STRING); + "ZFS pool version %s, ZFS filesystem version %s\n", + ZFS_META_GITREV, + SPA_VERSION_STRING, ZPL_VERSION_STRING); return (0); } diff --git a/module/os/windows/zfs/zfs_kstat_windows.c b/module/os/windows/zfs/zfs_kstat_windows.c index 1d2d48ea0f6..dee1bfdb209 100644 --- a/module/os/windows/zfs/zfs_kstat_windows.c +++ b/module/os/windows/zfs/zfs_kstat_windows.c @@ -33,7 +33,6 @@ #include #ifdef _KERNEL #include -#include #include #endif #include @@ -48,13 +47,9 @@ * In Solaris the tunable are set via /etc/system. Until we have a load * time configuration, we add them to writable kstat tunables. * - * This table is more or less populated from IllumOS mdb zfs_params sources - * https://github.com/illumos/illumos-gate/blob/master/usr/src/cmd/mdb/common/modules/zfs/zfs.c#L336-L392 * */ - - windows_kstat_t windows_kstat = { { "spa_version", KSTAT_DATA_UINT64 }, { "zpl_version", KSTAT_DATA_UINT64 }, @@ -114,7 +109,7 @@ windows_kstat_t windows_kstat = { {"zfs_default_bs", KSTAT_DATA_INT64 }, {"zfs_default_ibs", KSTAT_DATA_INT64 }, {"metaslab_aliquot", KSTAT_DATA_INT64 }, - {"spa_max_replication_override",KSTAT_DATA_INT64 }, + {"spa_max_replication_override", KSTAT_DATA_INT64 }, {"spa_mode_global", KSTAT_DATA_INT64 }, {"zfs_flags", KSTAT_DATA_INT64 }, {"zfs_txg_timeout", KSTAT_DATA_INT64 }, @@ -148,10 +143,10 @@ windows_kstat_t windows_kstat = { {"zfs_recv_queue_length", KSTAT_DATA_UINT64 }, {"zvol_inhibit_dev", KSTAT_DATA_UINT64 }, - {"zfs_send_set_freerecords_bit",KSTAT_DATA_UINT64 }, + {"zfs_send_set_freerecords_bit", KSTAT_DATA_UINT64 }, - {"zfs_write_implies_delete_child",KSTAT_DATA_UINT64 }, - {"zfs_send_holes_without_brth_tme",KSTAT_DATA_UINT64 }, + {"zfs_write_implies_delete_child", KSTAT_DATA_UINT64 }, + {"zfs_send_holes_without_brth_tme", KSTAT_DATA_UINT64 }, {"dbuf_cache_max_bytes", KSTAT_DATA_UINT64 }, @@ -175,7 +170,7 @@ windows_kstat_t windows_kstat = { { "zfs_disable_removablemedia", KSTAT_DATA_UINT64 }, { "zfs_vdev_initialize_value", KSTAT_DATA_UINT64 }, { "zfs_autoimport_disable", KSTAT_DATA_UINT64 }, - + }; @@ -183,11 +178,12 @@ windows_kstat_t windows_kstat = { static kstat_t *windows_kstat_ksp; -#if !defined (__OPTIMIZE__) +#if !defined(__OPTIMIZE__) #pragma GCC diagnostic ignored "-Wframe-larger-than=" #endif -static int windows_kstat_update(kstat_t *ksp, int rw) +static int +windows_kstat_update(kstat_t *ksp, int rw) { windows_kstat_t *ks = ksp->ks_data; @@ -200,10 +196,14 @@ static int windows_kstat_update(kstat_t *ksp, int rw) saveBuffer(); if (ks->win32_debug.value.ui64 == 9119) panic("ZFS: User requested panic\n"); - zfs_vnop_ignore_negatives = ks->win32_ignore_negatives.value.ui64; - zfs_vnop_ignore_positives = ks->win32_ignore_positives.value.ui64; - zfs_vnop_create_negatives = ks->win32_create_negatives.value.ui64; - zfs_vnop_skip_unlinked_drain = ks->win32_skip_unlinked_drain.value.ui64; + zfs_vnop_ignore_negatives = + ks->win32_ignore_negatives.value.ui64; + zfs_vnop_ignore_positives = + ks->win32_ignore_positives.value.ui64; + zfs_vnop_create_negatives = + ks->win32_create_negatives.value.ui64; + zfs_vnop_skip_unlinked_drain = + ks->win32_skip_unlinked_drain.value.ui64; zfs_vfs_sync_paranoia = ks->win32_use_system_sync.value.ui64; /* L2ARC */ @@ -221,121 +221,121 @@ static int windows_kstat_update(kstat_t *ksp, int rw) /* vdev_queue */ zfs_vdev_max_active = - ks->zfs_vdev_max_active.value.ui64; + ks->zfs_vdev_max_active.value.ui64; zfs_vdev_sync_read_min_active = - ks->zfs_vdev_sync_read_min_active.value.ui64; + ks->zfs_vdev_sync_read_min_active.value.ui64; zfs_vdev_sync_read_max_active = - ks->zfs_vdev_sync_read_max_active.value.ui64; + ks->zfs_vdev_sync_read_max_active.value.ui64; zfs_vdev_sync_write_min_active = - ks->zfs_vdev_sync_write_min_active.value.ui64; + ks->zfs_vdev_sync_write_min_active.value.ui64; zfs_vdev_sync_write_max_active = - ks->zfs_vdev_sync_write_max_active.value.ui64; + ks->zfs_vdev_sync_write_max_active.value.ui64; zfs_vdev_async_read_min_active = - ks->zfs_vdev_async_read_min_active.value.ui64; + ks->zfs_vdev_async_read_min_active.value.ui64; zfs_vdev_async_read_max_active = - ks->zfs_vdev_async_read_max_active.value.ui64; + ks->zfs_vdev_async_read_max_active.value.ui64; zfs_vdev_async_write_min_active = - ks->zfs_vdev_async_write_min_active.value.ui64; + ks->zfs_vdev_async_write_min_active.value.ui64; zfs_vdev_async_write_max_active = - ks->zfs_vdev_async_write_max_active.value.ui64; + ks->zfs_vdev_async_write_max_active.value.ui64; zfs_vdev_scrub_min_active = - ks->zfs_vdev_scrub_min_active.value.ui64; + ks->zfs_vdev_scrub_min_active.value.ui64; zfs_vdev_scrub_max_active = - ks->zfs_vdev_scrub_max_active.value.ui64; + ks->zfs_vdev_scrub_max_active.value.ui64; zfs_vdev_async_write_active_min_dirty_percent = - ks->zfs_vdev_async_write_active_min_dirty_percent.value.i64; + ks->zfs_vdev_async_write_active_min_dirty_percent.value.i64; zfs_vdev_async_write_active_max_dirty_percent = - ks->zfs_vdev_async_write_active_max_dirty_percent.value.i64; + ks->zfs_vdev_async_write_active_max_dirty_percent.value.i64; zfs_vdev_aggregation_limit = - ks->zfs_vdev_aggregation_limit.value.i64; + ks->zfs_vdev_aggregation_limit.value.i64; zfs_vdev_read_gap_limit = - ks->zfs_vdev_read_gap_limit.value.i64; + ks->zfs_vdev_read_gap_limit.value.i64; zfs_vdev_write_gap_limit = - ks->zfs_vdev_write_gap_limit.value.i64; + ks->zfs_vdev_write_gap_limit.value.i64; arc_lotsfree_percent = - ks->arc_lotsfree_percent.value.i64; + ks->arc_lotsfree_percent.value.i64; zfs_dirty_data_max = - ks->zfs_dirty_data_max.value.i64; + ks->zfs_dirty_data_max.value.i64; zfs_delay_max_ns = - ks->zfs_delay_max_ns.value.i64; + ks->zfs_delay_max_ns.value.i64; zfs_delay_min_dirty_percent = - ks->zfs_delay_min_dirty_percent.value.i64; + ks->zfs_delay_min_dirty_percent.value.i64; zfs_delay_scale = - ks->zfs_delay_scale.value.i64; + ks->zfs_delay_scale.value.i64; spa_asize_inflation = - ks->spa_asize_inflation.value.i64; + ks->spa_asize_inflation.value.i64; zfs_prefetch_disable = - ks->zfs_prefetch_disable.value.i64; + ks->zfs_prefetch_disable.value.i64; zfetch_max_streams = - ks->zfetch_max_streams.value.i64; + ks->zfetch_max_streams.value.i64; zfetch_min_sec_reap = - ks->zfetch_min_sec_reap.value.i64; + ks->zfetch_min_sec_reap.value.i64; zfetch_array_rd_sz = - ks->zfetch_array_rd_sz.value.i64; + ks->zfetch_array_rd_sz.value.i64; zfs_default_bs = - ks->zfs_default_bs.value.i64; + ks->zfs_default_bs.value.i64; zfs_default_ibs = - ks->zfs_default_ibs.value.i64; + ks->zfs_default_ibs.value.i64; metaslab_aliquot = - ks->metaslab_aliquot.value.i64; + ks->metaslab_aliquot.value.i64; spa_max_replication_override = - ks->spa_max_replication_override.value.i64; + ks->spa_max_replication_override.value.i64; spa_mode_global = - ks->spa_mode_global.value.i64; + ks->spa_mode_global.value.i64; zfs_flags = - ks->zfs_flags.value.i64; + ks->zfs_flags.value.i64; zfs_txg_timeout = - ks->zfs_txg_timeout.value.i64; + ks->zfs_txg_timeout.value.i64; zfs_vdev_cache_max = - ks->zfs_vdev_cache_max.value.i64; + ks->zfs_vdev_cache_max.value.i64; zfs_vdev_cache_size = - ks->zfs_vdev_cache_size.value.i64; + ks->zfs_vdev_cache_size.value.i64; zfs_no_scrub_io = - ks->zfs_no_scrub_io.value.i64; + ks->zfs_no_scrub_io.value.i64; zfs_no_scrub_prefetch = - ks->zfs_no_scrub_prefetch.value.i64; + ks->zfs_no_scrub_prefetch.value.i64; fzap_default_block_shift = - ks->fzap_default_block_shift.value.i64; + ks->fzap_default_block_shift.value.i64; zfs_immediate_write_sz = - ks->zfs_immediate_write_sz.value.i64; + ks->zfs_immediate_write_sz.value.i64; zfs_read_chunk_size = - ks->zfs_read_chunk_size.value.i64; + ks->zfs_read_chunk_size.value.i64; zfs_nocacheflush = - ks->zfs_nocacheflush.value.i64; + ks->zfs_nocacheflush.value.i64; zil_replay_disable = - ks->zil_replay_disable.value.i64; + ks->zil_replay_disable.value.i64; metaslab_df_alloc_threshold = - ks->metaslab_df_alloc_threshold.value.i64; + ks->metaslab_df_alloc_threshold.value.i64; metaslab_df_free_pct = - ks->metaslab_df_free_pct.value.i64; + ks->metaslab_df_free_pct.value.i64; zio_injection_enabled = - ks->zio_injection_enabled.value.i64; + ks->zio_injection_enabled.value.i64; zvol_immediate_write_sz = - ks->zvol_immediate_write_sz.value.i64; + ks->zvol_immediate_write_sz.value.i64; zfs_recover = - ks->zfs_recover.value.i64; + ks->zfs_recover.value.i64; zfs_free_bpobj_enabled = - ks->zfs_free_bpobj_enabled.value.i64; + ks->zfs_free_bpobj_enabled.value.i64; zfs_send_corrupt_data = - ks->zfs_send_corrupt_data.value.ui64; + ks->zfs_send_corrupt_data.value.ui64; zfs_send_queue_length = - ks->zfs_send_queue_length.value.ui64; + ks->zfs_send_queue_length.value.ui64; zfs_recv_queue_length = - ks->zfs_recv_queue_length.value.ui64; + ks->zfs_recv_queue_length.value.ui64; zvol_inhibit_dev = - ks->zvol_inhibit_dev.value.ui64; + ks->zvol_inhibit_dev.value.ui64; zfs_send_set_freerecords_bit = - ks->zfs_send_set_freerecords_bit.value.ui64; + ks->zfs_send_set_freerecords_bit.value.ui64; zfs_write_implies_delete_child = - ks->zfs_write_implies_delete_child.value.ui64; + ks->zfs_write_implies_delete_child.value.ui64; send_holes_without_birth_time = - ks->zfs_send_holes_without_birth_time.value.ui64; + ks->zfs_send_holes_without_birth_time.value.ui64; dbuf_cache_max_bytes = ks->dbuf_cache_max_bytes.value.ui64; @@ -344,7 +344,7 @@ static int windows_kstat_update(kstat_t *ksp, int rw) ks->zfs_vdev_queue_depth_pct.value.ui64; zio_dva_throttle_enabled = - (boolean_t) ks->zio_dva_throttle_enabled.value.ui64; + (boolean_t)ks->zio_dva_throttle_enabled.value.ui64; zfs_lua_max_instrlimit = ks->zfs_lua_max_instrlimit.value.ui64; @@ -352,215 +352,222 @@ static int windows_kstat_update(kstat_t *ksp, int rw) ks->zfs_lua_max_memlimit.value.ui64; zfs_trim_extent_bytes_max = - ks->zfs_trim_extent_bytes_max.value.ui64; + ks->zfs_trim_extent_bytes_max.value.ui64; zfs_trim_extent_bytes_min = - ks->zfs_trim_extent_bytes_min.value.ui64; + ks->zfs_trim_extent_bytes_min.value.ui64; zfs_trim_metaslab_skip = - ks->zfs_trim_metaslab_skip.value.ui64; + ks->zfs_trim_metaslab_skip.value.ui64; zfs_trim_txg_batch = - ks->zfs_trim_txg_batch.value.ui64; + ks->zfs_trim_txg_batch.value.ui64; zfs_trim_queue_limit = - ks->zfs_trim_queue_limit.value.ui64; + ks->zfs_trim_queue_limit.value.ui64; spl_hostid = ks->win32_hw_hostid.value.ui32; zfs_send_unmodified_spill_blocks = - ks->zfs_send_unmodified_spill_blocks.value.ui64; + ks->zfs_send_unmodified_spill_blocks.value.ui64; zfs_special_class_metadata_reserve_pct = - ks->zfs_special_class_metadata_reserve_pct.value.ui64; + ks->zfs_special_class_metadata_reserve_pct.value.ui64; zfs_disable_wincache = - ks->zfs_disable_wincache.value.ui64; + ks->zfs_disable_wincache.value.ui64; zfs_disable_removablemedia = - ks->zfs_disable_removablemedia.value.ui64; + ks->zfs_disable_removablemedia.value.ui64; zfs_initialize_value = - ks->zfs_vdev_initialize_value.value.ui64; + ks->zfs_vdev_initialize_value.value.ui64; zfs_autoimport_disable = - ks->zfs_autoimport_disable.value.ui64; + ks->zfs_autoimport_disable.value.ui64; } else { /* kstat READ */ - ks->spa_version.value.ui64 = SPA_VERSION; - ks->zpl_version.value.ui64 = ZPL_VERSION; + ks->spa_version.value.ui64 = SPA_VERSION; + ks->zpl_version.value.ui64 = ZPL_VERSION; /* win32 */ - ks->win32_active_vnodes.value.ui64 = vnop_num_vnodes; - ks->win32_reclaim_nodes.value.ui64 = vnop_num_reclaims; - ks->win32_ignore_negatives.value.ui64 = zfs_vnop_ignore_negatives; - ks->win32_ignore_positives.value.ui64 = zfs_vnop_ignore_positives; - ks->win32_create_negatives.value.ui64 = zfs_vnop_create_negatives; - ks->win32_skip_unlinked_drain.value.ui64 = zfs_vnop_skip_unlinked_drain; + ks->win32_active_vnodes.value.ui64 = vnop_num_vnodes; + ks->win32_reclaim_nodes.value.ui64 = vnop_num_reclaims; + ks->win32_ignore_negatives.value.ui64 = + zfs_vnop_ignore_negatives; + ks->win32_ignore_positives.value.ui64 = + zfs_vnop_ignore_positives; + ks->win32_create_negatives.value.ui64 = + zfs_vnop_create_negatives; + ks->win32_skip_unlinked_drain.value.ui64 = + zfs_vnop_skip_unlinked_drain; ks->win32_use_system_sync.value.ui64 = zfs_vfs_sync_paranoia; /* L2ARC */ - ks->l2arc_write_max.value.ui64 = l2arc_write_max; - ks->l2arc_write_boost.value.ui64 = l2arc_write_boost; - ks->l2arc_headroom.value.ui64 = l2arc_headroom; - ks->l2arc_headroom_boost.value.ui64 = l2arc_headroom_boost; - ks->l2arc_feed_secs.value.ui64 = l2arc_feed_secs; - ks->l2arc_feed_min_ms.value.ui64 = l2arc_feed_min_ms; + ks->l2arc_write_max.value.ui64 = l2arc_write_max; + ks->l2arc_write_boost.value.ui64 = l2arc_write_boost; + ks->l2arc_headroom.value.ui64 = l2arc_headroom; + ks->l2arc_headroom_boost.value.ui64 = l2arc_headroom_boost; + ks->l2arc_feed_secs.value.ui64 = l2arc_feed_secs; + ks->l2arc_feed_min_ms.value.ui64 = l2arc_feed_min_ms; - ks->l2arc_noprefetch.value.i64 = l2arc_noprefetch; - ks->l2arc_feed_again.value.i64 = l2arc_feed_again; - ks->l2arc_norw.value.i64 = l2arc_norw; + ks->l2arc_noprefetch.value.i64 = l2arc_noprefetch; + ks->l2arc_feed_again.value.i64 = l2arc_feed_again; + ks->l2arc_norw.value.i64 = l2arc_norw; /* vdev_queue */ ks->zfs_vdev_max_active.value.ui64 = - zfs_vdev_max_active ; + zfs_vdev_max_active; ks->zfs_vdev_sync_read_min_active.value.ui64 = - zfs_vdev_sync_read_min_active ; + zfs_vdev_sync_read_min_active; ks->zfs_vdev_sync_read_max_active.value.ui64 = - zfs_vdev_sync_read_max_active ; + zfs_vdev_sync_read_max_active; ks->zfs_vdev_sync_write_min_active.value.ui64 = - zfs_vdev_sync_write_min_active ; + zfs_vdev_sync_write_min_active; ks->zfs_vdev_sync_write_max_active.value.ui64 = - zfs_vdev_sync_write_max_active ; + zfs_vdev_sync_write_max_active; ks->zfs_vdev_async_read_min_active.value.ui64 = - zfs_vdev_async_read_min_active ; + zfs_vdev_async_read_min_active; ks->zfs_vdev_async_read_max_active.value.ui64 = - zfs_vdev_async_read_max_active ; + zfs_vdev_async_read_max_active; ks->zfs_vdev_async_write_min_active.value.ui64 = - zfs_vdev_async_write_min_active ; + zfs_vdev_async_write_min_active; ks->zfs_vdev_async_write_max_active.value.ui64 = - zfs_vdev_async_write_max_active ; + zfs_vdev_async_write_max_active; ks->zfs_vdev_scrub_min_active.value.ui64 = - zfs_vdev_scrub_min_active ; + zfs_vdev_scrub_min_active; ks->zfs_vdev_scrub_max_active.value.ui64 = - zfs_vdev_scrub_max_active ; + zfs_vdev_scrub_max_active; ks->zfs_vdev_async_write_active_min_dirty_percent.value.i64 = - zfs_vdev_async_write_active_min_dirty_percent ; + zfs_vdev_async_write_active_min_dirty_percent; ks->zfs_vdev_async_write_active_max_dirty_percent.value.i64 = - zfs_vdev_async_write_active_max_dirty_percent ; + zfs_vdev_async_write_active_max_dirty_percent; ks->zfs_vdev_aggregation_limit.value.i64 = - zfs_vdev_aggregation_limit ; + zfs_vdev_aggregation_limit; ks->zfs_vdev_read_gap_limit.value.i64 = - zfs_vdev_read_gap_limit ; + zfs_vdev_read_gap_limit; ks->zfs_vdev_write_gap_limit.value.i64 = - zfs_vdev_write_gap_limit; + zfs_vdev_write_gap_limit; ks->arc_lotsfree_percent.value.i64 = - arc_lotsfree_percent; + arc_lotsfree_percent; ks->zfs_dirty_data_max.value.i64 = - zfs_dirty_data_max; + zfs_dirty_data_max; ks->zfs_delay_max_ns.value.i64 = - zfs_delay_max_ns; + zfs_delay_max_ns; ks->zfs_delay_min_dirty_percent.value.i64 = - zfs_delay_min_dirty_percent; + zfs_delay_min_dirty_percent; ks->zfs_delay_scale.value.i64 = - zfs_delay_scale; + zfs_delay_scale; ks->spa_asize_inflation.value.i64 = - spa_asize_inflation; + spa_asize_inflation; ks->zfs_prefetch_disable.value.i64 = - zfs_prefetch_disable; + zfs_prefetch_disable; ks->zfetch_max_streams.value.i64 = - zfetch_max_streams; + zfetch_max_streams; ks->zfetch_min_sec_reap.value.i64 = - zfetch_min_sec_reap; + zfetch_min_sec_reap; ks->zfetch_array_rd_sz.value.i64 = - zfetch_array_rd_sz; + zfetch_array_rd_sz; ks->zfs_default_bs.value.i64 = - zfs_default_bs; + zfs_default_bs; ks->zfs_default_ibs.value.i64 = - zfs_default_ibs; + zfs_default_ibs; ks->metaslab_aliquot.value.i64 = - metaslab_aliquot; + metaslab_aliquot; ks->spa_max_replication_override.value.i64 = - spa_max_replication_override; + spa_max_replication_override; ks->spa_mode_global.value.i64 = - spa_mode_global; + spa_mode_global; ks->zfs_flags.value.i64 = - zfs_flags; + zfs_flags; ks->zfs_txg_timeout.value.i64 = - zfs_txg_timeout; + zfs_txg_timeout; ks->zfs_vdev_cache_max.value.i64 = - zfs_vdev_cache_max; + zfs_vdev_cache_max; ks->zfs_vdev_cache_size.value.i64 = - zfs_vdev_cache_size; + zfs_vdev_cache_size; ks->zfs_no_scrub_io.value.i64 = - zfs_no_scrub_io; + zfs_no_scrub_io; ks->zfs_no_scrub_prefetch.value.i64 = - zfs_no_scrub_prefetch; + zfs_no_scrub_prefetch; ks->fzap_default_block_shift.value.i64 = - fzap_default_block_shift; + fzap_default_block_shift; ks->zfs_immediate_write_sz.value.i64 = - zfs_immediate_write_sz; + zfs_immediate_write_sz; ks->zfs_read_chunk_size.value.i64 = - zfs_read_chunk_size; + zfs_read_chunk_size; ks->zfs_nocacheflush.value.i64 = - zfs_nocacheflush; + zfs_nocacheflush; ks->zil_replay_disable.value.i64 = - zil_replay_disable; + zil_replay_disable; ks->metaslab_df_alloc_threshold.value.i64 = - metaslab_df_alloc_threshold; + metaslab_df_alloc_threshold; ks->metaslab_df_free_pct.value.i64 = - metaslab_df_free_pct; + metaslab_df_free_pct; ks->zio_injection_enabled.value.i64 = - zio_injection_enabled; + zio_injection_enabled; ks->zvol_immediate_write_sz.value.i64 = - zvol_immediate_write_sz; + zvol_immediate_write_sz; ks->zfs_recover.value.i64 = - zfs_recover; + zfs_recover; ks->zfs_free_bpobj_enabled.value.i64 = - zfs_free_bpobj_enabled; + zfs_free_bpobj_enabled; ks->zfs_send_corrupt_data.value.ui64 = - zfs_send_corrupt_data; + zfs_send_corrupt_data; ks->zfs_send_queue_length.value.ui64 = - zfs_send_queue_length; + zfs_send_queue_length; ks->zfs_recv_queue_length.value.ui64 = - zfs_recv_queue_length; + zfs_recv_queue_length; ks->zvol_inhibit_dev.value.ui64 = - zvol_inhibit_dev; + zvol_inhibit_dev; ks->zfs_send_set_freerecords_bit.value.ui64 = - zfs_send_set_freerecords_bit; + zfs_send_set_freerecords_bit; ks->zfs_write_implies_delete_child.value.ui64 = - zfs_write_implies_delete_child; + zfs_write_implies_delete_child; ks->zfs_send_holes_without_birth_time.value.ui64 = - send_holes_without_birth_time; + send_holes_without_birth_time; ks->dbuf_cache_max_bytes.value.ui64 = dbuf_cache_max_bytes; - ks->zfs_vdev_queue_depth_pct.value.ui64 = zfs_vdev_queue_depth_pct; - ks->zio_dva_throttle_enabled.value.ui64 = (uint64_t) zio_dva_throttle_enabled; + ks->zfs_vdev_queue_depth_pct.value.ui64 = + zfs_vdev_queue_depth_pct; + ks->zio_dva_throttle_enabled.value.ui64 = + (uint64_t)zio_dva_throttle_enabled; ks->zfs_lua_max_instrlimit.value.ui64 = zfs_lua_max_instrlimit; ks->zfs_lua_max_memlimit.value.ui64 = zfs_lua_max_memlimit; ks->zfs_trim_extent_bytes_max.value.ui64 = - zfs_trim_extent_bytes_max; + zfs_trim_extent_bytes_max; ks->zfs_trim_extent_bytes_min.value.ui64 = - zfs_trim_extent_bytes_min; + zfs_trim_extent_bytes_min; ks->zfs_trim_metaslab_skip.value.ui64 = - zfs_trim_metaslab_skip; + zfs_trim_metaslab_skip; ks->zfs_trim_txg_batch.value.ui64 = - zfs_trim_txg_batch; + zfs_trim_txg_batch; ks->zfs_trim_queue_limit.value.ui64 = - zfs_trim_queue_limit; + zfs_trim_queue_limit; ks->win32_hw_hostid.value.ui32 = spl_hostid; ks->zfs_send_unmodified_spill_blocks.value.ui64 = - zfs_send_unmodified_spill_blocks; + zfs_send_unmodified_spill_blocks; ks->zfs_special_class_metadata_reserve_pct.value.ui64 = - zfs_special_class_metadata_reserve_pct; + zfs_special_class_metadata_reserve_pct; ks->zfs_disable_wincache.value.ui64 = - zfs_disable_wincache; + zfs_disable_wincache; ks->zfs_disable_removablemedia.value.ui64 = - zfs_disable_removablemedia; + zfs_disable_removablemedia; ks->zfs_vdev_initialize_value.value.ui64 = - zfs_initialize_value; + zfs_initialize_value; ks->zfs_autoimport_disable.value.ui64 = - zfs_autoimport_disable; + zfs_autoimport_disable; } - return 0; + return (0); } -int kstat_windows_init(void *arg) +int +kstat_windows_init(void *arg) { int error = 0; PUNICODE_STRING RegistryPath = arg; @@ -590,13 +597,14 @@ int kstat_windows_init(void *arg) KSTAT_EXIT(windows_kstat_ksp); } - return 0; + return (0); } -void kstat_windows_fini(void) +void +kstat_windows_fini(void) { - if (windows_kstat_ksp != NULL) { - kstat_delete(windows_kstat_ksp); - windows_kstat_ksp = NULL; - } + if (windows_kstat_ksp != NULL) { + kstat_delete(windows_kstat_ksp); + windows_kstat_ksp = NULL; + } } diff --git a/module/os/windows/zfs/zfs_vfsops.c b/module/os/windows/zfs/zfs_vfsops.c index a5d416029f5..d5b8341cad3 100644 --- a/module/os/windows/zfs/zfs_vfsops.c +++ b/module/os/windows/zfs/zfs_vfsops.c @@ -1203,7 +1203,7 @@ zfs_vfs_mount(struct mount *vfsp, vnode_t *mvp /* devvp */, user_addr_t data, vfs_context_t context) { int error = 0; - cred_t *cr = NULL;//(cred_t *)vfs_context_ucred(context); + cred_t *cr = NULL; // (cred_t *)vfs_context_ucred(context); char *osname = NULL; char *options = NULL; uint64_t flags = vfs_flags(vfsp); @@ -1215,14 +1215,14 @@ zfs_vfs_mount(struct mount *vfsp, vnode_t *mvp /* devvp */, size_t osnamelen = 0; uint32_t cmdflags = 0; -dprintf("%s\n", __func__); - cmdflags = (uint32_t) vfs_flags(vfsp) & MNT_CMDFLAGS; + dprintf("%s\n", __func__); + cmdflags = (uint32_t)vfs_flags(vfsp) & MNT_CMDFLAGS; rdonly = vfs_isrdonly(vfsp); -dprintf("%s cmdflags %u rdonly %d\n", __func__, cmdflags, rdonly); + dprintf("%s cmdflags %u rdonly %d\n", __func__, cmdflags, rdonly); /* - * Get the objset name (the "special" mount argument). - */ + * Get the objset name (the "special" mount argument). + */ if (data) { // Allocate string area @@ -1232,7 +1232,7 @@ dprintf("%s cmdflags %u rdonly %d\n", __func__, cmdflags, rdonly); } - if (mnt_args->struct_size == sizeof(*mnt_args)) { + if (mnt_args->struct_size == sizeof (*mnt_args)) { mflag = mnt_args->mflag; @@ -1240,14 +1240,14 @@ dprintf("%s cmdflags %u rdonly %d\n", __func__, cmdflags, rdonly); options = kmem_alloc(mnt_args->optlen, KM_SLEEP); strlcpy(options, mnt_args->optptr, mnt_args->optlen); } - //dprintf("vfs_mount: fspec '%s' : mflag %04llx : optptr %p : optlen %d :" + dprintf("%s: fspec '%s' : mflag %04x : optptr %p : optlen %d :" " options %s\n", __func__, - osname, - mnt_args->mflag, - mnt_args->optptr, - mnt_args->optlen, - options); + osname, + mnt_args->mflag, + mnt_args->optptr, + mnt_args->optlen, + options); } if (mflag & MS_RDONLY) { diff --git a/module/os/windows/zfs/zfs_vnops.c b/module/os/windows/zfs/zfs_vnops.c index c39cf91e7c4..395653f02ab 100644 --- a/module/os/windows/zfs/zfs_vnops.c +++ b/module/os/windows/zfs/zfs_vnops.c @@ -985,7 +985,7 @@ zfs_write_simple(znode_t *zp, const void *data, size_t len, ssize_t resid; error = zfs_vn_rdwr(UIO_WRITE, ZTOV(zp), data, len, - pos, UIO_SYSSPACE, 0 /*IO_SYNC*/, RLIM64_INFINITY, NULL, &resid); + pos, UIO_SYSSPACE, 0 /* IO_SYNC */, RLIM64_INFINITY, NULL, &resid); if (error) { return (SET_ERROR(error)); @@ -1759,11 +1759,11 @@ zfs_remove(znode_t *dzp, char *name, cred_t *cr, int flags) zfs_dirent_unlock(dl); - if (delete_now) + if (delete_now) { zrele(zp); - else + } else { zfs_zrele_async(zp); - + } if (xzp) zfs_zrele_async(xzp); @@ -2117,7 +2117,8 @@ zfs_rmdir(znode_t *dzp, char *name, znode_t *cwd, cred_t *cr, */ /* ARGSUSED */ int -zfs_readdir(vnode_t *vp, uio_t *uio, cred_t *cr, zfs_dirlist_t *zccb, int flags, int dirlisttype, int *a_numdirent) +zfs_readdir(vnode_t *vp, uio_t *uio, cred_t *cr, zfs_dirlist_t *zccb, + int flags, int dirlisttype, int *a_numdirent) { int error = 0; @@ -2147,13 +2148,13 @@ zfs_readdir(vnode_t *vp, uio_t *uio, cred_t *cr, zfs_dirlist_t *zccb, int flags, int last_alignment = 0; int skip_this_entry; int structsize = 0; - int flag_index_specified = flags & SL_INDEX_SPECIFIED ? 1 : 0; - int flag_restart_scan = flags & SL_RESTART_SCAN ? 1 : 0; - int flag_return_single_entry= flags & SL_RETURN_SINGLE_ENTRY ? 1 : 0; + int flag_index_specified = flags & SL_INDEX_SPECIFIED ? 1 : 0; + int flag_restart_scan = flags & SL_RESTART_SCAN ? 1 : 0; + int flag_return_single_entry = flags & SL_RETURN_SINGLE_ENTRY ? 1 : 0; FILE_DIRECTORY_INFORMATION *fdi; dprintf("+zfs_readdir: Index %d, Restart %d, Single %d\n", - flag_index_specified, flag_restart_scan, flag_return_single_entry); + flag_index_specified, flag_restart_scan, flag_return_single_entry); ZFS_ENTER(zfsvfs); ZFS_VERIFY_ZP(zp); @@ -2197,7 +2198,8 @@ zfs_readdir(vnode_t *vp, uio_t *uio, cred_t *cr, zfs_dirlist_t *zccb, int flags, case FileIdFullDirectoryInformation: break; default: - dprintf("%s: ** Directory type %d not handled!\n", __func__, dirlisttype); + dprintf("%s: ** Directory type %d not handled!\n", + __func__, dirlisttype); ZFS_EXIT(zfsvfs); return ((EINVAL)); } @@ -2247,7 +2249,7 @@ zfs_readdir(vnode_t *vp, uio_t *uio, cred_t *cr, zfs_dirlist_t *zccb, int flags, /* * Transform to file-system independent format */ - //zfsvfs->z_show_ctldir = ZFS_SNAPDIR_VISIBLE; + // zfsvfs->z_show_ctldir = ZFS_SNAPDIR_VISIBLE; outcount = 0; while (outcount < bytes_wanted) { @@ -2265,19 +2267,20 @@ zfs_readdir(vnode_t *vp, uio_t *uio, cred_t *cr, zfs_dirlist_t *zccb, int flags, * Special case `.', `..', and `.zfs'. */ if (offset == 0) { - (void)strlcpy(zap.za_name, ".", MAXNAMELEN); + (void) strlcpy(zap.za_name, ".", MAXNAMELEN); zap.za_normalization_conflict = 0; objnum = (zp->z_id == zfsvfs->z_root) ? 2 : zp->z_id; type = DT_DIR; } else if (offset == 1) { - (void)strlcpy(zap.za_name, "..", MAXNAMELEN); + (void) strlcpy(zap.za_name, "..", MAXNAMELEN); zap.za_normalization_conflict = 0; objnum = (parent == zfsvfs->z_root) ? 2 : parent; objnum = (zp->z_id == zfsvfs->z_root) ? 1 : objnum; type = DT_DIR; #if 1 } else if (offset == 2 && zfs_show_ctldir(zp)) { - (void)strlcpy(zap.za_name, ZFS_CTLDIR_NAME, MAXNAMELEN); + (void) strlcpy(zap.za_name, ZFS_CTLDIR_NAME, + MAXNAMELEN); zap.za_normalization_conflict = 0; objnum = ZFSCTL_INO_ROOT; type = DT_DIR; @@ -2295,11 +2298,11 @@ zfs_readdir(vnode_t *vp, uio_t *uio, cred_t *cr, zfs_dirlist_t *zccb, int flags, } if (zap.za_integer_length != 8 || - zap.za_num_integers != 1) { + zap.za_num_integers != 1) { cmn_err(CE_WARN, "zap_readdir: bad directory " - "entry, obj = %lld, offset = %lld\n", - (u_longlong_t)zp->z_id, - (u_longlong_t)offset); + "entry, obj = %lld, offset = %lld\n", + (u_longlong_t)zp->z_id, + (u_longlong_t)offset); error = SET_ERROR(ENXIO); goto update; } @@ -2314,7 +2317,7 @@ zfs_readdir(vnode_t *vp, uio_t *uio, cred_t *cr, zfs_dirlist_t *zccb, int flags, if (check_sysattrs && !zap.za_normalization_conflict) { #ifdef TODO zap.za_normalization_conflict = - xattr_sysattr_casechk(zap.za_name); + xattr_sysattr_casechk(zap.za_name); #else panic("%s:%u: TODO", __func__, __LINE__); #endif @@ -2324,13 +2327,14 @@ zfs_readdir(vnode_t *vp, uio_t *uio, cred_t *cr, zfs_dirlist_t *zccb, int flags, /* * Check if name will fit. * - * Note: non-ascii names may expand (up to 3x) when converted to NFD + * Note: non-ascii names may expand (up to 3x) when converted + * to NFD */ namelen = strlen(zap.za_name); /* sysctl to force formD normalization of vnop output */ if (zfs_vnop_force_formd_normalized_output && - !is_ascii_str(zap.za_name)) + !is_ascii_str(zap.za_name)) force_formd_normalized_output = 1; else force_formd_normalized_output = 0; @@ -2343,68 +2347,70 @@ zfs_readdir(vnode_t *vp, uio_t *uio, cred_t *cr, zfs_dirlist_t *zccb, int flags, * Do magic filename conversion for Windows here */ - error = RtlUTF8ToUnicodeN(NULL, 0, &namelenholder, zap.za_name, namelen); + error = RtlUTF8ToUnicodeN(NULL, 0, &namelenholder, + zap.za_name, namelen); // Did they provide a search pattern if (zccb->searchname.Buffer && zccb->searchname.Length) { UNICODE_STRING thisname; WCHAR tmpname[PATH_MAX]; ULONG tmpnamelen; - // We need to convert name to a tmp buffer here, as the output - // buffer might not have enough room to hold the whole name, and - // we need the whole name to do search match. - error = RtlUTF8ToUnicodeN(tmpname, PATH_MAX, &tmpnamelen, zap.za_name, namelen); - //dprintf("%s: '%.*S' -> '%s'\n", __func__, - // tmpnamelen / sizeof(WCHAR), tmpname, zap.za_name); - + // We need to convert name to a tmp buffer here, as the + // output buffer might not have enough room to hold the + // whole name, and we need the whole name to do search + // match. + error = RtlUTF8ToUnicodeN(tmpname, PATH_MAX, + &tmpnamelen, zap.za_name, namelen); + // dprintf("%s: '%.*S' -> '%s'\n", __func__, + // tmpnamelen / sizeof(WCHAR), tmpname, zap.za_name); thisname.Buffer = tmpname; thisname.Length = thisname.MaximumLength = tmpnamelen; // wildcard? if (zccb->ContainsWildCards) { if (!FsRtlIsNameInExpression(&zccb->searchname, - &thisname, - !(zfsvfs->z_case == ZFS_CASE_SENSITIVE), - NULL)) + &thisname, + !(zfsvfs->z_case == ZFS_CASE_SENSITIVE), + NULL)) skip_this_entry = 1; } else { if (!FsRtlAreNamesEqual(&thisname, - &zccb->searchname, - !(zfsvfs->z_case == ZFS_CASE_SENSITIVE), - NULL)) + &zccb->searchname, + !(zfsvfs->z_case == ZFS_CASE_SENSITIVE), + NULL)) skip_this_entry = 1; } #if 0 dprintf("comparing names '%.*S' == '%.*S' skip %d\n", - thisname.Length / sizeof(WCHAR), thisname.Buffer, - zccb->searchname.Length / sizeof(WCHAR), zccb->searchname.Buffer, - skip_this_entry); + thisname.Length / sizeof (WCHAR), thisname.Buffer, + zccb->searchname.Length / sizeof (WCHAR), + zccb->searchname.Buffer, + skip_this_entry); #endif } if (!skip_this_entry) { - // Windows combines vnop_readdir and vnop_getattr, so we need to lookup - // a bunch of values, we try to do that as lightweight as possible. + // Windows combines vnop_readdir and vnop_getattr, + // so we need to lookup a bunch of values, we try + // to do that as lightweight as possible. znode_t dummy = { 0 }; // For "." and ".." int get_zp = ENOENT; tzp = &dummy; - // If "." use zp, if ".." use dzp, neither needs releasing. Otherwise, call zget. + // If "." use zp, if ".." use dzp, neither needs + // releasing. Otherwise, call zget. if (offset == 0 || offset == 1) tzp = zp; else get_zp = zfs_zget_ext(zfsvfs, - offset == 1 ? parent : objnum, &tzp, // objnum is adjusted above -#if 1 - ZGET_FLAG_UNLINKED); -#else - ZGET_FLAG_UNLINKED | ZGET_FLAG_WITHOUT_VNODE ); -#endif + offset == 1 ? parent : objnum, &tzp, + ZGET_FLAG_UNLINKED); - // If we failed to get the node (someone else might have deleted it), but we - // need to return the name still, so it can be removed. + // If we failed to get the node (someone else might have + // deleted it), but we need to return the name still, + // so it can be removed. if (get_zp != 0 && tzp == NULL) skip_this_entry = 1; @@ -2417,49 +2423,98 @@ zfs_readdir(vnode_t *vp, uio_t *uio, cred_t *cr, zfs_dirlist_t *zccb, int flags, uint64_t mtime[2]; uint64_t ctime[2]; uint64_t crtime[2]; - SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, &mtime, 16); - SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, &ctime, 16); - SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CRTIME(zfsvfs), NULL, &crtime, 16); + SA_ADD_BULK_ATTR(bulk, count, + SA_ZPL_MTIME(zfsvfs), NULL, &mtime, 16); + SA_ADD_BULK_ATTR(bulk, count, + SA_ZPL_CTIME(zfsvfs), NULL, &ctime, 16); + SA_ADD_BULK_ATTR(bulk, count, + SA_ZPL_CRTIME(zfsvfs), NULL, &crtime, 16); sa_bulk_lookup(tzp->z_sa_hdl, bulk, count); - // Is it worth warning about failed lookup here? + // Is it worth warning about failed lookup here? structsize = 0; + /* + * This giant switch is a bit awkward with such + * little indentation left, and should be moved + * to own function, so that zfs_ctldir.c can + * also use it. + */ + switch (dirlisttype) { case FileFullDirectoryInformation: - structsize = FIELD_OFFSET(FILE_FULL_DIR_INFORMATION, FileName[0]); - if (outcount + structsize + namelenholder > bufsize) break; - - eodp = (FILE_FULL_DIR_INFORMATION *)bufptr; + structsize = FIELD_OFFSET( + FILE_FULL_DIR_INFORMATION, + FileName[0]); + if (outcount + structsize + + namelenholder > bufsize) + break; + + eodp = + (FILE_FULL_DIR_INFORMATION *)bufptr; eodp->FileIndex = offset; - eodp->AllocationSize.QuadPart = S_ISDIR(tzp->z_mode) ? 0 : P2ROUNDUP(tzp->z_size, zfs_blksz(tzp)); // File size in block alignment - eodp->EndOfFile.QuadPart = S_ISDIR(tzp->z_mode) ? 0 : tzp->z_size; // File size in bytes - TIME_UNIX_TO_WINDOWS(mtime, eodp->LastWriteTime.QuadPart); - TIME_UNIX_TO_WINDOWS(ctime, eodp->ChangeTime.QuadPart); - TIME_UNIX_TO_WINDOWS(crtime, eodp->CreationTime.QuadPart); - TIME_UNIX_TO_WINDOWS(tzp->z_atime, eodp->LastAccessTime.QuadPart); - eodp->EaSize = tzp->z_pflags & ZFS_REPARSE ? 0xa0000003 : xattr_getsize(ZTOV(tzp)); // Magic code to change dir icon to link - eodp->FileAttributes = zfs_getwinflags(tzp); + eodp->AllocationSize.QuadPart = + S_ISDIR(tzp->z_mode) ? 0 : + P2ROUNDUP(tzp->z_size, + zfs_blksz(tzp)); + eodp->EndOfFile.QuadPart = + S_ISDIR(tzp->z_mode) ? 0 : + tzp->z_size; + TIME_UNIX_TO_WINDOWS(mtime, + eodp->LastWriteTime.QuadPart); + TIME_UNIX_TO_WINDOWS(ctime, + eodp->ChangeTime.QuadPart); + TIME_UNIX_TO_WINDOWS(crtime, + eodp->CreationTime.QuadPart); + TIME_UNIX_TO_WINDOWS(tzp->z_atime, + eodp->LastAccessTime.QuadPart); + // Magic code to change dir icon to link + eodp->EaSize = + tzp->z_pflags & ZFS_REPARSE ? + 0xa0000003 : + xattr_getsize(ZTOV(tzp)); + eodp->FileAttributes = + zfs_getwinflags(tzp); nameptr = eodp->FileName; eodp->FileNameLength = namelenholder; break; case FileIdBothDirectoryInformation: - structsize = FIELD_OFFSET(FILE_ID_BOTH_DIR_INFORMATION, FileName[0]); - if (outcount + structsize + namelenholder > bufsize) break; - - eodp = (FILE_FULL_DIR_INFORMATION *)bufptr; - FILE_ID_BOTH_DIR_INFORMATION *fibdi = (FILE_ID_BOTH_DIR_INFORMATION *)bufptr; - fibdi->AllocationSize.QuadPart = S_ISDIR(tzp->z_mode) ? 0 : P2ROUNDUP(tzp->z_size, zfs_blksz(tzp)); - fibdi->EndOfFile.QuadPart = S_ISDIR(tzp->z_mode) ? 0 : tzp->z_size; - TIME_UNIX_TO_WINDOWS(mtime, fibdi->LastWriteTime.QuadPart); - TIME_UNIX_TO_WINDOWS(ctime, fibdi->ChangeTime.QuadPart); - TIME_UNIX_TO_WINDOWS(crtime, fibdi->CreationTime.QuadPart); - TIME_UNIX_TO_WINDOWS(tzp->z_atime, fibdi->LastAccessTime.QuadPart); - fibdi->EaSize = tzp->z_pflags & ZFS_REPARSE ? 0xa0000003 : xattr_getsize(ZTOV(tzp)); - fibdi->FileAttributes = zfs_getwinflags(tzp); + structsize = FIELD_OFFSET( + FILE_ID_BOTH_DIR_INFORMATION, + FileName[0]); + if (outcount + structsize + + namelenholder > bufsize) + break; + + eodp = + (FILE_FULL_DIR_INFORMATION *)bufptr; + FILE_ID_BOTH_DIR_INFORMATION *fibdi; + fibdi = (FILE_ID_BOTH_DIR_INFORMATION *) + bufptr; + fibdi->AllocationSize.QuadPart = + S_ISDIR(tzp->z_mode) ? 0 : + P2ROUNDUP(tzp->z_size, + zfs_blksz(tzp)); + fibdi->EndOfFile.QuadPart = + S_ISDIR(tzp->z_mode) ? 0 : + tzp->z_size; + TIME_UNIX_TO_WINDOWS(mtime, + fibdi->LastWriteTime.QuadPart); + TIME_UNIX_TO_WINDOWS(ctime, + fibdi->ChangeTime.QuadPart); + TIME_UNIX_TO_WINDOWS(crtime, + fibdi->CreationTime.QuadPart); + TIME_UNIX_TO_WINDOWS(tzp->z_atime, + fibdi->LastAccessTime.QuadPart); + fibdi->EaSize = + tzp->z_pflags & ZFS_REPARSE ? + 0xa0000003 : + xattr_getsize(ZTOV(tzp)); + fibdi->FileAttributes = + zfs_getwinflags(tzp); fibdi->FileId.QuadPart = objnum; fibdi->FileIndex = offset; fibdi->ShortNameLength = 0; @@ -2469,19 +2524,38 @@ zfs_readdir(vnode_t *vp, uio_t *uio, cred_t *cr, zfs_dirlist_t *zccb, int flags, break; case FileBothDirectoryInformation: - structsize = FIELD_OFFSET(FILE_BOTH_DIR_INFORMATION, FileName[0]); - if (outcount + structsize + namelenholder > bufsize) break; - - eodp = (FILE_FULL_DIR_INFORMATION *)bufptr; - FILE_BOTH_DIR_INFORMATION *fbdi = (FILE_BOTH_DIR_INFORMATION *)bufptr; - fbdi->AllocationSize.QuadPart = S_ISDIR(tzp->z_mode) ? 0 : P2ROUNDUP(tzp->z_size, zfs_blksz(tzp)); - fbdi->EndOfFile.QuadPart = S_ISDIR(tzp->z_mode) ? 0 : tzp->z_size; - TIME_UNIX_TO_WINDOWS(mtime, fbdi->LastWriteTime.QuadPart); - TIME_UNIX_TO_WINDOWS(ctime, fbdi->ChangeTime.QuadPart); - TIME_UNIX_TO_WINDOWS(crtime, fbdi->CreationTime.QuadPart); - TIME_UNIX_TO_WINDOWS(tzp->z_atime, fbdi->LastAccessTime.QuadPart); - fbdi->EaSize = tzp->z_pflags & ZFS_REPARSE ? 0xa0000003 : xattr_getsize(ZTOV(tzp)); - fbdi->FileAttributes = zfs_getwinflags(tzp); + structsize = FIELD_OFFSET( + FILE_BOTH_DIR_INFORMATION, + FileName[0]); + if (outcount + structsize + + namelenholder > bufsize) + break; + + eodp = + (FILE_FULL_DIR_INFORMATION *)bufptr; + FILE_BOTH_DIR_INFORMATION *fbdi = + (FILE_BOTH_DIR_INFORMATION *)bufptr; + fbdi->AllocationSize.QuadPart = + S_ISDIR(tzp->z_mode) ? 0 : + P2ROUNDUP(tzp->z_size, + zfs_blksz(tzp)); + fbdi->EndOfFile.QuadPart = + S_ISDIR(tzp->z_mode) ? 0 : + tzp->z_size; + TIME_UNIX_TO_WINDOWS(mtime, + fbdi->LastWriteTime.QuadPart); + TIME_UNIX_TO_WINDOWS(ctime, + fbdi->ChangeTime.QuadPart); + TIME_UNIX_TO_WINDOWS(crtime, + fbdi->CreationTime.QuadPart); + TIME_UNIX_TO_WINDOWS(tzp->z_atime, + fbdi->LastAccessTime.QuadPart); + fbdi->EaSize = + tzp->z_pflags & ZFS_REPARSE ? + 0xa0000003 : + xattr_getsize(ZTOV(tzp)); + fbdi->FileAttributes = + zfs_getwinflags(tzp); fbdi->FileIndex = offset; fbdi->ShortNameLength = 0; nameptr = fbdi->FileName; @@ -2490,20 +2564,33 @@ zfs_readdir(vnode_t *vp, uio_t *uio, cred_t *cr, zfs_dirlist_t *zccb, int flags, break; case FileDirectoryInformation: - structsize = FIELD_OFFSET(FILE_DIRECTORY_INFORMATION, FileName[0]); - if (outcount + structsize + namelenholder > bufsize) break; - eodp = (FILE_FULL_DIR_INFORMATION *)bufptr; - //FILE_DIRECTORY_INFORMATION *fdi = (FILE_DIRECTORY_INFORMATION *)bufptr; - fdi = (FILE_DIRECTORY_INFORMATION *)bufptr; - fdi->AllocationSize.QuadPart = S_ISDIR(tzp->z_mode) ? 0 : P2ROUNDUP(tzp->z_size, zfs_blksz(tzp)); - fdi->EndOfFile.QuadPart = S_ISDIR(tzp->z_mode) ? 0 : tzp->z_size; - TIME_UNIX_TO_WINDOWS(mtime, fdi->LastWriteTime.QuadPart); - TIME_UNIX_TO_WINDOWS(ctime, fdi->ChangeTime.QuadPart); - TIME_UNIX_TO_WINDOWS(crtime, fdi->CreationTime.QuadPart); - TIME_UNIX_TO_WINDOWS(tzp->z_atime, fdi->LastAccessTime.QuadPart); - fdi->FileAttributes = zfs_getwinflags(tzp); - //dtype == DT_DIR ? FILE_ATTRIBUTE_DIRECTORY : - // tzp->z_pflags&ZFS_REPARSEPOINT ? FILE_ATTRIBUTE_REPARSE_POINT : FILE_ATTRIBUTE_NORMAL; + structsize = FIELD_OFFSET( + FILE_DIRECTORY_INFORMATION, + FileName[0]); + if (outcount + structsize + + namelenholder > bufsize) + break; + eodp = + (FILE_FULL_DIR_INFORMATION *)bufptr; + fdi = (FILE_DIRECTORY_INFORMATION *) + bufptr; + fdi->AllocationSize.QuadPart = + S_ISDIR(tzp->z_mode) ? 0 : + P2ROUNDUP(tzp->z_size, + zfs_blksz(tzp)); + fdi->EndOfFile.QuadPart = + S_ISDIR(tzp->z_mode) ? 0 : + tzp->z_size; + TIME_UNIX_TO_WINDOWS(mtime, + fdi->LastWriteTime.QuadPart); + TIME_UNIX_TO_WINDOWS(ctime, + fdi->ChangeTime.QuadPart); + TIME_UNIX_TO_WINDOWS(crtime, + fdi->CreationTime.QuadPart); + TIME_UNIX_TO_WINDOWS(tzp->z_atime, + fdi->LastAccessTime.QuadPart); + fdi->FileAttributes = + zfs_getwinflags(tzp); fdi->FileIndex = offset; nameptr = fdi->FileName; fdi->FileNameLength = namelenholder; @@ -2511,31 +2598,56 @@ zfs_readdir(vnode_t *vp, uio_t *uio, cred_t *cr, zfs_dirlist_t *zccb, int flags, break; case FileNamesInformation: - structsize = FIELD_OFFSET(FILE_NAMES_INFORMATION, FileName[0]); - if (outcount + structsize + namelenholder > bufsize) break; - eodp = (FILE_FULL_DIR_INFORMATION *)bufptr; - FILE_NAMES_INFORMATION *fni = (FILE_NAMES_INFORMATION *)bufptr; - fni = (FILE_NAMES_INFORMATION *)bufptr; + structsize = + FIELD_OFFSET(FILE_NAMES_INFORMATION, + FileName[0]); + if (outcount + structsize + + namelenholder > bufsize) + break; + eodp = + (FILE_FULL_DIR_INFORMATION *)bufptr; + FILE_NAMES_INFORMATION *fni = + (FILE_NAMES_INFORMATION *)bufptr; fni->FileIndex = offset; nameptr = fni->FileName; fni->FileNameLength = namelenholder; break; case FileIdFullDirectoryInformation: - structsize = FIELD_OFFSET(FILE_ID_FULL_DIR_INFORMATION, FileName[0]); - if (outcount + structsize + namelenholder > bufsize) break; - - eodp = (FILE_FULL_DIR_INFORMATION *)bufptr; - FILE_ID_FULL_DIR_INFORMATION *fifdi = (FILE_ID_FULL_DIR_INFORMATION *)bufptr; + structsize = FIELD_OFFSET( + FILE_ID_FULL_DIR_INFORMATION, + FileName[0]); + if (outcount + structsize + + namelenholder > bufsize) + break; + + eodp = + (FILE_FULL_DIR_INFORMATION *)bufptr; + FILE_ID_FULL_DIR_INFORMATION *fifdi; + fifdi = (FILE_ID_FULL_DIR_INFORMATION *) + bufptr; fifdi->FileIndex = offset; - fifdi->AllocationSize.QuadPart = S_ISDIR(tzp->z_mode) ? 0 : P2ROUNDUP(tzp->z_size, zfs_blksz(tzp)); // File size in block alignment - fifdi->EndOfFile.QuadPart = S_ISDIR(tzp->z_mode) ? 0 : tzp->z_size; // File size in bytes - TIME_UNIX_TO_WINDOWS(mtime, fifdi->LastWriteTime.QuadPart); - TIME_UNIX_TO_WINDOWS(ctime, fifdi->ChangeTime.QuadPart); - TIME_UNIX_TO_WINDOWS(crtime, fifdi->CreationTime.QuadPart); - TIME_UNIX_TO_WINDOWS(tzp->z_atime, fifdi->LastAccessTime.QuadPart); - fifdi->EaSize = tzp->z_pflags & ZFS_REPARSE ? 0xa0000003 : xattr_getsize(ZTOV(tzp)); // Magic code to change dir icon to link - fifdi->FileAttributes = zfs_getwinflags(tzp); + fifdi->AllocationSize.QuadPart = + S_ISDIR(tzp->z_mode) ? 0 : + P2ROUNDUP(tzp->z_size, + zfs_blksz(tzp)); + fifdi->EndOfFile.QuadPart = + S_ISDIR(tzp->z_mode) ? 0 : + tzp->z_size; + TIME_UNIX_TO_WINDOWS(mtime, + fifdi->LastWriteTime.QuadPart); + TIME_UNIX_TO_WINDOWS(ctime, + fifdi->ChangeTime.QuadPart); + TIME_UNIX_TO_WINDOWS(crtime, + fifdi->CreationTime.QuadPart); + TIME_UNIX_TO_WINDOWS(tzp->z_atime, + fifdi->LastAccessTime.QuadPart); + fifdi->EaSize = + tzp->z_pflags & ZFS_REPARSE ? + 0xa0000003 : + xattr_getsize(ZTOV(tzp)); + fifdi->FileAttributes = + zfs_getwinflags(tzp); fifdi->FileId.QuadPart = zp->z_id; nameptr = fifdi->FileName; fifdi->FileNameLength = namelenholder; @@ -2550,45 +2662,49 @@ zfs_readdir(vnode_t *vp, uio_t *uio, cred_t *cr, zfs_dirlist_t *zccb, int flags, if (get_zp == 0) { if (ZTOV(tzp) == NULL) { zfs_zinactive(tzp); - } - else { + } else { VN_RELE(ZTOV(tzp)); } } #endif // If know we can't fit struct, just leave - if (outcount + structsize + namelenholder > bufsize) break; + if (outcount + structsize + + namelenholder > bufsize) + break; rawsize = structsize + namelenholder; reclen = DIRENT_RECLEN(rawsize); /* - * Will this entry fit in the buffer? This time with alignment + * Will this entry fit in the buffer? + * This time with alignment */ if (outcount + reclen > bufsize) { - /* - * Did we manage to fit anything in the buffer? - */ if (!outcount) { error = (EINVAL); goto update; } break; } - // If it is going to fit, compute alignment, in case - // this dir entry is the last one, we don't align last one. + // If it is going to fit, compute alignment, + // in case this dir entry is the last one, + // we don't align last one. last_alignment = reclen - rawsize; - - // Convert the filename over, or as much as we can fit + // Convert the filename over, or as much + // as we can fit ULONG namelenholder2 = 0; - error = RtlUTF8ToUnicodeN(nameptr, namelenholder, &namelenholder2, zap.za_name, namelen); + error = RtlUTF8ToUnicodeN(nameptr, + namelenholder, &namelenholder2, + zap.za_name, namelen); ASSERT(namelenholder == namelenholder2); #if 0 - dprintf("%s: '%.*S' -> '%s' (namelen %d bytes: structsize %d)\n", __func__, - namelenholder / sizeof(WCHAR), nameptr, zap.za_name, namelenholder, structsize); + dprintf("%s: '%.*S' -> '%s' (namelen %d bytes: " + "structsize %d)\n", __func__, + namelenholder / sizeof (WCHAR), nameptr, + zap.za_name, namelenholder, structsize); #endif // If we aren't to skip, advance all pointers @@ -2604,7 +2720,8 @@ zfs_readdir(vnode_t *vp, uio_t *uio, cred_t *cr, zfs_dirlist_t *zccb, int flags, /* Prefetch znode */ if (prefetch) - dmu_prefetch(os, objnum, 0, 0, 0, ZIO_PRIORITY_SYNC_READ); + dmu_prefetch(os, objnum, 0, 0, 0, + ZIO_PRIORITY_SYNC_READ); /* * Move to the next entry, fill in the previous offset. @@ -2627,7 +2744,7 @@ zfs_readdir(vnode_t *vp, uio_t *uio, cred_t *cr, zfs_dirlist_t *zccb, int flags, // aligned (to 8 bytes) length. But the last entry should not // be rounded-up. if ((outcount > last_alignment) && - (last_alignment > 0)) { + (last_alignment > 0)) { outcount -= last_alignment; } @@ -2888,129 +3005,8 @@ zfs_getattr(vnode_t *vp, vattr_t *vap, int flags, cred_t *cr, return (0); } -void kx_qsort(void* array, size_t nm, size_t member_size, int (*)(const void *, const void *)); - -#ifdef NOTSUREYET -/* - * For the operation of changing file's user/group/project, we need to - * handle not only the main object that is assigned to the file directly, - * but also the ones that are used by the file via hidden xattr directory. - * - * Because the xattr directory may contains many EA entries, as to it may - * be impossible to change all of them via the transaction of changing the - * main object's user/group/project attributes. Then we have to change them - * via other multiple independent transactions one by one. It may be not good - * solution, but we have no better idea yet. - */ -static int -zfs_setattr_dir(znode_t *dzp) -{ - struct vnode *dxip = ZTOI(dzp); - struct vnode *xip = NULL; - zfsvfs_t *zfsvfs = ZTOZSB(dzp); - objset_t *os = zfsvfs->z_os; - zap_cursor_t zc; - zap_attribute_t zap; - zfs_dirlock_t *dl; - znode_t *zp; - dmu_tx_t *tx = NULL; - uint64_t uid, gid; - sa_bulk_attr_t bulk[4]; - int count; - int err; - - zap_cursor_init(&zc, os, dzp->z_id); - while ((err = zap_cursor_retrieve(&zc, &zap)) == 0) { - count = 0; - if (zap.za_integer_length != 8 || zap.za_num_integers != 1) { - err = ENXIO; - break; - } - - err = zfs_dirent_lock(&dl, dzp, (char *)zap.za_name, &zp, - ZEXISTS, NULL, NULL); - if (err == ENOENT) - goto next; - if (err) - break; - - xip = ZTOI(zp); - if (zp->z_uid == dzp->z_uid && - zp->z_gid == dzp->z_gid && - zp->z_projid == dzp->z_projid) - goto next; - - tx = dmu_tx_create(os); - if (!(zp->z_pflags & ZFS_PROJID)) - dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE); - else - dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE); - - err = dmu_tx_assign(tx, TXG_WAIT); - if (err) - break; - - mutex_enter(&dzp->z_lock); - - if (zp->z_uid != dxzp->z_uid) { - zp->z_uid = dzp->z_uid; - uid = zfs_uid_read(dzp); - SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_UID(zfsvfs), NULL, - &uid, sizeof (uid)); - } - - if (KGID_TO_SGID(zp->z_gid) != KGID_TO_SGID(dxzp->z_gid)) { - zp->z_gid = dzp->z_gid; - gid = zfs_gid_read(dzp); - SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GID(zfsvfs), NULL, - &gid, sizeof (gid)); - } - - if (zp->z_projid != dzp->z_projid) { - if (!(zp->z_pflags & ZFS_PROJID)) { - zp->z_pflags |= ZFS_PROJID; - SA_ADD_BULK_ATTR(bulk, count, - SA_ZPL_FLAGS(zfsvfs), NULL, &zp->z_pflags, - sizeof (zp->z_pflags)); - } - - zp->z_projid = dzp->z_projid; - SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_PROJID(zfsvfs), - NULL, &zp->z_projid, sizeof (zp->z_projid)); - } - - mutex_exit(&dzp->z_lock); - - if (likely(count > 0)) { - err = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx); - dmu_tx_commit(tx); - } else { - dmu_tx_abort(tx); - } - tx = NULL; - if (err != 0 && err != ENOENT) - break; - -next: - if (zp) { - zrele(zp); - zp = NULL; - zfs_dirent_unlock(dl); - } - zap_cursor_advance(&zc); - } - - if (tx) - dmu_tx_abort(tx); - if (zp) { - zrele(zp); - zfs_dirent_unlock(dl); - } - zap_cursor_fini(&zc); - - return (err == ENOENT ? 0 : err); -} -#endif +void kx_qsort(void* array, size_t nm, size_t member_size, + int (*)(const void *, const void *)); /* * Set the file attributes to the values contained in the @@ -3018,89 +3014,54 @@ zfs_setattr_dir(znode_t *dzp) * * IN: zp - znode of file to be modified. * vap - new attribute values. - * If ATTR_XVATTR set, then optional attrs are being set + * If AT_XVATTR set, then optional attrs are being set * flags - ATTR_UTIME set if non-default time values provided. * - ATTR_NOACLCHECK (CIFS context only). * cr - credentials of caller. + * ct - caller context * - * RETURN: 0 if success - * error code if failure + * RETURN: 0 on success, error code on failure. * * Timestamps: - * ip - ctime updated, mtime updated if size changed. + * vp - ctime updated, mtime updated if size changed. */ /* ARGSUSED */ int zfs_setattr(znode_t *zp, vattr_t *vap, int flags, cred_t *cr) { - struct vnode *vp; - zfsvfs_t *zfsvfs = ZTOZSB(zp); + vnode_t *vp = ZTOV(zp); + zfsvfs_t *zfsvfs = zp->z_zfsvfs; objset_t *os = zfsvfs->z_os; zilog_t *zilog; dmu_tx_t *tx; vattr_t oldva; - xvattr_t *tmpxvattr; + xvattr_t tmpxvattr; uint_t mask = vap->va_mask; uint_t saved_mask = 0; + uint64_t saved_mode; int trim_mask = 0; uint64_t new_mode; - uint64_t new_kuid = 0, new_kgid = 0, new_uid, new_gid; + uint64_t new_uid, new_gid; uint64_t xattr_obj; - uint64_t mtime[2], ctime[2], atime[2], crtime[2]; + uint64_t mtime[2], ctime[2], crtime[2]; uint64_t projid = ZFS_INVALID_PROJID; znode_t *attrzp; int need_policy = FALSE; - int err, err2 = 0; + int err, err2; zfs_fuid_info_t *fuidp = NULL; xvattr_t *xvap = (xvattr_t *)vap; /* vap may be an xvattr_t * */ xoptattr_t *xoap; zfs_acl_t *aclp; + boolean_t skipaclchk = (flags & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE; boolean_t fuid_dirtied = B_FALSE; - boolean_t handle_eadir = B_FALSE; - sa_bulk_attr_t *bulk, *xattr_bulk; - int count = 0, xattr_count = 0, bulks = 9; + sa_bulk_attr_t bulk[7], xattr_bulk[7]; + int count = 0, xattr_count = 0; if (mask == 0) return (0); ZFS_ENTER(zfsvfs); ZFS_VERIFY_ZP(zp); - vp = ZTOV(zp); - - /* - * If this is a xvattr_t, then get a pointer to the structure of - * optional attributes. If this is NULL, then we have a vattr_t. - */ - xoap = xva_getxoptattr(xvap); - if (xoap != NULL && (mask & ATTR_XVATTR)) { - if (XVA_ISSET_REQ(xvap, XAT_PROJID)) { - if (!dmu_objset_projectquota_enabled(os) || - (!S_ISREG(zp->z_mode) && !S_ISDIR(zp->z_mode))) { - ZFS_EXIT(zfsvfs); - return (SET_ERROR(ENOTSUP)); - } - - projid = xoap->xoa_projid; - if (unlikely(projid == ZFS_INVALID_PROJID)) { - ZFS_EXIT(zfsvfs); - return (SET_ERROR(EINVAL)); - } - - if (projid == zp->z_projid && zp->z_pflags & ZFS_PROJID) - projid = ZFS_INVALID_PROJID; - else - need_policy = TRUE; - } - - if (XVA_ISSET_REQ(xvap, XAT_PROJINHERIT) && - (xoap->xoa_projinherit != - ((zp->z_pflags & ZFS_PROJINHERIT) != 0)) && - (!dmu_objset_projectquota_enabled(os) || - (!S_ISREG(zp->z_mode) && !S_ISDIR(zp->z_mode)))) { - ZFS_EXIT(zfsvfs); - return (SET_ERROR(ENOTSUP)); - } - } zilog = zfsvfs->z_log; @@ -3117,21 +3078,24 @@ zfs_setattr(znode_t *zp, vattr_t *vap, int flags, cred_t *cr) return (SET_ERROR(EINVAL)); } - if (mask & ATTR_SIZE && S_ISDIR(zp->z_mode)) { + if (mask & ATTR_SIZE && vnode_vtype(vp) == VDIR) { ZFS_EXIT(zfsvfs); return (SET_ERROR(EISDIR)); } - if (mask & ATTR_SIZE && !S_ISREG(zp->z_mode) && !S_ISFIFO(zp->z_mode)) { + if (mask & ATTR_SIZE && vnode_vtype(vp) != VREG && + vnode_vtype(vp) != VFIFO) { ZFS_EXIT(zfsvfs); return (SET_ERROR(EINVAL)); } - tmpxvattr = kmem_alloc(sizeof (xvattr_t), KM_SLEEP); - xva_init(tmpxvattr); + /* + * If this is an xvattr_t, then get a pointer to the structure of + * optional attributes. If this is NULL, then we have a vattr_t. + */ + xoap = xva_getxoptattr(xvap); - bulk = kmem_alloc(sizeof (sa_bulk_attr_t) * bulks, KM_SLEEP); - xattr_bulk = kmem_alloc(sizeof (sa_bulk_attr_t) * bulks, KM_SLEEP); + xva_init(&tmpxvattr); /* * Immutable files can only alter immutable bit and atime @@ -3139,14 +3103,13 @@ zfs_setattr(znode_t *zp, vattr_t *vap, int flags, cred_t *cr) if ((zp->z_pflags & ZFS_IMMUTABLE) && ((mask & (ATTR_SIZE|ATTR_UID|ATTR_GID|ATTR_MTIME|ATTR_MODE)) || ((mask & ATTR_XVATTR) && XVA_ISSET_REQ(xvap, XAT_CREATETIME)))) { - err = SET_ERROR(EPERM); - goto out3; + ZFS_EXIT(zfsvfs); + return (SET_ERROR(EPERM)); } - if ((mask & ATTR_SIZE) && (zp->z_pflags & ZFS_READONLY)) { - err = SET_ERROR(EPERM); - goto out3; - } + /* + * Note: ZFS_READONLY is handled in zfs_zaccess_common. + */ /* * Verify timestamps doesn't overflow 32 bits. @@ -3159,19 +3122,52 @@ zfs_setattr(znode_t *zp, vattr_t *vap, int flags, cred_t *cr) TIMESPEC_OVERFLOW(&vap->va_atime)) || ((mask & ATTR_MTIME) && TIMESPEC_OVERFLOW(&vap->va_mtime))) { - err = SET_ERROR(EOVERFLOW); - goto out3; + ZFS_EXIT(zfsvfs); + return (SET_ERROR(EOVERFLOW)); + } + } + if (xoap != NULL && (mask & ATTR_XVATTR)) { + if (XVA_ISSET_REQ(xvap, XAT_CREATETIME) && + TIMESPEC_OVERFLOW(&vap->va_create_time)) { + ZFS_EXIT(zfsvfs); + return (SET_ERROR(EOVERFLOW)); + } + + if (XVA_ISSET_REQ(xvap, XAT_PROJID)) { + if (!dmu_objset_projectquota_enabled(os) || + (!S_ISREG(zp->z_mode) && !S_ISDIR(zp->z_mode))) { + ZFS_EXIT(zfsvfs); + return (SET_ERROR(EOPNOTSUPP)); + } + + projid = xoap->xoa_projid; + if (unlikely(projid == ZFS_INVALID_PROJID)) { + ZFS_EXIT(zfsvfs); + return (SET_ERROR(EINVAL)); + } + + if (projid == zp->z_projid && zp->z_pflags & ZFS_PROJID) + projid = ZFS_INVALID_PROJID; + else + need_policy = TRUE; + } + + if (XVA_ISSET_REQ(xvap, XAT_PROJINHERIT) && + (xoap->xoa_projinherit != + ((zp->z_pflags & ZFS_PROJINHERIT) != 0)) && + (!dmu_objset_projectquota_enabled(os) || + (!S_ISREG(zp->z_mode) && !S_ISDIR(zp->z_mode)))) { + ZFS_EXIT(zfsvfs); + return (SET_ERROR(EOPNOTSUPP)); } } -top: attrzp = NULL; aclp = NULL; - /* Can this be moved to before the top label? */ if (zfs_is_readonly(zfsvfs)) { - err = SET_ERROR(EROFS); - goto out3; + ZFS_EXIT(zfsvfs); + return (SET_ERROR(EROFS)); } /* @@ -3179,10 +3175,6 @@ zfs_setattr(znode_t *zp, vattr_t *vap, int flags, cred_t *cr) */ if (mask & ATTR_SIZE) { - err = zfs_zaccess(zp, ACE_WRITE_DATA, 0, B_FALSE, cr); - if (err) - goto out3; - /* * XXX - Note, we are not providing any open * mode flags here (like FNDELAY), so we may @@ -3191,8 +3183,10 @@ zfs_setattr(znode_t *zp, vattr_t *vap, int flags, cred_t *cr) */ /* XXX - would it be OK to generate a log record here? */ err = zfs_freesp(zp, vap->va_size, 0, 0, FALSE); - if (err) - goto out3; + if (err) { + ZFS_EXIT(zfsvfs); + return (err); + } } if (mask & (ATTR_ATIME|ATTR_MTIME) || @@ -3204,7 +3198,7 @@ zfs_setattr(znode_t *zp, vattr_t *vap, int flags, cred_t *cr) XVA_ISSET_REQ(xvap, XAT_CREATETIME) || XVA_ISSET_REQ(xvap, XAT_SYSTEM)))) { need_policy = zfs_zaccess(zp, ACE_WRITE_ATTRIBUTES, 0, - B_FALSE, cr); + skipaclchk, cr); } if (mask & (ATTR_UID|ATTR_GID)) { @@ -3237,16 +3231,16 @@ zfs_setattr(znode_t *zp, vattr_t *vap, int flags, cred_t *cr) * */ - if (((idmask == (ATTR_UID|ATTR_GID)) && - take_owner && take_group) || + if (((idmask == (ATTR_UID|ATTR_GID)) && take_owner && + take_group) || ((idmask == ATTR_UID) && take_owner) || ((idmask == ATTR_GID) && take_group)) { if (zfs_zaccess(zp, ACE_WRITE_OWNER, 0, - B_FALSE, cr) == 0) { + skipaclchk, cr) == 0) { /* * Remove setuid/setgid for non-privileged users */ - (void) secpolicy_setid_clear(vap, cr); + secpolicy_setid_clear(vap, cr); trim_mask = (mask & (ATTR_UID|ATTR_GID)); } else { need_policy = TRUE; @@ -3256,7 +3250,6 @@ zfs_setattr(znode_t *zp, vattr_t *vap, int flags, cred_t *cr) } } - mutex_enter(&zp->z_lock); oldva.va_mode = zp->z_mode; zfs_fuid_map_ids(zp, cr, &oldva.va_uid, &oldva.va_gid); if (mask & ATTR_XVATTR) { @@ -3273,7 +3266,7 @@ zfs_setattr(znode_t *zp, vattr_t *vap, int flags, cred_t *cr) need_policy = TRUE; } else { XVA_CLR_REQ(xvap, XAT_APPENDONLY); - XVA_SET_REQ(tmpxvattr, XAT_APPENDONLY); + XVA_SET_REQ(&tmpxvattr, XAT_APPENDONLY); } } @@ -3283,7 +3276,7 @@ zfs_setattr(znode_t *zp, vattr_t *vap, int flags, cred_t *cr) need_policy = TRUE; } else { XVA_CLR_REQ(xvap, XAT_PROJINHERIT); - XVA_SET_REQ(tmpxvattr, XAT_PROJINHERIT); + XVA_SET_REQ(&tmpxvattr, XAT_PROJINHERIT); } } @@ -3293,7 +3286,7 @@ zfs_setattr(znode_t *zp, vattr_t *vap, int flags, cred_t *cr) need_policy = TRUE; } else { XVA_CLR_REQ(xvap, XAT_NOUNLINK); - XVA_SET_REQ(tmpxvattr, XAT_NOUNLINK); + XVA_SET_REQ(&tmpxvattr, XAT_NOUNLINK); } } @@ -3303,7 +3296,7 @@ zfs_setattr(znode_t *zp, vattr_t *vap, int flags, cred_t *cr) need_policy = TRUE; } else { XVA_CLR_REQ(xvap, XAT_IMMUTABLE); - XVA_SET_REQ(tmpxvattr, XAT_IMMUTABLE); + XVA_SET_REQ(&tmpxvattr, XAT_IMMUTABLE); } } @@ -3313,7 +3306,7 @@ zfs_setattr(znode_t *zp, vattr_t *vap, int flags, cred_t *cr) need_policy = TRUE; } else { XVA_CLR_REQ(xvap, XAT_NODUMP); - XVA_SET_REQ(tmpxvattr, XAT_NODUMP); + XVA_SET_REQ(&tmpxvattr, XAT_NODUMP); } } @@ -3323,26 +3316,25 @@ zfs_setattr(znode_t *zp, vattr_t *vap, int flags, cred_t *cr) need_policy = TRUE; } else { XVA_CLR_REQ(xvap, XAT_AV_MODIFIED); - XVA_SET_REQ(tmpxvattr, XAT_AV_MODIFIED); + XVA_SET_REQ(&tmpxvattr, XAT_AV_MODIFIED); } } if (XVA_ISSET_REQ(xvap, XAT_AV_QUARANTINED)) { - if ((!S_ISREG(zp->z_mode) && + if ((vnode_vtype(vp) != VREG && xoap->xoa_av_quarantined) || xoap->xoa_av_quarantined != ((zp->z_pflags & ZFS_AV_QUARANTINED) != 0)) { need_policy = TRUE; } else { XVA_CLR_REQ(xvap, XAT_AV_QUARANTINED); - XVA_SET_REQ(tmpxvattr, XAT_AV_QUARANTINED); + XVA_SET_REQ(&tmpxvattr, XAT_AV_QUARANTINED); } } if (XVA_ISSET_REQ(xvap, XAT_REPARSE)) { - mutex_exit(&zp->z_lock); - err = SET_ERROR(EPERM); - goto out3; + ZFS_EXIT(zfsvfs); + return (SET_ERROR(EPERM)); } if (need_policy == FALSE && @@ -3352,15 +3344,14 @@ zfs_setattr(znode_t *zp, vattr_t *vap, int flags, cred_t *cr) } } - mutex_exit(&zp->z_lock); - if (mask & ATTR_MODE) { - if (zfs_zaccess(zp, ACE_WRITE_ACL, 0, B_FALSE, cr) == 0) { + if (zfs_zaccess(zp, ACE_WRITE_ACL, 0, skipaclchk, cr) == 0) { err = secpolicy_setid_setsticky_clear(vp, vap, &oldva, cr); - if (err) - goto out3; - + if (err) { + ZFS_EXIT(zfsvfs); + return (err); + } trim_mask |= ATTR_MODE; } else { need_policy = TRUE; @@ -3379,14 +3370,31 @@ zfs_setattr(znode_t *zp, vattr_t *vap, int flags, cred_t *cr) if (trim_mask) { saved_mask = vap->va_mask; vap->va_mask &= ~trim_mask; + if (trim_mask & ATTR_MODE) { + /* + * Save the mode, as secpolicy_vnode_setattr() + * will overwrite it with ova.va_mode. + */ + saved_mode = vap->va_mode; + } } err = secpolicy_vnode_setattr(cr, vp, vap, &oldva, flags, (int (*)(void *, int, cred_t *))zfs_zaccess_unix, zp); - if (err) - goto out3; + if (err) { + ZFS_EXIT(zfsvfs); + return (err); + } - if (trim_mask) + if (trim_mask) { vap->va_mask |= saved_mask; + if (trim_mask & ATTR_MODE) { + /* + * Recover the mode after + * secpolicy_vnode_setattr(). + */ + vap->va_mode = saved_mode; + } + } } /* @@ -3396,21 +3404,20 @@ zfs_setattr(znode_t *zp, vattr_t *vap, int flags, cred_t *cr) mask = vap->va_mask; if ((mask & (ATTR_UID | ATTR_GID)) || projid != ZFS_INVALID_PROJID) { - handle_eadir = B_TRUE; err = sa_lookup(zp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs), &xattr_obj, sizeof (xattr_obj)); if (err == 0 && xattr_obj) { - err = zfs_zget(ZTOZSB(zp), xattr_obj, &attrzp); + err = zfs_zget(zp->z_zfsvfs, xattr_obj, &attrzp); if (err) goto out2; } if (mask & ATTR_UID) { - new_kuid = zfs_fuid_create(zfsvfs, + new_uid = zfs_fuid_create(zfsvfs, (uint64_t)vap->va_uid, cr, ZFS_OWNER, &fuidp); - if (new_kuid != zp->z_uid && + if (new_uid != zp->z_uid && zfs_id_overquota(zfsvfs, DMU_USERUSED_OBJECT, - new_kuid)) { + new_uid)) { if (attrzp) zrele(attrzp); err = SET_ERROR(EDQUOT); @@ -3419,11 +3426,11 @@ zfs_setattr(znode_t *zp, vattr_t *vap, int flags, cred_t *cr) } if (mask & ATTR_GID) { - new_kgid = zfs_fuid_create(zfsvfs, - (uint64_t)vap->va_gid, cr, ZFS_GROUP, &fuidp); - if (new_kgid != zp->z_gid && + new_gid = zfs_fuid_create(zfsvfs, (uint64_t)vap->va_gid, + cr, ZFS_GROUP, &fuidp); + if (new_gid != zp->z_gid && zfs_id_overquota(zfsvfs, DMU_GROUPUSED_OBJECT, - new_kgid)) { + new_gid)) { if (attrzp) zrele(attrzp); err = SET_ERROR(EDQUOT); @@ -3435,7 +3442,7 @@ zfs_setattr(znode_t *zp, vattr_t *vap, int flags, cred_t *cr) zfs_id_overquota(zfsvfs, DMU_PROJECTUSED_OBJECT, projid)) { if (attrzp) zrele(attrzp); - err = EDQUOT; + err = SET_ERROR(EDQUOT); goto out2; } } @@ -3446,10 +3453,15 @@ zfs_setattr(znode_t *zp, vattr_t *vap, int flags, cred_t *cr) uint64_t acl_obj; new_mode = (pmode & S_IFMT) | (vap->va_mode & ~S_IFMT); + if (zp->z_zfsvfs->z_acl_mode == ZFS_ACL_RESTRICTED && + !(zp->z_pflags & ZFS_ACL_TRIVIAL)) { + err = SET_ERROR(EPERM); + goto out; + } + if ((err = zfs_acl_chmod_setattr(zp, &aclp, new_mode))) goto out; - mutex_enter(&zp->z_lock); if (!zp->z_is_sa && ((acl_obj = zfs_external_acl(zp)) != 0)) { /* * Are we upgrading ACL from old V0 format @@ -3470,7 +3482,6 @@ zfs_setattr(znode_t *zp, vattr_t *vap, int flags, cred_t *cr) dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0, aclp->z_acl_bytes); } - mutex_exit(&zp->z_lock); dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE); } else { if (((mask & ATTR_XVATTR) && @@ -3528,7 +3539,6 @@ zfs_setattr(znode_t *zp, vattr_t *vap, int flags, cred_t *cr) if (mask & (ATTR_UID|ATTR_GID|ATTR_MODE)) mutex_enter(&zp->z_acl_lock); - mutex_enter(&zp->z_lock); SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL, &zp->z_pflags, sizeof (zp->z_pflags)); @@ -3536,7 +3546,6 @@ zfs_setattr(znode_t *zp, vattr_t *vap, int flags, cred_t *cr) if (attrzp) { if (mask & (ATTR_UID|ATTR_GID|ATTR_MODE)) mutex_enter(&attrzp->z_acl_lock); - mutex_enter(&attrzp->z_lock); SA_ADD_BULK_ATTR(xattr_bulk, xattr_count, SA_ZPL_FLAGS(zfsvfs), NULL, &attrzp->z_pflags, sizeof (attrzp->z_pflags)); @@ -3551,7 +3560,6 @@ zfs_setattr(znode_t *zp, vattr_t *vap, int flags, cred_t *cr) if (mask & (ATTR_UID|ATTR_GID)) { if (mask & ATTR_UID) { - new_uid = new_kuid; SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_UID(zfsvfs), NULL, &new_uid, sizeof (new_uid)); zp->z_uid = new_uid; @@ -3564,7 +3572,6 @@ zfs_setattr(znode_t *zp, vattr_t *vap, int flags, cred_t *cr) } if (mask & ATTR_GID) { - new_gid = new_kgid; SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GID(zfsvfs), NULL, &new_gid, sizeof (new_gid)); zp->z_gid = new_gid; @@ -3592,7 +3599,7 @@ zfs_setattr(znode_t *zp, vattr_t *vap, int flags, cred_t *cr) SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MODE(zfsvfs), NULL, &new_mode, sizeof (new_mode)); zp->z_mode = new_mode; - ASSERT3P(aclp, !=, NULL); + ASSERT3U((uintptr_t)aclp, !=, 0); err = zfs_aclset_common(zp, aclp, cr, tx); ASSERT0(err); if (zp->z_acl_cached) @@ -3601,25 +3608,19 @@ zfs_setattr(znode_t *zp, vattr_t *vap, int flags, cred_t *cr) aclp = NULL; } - if ((mask & ATTR_ATIME) || zp->z_atime_dirty) { - zp->z_atime_dirty = B_FALSE; + + if (mask & ATTR_ATIME) { ZFS_TIME_ENCODE(&vap->va_atime, zp->z_atime); SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_ATIME(zfsvfs), NULL, - &atime, sizeof (atime)); + &zp->z_atime, sizeof (zp->z_atime)); } - if (mask & (ATTR_MTIME | ATTR_SIZE)) { + if (mask & ATTR_MTIME) { ZFS_TIME_ENCODE(&vap->va_mtime, mtime); SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, mtime, sizeof (mtime)); } - if (mask & (ATTR_CTIME | ATTR_SIZE)) { - ZFS_TIME_ENCODE(&vap->va_ctime, ctime); - SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, - ctime, sizeof (ctime)); - } - if (mask & ATTR_CRTIME) { ZFS_TIME_ENCODE(&vap->va_crtime, crtime); SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CRTIME(zfsvfs), NULL, @@ -3633,10 +3634,24 @@ zfs_setattr(znode_t *zp, vattr_t *vap, int flags, cred_t *cr) sizeof (zp->z_projid)); } - if (attrzp && mask) { - SA_ADD_BULK_ATTR(xattr_bulk, xattr_count, - SA_ZPL_CTIME(zfsvfs), NULL, &ctime, - sizeof (ctime)); + /* XXX - shouldn't this be done *before* the ATIME/MTIME checks? */ + if (mask & ATTR_SIZE && !(mask & ATTR_MTIME)) { + SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), + NULL, mtime, sizeof (mtime)); + SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, + &ctime, sizeof (ctime)); + zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime); + } else if (mask != 0) { + SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, + &ctime, sizeof (ctime)); + zfs_tstamp_update_setup(zp, STATE_CHANGED, mtime, ctime); + if (attrzp) { + SA_ADD_BULK_ATTR(xattr_bulk, xattr_count, + SA_ZPL_CTIME(zfsvfs), NULL, + &ctime, sizeof (ctime)); + zfs_tstamp_update_setup(attrzp, STATE_CHANGED, + mtime, ctime); + } } /* @@ -3646,35 +3661,37 @@ zfs_setattr(znode_t *zp, vattr_t *vap, int flags, cred_t *cr) if (xoap && (mask & ATTR_XVATTR)) { + if (XVA_ISSET_REQ(xvap, XAT_CREATETIME)) + xoap->xoa_createtime = vap->va_create_time; /* * restore trimmed off masks * so that return masks can be set for caller. */ - if (XVA_ISSET_REQ(tmpxvattr, XAT_APPENDONLY)) { + if (XVA_ISSET_REQ(&tmpxvattr, XAT_APPENDONLY)) { XVA_SET_REQ(xvap, XAT_APPENDONLY); } - if (XVA_ISSET_REQ(tmpxvattr, XAT_NOUNLINK)) { + if (XVA_ISSET_REQ(&tmpxvattr, XAT_NOUNLINK)) { XVA_SET_REQ(xvap, XAT_NOUNLINK); } - if (XVA_ISSET_REQ(tmpxvattr, XAT_IMMUTABLE)) { + if (XVA_ISSET_REQ(&tmpxvattr, XAT_IMMUTABLE)) { XVA_SET_REQ(xvap, XAT_IMMUTABLE); } - if (XVA_ISSET_REQ(tmpxvattr, XAT_NODUMP)) { + if (XVA_ISSET_REQ(&tmpxvattr, XAT_NODUMP)) { XVA_SET_REQ(xvap, XAT_NODUMP); } - if (XVA_ISSET_REQ(tmpxvattr, XAT_AV_MODIFIED)) { + if (XVA_ISSET_REQ(&tmpxvattr, XAT_AV_MODIFIED)) { XVA_SET_REQ(xvap, XAT_AV_MODIFIED); } - if (XVA_ISSET_REQ(tmpxvattr, XAT_AV_QUARANTINED)) { + if (XVA_ISSET_REQ(&tmpxvattr, XAT_AV_QUARANTINED)) { XVA_SET_REQ(xvap, XAT_AV_QUARANTINED); } - if (XVA_ISSET_REQ(tmpxvattr, XAT_PROJINHERIT)) { + if (XVA_ISSET_REQ(&tmpxvattr, XAT_PROJINHERIT)) { XVA_SET_REQ(xvap, XAT_PROJINHERIT); } if (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP)) - ASSERT(S_ISREG(zp->z_mode)); + ASSERT(vp->v_type == VREG); zfs_xvattr_set(zp, xvap, tx); } @@ -3685,22 +3702,23 @@ zfs_setattr(znode_t *zp, vattr_t *vap, int flags, cred_t *cr) if (mask != 0) zfs_log_setattr(zilog, tx, TX_SETATTR, zp, vap, mask, fuidp); - mutex_exit(&zp->z_lock); if (mask & (ATTR_UID|ATTR_GID|ATTR_MODE)) mutex_exit(&zp->z_acl_lock); if (attrzp) { if (mask & (ATTR_UID|ATTR_GID|ATTR_MODE)) mutex_exit(&attrzp->z_acl_lock); - mutex_exit(&attrzp->z_lock); } out: - if (err == 0 && xattr_count > 0) { + if (err == 0 && attrzp) { err2 = sa_bulk_update(attrzp->z_sa_hdl, xattr_bulk, xattr_count, tx); ASSERT(err2 == 0); } + if (attrzp) + zrele(attrzp); + if (aclp) zfs_acl_free(aclp); @@ -3711,27 +3729,15 @@ zfs_setattr(znode_t *zp, vattr_t *vap, int flags, cred_t *cr) if (err) { dmu_tx_abort(tx); - if (attrzp) - zrele(attrzp); - if (err == ERESTART) - goto top; } else { - if (count > 0) - err2 = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx); + err2 = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx); dmu_tx_commit(tx); - if (attrzp) { - zrele(attrzp); - } } out2: if (os->os_sync == ZFS_SYNC_ALWAYS) zil_commit(zilog, 0); -out3: - kmem_free(xattr_bulk, sizeof (sa_bulk_attr_t) * bulks); - kmem_free(bulk, sizeof (sa_bulk_attr_t) * bulks); - kmem_free(tmpxvattr, sizeof (xvattr_t)); ZFS_EXIT(zfsvfs); return (err); } diff --git a/module/os/windows/zfs/zfs_vnops_windows.c b/module/os/windows/zfs/zfs_vnops_windows.c index c945d2db53b..01455ecfb37 100644 --- a/module/os/windows/zfs/zfs_vnops_windows.c +++ b/module/os/windows/zfs/zfs_vnops_windows.c @@ -36,16 +36,15 @@ #include #include - // I have no idea what black magic is needed to get ntifs.h to define these - +// I have no idea what black magic is needed to get ntifs.h to define these #ifndef FsRtlEnterFileSystem -#define FsRtlEnterFileSystem() { \ +#define FsRtlEnterFileSystem() { \ KeEnterCriticalRegion(); \ } #endif #ifndef FsRtlExitFileSystem -#define FsRtlExitFileSystem() { \ +#define FsRtlExitFileSystem() { \ KeLeaveCriticalRegion(); \ } #endif @@ -69,18 +68,10 @@ #include #include -//#include -//#include -#include #include #include #include #include -//#include -//#include -//#include -//#include - PDEVICE_OBJECT ioctlDeviceObject = NULL; PDEVICE_OBJECT fsDiskDeviceObject = NULL; @@ -118,32 +109,36 @@ uint64_t vnop_num_vnodes = 0; uint64_t zfs_disable_wincache = 0; #endif -extern void UnlockAndFreeMdl(PMDL ); +extern void UnlockAndFreeMdl(PMDL); -BOOLEAN zfs_AcquireForLazyWrite(void *Context, BOOLEAN Wait) +BOOLEAN +zfs_AcquireForLazyWrite(void *Context, BOOLEAN Wait) { struct vnode *vp = Context; dprintf("%s:\n", __func__); - if (vp == NULL) return FALSE; + if (vp == NULL) + return (FALSE); if (VN_HOLD(vp) == 0) { - if (!ExAcquireResourceSharedLite(vp->FileHeader.PagingIoResource, Wait)) { + if (!ExAcquireResourceSharedLite( + vp->FileHeader.PagingIoResource, Wait)) { dprintf("Failed\n"); VN_RELE(vp); - return FALSE; + return (FALSE); } vnode_ref(vp); VN_RELE(vp); - return TRUE; + return (TRUE); } - return FALSE; + return (FALSE); } -void zfs_ReleaseFromLazyWrite(void *Context) +void +zfs_ReleaseFromLazyWrite(void *Context) { struct vnode *vp = Context; dprintf("%s:\n", __func__); @@ -154,30 +149,34 @@ void zfs_ReleaseFromLazyWrite(void *Context) } } -BOOLEAN zfs_AcquireForReadAhead(void *Context, BOOLEAN Wait) +BOOLEAN +zfs_AcquireForReadAhead(void *Context, BOOLEAN Wait) { struct vnode *vp = Context; dprintf("%s:\n", __func__); - if (vp == NULL) return FALSE; + if (vp == NULL) + return (FALSE); if (VN_HOLD(vp) == 0) { - if (!ExAcquireResourceSharedLite(vp->FileHeader.Resource, Wait)) { + if (!ExAcquireResourceSharedLite(vp->FileHeader.Resource, + Wait)) { dprintf("Failed\n"); VN_RELE(vp); - return FALSE; + return (FALSE); } vnode_ref(vp); VN_RELE(vp); - return TRUE; + return (TRUE); } - return FALSE; + return (FALSE); } -void zfs_ReleaseFromReadAhead(void *Context) +void +zfs_ReleaseFromReadAhead(void *Context) { struct vnode *vp = Context; dprintf("%s:\n", __func__); @@ -200,9 +199,9 @@ void zfs_init_cache(FILE_OBJECT *fo, struct vnode *vp) { CcInitializeCacheMap(fo, - (PCC_FILE_SIZES)&vp->FileHeader.AllocationSize, - FALSE, - &CacheManagerCallbacks, vp); + (PCC_FILE_SIZES)&vp->FileHeader.AllocationSize, + FALSE, + &CacheManagerCallbacks, vp); dprintf("CcInitializeCacheMap called on vp %p\n", vp); CcSetAdditionalCacheAttributes(fo, TRUE, TRUE); // FIXME: for now fo->Flags |= FO_CACHE_SUPPORTED; @@ -215,14 +214,18 @@ zfs_init_cache(FILE_OBJECT *fo, struct vnode *vp) */ /* - * FileObject->FsContext will point to vnode, many FileObjects can point to same vnode. - * FileObject->FsContext2 will point to own "zfs_dirlist_t" and be unique to each FileObject. - * - which could also be done with TSD data, but this appears to be the Windows norm. + * FileObject->FsContext will point to vnode, many FileObjects can point + * to same vnode. + * FileObject->FsContext2 will point to own "zfs_dirlist_t" and be unique + * to each FileObject. + * - which could also be done with TSD data, but this appears to be + * the Windows norm. */ -void zfs_couplefileobject(vnode_t *vp, FILE_OBJECT *fileobject, uint64_t size) +void +zfs_couplefileobject(vnode_t *vp, FILE_OBJECT *fileobject, uint64_t size) { - ASSERT3P(fileobject->FsContext2, == , NULL); - zfs_dirlist_t *zccb = kmem_zalloc(sizeof(zfs_dirlist_t), KM_SLEEP); + ASSERT3P(fileobject->FsContext2, ==, NULL); + zfs_dirlist_t *zccb = kmem_zalloc(sizeof (zfs_dirlist_t), KM_SLEEP); zccb->magic = ZFS_DIRLIST_MAGIC; fileobject->FsContext2 = zccb; @@ -231,21 +234,23 @@ void zfs_couplefileobject(vnode_t *vp, FILE_OBJECT *fileobject, uint64_t size) zfs_init_cache(fileobject, vp); } -void zfs_decouplefileobject(vnode_t *vp, FILE_OBJECT *fileobject) +void +zfs_decouplefileobject(vnode_t *vp, FILE_OBJECT *fileobject) { // We release FsContext2 at CLEANUP, but fastfat releases it in // CLOSE. Does this matter? - zfs_dirlist_t* zccb = fileobject->FsContext2; + zfs_dirlist_t *zccb = fileobject->FsContext2; if (zccb != NULL) { if (zccb->searchname.Buffer != NULL) { - kmem_free(zccb->searchname.Buffer, zccb->searchname.MaximumLength); + kmem_free(zccb->searchname.Buffer, + zccb->searchname.MaximumLength); zccb->searchname.Buffer = NULL; zccb->searchname.MaximumLength = 0; } - kmem_free(zccb, sizeof(zfs_dirlist_t)); + kmem_free(zccb, sizeof (zfs_dirlist_t)); fileobject->FsContext2 = NULL; } @@ -256,22 +261,25 @@ void zfs_decouplefileobject(vnode_t *vp, FILE_OBJECT *fileobject) * Take filename, look for colons ":". * No colon, return OK. * if ends with "::$DATA". Terminate on colon, return OK (regular file open). - * if ends with anything not ":$DATA", return error. (we don't handle other types) - * if colon, parse name up until next colon. Assign colonname to point to stream name. + * if ends with anything not ":$DATA", return error. + * (we don't handle other types) + * if colon, parse name up until next colon. Assign colonname to + * point to stream name. */ -int stream_parse(char *filename, char **streamname) +int +stream_parse(char *filename, char **streamname) { char *colon, *second; // Just a filename, no streams. colon = strchr(filename, ':'); if (colon == NULL) - return 0; + return (0); // Regular file, with "::$DATA" end? - if (!strcmp(colon, "::$DATA")) { + if (strcmp(colon, "::$DATA") == 0) { *colon = 0; // Terminate before colon - return 0; + return (0); } // Look for second colon @@ -285,24 +293,24 @@ int stream_parse(char *filename, char **streamname) // We now ADD ":$DATA" to the stream name. strcat(*streamname, ":$DATA"); - return 0; + return (0); } // Have second colon, better be ":$DATA". - if (!strcmp(second, ":$DATA")) { + if (strcmp(second, ":$DATA") == 0) { // Terminate at second colon, set streamname - // We now keep the ":$DATA" extension in the xattr name + // We now keep the ":$DATA" extension in the xattr name // *second = 0; *streamname = &colon[1]; *colon = 0; // Cut of streamname from filename - return 0; + return (0); } // Not $DATA dprintf("%s: Not handling StreamType '%s'\n", __func__, second); - return EINVAL; + return (EINVAL); } /* @@ -313,8 +321,10 @@ int stream_parse(char *filename, char **streamname) * - HOLD on vp * - final parsed filename part in 'lastname' (in the case of creating an entry) */ -int zfs_find_dvp_vp(zfsvfs_t *zfsvfs, char *filename, int finalpartmaynotexist, int finalpartmustnotexist, - char **lastname, struct vnode **dvpp, struct vnode **vpp, int flags) +int +zfs_find_dvp_vp(zfsvfs_t *zfsvfs, char *filename, int finalpartmaynotexist, + int finalpartmustnotexist, char **lastname, struct vnode **dvpp, + struct vnode **vpp, int flags) { int error = ENOENT; znode_t *zp; @@ -331,33 +341,35 @@ int zfs_find_dvp_vp(zfsvfs_t *zfsvfs, char *filename, int finalpartmaynotexist, if (dvp == NULL) { // Grab a HOLD error = zfs_zget(zfsvfs, zfsvfs->z_root, &zp); - if (error != 0) return ESRCH; // No such dir + if (error != 0) + return (ESRCH); // No such dir dvp = ZTOV(zp); } else { // Passed in dvp is already HELD, but grab one now // since we release dirs as we descend dprintf("%s: passed in dvp\n", __func__); - if (VN_HOLD(dvp) != 0) return ESRCH; + if (VN_HOLD(dvp) != 0) + return (ESRCH); } fullstrlen = strlen(filename); - // Sometimes we are given a path like "\Directory\directory\" with the final - // separator, we want to eat that final character. + // Sometimes we are given a path like "\Directory\directory\" + // with the final separator, we want to eat that final character. if ((fullstrlen > 2) && - (filename[fullstrlen - 1] == '\\')) + (filename[fullstrlen - 1] == '\\')) filename[--fullstrlen] = 0; for (word = strtok_r(filename, "/\\", &brkt); - word; - word = strtok_r(NULL, "/\\", &brkt)) { + word; + word = strtok_r(NULL, "/\\", &brkt)) { - //dprintf("..'%s'..", word); + // dprintf("..'%s'..", word); // If a component part name is too long if (strlen(word) > MAXNAMELEN - 1) { VN_RELE(dvp); - return STATUS_OBJECT_NAME_INVALID; + return (STATUS_OBJECT_NAME_INVALID); } cn.cn_nameiop = LOOKUP; @@ -366,14 +378,16 @@ int zfs_find_dvp_vp(zfsvfs_t *zfsvfs, char *filename, int finalpartmaynotexist, cn.cn_nameptr = word; error = zfs_lookup(VTOZ(dvp), word, - &zp, &cn, cn.cn_nameiop, NULL, flags); + &zp, &cn, cn.cn_nameiop, NULL, flags); if (error != 0) { // If we are creating a file, or looking up parent, // allow it not to exist - if (finalpartmaynotexist) break; + if (finalpartmaynotexist) + break; dprintf("failing out here\n"); - VN_RELE(dvp); // since we weren't successful, we should release dvp here + // since we weren't successful, release dvp here + VN_RELE(dvp); dvp = NULL; break; } @@ -385,16 +399,19 @@ int zfs_find_dvp_vp(zfsvfs_t *zfsvfs, char *filename, int finalpartmaynotexist, // Quick check to see if we are reparsepoint directory if (zp->z_pflags & ZFS_REPARSE) { - /* How reparse points work from the point of view of the filesystem appears to - * undocumented. When returning STATUS_REPARSE, MSDN encourages us to return - * IO_REPARSE in Irp->IoStatus.Information, but that means we have to do our own - * translation. If we instead return the reparse tag in Information, and store - * a pointer to the reparse data buffer in Irp->Tail.Overlay.AuxiliaryBuffer, - * IopSymlinkProcessReparse will do the translation for us. - * - maharmstone - */ +/* + * How reparse points work from the point of view of the filesystem appears to + * undocumented. When returning STATUS_REPARSE, MSDN encourages us to return + * IO_REPARSE in Irp->IoStatus.Information, but that means we have to do + * our own translation. If we instead return the reparse tag in Information, + * and store a pointer to the reparse data buffer in + * Irp->Tail.Overlay.AuxiliaryBuffer, + * IopSymlinkProcessReparse will do the translation for us. + * - maharmstone + */ REPARSE_DATA_BUFFER *rpb; - rpb = ExAllocatePoolWithTag(PagedPool, zp->z_size, '!FSZ'); + rpb = ExAllocatePoolWithTag(PagedPool, + zp->z_size, '!FSZ'); uio_t *uio; uio = uio_create(1, 0, UIO_SYSSPACE, UIO_READ); uio_addiov(uio, (user_addr_t)rpb, zp->z_size); @@ -402,14 +419,18 @@ int zfs_find_dvp_vp(zfsvfs_t *zfsvfs, char *filename, int finalpartmaynotexist, uio_free(uio); VN_RELE(vp); - // Return in Reserved the amount of path that was parsed. - /* FileObject->FileName.Length - parsed*/ - rpb->Reserved = (fullstrlen - ( ( word - filename ) + strlen(word))) * sizeof(WCHAR); - // We overload the lastname thing a bit, to return the reparsebuffer + // Return in Reserved the amount of path + // that was parsed. + /* FileObject->FileName.Length - parsed */ + rpb->Reserved = (fullstrlen - + ((word - filename) + + strlen(word))) * sizeof (WCHAR); + // We overload the lastname thing a bit, + // to return the reparsebuffer if (lastname) *lastname = (char *)rpb; dprintf("%s: returning REPARSE\n", __func__); VN_RELE(dvp); - return STATUS_REPARSE; + return (STATUS_REPARSE); } // Not reparse @@ -417,45 +438,48 @@ int zfs_find_dvp_vp(zfsvfs_t *zfsvfs, char *filename, int finalpartmaynotexist, dvp = vp; vp = NULL; } else { - // If we aren't the final component, descending dirs, and it's a file? + // If we aren't the final component, descending dirs, + // and it's a file? if (brkt != NULL && *brkt != 0) { - dprintf("%s: not a DIR triggered '%s'\n", __func__, word); + dprintf("%s: not a DIR triggered '%s'\n", + __func__, word); VN_RELE(dvp); - return ENOTDIR; + return (ENOTDIR); } break; } // is dir or not } // for word - //dprintf("\n"); + // dprintf("\n"); if (dvp) { // We return with dvp HELD - //VN_RELE(dvp); + // VN_RELE(dvp); } else { - dprintf("%s: failed to find dvp for '%s' word '%s' err %d\n", __func__, filename, - word?word:"(null)", error); + dprintf("%s: failed to find dvp for '%s' word '%s' err %d\n", + __func__, filename, word?word:"(null)", error); VN_RELE(dvp); - return error; + return (error); } if (error != 0 && !vp && !finalpartmaynotexist) { VN_RELE(dvp); - return ENOENT; + return (ENOENT); } if (!word && finalpartmustnotexist && dvp && !vp) { dprintf("CREATE with existing dir exit?\n"); VN_RELE(dvp); - return EEXIST; + return (EEXIST); } // If finalpartmaynotexist is TRUE, make sure we are looking at // the finalpart, and not in the middle of descending if (finalpartmaynotexist && brkt != NULL && *brkt != 0) { - dprintf("finalpartmaynotexist, but not at finalpart: %s\n", brkt); + dprintf("finalpartmaynotexist, but not at finalpart: %s\n", + brkt); VN_RELE(dvp); - return ESRCH; + return (ESRCH); } if (lastname) { @@ -464,7 +488,8 @@ int zfs_find_dvp_vp(zfsvfs_t *zfsvfs, char *filename, int finalpartmaynotexist, // Skip any leading "\" while (*lastname != NULL && - (**lastname == '\\' || **lastname == '/')) (*lastname)++; + (**lastname == '\\' || **lastname == '/')) + (*lastname)++; } @@ -473,12 +498,12 @@ int zfs_find_dvp_vp(zfsvfs_t *zfsvfs, char *filename, int finalpartmaynotexist, if (vpp != NULL) *vpp = vp; - return 0; + return (0); } /* * In POSIX, the vnop_lookup() would return with iocount still held - * for the caller to issue VN_RELE() on when done. + * for the caller to issue VN_RELE() on when done. * The above zfs_find_dvp_vp() behaves a little like that, in that * if a successful "vp" is returned, it has a iocount lock, and * is released here when finished. @@ -486,7 +511,9 @@ int zfs_find_dvp_vp(zfsvfs_t *zfsvfs, char *filename, int finalpartmaynotexist, * and will assign FileObject->FsContext as appropriate, with usecount set * when required, but it will not hold iocount. */ -int zfs_vnop_lookup_impl(PIRP Irp, PIO_STACK_LOCATION IrpSp, mount_t *zmo, char *filename, vattr_t *vap) +int +zfs_vnop_lookup_impl(PIRP Irp, PIO_STACK_LOCATION IrpSp, mount_t *zmo, + char *filename, vattr_t *vap) { int error; cred_t *cr = NULL; @@ -524,7 +551,8 @@ int zfs_vnop_lookup_impl(PIRP Irp, PIO_STACK_LOCATION IrpSp, mount_t *zmo, char NTSTATUS Status = STATUS_SUCCESS; ACCESS_MASK granted_access = 0; - if (zfsvfs == NULL) return STATUS_OBJECT_PATH_NOT_FOUND; + if (zfsvfs == NULL) + return (STATUS_OBJECT_PATH_NOT_FOUND); FileObject = IrpSp->FileObject; Options = IrpSp->Parameters.Create.Options; @@ -535,78 +563,97 @@ int zfs_vnop_lookup_impl(PIRP Irp, PIO_STACK_LOCATION IrpSp, mount_t *zmo, char FileObject->Vpb = FileObject->RelatedFileObject->Vpb; // A relative open must be via a relative path. if (FileObject->FileName.Length != 0 && - FileObject->FileName.Buffer[0] == L'\\') { - return STATUS_INVALID_PARAMETER; + FileObject->FileName.Buffer[0] == L'\\') { + return (STATUS_INVALID_PARAMETER); } } else { FileObject->Vpb = zmo->vpb; } - - DirectoryFile = BooleanFlagOn(Options, FILE_DIRECTORY_FILE); - NonDirectoryFile = BooleanFlagOn(Options, FILE_NON_DIRECTORY_FILE); - NoIntermediateBuffering = BooleanFlagOn(Options, FILE_NO_INTERMEDIATE_BUFFERING); - NoEaKnowledge = BooleanFlagOn(Options, FILE_NO_EA_KNOWLEDGE); - DeleteOnClose = BooleanFlagOn(Options, FILE_DELETE_ON_CLOSE); - FileOpenByFileId = BooleanFlagOn(Options, FILE_OPEN_BY_FILE_ID); + + DirectoryFile = + BooleanFlagOn(Options, FILE_DIRECTORY_FILE); + NonDirectoryFile = + BooleanFlagOn(Options, FILE_NON_DIRECTORY_FILE); + NoIntermediateBuffering = + BooleanFlagOn(Options, FILE_NO_INTERMEDIATE_BUFFERING); + NoEaKnowledge = + BooleanFlagOn(Options, FILE_NO_EA_KNOWLEDGE); + DeleteOnClose = + BooleanFlagOn(Options, FILE_DELETE_ON_CLOSE); + FileOpenByFileId = + BooleanFlagOn(Options, FILE_OPEN_BY_FILE_ID); // Should be passed an 8 byte FileId instead. - if (FileOpenByFileId && FileObject->FileName.Length != sizeof(ULONGLONG)) - return STATUS_INVALID_PARAMETER; + if (FileOpenByFileId && FileObject->FileName.Length != + sizeof (ULONGLONG)) + return (STATUS_INVALID_PARAMETER); TemporaryFile = BooleanFlagOn(IrpSp->Parameters.Create.FileAttributes, - FILE_ATTRIBUTE_TEMPORARY); + FILE_ATTRIBUTE_TEMPORARY); CreateDisposition = (Options >> 24) & 0x000000ff; IsPagingFile = BooleanFlagOn(IrpSp->Flags, SL_OPEN_PAGING_FILE); ASSERT(!IsPagingFile); - //ASSERT(!OpenRequiringOplock); + // ASSERT(!OpenRequiringOplock); // Open the directory instead of the file - OpenTargetDirectory = BooleanFlagOn(IrpSp->Flags, SL_OPEN_TARGET_DIRECTORY); - /* - * CreateDisposition value Action if file exists Action if file does not exist UNIX Perms - FILE_SUPERSEDE Replace the file. Create the file. Unlink + O_CREAT | O_TRUNC - FILE_CREATE Return an error. Create the file. O_CREAT | O_EXCL - FILE_OPEN Open the file. Return an error. 0 - FILE_OPEN_IF Open the file. Create the file. O_CREAT - FILE_OVERWRITE Open the file, overwrite it. Return an error. O_TRUNC - FILE_OVERWRITE_IF Open the file, overwrite it. Create the file. O_CREAT | O_TRUNC - - Apparently SUPERSEDE is more of less Unlink entry before recreate, so it loses ACLs, XATTRs and NamedStreams. - - IoStatus return codes: - FILE_CREATED - FILE_OPENED - FILE_OVERWRITTEN - FILE_SUPERSEDED - FILE_EXISTS - FILE_DOES_NOT_EXIST - - */ - + OpenTargetDirectory = BooleanFlagOn(IrpSp->Flags, + SL_OPEN_TARGET_DIRECTORY); +/* + * CreateDisposition value Action if file exists + * Action if file does not exist UNIX Perms + * FILE_SUPERSEDE Replace the file. + * Create the file. * Unlink + O_CREAT | O_TRUNC + * FILE_CREATE Return an error. + * Create the file. * O_CREAT | O_EXCL + * FILE_OPEN Open the file. + * Return an error. * 0 + * FILE_OPEN_IF Open the file. + * Create the file. * O_CREAT + * FILE_OVERWRITE Open the file, overwrite it. + * Return an error. * O_TRUNC + * FILE_OVERWRITE_IF Open the file, overwrite it. + * Create the file. * O_CREAT | O_TRUNC + * + * Apparently SUPERSEDE is more or less Unlink entry before recreate, + * so it loses ACLs, XATTRs and NamedStreams. + * + * IoStatus return codes: + * FILE_CREATED + * FILE_OPENED + * FILE_OVERWRITTEN + * FILE_SUPERSEDED + * FILE_EXISTS + * FILE_DOES_NOT_EXIST + * + */ + // Dir create/open is straight forward, do that here // Files are harder, do that once we know if it exists. CreateDirectory = (BOOLEAN)(DirectoryFile && - ((CreateDisposition == FILE_CREATE) || - (CreateDisposition == FILE_OPEN_IF))); + ((CreateDisposition == FILE_CREATE) || + (CreateDisposition == FILE_OPEN_IF))); OpenDirectory = (BOOLEAN)(DirectoryFile && - ((CreateDisposition == FILE_OPEN) || - (CreateDisposition == FILE_OPEN_IF))); + ((CreateDisposition == FILE_OPEN) || + (CreateDisposition == FILE_OPEN_IF))); CreateFile = (BOOLEAN)( - ((CreateDisposition == FILE_CREATE) || - (CreateDisposition == FILE_OPEN_IF) || - (CreateDisposition == FILE_SUPERSEDE) || - (CreateDisposition == FILE_OVERWRITE_IF))); - - // If it is a volumeopen, we just grab rootvp so that directory listings work - if (FileObject->FileName.Length == 0 && FileObject->RelatedFileObject == NULL) { + ((CreateDisposition == FILE_CREATE) || + (CreateDisposition == FILE_OPEN_IF) || + (CreateDisposition == FILE_SUPERSEDE) || + (CreateDisposition == FILE_OVERWRITE_IF))); + + // If it is a volumeopen, we just grab rootvp so that directory + // listings work + if (FileObject->FileName.Length == 0 && + FileObject->RelatedFileObject == NULL) { // If DirectoryFile return STATUS_NOT_A_DIRECTORY // If OpenTargetDirectory return STATUS_INVALID_PARAMETER dprintf("Started NULL open, returning root of mount\n"); error = zfs_zget(zfsvfs, zfsvfs->z_root, &zp); - if (error != 0) return FILE_DOES_NOT_EXIST; // No root dir?! + if (error != 0) + return (FILE_DOES_NOT_EXIST); // No root dir?! dvp = ZTOV(zp); vnode_ref(dvp); // Hold open reference, until CLOSE @@ -615,41 +662,53 @@ int zfs_vnop_lookup_impl(PIRP Irp, PIO_STACK_LOCATION IrpSp, mount_t *zmo, char VN_RELE(dvp); Irp->IoStatus.Information = FILE_OPENED; - return STATUS_SUCCESS; + return (STATUS_SUCCESS); } // No name conversion with FileID if (!FileOpenByFileId) { - if (FileObject->FileName.Buffer != NULL && FileObject->FileName.Length > 0) { + if (FileObject->FileName.Buffer != NULL && + FileObject->FileName.Length > 0) { // Convert incoming filename to utf8 error = RtlUnicodeToUTF8N(filename, PATH_MAX, &outlen, - FileObject->FileName.Buffer, FileObject->FileName.Length); + FileObject->FileName.Buffer, + FileObject->FileName.Length); if (error != STATUS_SUCCESS && - error != STATUS_SOME_NOT_MAPPED) { - dprintf("RtlUnicodeToUTF8N returned 0x%x input len %d\n", error, FileObject->FileName.Length); - return STATUS_OBJECT_NAME_INVALID; + error != STATUS_SOME_NOT_MAPPED) { + dprintf("RtlUnicodeToUTF8N returned 0x%x " + "input len %d\n", + error, FileObject->FileName.Length); + return (STATUS_OBJECT_NAME_INVALID); } - //ASSERT(error != STATUS_SOME_NOT_MAPPED); - // Output string is only null terminated if input is, so do so now. + // ASSERT(error != STATUS_SOME_NOT_MAPPED); + // Output string is only null terminated if input is, + // so do so now. filename[outlen] = 0; - dprintf("%s: converted name is '%s' input len bytes %d (err %d) %s %s\n", __func__, filename, FileObject->FileName.Length, error, - DeleteOnClose ? "DeleteOnClose" : "", - IrpSp->Flags&SL_CASE_SENSITIVE ? "CaseSensitive" : "CaseInsensitive"); + dprintf("%s: converted name is '%s' input len bytes %d " + "(err %d) %s %s\n", __func__, filename, + FileObject->FileName.Length, error, + DeleteOnClose ? "DeleteOnClose" : "", + IrpSp->Flags&SL_CASE_SENSITIVE ? "CaseSensitive" : + "CaseInsensitive"); #if 0 - if (strcmp("\\System Volume Information\\WPSettings.dat", filename) == 0) - return STATUS_OBJECT_NAME_INVALID; + if (strcmp( + "\\System Volume Information\\WPSettings.dat", + filename) == 0) + return (STATUS_OBJECT_NAME_INVALID); #endif if (Irp->Overlay.AllocationSize.QuadPart > 0) - dprintf("AllocationSize requested %llu\n", Irp->Overlay.AllocationSize.QuadPart); + dprintf("AllocationSize requested %llu\n", + Irp->Overlay.AllocationSize.QuadPart); // Check if we are called as VFS_ROOT(); - OpenRoot = (strncmp("\\", filename, PATH_MAX) == 0 || strncmp("\\*", filename, PATH_MAX) == 0); + OpenRoot = (strncmp("\\", filename, PATH_MAX) == 0 || + strncmp("\\*", filename, PATH_MAX) == 0); if (OpenRoot) { @@ -657,85 +716,92 @@ int zfs_vnop_lookup_impl(PIRP Irp, PIO_STACK_LOCATION IrpSp, mount_t *zmo, char if (error == 0) { vp = ZTOV(zp); - zfs_couplefileobject(vp, FileObject, zp->z_size); - vnode_ref(vp); // Hold open reference, until CLOSE + zfs_couplefileobject(vp, FileObject, + zp->z_size); + vnode_ref(vp); // Hold ref, until CLOSE VN_RELE(vp); Irp->IoStatus.Information = FILE_OPENED; - return STATUS_SUCCESS; + return (STATUS_SUCCESS); } Irp->IoStatus.Information = FILE_DOES_NOT_EXIST; - return STATUS_OBJECT_PATH_NOT_FOUND; + return (STATUS_OBJECT_PATH_NOT_FOUND); } // OpenRoot } else { // If got filename - // If no filename, we should fail, unless related is set. + // If no filename, we should fail, + // unless related is set. if (FileObject->RelatedFileObject == NULL) { // Fail - return STATUS_OBJECT_NAME_INVALID; + return (STATUS_OBJECT_NAME_INVALID); } // Related set, return it as opened. dvp = FileObject->RelatedFileObject->FsContext; zp = VTOZ(dvp); - dprintf("%s: Relative null-name open: '%s'\n", __func__, zp->z_name_cache); + dprintf("%s: Relative null-name open: '%s'\n", + __func__, zp->z_name_cache); // Check types if (NonDirectoryFile && vnode_isdir(dvp)) { Irp->IoStatus.Information = FILE_DOES_NOT_EXIST; - return STATUS_FILE_IS_A_DIRECTORY; // wanted file, found dir error + return (STATUS_FILE_IS_A_DIRECTORY); } if (DirectoryFile && !vnode_isdir(dvp)) { Irp->IoStatus.Information = FILE_DOES_NOT_EXIST; - return STATUS_NOT_A_DIRECTORY; // wanted dir, found file error + return (STATUS_NOT_A_DIRECTORY); } // Grab vnode to ref if (VN_HOLD(dvp) == 0) { - vnode_ref(dvp); // Hold open reference, until CLOSE + vnode_ref(dvp); // Hold ref, until CLOSE zfs_couplefileobject(dvp, FileObject, 0ULL); VN_RELE(dvp); } else { Irp->IoStatus.Information = 0; - return STATUS_OBJECT_PATH_NOT_FOUND; + return (STATUS_OBJECT_PATH_NOT_FOUND); } Irp->IoStatus.Information = FILE_OPENED; - return STATUS_SUCCESS; + return (STATUS_SUCCESS); } // We have converted the filename, continue.. - if (FileObject->RelatedFileObject && FileObject->RelatedFileObject->FsContext) { + if (FileObject->RelatedFileObject && + FileObject->RelatedFileObject->FsContext) { dvp = FileObject->RelatedFileObject->FsContext; // This branch here, if failure, should not release dvp dvp_no_rele = 1; } - /* - * Here, we want to check for Streams, which come in the syntax filename.ext:Stream:Type - * Type: appears optional, or we handle ":DATA". All others will be rejected. - * Stream: name of the stream, we convert this into XATTR named Stream - * It is valid to create a filename containing colons, so who knows what will - * happen here. - */ +/* + * Here, we want to check for Streams, which come in the syntax + * filename.ext:Stream:Type + * Type: appears optional, or we handle ":DATA". All others will be rejected. + * Stream: name of the stream, we convert this into XATTR named Stream + * It is valid to create a filename containing colons, so who knows what will + * happen here. + */ error = stream_parse(filename, &stream_name); if (error) { Irp->IoStatus.Information = 0; - return STATUS_INVALID_PARAMETER; + return (STATUS_INVALID_PARAMETER); } - if (stream_name != NULL) - dprintf("%s: Parsed out streamname '%s'\n", __func__, stream_name); - - - + if (stream_name != NULL) + dprintf("%s: Parsed out streamname '%s'\n", + __func__, stream_name); - // There is a special case, where name is just the stream ":ZoneIdentifier:$DATA", and + // There is a special case, where name is just the stream + // ":ZoneIdentifier:$DATA", and // RelatedFileObject is set to the object. if (stream_name != NULL && - FileObject->RelatedFileObject && FileObject->RelatedFileObject->FsContext && - strlen(filename) == 0) { - - // The RelatedFileObject conditional above will assign "dvp" - but - // the stream_name check below will expect it in "vp". dvp_no_rele is already set. + FileObject->RelatedFileObject && + FileObject->RelatedFileObject->FsContext && + strlen(filename) == 0) { + + // The RelatedFileObject conditional above will + // assign "dvp" - but + // the stream_name check below will expect it in "vp". + // dvp_no_rele is already set. dvp_no_rele = 1; vp = FileObject->RelatedFileObject->FsContext; dvp = NULL; @@ -744,36 +810,40 @@ int zfs_vnop_lookup_impl(PIRP Irp, PIO_STACK_LOCATION IrpSp, mount_t *zmo, char } else { // If we have dvp, it is HELD - error = zfs_find_dvp_vp(zfsvfs, filename, (CreateFile || OpenTargetDirectory), (CreateDisposition == FILE_CREATE), &finalname, &dvp, &vp, flags); + error = zfs_find_dvp_vp(zfsvfs, filename, + (CreateFile || OpenTargetDirectory), + (CreateDisposition == FILE_CREATE), + &finalname, &dvp, &vp, flags); } } else { // Open By File ID - error = zfs_zget(zfsvfs, *((uint64_t *)IrpSp->FileObject->FileName.Buffer), &zp); + error = zfs_zget(zfsvfs, + *((uint64_t *)IrpSp->FileObject->FileName.Buffer), &zp); // Code below assumed dvp is also open if (error == 0) { uint64_t parent; znode_t *dzp; - error = sa_lookup(zp->z_sa_hdl, SA_ZPL_PARENT(zfsvfs), &parent, sizeof(parent)); + error = sa_lookup(zp->z_sa_hdl, SA_ZPL_PARENT(zfsvfs), + &parent, sizeof (parent)); if (error == 0) { error = zfs_zget(zfsvfs, parent, &dzp); } if (error != 0) { VN_RELE(ZTOV(zp)); - return error; + return (error); } // failed to get parentid, or find parent // Copy over the vp info for below, both are held. vp = ZTOV(zp); dvp = ZTOV(dzp); } } - + // If successful: // - vp is HELD // - dvp is HELD // we need dvp from here on down. - if (error) { @@ -781,36 +851,39 @@ int zfs_vnop_lookup_impl(PIRP Irp, PIO_STACK_LOCATION IrpSp, mount_t *zmo, char if (vp) VN_RELE(vp); if (error == STATUS_REPARSE) { - REPARSE_DATA_BUFFER *rpb = (REPARSE_DATA_BUFFER *)finalname; + REPARSE_DATA_BUFFER *rpb = + (REPARSE_DATA_BUFFER *)finalname; Irp->IoStatus.Information = rpb->ReparseTag; Irp->Tail.Overlay.AuxiliaryBuffer = (void*)rpb; - return error; + return (error); } if (!dvp && error == ESRCH) { - dprintf("%s: failed to find dvp for '%s' \n", __func__, filename); + dprintf("%s: failed to find dvp for '%s' \n", + __func__, filename); Irp->IoStatus.Information = FILE_DOES_NOT_EXIST; - return STATUS_OBJECT_PATH_NOT_FOUND; + return (STATUS_OBJECT_PATH_NOT_FOUND); } if (error == STATUS_OBJECT_NAME_INVALID) { dprintf("%s: filename component too long\n", __func__); - return error; + return (error); } // Open dir with FILE_CREATE but it exists if (error == EEXIST) { dprintf("%s: dir exists, wont create\n", __func__); Irp->IoStatus.Information = FILE_EXISTS; - return STATUS_OBJECT_NAME_COLLISION; + return (STATUS_OBJECT_NAME_COLLISION); } // A directory component did not exist, or was a file if ((dvp == NULL) || (error == ENOTDIR)) { - dprintf("%s: failed to find dvp - or dvp is a file\n", __func__); + dprintf("%s: failed to find dvp - or dvp is a file\n", + __func__); Irp->IoStatus.Information = 0; - return STATUS_OBJECT_NAME_NOT_FOUND; + return (STATUS_OBJECT_NAME_NOT_FOUND); } dprintf("%s: failed to find vp in dvp\n", __func__); Irp->IoStatus.Information = FILE_DOES_NOT_EXIST; - return STATUS_OBJECT_NAME_NOT_FOUND; + return (STATUS_OBJECT_NAME_NOT_FOUND); } @@ -818,17 +891,18 @@ int zfs_vnop_lookup_impl(PIRP Irp, PIO_STACK_LOCATION IrpSp, mount_t *zmo, char // If we opened vp, grab its xattrdir, and try to to locate stream if (stream_name != NULL && vp != NULL) { // Here, we will release dvp, and attempt to open the xattr dir. - // xattr dir will be the new dvp. Then we will look for streamname - // in xattrdir, and assign vp. + // xattr dir will be the new dvp. Then we will look for + // streamname in xattrdir, and assign vp. VERIFY3P(dvp, !=, vp); // Create the xattrdir only if we are to create a new entry zp = VTOZ(vp); - if (error = zfs_get_xattrdir(zp, &dzp, cr, CreateFile ? CREATE_XATTR_DIR : 0)) { + if (error = zfs_get_xattrdir(zp, &dzp, cr, + CreateFile ? CREATE_XATTR_DIR : 0)) { Irp->IoStatus.Information = FILE_DOES_NOT_EXIST; VN_RELE(vp); - return STATUS_OBJECT_NAME_NOT_FOUND; + return (STATUS_OBJECT_NAME_NOT_FOUND); } VN_RELE(vp); if (dvp_no_rele) @@ -836,10 +910,11 @@ int zfs_vnop_lookup_impl(PIRP Irp, PIO_STACK_LOCATION IrpSp, mount_t *zmo, char vp = NULL; dvp = ZTOV(dzp); int direntflags = 0; // To detect ED_CASE_CONFLICT - error = zfs_dirlook(dzp, stream_name, &zp, 0 /*FIGNORECASE*/, &direntflags, NULL); + error = zfs_dirlook(dzp, stream_name, &zp, 0 /* FIGNORECASE */, + &direntflags, NULL); if (error) { Irp->IoStatus.Information = FILE_DOES_NOT_EXIST; - return STATUS_OBJECT_NAME_NOT_FOUND; + return (STATUS_OBJECT_NAME_NOT_FOUND); } // Here, it may not exist, as we are to create it. @@ -852,38 +927,38 @@ int zfs_vnop_lookup_impl(PIRP Irp, PIO_STACK_LOCATION IrpSp, mount_t *zmo, char if (dvp) { #if 0 - // If we asked for PARENT of a non-existing file, do we return error? + // If we asked for PARENT of a non-existing file, + // do we return error? if (vp == NULL) { - dprintf("%s: opening PARENT directory - but file is ENOENT\n", __func__); + dprintf("%s: opening PARENT dir, is ENOENT\n", + __func__); VN_RELE(dvp); Irp->IoStatus.Information = FILE_DOES_NOT_EXIST; - return STATUS_OBJECT_NAME_NOT_FOUND; + return (STATUS_OBJECT_NAME_NOT_FOUND); } #endif dprintf("%s: opening PARENT directory\n", __func__); zfs_couplefileobject(dvp, FileObject, 0ULL); vnode_ref(dvp); // Hold open reference, until CLOSE - if (DeleteOnClose) + if (DeleteOnClose) Status = zfs_setunlink(FileObject, dvp); if (Status == STATUS_SUCCESS) Irp->IoStatus.Information = FILE_OPENED; - if (vp) VN_RELE(vp); //xxx + if (vp) VN_RELE(vp); VN_RELE(dvp); - return Status; + return (Status); } ASSERT(vp == NULL); ASSERT(dvp == NULL); Irp->IoStatus.Information = FILE_DOES_NOT_EXIST; - return STATUS_OBJECT_NAME_NOT_FOUND; + return (STATUS_OBJECT_NAME_NOT_FOUND); } // Here we have "dvp" of the directory. // "vp" if the final part was a file. - - // Don't create if FILE_OPEN_IF (open existing) if ((CreateDisposition == FILE_OPEN_IF) && (vp != NULL)) CreateDirectory = 0; @@ -893,19 +968,19 @@ int zfs_vnop_lookup_impl(PIRP Irp, PIO_STACK_LOCATION IrpSp, mount_t *zmo, char VN_RELE(vp); VN_RELE(dvp); Irp->IoStatus.Information = FILE_EXISTS; - return STATUS_OBJECT_NAME_COLLISION; // create file error + return (STATUS_OBJECT_NAME_COLLISION); // create file error } if (CreateDirectory && finalname) { - if (TemporaryFile) - return STATUS_INVALID_PARAMETER; + if (TemporaryFile) + return (STATUS_INVALID_PARAMETER); - if (zfsvfs->z_rdonly || vfs_isrdonly(zfsvfs->z_vfs) || - !spa_writeable(dmu_objset_spa(zfsvfs->z_os))) { + if (zfsvfs->z_rdonly || vfs_isrdonly(zfsvfs->z_vfs) || + !spa_writeable(dmu_objset_spa(zfsvfs->z_os))) { VN_RELE(dvp); Irp->IoStatus.Information = 0; // ? - return STATUS_MEDIA_WRITE_PROTECTED; + return (STATUS_MEDIA_WRITE_PROTECTED); } vap->va_type = VDIR; @@ -916,8 +991,8 @@ int zfs_vnop_lookup_impl(PIRP Irp, PIO_STACK_LOCATION IrpSp, mount_t *zmo, char vap->va_mask |= (ATTR_MODE | ATTR_TYPE); ASSERT(strchr(finalname, '\\') == NULL); - error = zfs_mkdir(VTOZ(dvp), finalname, vap, &zp, NULL, - NULL, 0); + error = zfs_mkdir(VTOZ(dvp), finalname, vap, &zp, NULL, + NULL, 0); if (error == 0) { vp = ZTOV(zp); zfs_couplefileobject(vp, FileObject, 0ULL); @@ -929,24 +1004,28 @@ int zfs_vnop_lookup_impl(PIRP Irp, PIO_STACK_LOCATION IrpSp, mount_t *zmo, char Irp->IoStatus.Information = FILE_CREATED; // Update pflags, if needed - zfs_setwinflags(zp, IrpSp->Parameters.Create.FileAttributes); - - IoSetShareAccess(IrpSp->Parameters.Create.SecurityContext->DesiredAccess, - IrpSp->Parameters.Create.ShareAccess, - FileObject, - &vp->share_access); - - zfs_send_notify(zfsvfs, zp->z_name_cache, zp->z_name_offset, - FILE_NOTIFY_CHANGE_DIR_NAME, - FILE_ACTION_ADDED); + zfs_setwinflags(zp, + IrpSp->Parameters.Create.FileAttributes); + + IoSetShareAccess( + IrpSp->Parameters.Create.SecurityContext-> + DesiredAccess, + IrpSp->Parameters.Create.ShareAccess, + FileObject, + &vp->share_access); + + zfs_send_notify(zfsvfs, zp->z_name_cache, + zp->z_name_offset, + FILE_NOTIFY_CHANGE_DIR_NAME, + FILE_ACTION_ADDED); } VN_RELE(vp); VN_RELE(dvp); - return Status; + return (Status); } VN_RELE(dvp); Irp->IoStatus.Information = FILE_DOES_NOT_EXIST; - return STATUS_OBJECT_PATH_NOT_FOUND; // failed to create error? + return (STATUS_OBJECT_PATH_NOT_FOUND); } // If they requested just directory, fail non directories @@ -955,7 +1034,7 @@ int zfs_vnop_lookup_impl(PIRP Irp, PIO_STACK_LOCATION IrpSp, mount_t *zmo, char VN_RELE(vp); VN_RELE(dvp); Irp->IoStatus.Information = FILE_DOES_NOT_EXIST; - return STATUS_FILE_IS_A_DIRECTORY; // wanted dir, found file error + return (STATUS_FILE_IS_A_DIRECTORY); } // Asked for non-directory, but we got directory @@ -963,7 +1042,7 @@ int zfs_vnop_lookup_impl(PIRP Irp, PIO_STACK_LOCATION IrpSp, mount_t *zmo, char dprintf("%s: asked for file but found directory\n", __func__); VN_RELE(dvp); Irp->IoStatus.Information = FILE_DOES_NOT_EXIST; - return STATUS_FILE_IS_A_DIRECTORY; // wanted file, found dir error + return (STATUS_FILE_IS_A_DIRECTORY); } if (vp) { @@ -973,50 +1052,61 @@ int zfs_vnop_lookup_impl(PIRP Irp, PIO_STACK_LOCATION IrpSp, mount_t *zmo, char // If HIDDEN and SYSTEM are set, then the open of file must also have // HIDDEN and SYSTEM set. if ((zp != NULL) && - ((CreateDisposition == FILE_SUPERSEDE) || - (CreateDisposition == FILE_OVERWRITE) || - (CreateDisposition == FILE_OVERWRITE_IF))) { - if (((zp->z_pflags&ZFS_HIDDEN) && !FlagOn(IrpSp->Parameters.Create.FileAttributes, FILE_ATTRIBUTE_HIDDEN)) || - ((zp->z_pflags&ZFS_SYSTEM) && !FlagOn(IrpSp->Parameters.Create.FileAttributes, FILE_ATTRIBUTE_SYSTEM))) { + ((CreateDisposition == FILE_SUPERSEDE) || + (CreateDisposition == FILE_OVERWRITE) || + (CreateDisposition == FILE_OVERWRITE_IF))) { + if (((zp->z_pflags&ZFS_HIDDEN) && + !FlagOn(IrpSp->Parameters.Create.FileAttributes, + FILE_ATTRIBUTE_HIDDEN)) || + ((zp->z_pflags&ZFS_SYSTEM) && + !FlagOn(IrpSp->Parameters.Create.FileAttributes, + FILE_ATTRIBUTE_SYSTEM))) { VN_RELE(vp); VN_RELE(dvp); - dprintf("%s: denied due to hidden+system combo\n", __func__); - return STATUS_ACCESS_DENIED; + dprintf("%s: denied due to hidden+system combo\n", + __func__); + return (STATUS_ACCESS_DENIED); } } - // If overwrite, and tagged readonly, fail (note, supersede should succeed) + // If overwrite, and tagged readonly, fail + // (note, supersede should succeed) if ((zp != NULL) && - ((CreateDisposition == FILE_OVERWRITE) || - (CreateDisposition == FILE_OVERWRITE_IF))) { + ((CreateDisposition == FILE_OVERWRITE) || + (CreateDisposition == FILE_OVERWRITE_IF))) { if (zp->z_pflags&ZFS_READONLY) { VN_RELE(vp); VN_RELE(dvp); - dprintf("%s: denied due to ZFS_READONLY + OVERWRITE\n", __func__); - return STATUS_ACCESS_DENIED; + dprintf("%s: denied due to ZFS_READONLY + OVERWRITE\n", + __func__); + return (STATUS_ACCESS_DENIED); } } // If flags are readonly, and tries to open with write, fail - if ((zp != NULL) && (IrpSp->Parameters.Create.SecurityContext->DesiredAccess&(FILE_WRITE_DATA | FILE_APPEND_DATA)) && - (zp->z_pflags&ZFS_READONLY)) { + if ((zp != NULL) && + (IrpSp->Parameters.Create.SecurityContext-> + DesiredAccess&(FILE_WRITE_DATA | FILE_APPEND_DATA)) && + (zp->z_pflags&ZFS_READONLY)) { VN_RELE(vp); VN_RELE(dvp); - dprintf("%s: denied due to ZFS_READONLY + WRITE_DATA\n", __func__); - return STATUS_ACCESS_DENIED; + dprintf("%s: denied due to ZFS_READONLY + WRITE_DATA\n", + __func__); + return (STATUS_ACCESS_DENIED); } if (DeleteOnClose && - vp && zp && - dvp && VTOZ(dvp) && - zfs_zaccess_delete(VTOZ(dvp), zp, 0) > 0) { + vp && zp && + dvp && VTOZ(dvp) && + zfs_zaccess_delete(VTOZ(dvp), zp, 0) > 0) { VN_RELE(vp); if (dvp) VN_RELE(dvp); - dprintf("%s: denied due to ZFS_IMMUTABLE + ZFS_NOUNLINK\n", __func__); - return STATUS_ACCESS_DENIED; + dprintf("%s: denied due to IMMUTABLE+NOUNLINK\n", + __func__); + return (STATUS_ACCESS_DENIED); } @@ -1032,53 +1122,81 @@ int zfs_vnop_lookup_impl(PIRP Irp, PIO_STACK_LOCATION IrpSp, mount_t *zmo, char // Streams do not call SeAccessCheck? if (stream_name != NULL) { - IoSetShareAccess(IrpSp->Parameters.Create.SecurityContext->DesiredAccess, IrpSp->Parameters.Create.ShareAccess, - FileObject, vp ? &vp->share_access : &dvp->share_access); - - - } else if (IrpSp->Parameters.Create.SecurityContext->DesiredAccess != 0 && vp) { - - - SeLockSubjectContext(&IrpSp->Parameters.Create.SecurityContext->AccessState->SubjectSecurityContext); + IoSetShareAccess( + IrpSp->Parameters.Create.SecurityContext-> + DesiredAccess, + IrpSp->Parameters.Create.ShareAccess, + FileObject, vp ? &vp->share_access : + &dvp->share_access); + + } else if ( + IrpSp->Parameters.Create.SecurityContext-> + DesiredAccess != 0 && vp) { + + SeLockSubjectContext( + &IrpSp->Parameters.Create.SecurityContext-> + AccessState->SubjectSecurityContext); #if 1 - if (!SeAccessCheck(/* (fileref->fcb->ads || fileref->fcb == Vcb->dummy_fcb) ? fileref->parent->fcb->sd : */ vnode_security(vp ? vp : dvp), - &IrpSp->Parameters.Create.SecurityContext->AccessState->SubjectSecurityContext, - TRUE, IrpSp->Parameters.Create.SecurityContext->DesiredAccess, 0, NULL, - IoGetFileObjectGenericMapping(), IrpSp->Flags & SL_FORCE_ACCESS_CHECK ? UserMode : Irp->RequestorMode, - &granted_access, &Status)) { - SeUnlockSubjectContext(&IrpSp->Parameters.Create.SecurityContext->AccessState->SubjectSecurityContext); + if (!SeAccessCheck(vnode_security(vp ? vp : dvp), + &IrpSp->Parameters.Create.SecurityContext-> + AccessState->SubjectSecurityContext, + TRUE, + IrpSp->Parameters.Create.SecurityContext-> + DesiredAccess, + 0, NULL, + IoGetFileObjectGenericMapping(), + IrpSp->Flags & SL_FORCE_ACCESS_CHECK ? UserMode : + Irp->RequestorMode, + &granted_access, &Status)) { + SeUnlockSubjectContext( + &IrpSp->Parameters.Create.SecurityContext-> + AccessState->SubjectSecurityContext); if (vp) VN_RELE(vp); VN_RELE(dvp); - dprintf("%s: denied due to SeAccessCheck()\n", __func__); - return Status; + dprintf("%s: denied due to SeAccessCheck()\n", + __func__); + return (Status); } #endif - SeUnlockSubjectContext(&IrpSp->Parameters.Create.SecurityContext->AccessState->SubjectSecurityContext); + SeUnlockSubjectContext( + &IrpSp->Parameters.Create.SecurityContext-> + AccessState->SubjectSecurityContext); } else { granted_access = 0; } - - // Io*ShareAccess(): X is not an atomic operation. Therefore, drivers calling this routine must protect the shared file object + + // Io*ShareAccess(): X is not an atomic operation. Therefore, + // drivers calling this routine must protect the shared + // file object vnode_lock(vp ? vp : dvp); - if (vnode_isinuse(vp ? vp : dvp, 0)) { // 0 is we are the only (usecount added below), 1+ if already open. - Status = IoCheckShareAccess(granted_access, IrpSp->Parameters.Create.ShareAccess, FileObject, vp ? &vp->share_access : &dvp->share_access, FALSE); + if (vnode_isinuse(vp ? vp : dvp, 0)) { +// 0 is we are the only (usecount added below), 1+ if already open. + Status = IoCheckShareAccess(granted_access, + IrpSp->Parameters.Create.ShareAccess, FileObject, + vp ? &vp->share_access : &dvp->share_access, FALSE); if (!NT_SUCCESS(Status)) { vnode_unlock(vp ? vp : dvp); if (vp) VN_RELE(vp); VN_RELE(dvp); - dprintf("%s: denied due to IoCheckShareAccess\n", __func__); - return Status; + dprintf("%s: denied IoCheckShareAccess\n", + __func__); + return (Status); } - IoUpdateShareAccess(FileObject, vp ? &vp->share_access : &dvp->share_access); + IoUpdateShareAccess(FileObject, + vp ? &vp->share_access : &dvp->share_access); } else { - IoSetShareAccess(granted_access, IrpSp->Parameters.Create.ShareAccess, FileObject, vp ? &vp->share_access : &dvp->share_access); + IoSetShareAccess(granted_access, + IrpSp->Parameters.Create.ShareAccess, + FileObject, + vp ? &vp->share_access : &dvp->share_access); } - // Since we've updated ShareAccess here, if we cancel the open we need to undo it. + // Since we've updated ShareAccess here, if we cancel + // the open we need to undo it. UndoShareAccess = TRUE; vnode_unlock(vp ? vp : dvp); } -#define UNDO_SHARE_ACCESS(vp) \ +#define UNDO_SHARE_ACCESS(vp) \ if ((vp) && UndoShareAccess) { \ vnode_lock((vp)); \ IoRemoveShareAccess(FileObject, &(vp)->share_access); \ @@ -1089,12 +1207,12 @@ int zfs_vnop_lookup_impl(PIRP Irp, PIO_STACK_LOCATION IrpSp, mount_t *zmo, char // We can not DeleteOnClose if readonly filesystem if (DeleteOnClose) { if (zfsvfs->z_rdonly || vfs_isrdonly(zfsvfs->z_vfs) || - !spa_writeable(dmu_objset_spa(zfsvfs->z_os))) { + !spa_writeable(dmu_objset_spa(zfsvfs->z_os))) { UNDO_SHARE_ACCESS(vp); if (vp) VN_RELE(vp); VN_RELE(dvp); Irp->IoStatus.Information = 0; // ? - return STATUS_MEDIA_WRITE_PROTECTED; + return (STATUS_MEDIA_WRITE_PROTECTED); } } @@ -1102,12 +1220,12 @@ int zfs_vnop_lookup_impl(PIRP Irp, PIO_STACK_LOCATION IrpSp, mount_t *zmo, char int replacing = 0; if (zfsvfs->z_rdonly || vfs_isrdonly(zfsvfs->z_vfs) || - !spa_writeable(dmu_objset_spa(zfsvfs->z_os))) { + !spa_writeable(dmu_objset_spa(zfsvfs->z_os))) { UNDO_SHARE_ACCESS(vp); if (vp) VN_RELE(vp); VN_RELE(dvp); Irp->IoStatus.Information = 0; // ? - return STATUS_MEDIA_WRITE_PROTECTED; + return (STATUS_MEDIA_WRITE_PROTECTED); } // Would we replace file? @@ -1133,52 +1251,67 @@ int zfs_vnop_lookup_impl(PIRP Irp, PIO_STACK_LOCATION IrpSp, mount_t *zmo, char } // O_EXCL only if FILE_CREATE - error = zfs_create(VTOZ(dvp), finalname, vap, CreateDisposition == FILE_CREATE, vap->va_mode, &zp, NULL, 0, NULL); + error = zfs_create(VTOZ(dvp), finalname, vap, + CreateDisposition == FILE_CREATE, vap->va_mode, + &zp, NULL, 0, NULL); if (error == 0) { vp = ZTOV(zp); - zfs_couplefileobject(vp, FileObject, zp?zp->z_size:0ULL); + zfs_couplefileobject(vp, FileObject, + zp ? zp->z_size : 0ULL); vnode_ref(vp); // Hold open reference, until CLOSE - if (DeleteOnClose) + if (DeleteOnClose) Status = zfs_setunlink(FileObject, dvp); if (Status == STATUS_SUCCESS) { - Irp->IoStatus.Information = replacing ? CreateDisposition == FILE_SUPERSEDE ? - FILE_SUPERSEDED : FILE_OVERWRITTEN : FILE_CREATED; + Irp->IoStatus.Information = replacing ? + CreateDisposition == FILE_SUPERSEDE ? + FILE_SUPERSEDED : FILE_OVERWRITTEN : + FILE_CREATED; // Update pflags, if needed - zfs_setwinflags(zp, IrpSp->Parameters.Create.FileAttributes | FILE_ATTRIBUTE_ARCHIVE); + zfs_setwinflags(zp, + IrpSp->Parameters.Create.FileAttributes | + FILE_ATTRIBUTE_ARCHIVE); // Did they ask for an AllocationSize if (Irp->Overlay.AllocationSize.QuadPart > 0) { - uint64_t allocsize = Irp->Overlay.AllocationSize.QuadPart; - //zp->z_blksz = P2ROUNDUP(allocsize, 512); + uint64_t allocsize = Irp-> + Overlay.AllocationSize.QuadPart; + // zp->z_blksz = + // P2ROUNDUP(allocsize, 512); } vnode_lock(vp); - IoSetShareAccess(IrpSp->Parameters.Create.SecurityContext->DesiredAccess, - IrpSp->Parameters.Create.ShareAccess, - FileObject, - &vp->share_access); + IoSetShareAccess( + IrpSp->Parameters.Create.SecurityContext-> + DesiredAccess, + IrpSp->Parameters.Create.ShareAccess, + FileObject, + &vp->share_access); vnode_unlock(vp); if (stream_name == NULL) - zfs_send_notify(zfsvfs, zp->z_name_cache, zp->z_name_offset, - FILE_NOTIFY_CHANGE_FILE_NAME, - FILE_ACTION_ADDED); + zfs_send_notify(zfsvfs, + zp->z_name_cache, + zp->z_name_offset, + FILE_NOTIFY_CHANGE_FILE_NAME, + FILE_ACTION_ADDED); else - zfs_send_notify_stream(zfsvfs, zp->z_name_cache, zp->z_name_offset, - FILE_NOTIFY_CHANGE_STREAM_NAME, - FILE_ACTION_ADDED_STREAM, - stream_name); + zfs_send_notify_stream(zfsvfs, + zp->z_name_cache, + zp->z_name_offset, + FILE_NOTIFY_CHANGE_STREAM_NAME, + FILE_ACTION_ADDED_STREAM, + stream_name); } VN_RELE(vp); VN_RELE(dvp); - return Status; + return (Status); } if (error == EEXIST) Irp->IoStatus.Information = FILE_EXISTS; @@ -1187,7 +1320,7 @@ int zfs_vnop_lookup_impl(PIRP Irp, PIO_STACK_LOCATION IrpSp, mount_t *zmo, char UNDO_SHARE_ACCESS(dvp); VN_RELE(dvp); - return STATUS_OBJECT_NAME_COLLISION; // create file error + return (STATUS_OBJECT_NAME_COLLISION); // create file error } @@ -1196,16 +1329,18 @@ int zfs_vnop_lookup_impl(PIRP Irp, PIO_STACK_LOCATION IrpSp, mount_t *zmo, char if (vp == NULL) { zfs_couplefileobject(dvp, FileObject, 0ULL); vnode_ref(dvp); // Hold open reference, until CLOSE - if (DeleteOnClose) + if (DeleteOnClose) Status = zfs_setunlink(FileObject, dvp); - if(Status == STATUS_SUCCESS) { + if (Status == STATUS_SUCCESS) { if (UndoShareAccess == FALSE) { vnode_lock(dvp); - IoSetShareAccess(IrpSp->Parameters.Create.SecurityContext->DesiredAccess, - IrpSp->Parameters.Create.ShareAccess, - FileObject, - &dvp->share_access); + IoSetShareAccess( + IrpSp->Parameters.Create.SecurityContext-> + DesiredAccess, + IrpSp->Parameters.Create.ShareAccess, + FileObject, + &dvp->share_access); vnode_unlock(dvp); } } else { @@ -1213,41 +1348,49 @@ int zfs_vnop_lookup_impl(PIRP Irp, PIO_STACK_LOCATION IrpSp, mount_t *zmo, char } VN_RELE(dvp); } else { - // Technically, this should call zfs_open() - but it is mostly empty + // Technically, this should call zfs_open() - + // but zfs_open is mostly empty zfs_couplefileobject(vp, FileObject, zp->z_size); vnode_ref(vp); // Hold open reference, until CLOSE if (DeleteOnClose) Status = zfs_setunlink(FileObject, dvp); - if(Status == STATUS_SUCCESS) { + if (Status == STATUS_SUCCESS) { Irp->IoStatus.Information = FILE_OPENED; // Did they set the open flags (clearing archive?) if (IrpSp->Parameters.Create.FileAttributes) - zfs_setwinflags(zp, IrpSp->Parameters.Create.FileAttributes); + zfs_setwinflags(zp, + IrpSp->Parameters.Create.FileAttributes); // If we are to truncate the file: if (CreateDisposition == FILE_OVERWRITE) { Irp->IoStatus.Information = FILE_OVERWRITTEN; zp->z_pflags |= ZFS_ARCHIVE; - // zfs_freesp() path uses vnode_pager_setsize() so we need to make sure fileobject is set. + // zfs_freesp() path uses vnode_pager_setsize() + // so we need to make sure fileobject is set. zfs_freesp(zp, 0, 0, FWRITE, B_TRUE); // Did they ask for an AllocationSize if (Irp->Overlay.AllocationSize.QuadPart > 0) { - uint64_t allocsize = Irp->Overlay.AllocationSize.QuadPart; - //zp->z_blksz = P2ROUNDUP(allocsize, 512); + uint64_t allocsize = Irp-> + Overlay.AllocationSize.QuadPart; + // zp->z_blksz = + // P2ROUNDUP(allocsize, 512); } } // Update sizes in header. - vp->FileHeader.AllocationSize.QuadPart = P2ROUNDUP(zp->z_size, zp->z_blksz); + vp->FileHeader.AllocationSize.QuadPart = + P2ROUNDUP(zp->z_size, zp->z_blksz); vp->FileHeader.FileSize.QuadPart = zp->z_size; vp->FileHeader.ValidDataLength.QuadPart = zp->z_size; // If we created something new, add this permission if (UndoShareAccess == FALSE) { vnode_lock(vp); - IoSetShareAccess(IrpSp->Parameters.Create.SecurityContext->DesiredAccess, - IrpSp->Parameters.Create.ShareAccess, - FileObject, - &vp->share_access); + IoSetShareAccess( + IrpSp->Parameters.Create.SecurityContext-> + DesiredAccess, + IrpSp->Parameters.Create.ShareAccess, + FileObject, + &vp->share_access); vnode_unlock(vp); } } else { @@ -1257,13 +1400,16 @@ int zfs_vnop_lookup_impl(PIRP Irp, PIO_STACK_LOCATION IrpSp, mount_t *zmo, char VN_RELE(dvp); } - IrpSp->Parameters.Create.SecurityContext->AccessState->PreviouslyGrantedAccess |= granted_access; - IrpSp->Parameters.Create.SecurityContext->AccessState->RemainingDesiredAccess &= ~(granted_access | MAXIMUM_ALLOWED); + IrpSp->Parameters.Create.SecurityContext->AccessState-> + PreviouslyGrantedAccess |= granted_access; + IrpSp->Parameters.Create.SecurityContext->AccessState-> + RemainingDesiredAccess &= ~(granted_access | MAXIMUM_ALLOWED); - return Status; + return (Status); } -int zfs_vnop_lookup(PIRP Irp, PIO_STACK_LOCATION IrpSp, mount_t *zmo) +int +zfs_vnop_lookup(PIRP Irp, PIO_STACK_LOCATION IrpSp, mount_t *zmo) { int status; char *filename = NULL; @@ -1271,12 +1417,15 @@ int zfs_vnop_lookup(PIRP Irp, PIO_STACK_LOCATION IrpSp, mount_t *zmo) // Check the EA buffer is good, if supplied. if (Irp->AssociatedIrp.SystemBuffer != NULL && - IrpSp->Parameters.Create.EaLength > 0) { + IrpSp->Parameters.Create.EaLength > 0) { ULONG offset; - status = IoCheckEaBufferValidity(Irp->AssociatedIrp.SystemBuffer, IrpSp->Parameters.Create.EaLength, &offset); + status = IoCheckEaBufferValidity( + Irp->AssociatedIrp.SystemBuffer, + IrpSp->Parameters.Create.EaLength, &offset); if (!NT_SUCCESS(status)) { - dprintf("IoCheckEaBufferValidity returned %08x (error at offset %u)\n", status, offset); - return status; + dprintf("IoCheckEaBufferValidity returned %08x " + "(error at offset %u)\n", status, offset); + return (status); } } @@ -1284,29 +1433,34 @@ int zfs_vnop_lookup(PIRP Irp, PIO_STACK_LOCATION IrpSp, mount_t *zmo) filename = kmem_alloc(PATH_MAX, KM_SLEEP); // Deal with ExtraCreateParameters -#if defined (NTDDI_WIN10_RS5) && (NTDDI_VERSION >= NTDDI_WIN10_RS5) +#if defined(NTDDI_WIN10_RS5) && (NTDDI_VERSION >= NTDDI_WIN10_RS5) /* Check for ExtraCreateParameters */ PECP_LIST ecp = NULL; PQUERY_ON_CREATE_ECP_CONTEXT qocContext = NULL; FsRtlGetEcpListFromIrp(Irp, &ecp); if (ecp) { GUID ecpType; - VOID *ecpContext = NULL; + void *ecpContext = NULL; ULONG ecpContextSize; - while (NT_SUCCESS(FsRtlGetNextExtraCreateParameter(ecp, ecpContext, - &ecpType, &ecpContext, &ecpContextSize))) { + while (NT_SUCCESS(FsRtlGetNextExtraCreateParameter(ecp, + ecpContext, &ecpType, &ecpContext, &ecpContextSize))) { if (IsEqualGUID(&ecpType, &GUID_ECP_ATOMIC_CREATE)) { dprintf("GUID_ECP_ATOMIC_CREATE\n"); // More code to come here: - } else if (IsEqualGUID(&ecpType, &GUID_ECP_QUERY_ON_CREATE)) { + } else if (IsEqualGUID(&ecpType, + &GUID_ECP_QUERY_ON_CREATE)) { dprintf("GUID_ECP_QUERY_ON_CREATE\n"); - // It wants a getattr call on success, before we finish up - qocContext = (PQUERY_ON_CREATE_ECP_CONTEXT)ecpContext; - } else if (IsEqualGUID(&ecpType, &GUID_ECP_CREATE_REDIRECTION)) { + // It wants a getattr call on success, + // before we finish up + qocContext = + (PQUERY_ON_CREATE_ECP_CONTEXT)ecpContext; + } else if (IsEqualGUID(&ecpType, + &GUID_ECP_CREATE_REDIRECTION)) { dprintf("GUID_ECP_CREATE_REDIRECTION\n"); // We get this one a lot. } else { - dprintf("Other GUID_ECP type\n"); // IopSymlinkECPGuid "73d5118a-88ba-439f-92f4-46d38952d250" + dprintf("Other GUID_ECP type\n"); +// IopSymlinkECPGuid "73d5118a-88ba-439f-92f4-46d38952d250" } }// while } // if ecp @@ -1317,15 +1471,18 @@ int zfs_vnop_lookup(PIRP Irp, PIO_STACK_LOCATION IrpSp, mount_t *zmo) // handle in a special way, before we call zfs_vnop_lookup_impl(). // We handle the regular EAs afterward. if (Irp->AssociatedIrp.SystemBuffer != NULL && - IrpSp->Parameters.Create.EaLength > 0) { + IrpSp->Parameters.Create.EaLength > 0) { PFILE_FULL_EA_INFORMATION ea; - for (ea = (PFILE_FULL_EA_INFORMATION)Irp->AssociatedIrp.SystemBuffer; - ; - ea = (PFILE_FULL_EA_INFORMATION)((uint8_t*)ea + ea->NextEntryOffset)) { - // only parse $LX attrs right now -- things we can store before the file - // gets created. + for (ea = + (PFILE_FULL_EA_INFORMATION)Irp->AssociatedIrp.SystemBuffer; + /* empty */; + ea = (PFILE_FULL_EA_INFORMATION)((uint8_t *)ea + + ea->NextEntryOffset)) { + // only parse $LX attrs right now -- things we can store + // before the file gets created. if (vattr_apply_lx_ea(&vap, ea)) { - dprintf(" encountered special attrs EA '%.*s'\n", ea->EaNameLength, ea->EaName); + dprintf("encountered special attrs EA '%.*s'\n", + ea->EaNameLength, ea->EaName); } if (ea->NextEntryOffset == 0) break; @@ -1339,7 +1496,7 @@ int zfs_vnop_lookup(PIRP Irp, PIO_STACK_LOCATION IrpSp, mount_t *zmo) -#if defined (NTDDI_WIN10_RS5) && (NTDDI_VERSION >= NTDDI_WIN10_RS5) +#if defined(NTDDI_WIN10_RS5) && (NTDDI_VERSION >= NTDDI_WIN10_RS5) // Did ECP ask for getattr to be returned? None, one or both can be set. // This requires vnode_couplefileobject() was called if (NT_SUCCESS(status) && qocContext && IrpSp->FileObject->FsContext) { @@ -1347,7 +1504,7 @@ int zfs_vnop_lookup(PIRP Irp, PIO_STACK_LOCATION IrpSp, mount_t *zmo) ULONG classes = 0; // Handle RS5 >= version < 19H1 when the struct had "Flags". -#if defined (NTDDI_WIN10_19H1) && (NTDDI_VERSION >= NTDDI_WIN10_19H1) +#if defined(NTDDI_WIN10_19H1) && (NTDDI_VERSION >= NTDDI_WIN10_19H1) classes = qocContext->RequestedClasses; #else classes = qocContext->Flags; @@ -1355,18 +1512,19 @@ int zfs_vnop_lookup(PIRP Irp, PIO_STACK_LOCATION IrpSp, mount_t *zmo) if (BooleanFlagOn(classes, QoCFileStatInformation)) { file_stat_information(IrpSp->DeviceObject, Irp, IrpSp, - &qocContext->StatInformation); + &qocContext->StatInformation); } if (BooleanFlagOn(classes, QoCFileLxInformation)) { - file_stat_lx_information(IrpSp->DeviceObject, Irp, IrpSp, - &qocContext->LxInformation); + file_stat_lx_information(IrpSp->DeviceObject, Irp, + IrpSp, &qocContext->LxInformation); } if (BooleanFlagOn(classes, QoCFileEaInformation)) { dprintf("%s: unsupported QoC: QoCFileEaInformation\n"); } -#if defined (NTDDI_WIN10_19H1) && (NTDDI_VERSION >= NTDDI_WIN10_19H1) +#if defined(NTDDI_WIN10_19H1) && (NTDDI_VERSION >= NTDDI_WIN10_19H1) // We should fill this in, right? Only set those we understand. - qocContext->ClassesProcessed = classes & (QoCFileStatInformation|QoCFileLxInformation); + qocContext->ClassesProcessed = + classes & (QoCFileStatInformation|QoCFileLxInformation); qocContext->ClassesWithErrors = 0; qocContext->ClassesWithNoData = 0; #endif @@ -1378,14 +1536,17 @@ int zfs_vnop_lookup(PIRP Irp, PIO_STACK_LOCATION IrpSp, mount_t *zmo) // Now handle proper EAs properly if (NT_SUCCESS(status)) { if (Irp->AssociatedIrp.SystemBuffer && - IrpSp->FileObject->FsContext) { - // Second pass: this will apply all EAs that are not only LX EAs + IrpSp->FileObject->FsContext) { + // Second pass: this will apply all EAs that are + // not only LX EAs vnode_apply_eas(IrpSp->FileObject->FsContext, - (PFILE_FULL_EA_INFORMATION)Irp->AssociatedIrp.SystemBuffer, - IrpSp->Parameters.Create.EaLength, NULL); + (PFILE_FULL_EA_INFORMATION) + Irp->AssociatedIrp.SystemBuffer, + IrpSp->Parameters.Create.EaLength, NULL); } - if (!BooleanFlagOn(IrpSp->Parameters.Create.Options, FILE_NO_INTERMEDIATE_BUFFERING)) { + if (!BooleanFlagOn(IrpSp->Parameters.Create.Options, + FILE_NO_INTERMEDIATE_BUFFERING)) { IrpSp->FileObject->Flags |= FO_CACHE_SUPPORTED; } } @@ -1394,9 +1555,10 @@ int zfs_vnop_lookup(PIRP Irp, PIO_STACK_LOCATION IrpSp, mount_t *zmo) kmem_free(filename, PATH_MAX); dprintf("%s: %s with %s\n", __func__, - common_status_str(status), create_reply(status, Irp->IoStatus.Information)); + common_status_str(status), + create_reply(status, Irp->IoStatus.Information)); - return status; + return (status); } @@ -1405,19 +1567,20 @@ int zfs_vnop_lookup(PIRP Irp, PIO_STACK_LOCATION IrpSp, mount_t *zmo) * VFS (spl-vnode.c) will hold iocount == 1, usecount == 0 * so release associated ZFS node, and free everything */ -int zfs_vnop_reclaim(struct vnode *vp) +int +zfs_vnop_reclaim(struct vnode *vp) { znode_t *zp = VTOZ(vp); if (zp == NULL) { ASSERT("NULL zp in reclaim?"); - return 0; + return (0); } zfsvfs_t *zfsvfs = zp->z_zfsvfs; boolean_t fastpath; dprintf(" zfs_vnop_recycle: releasing zp %p and vp %p: '%s'\n", zp, vp, - zp->z_name_cache ? zp->z_name_cache : ""); + zp->z_name_cache ? zp->z_name_cache : ""); void *sd = vnode_security(vp); if (sd != NULL) @@ -1425,13 +1588,13 @@ int zfs_vnop_reclaim(struct vnode *vp) vnode_setsecurity(vp, NULL); // Decouple the nodes - ASSERT(ZTOV(zp) != (vnode_t*)0xdeadbeefdeadbeef); + ASSERT(ZTOV(zp) != (vnode_t *)0xdeadbeefdeadbeef); mutex_enter(&zp->z_lock); ZTOV(zp) = NULL; vnode_clearfsnode(vp); /* vp->v_data = NULL */ mutex_exit(&zp->z_lock); - //vnode_removefsref(vp); /* ADDREF from vnode_create */ + // vnode_removefsref(vp); /* ADDREF from vnode_create */ vp = NULL; @@ -1442,11 +1605,11 @@ int zfs_vnop_reclaim(struct vnode *vp) // Release znode /* - * This will release as much as it can, based on reclaim_reentry, - * if we are from fastpath, we do not call free here, as zfs_remove - * calls zfs_znode_delete() directly. - * zfs_zinactive() will leave earlier if z_reclaim_reentry is true. - */ + * This will release as much as it can, based on reclaim_reentry, + * if we are from fastpath, we do not call free here, as zfs_remove + * calls zfs_znode_delete() directly. + * zfs_zinactive() will leave earlier if z_reclaim_reentry is true. + */ rw_enter(&zfsvfs->z_teardown_inactive_lock, RW_READER); if (zp->z_sa_hdl == NULL) { zfs_znode_free(zp); @@ -1461,8 +1624,8 @@ int zfs_vnop_reclaim(struct vnode *vp) if (vnop_num_vnodes % 1000 == 0) dprintf("%s: num_vnodes %llu\n", __func__, vnop_num_vnodes); - - return 0; + + return (0); } @@ -1481,16 +1644,17 @@ getnewvnode_drop_reserve() /* * Get new vnode for znode. * - * This function uses zp->z_zfsvfs, zp->z_mode, zp->z_flags, zp->z_id and sets - * zp->z_vnode and zp->z_vid. - * If given parent, dzp, we can save some hassles. If not, looks it up internally. + * This function uses zp->z_zfsvfs, zp->z_mode, zp->z_flags, zp->z_id + * and sets zp->z_vnode and zp->z_vid. + * If given parent, dzp, we can save some hassles. If not, looks it + * up internally. */ int zfs_znode_getvnode(znode_t *zp, znode_t *dzp, zfsvfs_t *zfsvfs) { struct vnode *vp = NULL; int flags = 0; - //dprintf("getvnode zp %p with vp %p zfsvfs %p vfs %p\n", zp, vp, + // dprintf("getvnode zp %p with vp %p zfsvfs %p vfs %p\n", zp, vp, // zfsvfs, zfsvfs->z_vfs); if (zp->z_vnode) @@ -1509,17 +1673,19 @@ zfs_znode_getvnode(znode_t *zp, znode_t *dzp, zfsvfs_t *zfsvfs) atomic_inc_64(&vnop_num_vnodes); - //dprintf("Assigned zp %p with vp %p\n", zp, vp); + // dprintf("Assigned zp %p with vp %p\n", zp, vp); zp->z_vid = vnode_vid(vp); zp->z_vnode = vp; - // Build a fullpath string here, for Notifications and set_name_information + // Build a fullpath string here, for Notifications + // and set_name_information ASSERT(zp->z_name_cache == NULL); - if (zfs_build_path(zp, dzp, &zp->z_name_cache, &zp->z_name_len, &zp->z_name_offset) == -1) + if (zfs_build_path(zp, dzp, &zp->z_name_cache, &zp->z_name_len, + &zp->z_name_offset) == -1) dprintf("%s: failed to build fullpath\n", __func__); - // Assign security here. But, if we are XATTR, we do not? In Windows, it refers to Streams - // and they do not have Scurity? + // Assign security here. But, if we are XATTR, we do not? In Windows, + // it refers to Streams and they do not have Scurity? if (zp->z_pflags & ZFS_XATTR) ; else @@ -1529,8 +1695,10 @@ zfs_znode_getvnode(znode_t *zp, znode_t *dzp, zfsvfs_t *zfsvfs) } -NTSTATUS dev_ioctl(PDEVICE_OBJECT DeviceObject, ULONG ControlCode, PVOID InputBuffer, ULONG InputBufferSize, - PVOID OutputBuffer, ULONG OutputBufferSize, BOOLEAN Override, IO_STATUS_BLOCK* iosb) +NTSTATUS +dev_ioctl(PDEVICE_OBJECT DeviceObject, ULONG ControlCode, PVOID InputBuffer, + ULONG InputBufferSize, PVOID OutputBuffer, ULONG OutputBufferSize, + BOOLEAN Override, IO_STATUS_BLOCK* iosb) { PIRP Irp; KEVENT Event; @@ -1541,16 +1709,17 @@ NTSTATUS dev_ioctl(PDEVICE_OBJECT DeviceObject, ULONG ControlCode, PVOID InputBu KeInitializeEvent(&Event, NotificationEvent, FALSE); Irp = IoBuildDeviceIoControlRequest(ControlCode, - DeviceObject, - InputBuffer, - InputBufferSize, - OutputBuffer, - OutputBufferSize, - FALSE, - &Event, - &IoStatus); - - if (!Irp) return STATUS_INSUFFICIENT_RESOURCES; + DeviceObject, + InputBuffer, + InputBufferSize, + OutputBuffer, + OutputBufferSize, + FALSE, + &Event, + &IoStatus); + + if (!Irp) + return (STATUS_INSUFFICIENT_RESOURCES); if (Override) { Stack = IoGetNextIrpStackLocation(Irp); @@ -1560,44 +1729,55 @@ NTSTATUS dev_ioctl(PDEVICE_OBJECT DeviceObject, ULONG ControlCode, PVOID InputBu Status = IoCallDriver(DeviceObject, Irp); if (Status == STATUS_PENDING) { - KeWaitForSingleObject(&Event, Executive, KernelMode, FALSE, NULL); + KeWaitForSingleObject(&Event, Executive, KernelMode, + FALSE, NULL); Status = IoStatus.Status; } if (iosb) *iosb = IoStatus; - return Status; + return (Status); } // THIS IS THE PNP DEVICE ID -NTSTATUS pnp_query_id(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +pnp_query_id(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) { mount_t *zmo; - dprintf("%s: query id type %d\n", __func__, IrpSp->Parameters.QueryId.IdType); + dprintf("%s: query id type %d\n", __func__, + IrpSp->Parameters.QueryId.IdType); zmo = (mount_t *)DeviceObject->DeviceExtension; - Irp->IoStatus.Information = (void *)ExAllocatePoolWithTag(PagedPool, zmo->bus_name.Length + sizeof(UNICODE_NULL), '!OIZ'); - if (Irp->IoStatus.Information == NULL) return STATUS_NO_MEMORY; + Irp->IoStatus.Information = (void *)ExAllocatePoolWithTag(PagedPool, + zmo->bus_name.Length + sizeof (UNICODE_NULL), '!OIZ'); + if (Irp->IoStatus.Information == NULL) + return (STATUS_NO_MEMORY); - RtlCopyMemory(Irp->IoStatus.Information, zmo->bus_name.Buffer, zmo->bus_name.Length); - dprintf("replying with '%.*S'\n", zmo->uuid.Length/sizeof(WCHAR), Irp->IoStatus.Information); + RtlCopyMemory(Irp->IoStatus.Information, zmo->bus_name.Buffer, + zmo->bus_name.Length); + dprintf("replying with '%.*S'\n", zmo->uuid.Length/sizeof (WCHAR), + Irp->IoStatus.Information); - return STATUS_SUCCESS; + return (STATUS_SUCCESS); } -NTSTATUS pnp_device_state(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +pnp_device_state(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp) { dprintf("%s:\n", __func__); Irp->IoStatus.Information |= PNP_DEVICE_NOT_DISABLEABLE; - return STATUS_SUCCESS; + return (STATUS_SUCCESS); } -NTSTATUS query_volume_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +query_volume_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp) { NTSTATUS Status; int len; @@ -1606,207 +1786,255 @@ NTSTATUS query_volume_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STA mount_t *zmo = DeviceObject->DeviceExtension; if (!zmo || - (zmo->type != MOUNT_TYPE_VCB && - zmo->type != MOUNT_TYPE_DCB)) { - return STATUS_INVALID_PARAMETER; + (zmo->type != MOUNT_TYPE_VCB && + zmo->type != MOUNT_TYPE_DCB)) { + return (STATUS_INVALID_PARAMETER); } zfsvfs_t *zfsvfs = vfs_fsprivate(zmo); if (zfsvfs == NULL) - return STATUS_INVALID_PARAMETER; + return (STATUS_INVALID_PARAMETER); ZFS_ENTER(zfsvfs); // This returns EIO if fail switch (IrpSp->Parameters.QueryVolume.FsInformationClass) { - case FileFsAttributeInformation: + case FileFsAttributeInformation: // - // If overflow, set Information to input_size and NameLength to what we fit. + // If overflow, set Information to input_size and NameLength + // to what we fit. // dprintf("* %s: FileFsAttributeInformation\n", __func__); - if (IrpSp->Parameters.QueryVolume.Length < sizeof(FILE_FS_ATTRIBUTE_INFORMATION)) { - Irp->IoStatus.Information = sizeof(FILE_FS_ATTRIBUTE_INFORMATION); + if (IrpSp->Parameters.QueryVolume.Length < + sizeof (FILE_FS_ATTRIBUTE_INFORMATION)) { + Irp->IoStatus.Information = + sizeof (FILE_FS_ATTRIBUTE_INFORMATION); Status = STATUS_BUFFER_TOO_SMALL; break; } /* Do not enable until we have implemented FileRenameInformationEx method. */ #if (NTDDI_VERSION >= NTDDI_WIN10_RS1) -#define ZFS_FS_ATTRIBUTE_POSIX +#define ZFS_FS_ATTRIBUTE_POSIX #endif -#define ZFS_FS_ATTRIBUTE_CLEANUP_INFO - - FILE_FS_ATTRIBUTE_INFORMATION *ffai = Irp->AssociatedIrp.SystemBuffer; - ffai->FileSystemAttributes = FILE_CASE_PRESERVED_NAMES | FILE_NAMED_STREAMS | - FILE_PERSISTENT_ACLS | FILE_SUPPORTS_OBJECT_IDS | FILE_SUPPORTS_SPARSE_FILES | FILE_VOLUME_QUOTAS | - FILE_SUPPORTS_REPARSE_POINTS | FILE_UNICODE_ON_DISK | FILE_SUPPORTS_HARD_LINKS | FILE_SUPPORTS_OPEN_BY_FILE_ID | - FILE_SUPPORTS_EXTENDED_ATTRIBUTES | FILE_CASE_SENSITIVE_SEARCH ; -#if defined (ZFS_FS_ATTRIBUTE_POSIX) +#define ZFS_FS_ATTRIBUTE_CLEANUP_INFO + + FILE_FS_ATTRIBUTE_INFORMATION *ffai = + Irp->AssociatedIrp.SystemBuffer; + ffai->FileSystemAttributes = + FILE_CASE_PRESERVED_NAMES | FILE_NAMED_STREAMS | + FILE_PERSISTENT_ACLS | FILE_SUPPORTS_OBJECT_IDS | + FILE_SUPPORTS_SPARSE_FILES | FILE_VOLUME_QUOTAS | + FILE_SUPPORTS_REPARSE_POINTS | FILE_UNICODE_ON_DISK | + FILE_SUPPORTS_HARD_LINKS | FILE_SUPPORTS_OPEN_BY_FILE_ID | + FILE_SUPPORTS_EXTENDED_ATTRIBUTES | + FILE_CASE_SENSITIVE_SEARCH; +#if defined(ZFS_FS_ATTRIBUTE_POSIX) ffai->FileSystemAttributes |= FILE_SUPPORTS_POSIX_UNLINK_RENAME; #endif -#if defined (ZFS_FS_ATTRIBUTE_CLEANUP_INFO) +#if defined(ZFS_FS_ATTRIBUTE_CLEANUP_INFO) ffai->FileSystemAttributes |= FILE_RETURNS_CLEANUP_RESULT_INFO; #endif - /* - // NTFS has these: - FILE_CASE_SENSITIVE_SEARCH | FILE_FILE_COMPRESSION | FILE_RETURNS_CLEANUP_RESULT_INFO | FILE_SUPPORTS_POSIX_UNLINK_RENAME | - FILE_SUPPORTS_ENCRYPTION | FILE_SUPPORTS_TRANSACTIONS | FILE_SUPPORTS_USN_JOURNAL; - */ + /* + * NTFS has these: + * FILE_CASE_SENSITIVE_SEARCH | FILE_FILE_COMPRESSION | + * FILE_RETURNS_CLEANUP_RESULT_INFO | + * FILE_SUPPORTS_POSIX_UNLINK_RENAME | + * FILE_SUPPORTS_ENCRYPTION | FILE_SUPPORTS_TRANSACTIONS | + * FILE_SUPPORTS_USN_JOURNAL; + */ - if (zfsvfs->z_case == ZFS_CASE_SENSITIVE) - ffai->FileSystemAttributes |= FILE_CASE_SENSITIVE_SEARCH; + if (zfsvfs->z_case == ZFS_CASE_SENSITIVE) + ffai->FileSystemAttributes |= + FILE_CASE_SENSITIVE_SEARCH; - if (zfsvfs->z_rdonly) - SetFlag(ffai->FileSystemAttributes, FILE_READ_ONLY_VOLUME); + if (zfsvfs->z_rdonly) + SetFlag(ffai->FileSystemAttributes, + FILE_READ_ONLY_VOLUME); ffai->MaximumComponentNameLength = MAXNAMELEN - 1; // There is room for one char in the struct // Alas, many things compare string to "NTFS". - space = IrpSp->Parameters.QueryVolume.Length - FIELD_OFFSET(FILE_FS_ATTRIBUTE_INFORMATION, FileSystemName); - - UNICODE_STRING name; + space = IrpSp->Parameters.QueryVolume.Length - + FIELD_OFFSET(FILE_FS_ATTRIBUTE_INFORMATION, FileSystemName); + + UNICODE_STRING name; RtlInitUnicodeString(&name, L"NTFS"); space = MIN(space, name.Length); ffai->FileSystemNameLength = name.Length; RtlCopyMemory(ffai->FileSystemName, name.Buffer, space); - Irp->IoStatus.Information = FIELD_OFFSET(FILE_FS_ATTRIBUTE_INFORMATION, FileSystemName) + space; - + Irp->IoStatus.Information = + FIELD_OFFSET(FILE_FS_ATTRIBUTE_INFORMATION, + FileSystemName) + space; + Status = STATUS_SUCCESS; - ASSERT(Irp->IoStatus.Information <= IrpSp->Parameters.QueryVolume.Length); + ASSERT(Irp->IoStatus.Information <= + IrpSp->Parameters.QueryVolume.Length); break; case FileFsControlInformation: - dprintf("* %s: FileFsControlInformation NOT IMPLEMENTED\n", __func__); + dprintf("* %s: FileFsControlInformation NOT IMPLEMENTED\n", + __func__); break; case FileFsDeviceInformation: - dprintf("* %s: FileFsDeviceInformation NOT IMPLEMENTED\n", __func__); + dprintf("* %s: FileFsDeviceInformation NOT IMPLEMENTED\n", + __func__); break; case FileFsDriverPathInformation: - dprintf("* %s: FileFsDriverPathInformation NOT IMPLEMENTED\n", __func__); + dprintf("* %s: FileFsDriverPathInformation NOT IMPLEMENTED\n", + __func__); break; - case FileFsFullSizeInformation: //** + case FileFsFullSizeInformation: dprintf("* %s: FileFsFullSizeInformation\n", __func__); - if (IrpSp->Parameters.QueryVolume.Length < sizeof(FILE_FS_FULL_SIZE_INFORMATION)) { - Irp->IoStatus.Information = sizeof(FILE_FS_FULL_SIZE_INFORMATION); + if (IrpSp->Parameters.QueryVolume.Length < + sizeof (FILE_FS_FULL_SIZE_INFORMATION)) { + Irp->IoStatus.Information = + sizeof (FILE_FS_FULL_SIZE_INFORMATION); Status = STATUS_BUFFER_TOO_SMALL; break; } uint64_t refdbytes, availbytes, usedobjs, availobjs; dmu_objset_space(zfsvfs->z_os, - &refdbytes, &availbytes, &usedobjs, &availobjs); - - FILE_FS_FULL_SIZE_INFORMATION *fffsi = Irp->AssociatedIrp.SystemBuffer; - fffsi->TotalAllocationUnits.QuadPart = (refdbytes + availbytes) / 512ULL; - fffsi->ActualAvailableAllocationUnits.QuadPart = availbytes / 512ULL; - fffsi->CallerAvailableAllocationUnits.QuadPart = availbytes / 512ULL; + &refdbytes, &availbytes, &usedobjs, &availobjs); + + FILE_FS_FULL_SIZE_INFORMATION *fffsi = + Irp->AssociatedIrp.SystemBuffer; + fffsi->TotalAllocationUnits.QuadPart = + (refdbytes + availbytes) / 512ULL; + fffsi->ActualAvailableAllocationUnits.QuadPart = + availbytes / 512ULL; + fffsi->CallerAvailableAllocationUnits.QuadPart = + availbytes / 512ULL; fffsi->BytesPerSector = 512; fffsi->SectorsPerAllocationUnit = 1; - Irp->IoStatus.Information = sizeof(FILE_FS_FULL_SIZE_INFORMATION); + Irp->IoStatus.Information = + sizeof (FILE_FS_FULL_SIZE_INFORMATION); Status = STATUS_SUCCESS; break; case FileFsObjectIdInformation: dprintf("* %s: FileFsObjectIdInformation\n", __func__); - FILE_FS_OBJECTID_INFORMATION* ffoi = Irp->AssociatedIrp.SystemBuffer; - //RtlCopyMemory(ffoi->ObjectId, &Vcb->superblock.uuid.uuid[0], sizeof(UCHAR) * 16); - RtlZeroMemory(ffoi->ExtendedInfo, sizeof(ffoi->ExtendedInfo)); - Irp->IoStatus.Information = sizeof(FILE_FS_OBJECTID_INFORMATION); + FILE_FS_OBJECTID_INFORMATION* ffoi = + Irp->AssociatedIrp.SystemBuffer; + // RtlCopyMemory(ffoi->ObjectId, &Vcb->superblock.uuid.uuid[0], + // sizeof (UCHAR) * 16); + RtlZeroMemory(ffoi->ExtendedInfo, sizeof (ffoi->ExtendedInfo)); + Irp->IoStatus.Information = + sizeof (FILE_FS_OBJECTID_INFORMATION); Status = STATUS_OBJECT_NAME_NOT_FOUND; // returned by NTFS break; case FileFsVolumeInformation: dprintf("* %s: FileFsVolumeInformation\n", __func__); - if (IrpSp->Parameters.QueryVolume.Length < sizeof(FILE_FS_VOLUME_INFORMATION)) { - Irp->IoStatus.Information = sizeof(FILE_FS_VOLUME_INFORMATION); + if (IrpSp->Parameters.QueryVolume.Length < + sizeof (FILE_FS_VOLUME_INFORMATION)) { + Irp->IoStatus.Information = + sizeof (FILE_FS_VOLUME_INFORMATION); Status = STATUS_BUFFER_TOO_SMALL; break; } - FILE_FS_VOLUME_INFORMATION *ffvi = Irp->AssociatedIrp.SystemBuffer; + FILE_FS_VOLUME_INFORMATION *ffvi = + Irp->AssociatedIrp.SystemBuffer; TIME_UNIX_TO_WINDOWS_EX(zfsvfs->z_last_unmount_time, 0, - ffvi->VolumeCreationTime.QuadPart); + ffvi->VolumeCreationTime.QuadPart); ffvi->VolumeSerialNumber = 0x19831116; ffvi->SupportsObjects = TRUE; ffvi->VolumeLabelLength = - zmo->name.Length; + zmo->name.Length; - int space = IrpSp->Parameters.QueryFile.Length - FIELD_OFFSET(FILE_FS_VOLUME_INFORMATION, VolumeLabel); + int space = + IrpSp->Parameters.QueryFile.Length - + FIELD_OFFSET(FILE_FS_VOLUME_INFORMATION, VolumeLabel); space = MIN(space, ffvi->VolumeLabelLength); - /* + /* * This becomes the name displayed in Explorer, so we return the * dataset name here, as much as we can */ RtlCopyMemory(ffvi->VolumeLabel, zmo->name.Buffer, space); - - Irp->IoStatus.Information = FIELD_OFFSET(FILE_FS_VOLUME_INFORMATION, VolumeLabel) + space; - if (space < ffvi->VolumeLabelLength) + Irp->IoStatus.Information = + FIELD_OFFSET(FILE_FS_VOLUME_INFORMATION, + VolumeLabel) + space; + + if (space < ffvi->VolumeLabelLength) Status = STATUS_BUFFER_OVERFLOW; else Status = STATUS_SUCCESS; break; - case FileFsSizeInformation: + case FileFsSizeInformation: dprintf("* %s: FileFsSizeInformation\n", __func__); - if (IrpSp->Parameters.QueryVolume.Length < sizeof(FILE_FS_SIZE_INFORMATION)) { - Irp->IoStatus.Information = sizeof(FILE_FS_SIZE_INFORMATION); + if (IrpSp->Parameters.QueryVolume.Length < + sizeof (FILE_FS_SIZE_INFORMATION)) { + Irp->IoStatus.Information = + sizeof (FILE_FS_SIZE_INFORMATION); Status = STATUS_BUFFER_TOO_SMALL; break; } - FILE_FS_SIZE_INFORMATION *ffsi = Irp->AssociatedIrp.SystemBuffer; + FILE_FS_SIZE_INFORMATION *ffsi = + Irp->AssociatedIrp.SystemBuffer; ffsi->TotalAllocationUnits.QuadPart = 1024 * 1024 * 1024; ffsi->AvailableAllocationUnits.QuadPart = 1024 * 1024 * 1024; ffsi->SectorsPerAllocationUnit = 1; ffsi->BytesPerSector = 512; - Irp->IoStatus.Information = sizeof(FILE_FS_SIZE_INFORMATION); + Irp->IoStatus.Information = sizeof (FILE_FS_SIZE_INFORMATION); Status = STATUS_SUCCESS; break; case FileFsSectorSizeInformation: dprintf("* %s: FileFsSectorSizeInformation\n", __func__); - if (IrpSp->Parameters.QueryVolume.Length < sizeof(FILE_FS_SECTOR_SIZE_INFORMATION)) { - Irp->IoStatus.Information = sizeof(FILE_FS_SECTOR_SIZE_INFORMATION); + if (IrpSp->Parameters.QueryVolume.Length < + sizeof (FILE_FS_SECTOR_SIZE_INFORMATION)) { + Irp->IoStatus.Information = + sizeof (FILE_FS_SECTOR_SIZE_INFORMATION); Status = STATUS_BUFFER_TOO_SMALL; break; } - FILE_FS_SECTOR_SIZE_INFORMATION *ffssi = Irp->AssociatedIrp.SystemBuffer; + FILE_FS_SECTOR_SIZE_INFORMATION *ffssi = + Irp->AssociatedIrp.SystemBuffer; ffssi->LogicalBytesPerSector = 512; ffssi->PhysicalBytesPerSectorForAtomicity = 512; ffssi->PhysicalBytesPerSectorForPerformance = 512; - ffssi->FileSystemEffectivePhysicalBytesPerSectorForAtomicity = 512; + ffssi->FileSystemEffectivePhysicalBytesPerSectorForAtomicity = + 512; ffssi->Flags = SSINFO_FLAGS_NO_SEEK_PENALTY; ffssi->ByteOffsetForSectorAlignment = SSINFO_OFFSET_UNKNOWN; ffssi->ByteOffsetForPartitionAlignment = SSINFO_OFFSET_UNKNOWN; - Irp->IoStatus.Information = sizeof(FILE_FS_SECTOR_SIZE_INFORMATION); + Irp->IoStatus.Information = + sizeof (FILE_FS_SECTOR_SIZE_INFORMATION); Status = STATUS_SUCCESS; break; default: - dprintf("* %s: unknown class 0x%x\n", __func__, IrpSp->Parameters.QueryVolume.FsInformationClass); + dprintf("* %s: unknown class 0x%x\n", __func__, + IrpSp->Parameters.QueryVolume.FsInformationClass); Status = STATUS_NOT_IMPLEMENTED; break; } ZFS_EXIT(zfsvfs); - return Status; + return (Status); } -NTSTATUS lock_control(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +lock_control(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) { NTSTATUS Status = STATUS_SUCCESS; dprintf("%s: FileObject %p flags 0x%x %s %s\n", __func__, - IrpSp->FileObject, IrpSp->Flags, - IrpSp->Flags & SL_EXCLUSIVE_LOCK ? "Exclusive" : "Shared", - IrpSp->Flags & SL_FAIL_IMMEDIATELY ? "Nowait" : "Wait" - ); + IrpSp->FileObject, IrpSp->Flags, + IrpSp->Flags & SL_EXCLUSIVE_LOCK ? "Exclusive" : "Shared", + IrpSp->Flags & SL_FAIL_IMMEDIATELY ? "Nowait" : "Wait"); - return Status; + return (Status); } -NTSTATUS query_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +query_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp) { NTSTATUS Status = STATUS_NOT_IMPLEMENTED; ULONG usedspace = 0; @@ -1816,153 +2044,191 @@ NTSTATUS query_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCA if (IrpSp->FileObject && IrpSp->FileObject->FsContext) { vp = IrpSp->FileObject->FsContext; if (VN_HOLD(vp) != 0) - return STATUS_INVALID_PARAMETER; + return (STATUS_INVALID_PARAMETER); } - + switch (IrpSp->Parameters.QueryFile.FileInformationClass) { - - case FileAllInformation: - dprintf("%s: FileAllInformation: buffer 0x%x\n", __func__, IrpSp->Parameters.QueryFile.Length); - if (IrpSp->Parameters.QueryFile.Length < sizeof(FILE_ALL_INFORMATION)) { - Irp->IoStatus.Information = sizeof(FILE_ALL_INFORMATION); // We should send Plus Filename here, to be nice, but this doesnt happen + case FileAllInformation: + dprintf("%s: FileAllInformation: buffer 0x%x\n", __func__, + IrpSp->Parameters.QueryFile.Length); + + if (IrpSp->Parameters.QueryFile.Length < + sizeof (FILE_ALL_INFORMATION)) { + Irp->IoStatus.Information = + sizeof (FILE_ALL_INFORMATION); +// We should send Plus Filename here, to be nice, but this doesnt happen Status = STATUS_BUFFER_TOO_SMALL; break; } FILE_ALL_INFORMATION *all = Irp->AssociatedIrp.SystemBuffer; - // Even if the name does not fit, the other information should be correct - Status = file_basic_information(DeviceObject, Irp, IrpSp, &all->BasicInformation); - if (Status != STATUS_SUCCESS) break; - Status = file_standard_information(DeviceObject, Irp, IrpSp, &all->StandardInformation); - if (Status != STATUS_SUCCESS) break; - Status = file_position_information(DeviceObject, Irp, IrpSp, &all->PositionInformation); - if (Status != STATUS_SUCCESS) break; - Status = file_ea_information(DeviceObject, Irp, IrpSp, &all->EaInformation); - if (Status != STATUS_SUCCESS) break; + // Even if the name does not fit, the other information + // should be correct + Status = file_basic_information(DeviceObject, Irp, IrpSp, + &all->BasicInformation); + if (Status != STATUS_SUCCESS) + break; + Status = file_standard_information(DeviceObject, Irp, IrpSp, + &all->StandardInformation); + if (Status != STATUS_SUCCESS) + break; + Status = file_position_information(DeviceObject, Irp, IrpSp, + &all->PositionInformation); + if (Status != STATUS_SUCCESS) + break; + Status = file_ea_information(DeviceObject, Irp, IrpSp, + &all->EaInformation); + if (Status != STATUS_SUCCESS) + break; #if 0 - all->AccessInformation.AccessFlags = GENERIC_ALL | GENERIC_EXECUTE | GENERIC_READ | GENERIC_WRITE; + all->AccessInformation.AccessFlags = + GENERIC_ALL | GENERIC_EXECUTE | + GENERIC_READ | GENERIC_WRITE; if (vp) - all->ModeInformation.Mode = vnode_unlink(vp) ? FILE_DELETE_ON_CLOSE : 0; + all->ModeInformation.Mode = + vnode_unlink(vp) ? FILE_DELETE_ON_CLOSE : 0; #endif all->AlignmentInformation.AlignmentRequirement = 0; // First get the Name, to make sure we have room - IrpSp->Parameters.QueryFile.Length -= offsetof(FILE_ALL_INFORMATION, NameInformation); - Status = file_name_information(DeviceObject, Irp, IrpSp, &all->NameInformation, &usedspace, 0); - IrpSp->Parameters.QueryFile.Length += offsetof(FILE_ALL_INFORMATION, NameInformation); - - // file_name_information sets FileNameLength, so update size to be ALL struct not NAME struct - // However, there is room for one char in the struct, so subtract that from total. - Irp->IoStatus.Information = - FIELD_OFFSET(FILE_ALL_INFORMATION, NameInformation) + - FIELD_OFFSET(FILE_NAME_INFORMATION, FileName) + - usedspace; - //FIELD_OFFSET(FILE_ALL_INFORMATION, NameInformation.FileName) + usedspace; - - dprintf("Struct size 0x%x FileNameLen 0x%x Information retsize 0x%x\n", - sizeof(FILE_ALL_INFORMATION), - all->NameInformation.FileNameLength, - Irp->IoStatus.Information); + IrpSp->Parameters.QueryFile.Length -= + offsetof(FILE_ALL_INFORMATION, NameInformation); + Status = file_name_information(DeviceObject, Irp, IrpSp, + &all->NameInformation, &usedspace, 0); + IrpSp->Parameters.QueryFile.Length += + offsetof(FILE_ALL_INFORMATION, NameInformation); + + // file_name_information sets FileNameLength, so update size + // to be ALL struct not NAME struct + // However, there is room for one char in the struct, + // so subtract that from total. + Irp->IoStatus.Information = + FIELD_OFFSET(FILE_ALL_INFORMATION, NameInformation) + + FIELD_OFFSET(FILE_NAME_INFORMATION, FileName) + + usedspace; + // FIELD_OFFSET(FILE_ALL_INFORMATION, NameInformation.FileName) + // + usedspace; + + dprintf("Struct size 0x%x FileNameLen 0x%x " + "Information retsize 0x%x\n", + sizeof (FILE_ALL_INFORMATION), + all->NameInformation.FileNameLength, + Irp->IoStatus.Information); break; case FileAttributeTagInformation: - Status = file_attribute_tag_information(DeviceObject, Irp, IrpSp, - Irp->AssociatedIrp.SystemBuffer); + Status = file_attribute_tag_information(DeviceObject, Irp, + IrpSp, Irp->AssociatedIrp.SystemBuffer); break; case FileBasicInformation: - Status = file_basic_information(DeviceObject, Irp, IrpSp, Irp->AssociatedIrp.SystemBuffer); + Status = file_basic_information(DeviceObject, Irp, IrpSp, + Irp->AssociatedIrp.SystemBuffer); break; case FileCompressionInformation: - dprintf("* %s: FileCompressionInformation NOT IMPLEMENTED\n", __func__); + dprintf("* %s: FileCompressionInformation NOT IMPLEMENTED\n", + __func__); break; case FileEaInformation: - Status = file_ea_information(DeviceObject, Irp, IrpSp, - Irp->AssociatedIrp.SystemBuffer); + Status = file_ea_information(DeviceObject, Irp, IrpSp, + Irp->AssociatedIrp.SystemBuffer); break; case FileInternalInformation: - Status = file_internal_information(DeviceObject, Irp, IrpSp, - Irp->AssociatedIrp.SystemBuffer); + Status = file_internal_information(DeviceObject, Irp, IrpSp, + Irp->AssociatedIrp.SystemBuffer); break; case FileNormalizedNameInformation: dprintf("FileNormalizedNameInformation\n"); - // IFSTEST AllInformationTest requires this name, and FileAllInformation - // to be identical, so we no longer return the fullpath. - normalize = 1; + // IFSTEST AllInformationTest requires this name, and + // FileAllInformation to be identical, so we no longer + // return the fullpath. + normalize = 1; /* According to fastfat, this means never return shortnames */ /* fall through */ case FileNameInformation: // - // If overflow, set Information to input_size and NameLength to required size. + // If overflow, set Information to input_size and NameLength + // to required size. // - Status = file_name_information(DeviceObject, Irp, IrpSp, - Irp->AssociatedIrp.SystemBuffer, &usedspace, normalize); - Irp->IoStatus.Information = FIELD_OFFSET(FILE_NAME_INFORMATION, FileName) + usedspace; + Status = file_name_information(DeviceObject, Irp, IrpSp, + Irp->AssociatedIrp.SystemBuffer, &usedspace, normalize); + Irp->IoStatus.Information = + FIELD_OFFSET(FILE_NAME_INFORMATION, FileName) + usedspace; break; - case FileNetworkOpenInformation: - Status = file_network_open_information(DeviceObject, Irp, IrpSp, - Irp->AssociatedIrp.SystemBuffer); + case FileNetworkOpenInformation: + Status = file_network_open_information(DeviceObject, Irp, IrpSp, + Irp->AssociatedIrp.SystemBuffer); break; case FilePositionInformation: - Status = file_position_information(DeviceObject, Irp, IrpSp, - Irp->AssociatedIrp.SystemBuffer); + Status = file_position_information(DeviceObject, Irp, IrpSp, + Irp->AssociatedIrp.SystemBuffer); break; case FileStandardInformation: - Status = file_standard_information(DeviceObject, Irp, IrpSp, - Irp->AssociatedIrp.SystemBuffer); + Status = file_standard_information(DeviceObject, Irp, IrpSp, + Irp->AssociatedIrp.SystemBuffer); break; case FileStreamInformation: - Status = file_stream_information(DeviceObject, Irp, IrpSp, - Irp->AssociatedIrp.SystemBuffer, &usedspace); + Status = file_stream_information(DeviceObject, Irp, IrpSp, + Irp->AssociatedIrp.SystemBuffer, &usedspace); break; case FileHardLinkInformation: - dprintf("* %s: FileHardLinkInformation NOT IMPLEMENTED\n", __func__); + dprintf("* %s: FileHardLinkInformation NOT IMPLEMENTED\n", + __func__); break; // Not used - not handled by ntfs either case FileRemoteProtocolInformation: - dprintf("* %s: FileRemoteProtocolInformation NOT IMPLEMENTED\n", __func__); + dprintf("* %s: FileRemoteProtocolInformation NOT IMPLEMENTED\n", + __func__); #if 0 - Status = file_remote_protocol_information(DeviceObject, Irp, IrpSp, Irp->AssociatedIrp.SystemBuffer); + Status = file_remote_protocol_information(DeviceObject, Irp, + IrpSp, Irp->AssociatedIrp.SystemBuffer); #endif Status = STATUS_INVALID_PARAMETER; break; case FileStandardLinkInformation: - Status = file_standard_link_information(DeviceObject, Irp, IrpSp, - Irp->AssociatedIrp.SystemBuffer); + Status = file_standard_link_information(DeviceObject, Irp, + IrpSp, Irp->AssociatedIrp.SystemBuffer); break; case FileReparsePointInformation: break; case FileIdInformation: - Status = file_id_information(DeviceObject, Irp, IrpSp, - Irp->AssociatedIrp.SystemBuffer); + Status = file_id_information(DeviceObject, Irp, IrpSp, + Irp->AssociatedIrp.SystemBuffer); break; case FileCaseSensitiveInformation: - Status = file_case_sensitive_information(DeviceObject, Irp, IrpSp, - Irp->AssociatedIrp.SystemBuffer); + Status = file_case_sensitive_information(DeviceObject, Irp, + IrpSp, Irp->AssociatedIrp.SystemBuffer); break; case FileStatInformation: - // We call these functions from zfs_vnop_lookup, so size testing goes here - if (IrpSp->Parameters.QueryFile.Length < sizeof(FILE_STAT_INFORMATION)) { - Irp->IoStatus.Information = sizeof(FILE_STAT_INFORMATION); + // We call these functions from zfs_vnop_lookup, so size + // testing goes here + if (IrpSp->Parameters.QueryFile.Length < + sizeof (FILE_STAT_INFORMATION)) { + Irp->IoStatus.Information = + sizeof (FILE_STAT_INFORMATION); Status = STATUS_BUFFER_TOO_SMALL; break; } - Status = file_stat_information(DeviceObject, Irp, IrpSp, - Irp->AssociatedIrp.SystemBuffer); - Irp->IoStatus.Information = sizeof(FILE_STAT_INFORMATION); + Status = file_stat_information(DeviceObject, Irp, IrpSp, + Irp->AssociatedIrp.SystemBuffer); + Irp->IoStatus.Information = sizeof (FILE_STAT_INFORMATION); break; case FileStatLxInformation: - // We call these functions from zfs_vnop_lookup, so size testing goes here - if (IrpSp->Parameters.QueryFile.Length < sizeof(FILE_STAT_LX_INFORMATION)) { - Irp->IoStatus.Information = sizeof(FILE_STAT_LX_INFORMATION); + // We call these functions from zfs_vnop_lookup, so size + // testing goes here + if (IrpSp->Parameters.QueryFile.Length < + sizeof (FILE_STAT_LX_INFORMATION)) { + Irp->IoStatus.Information = + sizeof (FILE_STAT_LX_INFORMATION); Status = STATUS_BUFFER_TOO_SMALL; break; } Status = file_stat_lx_information(DeviceObject, Irp, IrpSp, - Irp->AssociatedIrp.SystemBuffer); - Irp->IoStatus.Information = sizeof(FILE_STAT_LX_INFORMATION); + Irp->AssociatedIrp.SystemBuffer); + Irp->IoStatus.Information = sizeof (FILE_STAT_LX_INFORMATION); break; default: - dprintf("* %s: unknown class 0x%x NOT IMPLEMENTED\n", __func__, IrpSp->Parameters.QueryFile.FileInformationClass); + dprintf("* %s: unknown class 0x%x NOT IMPLEMENTED\n", __func__, + IrpSp->Parameters.QueryFile.FileInformationClass); break; } @@ -1970,69 +2236,67 @@ NTSTATUS query_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCA VN_RELE(vp); vp = NULL; } - return Status; + return (Status); } PVOID -MapUserBuffer( - IN OUT PIRP Irp -) +MapUserBuffer(IN OUT PIRP Irp) { // // If there is no Mdl, then we must be in the Fsd, and we can simply // return the UserBuffer field from the Irp. // if (Irp->MdlAddress == NULL) { - return Irp->UserBuffer; + return (Irp->UserBuffer); } else { - PVOID Address = MmGetSystemAddressForMdlSafe(Irp->MdlAddress, NormalPagePriority | MdlMappingNoExecute); - return Address; + PVOID Address = MmGetSystemAddressForMdlSafe(Irp->MdlAddress, + NormalPagePriority | MdlMappingNoExecute); + return (Address); } } PVOID -BufferUserBuffer( - IN OUT PIRP Irp, - IN ULONG BufferLength -) +BufferUserBuffer(IN OUT PIRP Irp, IN ULONG BufferLength) { PUCHAR UserBuffer; - if (BufferLength == 0) { - return NULL; - } + if (BufferLength == 0) + return (NULL); + // // If there is no system buffer we must have been supplied an Mdl // describing the users input buffer, which we will now snapshot. // if (Irp->AssociatedIrp.SystemBuffer == NULL) { UserBuffer = MapUserBuffer(Irp); - Irp->AssociatedIrp.SystemBuffer = FsRtlAllocatePoolWithQuotaTag(NonPagedPoolNx, - BufferLength, - 'qtaf'); + Irp->AssociatedIrp.SystemBuffer = + FsRtlAllocatePoolWithQuotaTag(NonPagedPoolNx, + BufferLength, + 'qtaf'); // - // Set the flags so that the completion code knows to deallocate the - // buffer. + // Set the flags so that the completion code knows to + // deallocate the buffer. // Irp->Flags |= (IRP_BUFFERED_IO | IRP_DEALLOCATE_BUFFER); try { RtlCopyMemory(Irp->AssociatedIrp.SystemBuffer, - UserBuffer, - BufferLength); + UserBuffer, + BufferLength); } except(EXCEPTION_EXECUTE_HANDLER) { NTSTATUS Status; Status = GetExceptionCode(); } } - return Irp->AssociatedIrp.SystemBuffer; + return (Irp->AssociatedIrp.SystemBuffer); } // Insert an EA into an output buffer, if there is room, // EAName is always the FULL name length, even when we only // fit partial. // Return 0 for OK, 1 for overflow. -int zfswin_insert_xattrname(struct vnode *vp, char *xattrname, uint8_t *outbuffer, DWORD **lastNextEntryOffset, - uint64_t availablebytes, uint64_t *spaceused) +int +zfswin_insert_xattrname(struct vnode *vp, char *xattrname, uint8_t *outbuffer, + DWORD **lastNextEntryOffset, uint64_t availablebytes, uint64_t *spaceused) { // The first xattr struct we assume is already aligned, but further ones // should be padded here. @@ -2047,19 +2311,20 @@ int zfswin_insert_xattrname(struct vnode *vp, char *xattrname, uint8_t *outbuffe int error; // Check error? Do we care about convertion errors? - //error = RtlUTF8ToUnicodeN(NULL, 0, &needed_xattrnamelen, xattrname, strlen(xattrname)); + // error = RtlUTF8ToUnicodeN(NULL, 0, &needed_xattrnamelen, + // xattrname, strlen(xattrname)); needed_xattrnamelen = strlen(xattrname); // Is there room? We have to add the struct if there is room for it // and fill it out as much as possible, and copy in as much of the name // as we can. - if (*spaceused + sizeof(FILE_FULL_EA_INFORMATION) <= availablebytes) { + if (*spaceused + sizeof (FILE_FULL_EA_INFORMATION) <= availablebytes) { ea = (FILE_FULL_EA_INFORMATION *)&outbuffer[*spaceused]; // Room for one more struct, update privious's next ptr if (*lastNextEntryOffset != NULL) { - // Update previous structure to point to this one. + // Update previous structure to point to this one. **lastNextEntryOffset = (DWORD)*spaceused; } @@ -2069,17 +2334,18 @@ int zfswin_insert_xattrname(struct vnode *vp, char *xattrname, uint8_t *outbuffe ea->Flags = 0; // Fix me? ea->EaValueLength = 0; - // remember this struct's NextEntry, so the next one can fill it in. + // remember this struct's NextEntry, so the next one + // can fill it in. *lastNextEntryOffset = &ea->NextEntryOffset; // Return the total name length not counting null - ea->EaNameLength = needed_xattrnamelen; - + ea->EaNameLength = needed_xattrnamelen; + // Consume the space of the struct *spaceused += FIELD_OFFSET(FILE_FULL_EA_INFORMATION, EaName); uint64_t roomforname; - if (*spaceused + ea->EaNameLength + 1 <= availablebytes) { // Null byte + if (*spaceused + ea->EaNameLength + 1 <= availablebytes) { roomforname = ea->EaNameLength + 1; } else { roomforname = availablebytes - *spaceused; @@ -2106,34 +2372,39 @@ int zfswin_insert_xattrname(struct vnode *vp, char *xattrname, uint8_t *outbuffe overflow = 1; // Read in as much as we can - uio_t *uio = uio_create(1, 0, UIO_SYSSPACE, UIO_READ); - uio_addiov(uio, (user_addr_t)&outbuffer[*spaceused], roomforvalue); + uio_t *uio = uio_create(1, 0, UIO_SYSSPACE, + UIO_READ); + uio_addiov(uio, + (user_addr_t)&outbuffer[*spaceused], + roomforvalue); zfs_read(vp, uio, 0, NULL); // Consume as many bytes as we read *spaceused += roomforvalue - uio_resid(uio); - // Set the valuelen, should this be the full value or what we would need? + // Set the valuelen, should this be the full + // value or what we would need? // That is how the names work. - ea->EaValueLength = VTOZ(vp)->z_size; // double check! + ea->EaValueLength = VTOZ(vp)->z_size; uio_free(uio); } } dprintf("%s: added %s xattrname '%s'\n", __func__, - overflow ? "(partial)" : "", xattrname); + overflow ? "(partial)" : "", xattrname); } else { dprintf("%s: no room for '%s'\n", __func__, xattrname); overflow = 1; } - return overflow; + return (overflow); } /* - * Iterate through the XATTRs of an object, skipping streams. It works like readdir, with - * saving index point, restart_scan and single_entry flags. + * Iterate through the XATTRs of an object, skipping streams. It works + * like readdir, with saving index point, restart_scan and single_entry flags. * It can optionally supply QueryEa.EaList to query specific set of EAs. * Each output structure is 4 byte aligned */ -NTSTATUS query_ea(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +query_ea(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) { NTSTATUS Status = STATUS_SUCCESS; @@ -2156,9 +2427,11 @@ NTSTATUS query_ea(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpS struct vnode *vp = NULL, *xdvp = NULL; - if (IrpSp->FileObject == NULL) return STATUS_INVALID_PARAMETER; + if (IrpSp->FileObject == NULL) + return (STATUS_INVALID_PARAMETER); vp = IrpSp->FileObject->FsContext; - if (vp == NULL) return STATUS_INVALID_PARAMETER; + if (vp == NULL) + return (STATUS_INVALID_PARAMETER); zp = VTOZ(vp); zfsvfs = zp->z_zfsvfs; @@ -2175,9 +2448,7 @@ NTSTATUS query_ea(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpS // Grab the xattr dir - if any if (zfs_get_xattrdir(zp, &xdzp, NULL, 0) != 0) { - return STATUS_NO_EAS_ON_FILE; - Status = STATUS_NO_EAS_ON_FILE; - goto out; + return (STATUS_NO_EAS_ON_FILE); } xdvp = ZTOV(xdzp); Buffer = MapUserBuffer(Irp); @@ -2206,21 +2477,28 @@ NTSTATUS query_ea(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpS do { ea = (FILE_GET_EA_INFORMATION *)&Buffer[offset]; // Lookup ea if we can - error = zfs_dirlook(VTOZ(xdvp), ea->EaName, &xvp, 0, NULL, NULL); + error = zfs_dirlook(VTOZ(xdvp), ea->EaName, &xvp, + 0, NULL, NULL); if (error == 0) { - overflow += zfswin_insert_xattrname(xvp, ea->EaName, Buffer, &lastNextEntryOffset, UserBufferLength, &spaceused); + overflow += zfswin_insert_xattrname(xvp, + ea->EaName, Buffer, &lastNextEntryOffset, + UserBufferLength, &spaceused); VN_RELE(xvp); } else { // No such xattr, we then "dummy" up an ea - overflow += zfswin_insert_xattrname(NULL, ea->EaName, Buffer, &lastNextEntryOffset, UserBufferLength, &spaceused); + overflow += zfswin_insert_xattrname(NULL, + ea->EaName, Buffer, &lastNextEntryOffset, + UserBufferLength, &spaceused); } - if (overflow != 0) break; + if (overflow != 0) + break; zccb->ea_index++; offset = ea->NextEntryOffset; - if (ReturnSingleEntry) break; + if (ReturnSingleEntry) + break; } while (offset != 0); @@ -2234,23 +2512,30 @@ NTSTATUS query_ea(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpS if (start_index == 0) zap_cursor_init(&zc, os, VTOZ(xdvp)->z_id); else - zap_cursor_init_serialized(&zc, os, zp->z_id, start_index); + zap_cursor_init_serialized(&zc, os, zp->z_id, + start_index); - for ( /* empty */ ; - zap_cursor_retrieve(&zc, &za) == 0; zap_cursor_advance(&zc)) { + for (/* empty */; + zap_cursor_retrieve(&zc, &za) == 0; + zap_cursor_advance(&zc)) { if (xattr_protected(za.za_name)) continue; /* skip */ if (xattr_stream(za.za_name)) continue; /* skip */ - error = zfs_dirlook(VTOZ(xdvp), za.za_name, &xvp, 0, NULL, NULL); + error = zfs_dirlook(VTOZ(xdvp), za.za_name, &xvp, + 0, NULL, NULL); if (error == 0) { - overflow += zfswin_insert_xattrname(xvp, za.za_name, Buffer, &lastNextEntryOffset, UserBufferLength, &spaceused); + overflow += zfswin_insert_xattrname(xvp, + za.za_name, Buffer, &lastNextEntryOffset, + UserBufferLength, &spaceused); VN_RELE(xvp); - if (overflow != 0) break; + if (overflow != 0) + break; zccb->ea_index++; } - if (ReturnSingleEntry) break; + if (ReturnSingleEntry) + break; } zap_cursor_fini(&zc); } @@ -2265,13 +2550,14 @@ NTSTATUS query_ea(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpS else if (spaceused == 0) Status = STATUS_NO_MORE_EAS; - return Status; + return (Status); } /* * Receive an array of structs to set EAs, iterate until Next is null. */ -NTSTATUS set_ea(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +set_ea(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) { uint32_t input_len = IrpSp->Parameters.SetEa.Length; uint8_t *buffer = NULL, *UserBuffer = NULL; @@ -2279,33 +2565,40 @@ NTSTATUS set_ea(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) struct vnode *vp = NULL, *xdvp = NULL; vattr_t vap = { 0 }; - if (IrpSp->FileObject == NULL) return STATUS_INVALID_PARAMETER; + if (IrpSp->FileObject == NULL) + return (STATUS_INVALID_PARAMETER); vp = IrpSp->FileObject->FsContext; - if (vp == NULL) return STATUS_INVALID_PARAMETER; + if (vp == NULL) + return (STATUS_INVALID_PARAMETER); znode_t *zp = VTOZ(vp); dprintf("%s\n", __func__); - if (input_len == 0) return STATUS_INVALID_PARAMETER; + if (input_len == 0) + return (STATUS_INVALID_PARAMETER); // This magic is straight out of fastfat buffer = BufferUserBuffer(Irp, input_len); ULONG eaErrorOffset = 0; - Status = vnode_apply_eas(vp, (PFILE_FULL_EA_INFORMATION)buffer, input_len, &eaErrorOffset); - // (Information is ULONG_PTR; as win64 is a LLP64 platform, ULONG isn't the right length.) + Status = vnode_apply_eas(vp, (PFILE_FULL_EA_INFORMATION)buffer, + input_len, &eaErrorOffset); + // (Information is ULONG_PTR; as win64 is a LLP64 platform, + // ULONG isn't the right length.) Irp->IoStatus.Information = eaErrorOffset; if (!NT_SUCCESS(Status)) { dprintf("%s: failed vnode_apply_eas: 0x%x\n", __func__, Status); - return Status; + return (Status); } - return Status; + return (Status); } -NTSTATUS get_reparse_point(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +get_reparse_point(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp) { NTSTATUS Status = STATUS_NOT_A_REPARSE_POINT; PFILE_OBJECT FileObject = IrpSp->FileObject; @@ -2313,7 +2606,8 @@ NTSTATUS get_reparse_point(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCA void *buffer = Irp->AssociatedIrp.SystemBuffer; struct vnode *vp; - if (FileObject == NULL) return STATUS_INVALID_PARAMETER; + if (FileObject == NULL) + return (STATUS_INVALID_PARAMETER); vp = FileObject->FsContext; @@ -2343,10 +2637,12 @@ NTSTATUS get_reparse_point(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCA VN_RELE(vp); } dprintf("%s: returning 0x%x\n", __func__, Status); - return Status; + return (Status); } -NTSTATUS set_reparse_point(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +set_reparse_point(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp) { NTSTATUS Status = STATUS_NOT_IMPLEMENTED; PFILE_OBJECT FileObject = IrpSp->FileObject; @@ -2356,23 +2652,24 @@ NTSTATUS set_reparse_point(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCA ULONG tag; struct vnode *vp = IrpSp->FileObject->FsContext; - if (!FileObject) - return STATUS_INVALID_PARAMETER; + if (!FileObject) + return (STATUS_INVALID_PARAMETER); if (Irp->UserBuffer) - return STATUS_INVALID_PARAMETER; + return (STATUS_INVALID_PARAMETER); - if (inlen < sizeof(ULONG)) { - return STATUS_INVALID_BUFFER_SIZE; + if (inlen < sizeof (ULONG)) { + return (STATUS_INVALID_BUFFER_SIZE); } Status = FsRtlValidateReparsePointBuffer(inlen, rdb); if (!NT_SUCCESS(Status)) { - dprintf("FsRtlValidateReparsePointBuffer returned %08x\n", Status); + dprintf("FsRtlValidateReparsePointBuffer returned %08x\n", + Status); goto out; } - RtlCopyMemory(&tag, buffer, sizeof(ULONG)); + RtlCopyMemory(&tag, buffer, sizeof (ULONG)); dprintf("Received tag 0x%x\n", tag); VN_HOLD(vp); @@ -2387,7 +2684,7 @@ NTSTATUS set_reparse_point(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCA zp->z_pflags |= ZFS_REPARSE; // Start TX and save FLAGS, SIZE and SYMLINK to disk. -top: +top: tx = dmu_tx_create(zfsvfs->z_os); dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE); err = dmu_tx_assign(tx, TXG_WAIT); @@ -2398,20 +2695,20 @@ NTSTATUS set_reparse_point(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCA goto out; } - (void)sa_update(zp->z_sa_hdl, SA_ZPL_FLAGS(zfsvfs), - &zp->z_pflags, sizeof(zp->z_pflags), tx); + (void) sa_update(zp->z_sa_hdl, SA_ZPL_FLAGS(zfsvfs), + &zp->z_pflags, sizeof (zp->z_pflags), tx); mutex_enter(&zp->z_lock); if (zp->z_is_sa) err = sa_update(zp->z_sa_hdl, SA_ZPL_SYMLINK(zfsvfs), - buffer, inlen, tx); + buffer, inlen, tx); else zfs_sa_symlink(zp, buffer, inlen, tx); mutex_exit(&zp->z_lock); zp->z_size = inlen; - (void)sa_update(zp->z_sa_hdl, SA_ZPL_SIZE(zfsvfs), - &zp->z_size, sizeof(zp->z_size), tx); + (void) sa_update(zp->z_sa_hdl, SA_ZPL_SIZE(zfsvfs), + &zp->z_size, sizeof (zp->z_size), tx); dmu_tx_commit(tx); @@ -2423,10 +2720,12 @@ NTSTATUS set_reparse_point(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCA dprintf("%s: returning 0x%x\n", __func__, Status); - return Status; + return (Status); } -NTSTATUS create_or_get_object_id(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +create_or_get_object_id(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp) { NTSTATUS Status = STATUS_NOT_IMPLEMENTED; PFILE_OBJECT FileObject = IrpSp->FileObject; @@ -2435,11 +2734,11 @@ NTSTATUS create_or_get_object_id(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STAC FILE_OBJECTID_BUFFER *fob = buffer; if (!FileObject) - return STATUS_INVALID_PARAMETER; + return (STATUS_INVALID_PARAMETER); - if (!fob || inlen < sizeof(FILE_OBJECTID_BUFFER)) { - Irp->IoStatus.Information = sizeof(FILE_OBJECTID_BUFFER); - return STATUS_BUFFER_OVERFLOW; + if (!fob || inlen < sizeof (FILE_OBJECTID_BUFFER)) { + Irp->IoStatus.Information = sizeof (FILE_OBJECTID_BUFFER); + return (STATUS_BUFFER_OVERFLOW); } struct vnode *vp = IrpSp->FileObject->FsContext; @@ -2450,18 +2749,20 @@ NTSTATUS create_or_get_object_id(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STAC // ObjectID is 16 bytes to identify the file // Should we do endian work here? // znode id + pool guid - RtlCopyMemory(&fob->ObjectId[0], &zp->z_id, sizeof(UINT64)); + RtlCopyMemory(&fob->ObjectId[0], &zp->z_id, sizeof (UINT64)); uint64_t guid = dmu_objset_fsid_guid(zfsvfs->z_os); - RtlCopyMemory(&fob->ObjectId[sizeof(UINT64)], &guid, sizeof(UINT64)); + RtlCopyMemory(&fob->ObjectId[sizeof (UINT64)], &guid, sizeof (UINT64)); VN_RELE(vp); - Irp->IoStatus.Information = sizeof(FILE_OBJECTID_BUFFER); + Irp->IoStatus.Information = sizeof (FILE_OBJECTID_BUFFER); Status = STATUS_SUCCESS; - return Status; + return (Status); } -NTSTATUS user_fs_request(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +user_fs_request(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp) { NTSTATUS Status = STATUS_NOT_IMPLEMENTED; @@ -2515,7 +2816,8 @@ NTSTATUS user_fs_request(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATI break; } - if (IrpSp->Parameters.FileSystemControl.OutputBufferLength < sizeof(ULONG)) { + if (IrpSp->Parameters.FileSystemControl.OutputBufferLength < + sizeof (ULONG)) { Status = STATUS_INVALID_PARAMETER; break; } @@ -2523,7 +2825,7 @@ NTSTATUS user_fs_request(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATI *VolumeState = 0; if (0) SetFlag(*VolumeState, VOLUME_IS_DIRTY); - Irp->IoStatus.Information = sizeof(ULONG); + Irp->IoStatus.Information = sizeof (ULONG); Status = STATUS_SUCCESS; break; case FSCTL_GET_REPARSE_POINT: @@ -2539,15 +2841,20 @@ NTSTATUS user_fs_request(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATI Status = create_or_get_object_id(DeviceObject, Irp, IrpSp); break; case FSCTL_REQUEST_OPLOCK: - dprintf(" FSCTL_REQUEST_OPLOCK: \n" ); -#if 0 //not yet, store oplock in znode, init on open etc. - PREQUEST_OPLOCK_INPUT_BUFFER *req = Irp->AssociatedIrp.SystemBuffer; - int InputBufferLength = IrpSp->Parameters.FileSystemControl.InputBufferLength; - int OutputBufferLength = IrpSp->Parameters.FileSystemControl.OutputBufferLength; - - if ((InputBufferLength < sizeof(REQUEST_OPLOCK_INPUT_BUFFER)) || - (OutputBufferLength < sizeof(REQUEST_OPLOCK_OUTPUT_BUFFER))) { - return STATUS_BUFFER_TOO_SMALL; + dprintf(" FSCTL_REQUEST_OPLOCK: \n"); +#if 0 // not yet, store oplock in znode, init on open etc. + PREQUEST_OPLOCK_INPUT_BUFFER *req = + Irp->AssociatedIrp.SystemBuffer; + int InputBufferLength = + IrpSp->Parameters.FileSystemControl.InputBufferLength; + int OutputBufferLength = + IrpSp->Parameters.FileSystemControl.OutputBufferLength; + + if ((InputBufferLength < + sizeof (REQUEST_OPLOCK_INPUT_BUFFER)) || + (OutputBufferLength < + sizeof (REQUEST_OPLOCK_OUTPUT_BUFFER))) { + return (STATUS_BUFFER_TOO_SMALL); } OPLOCK oplock; FsRtlInitializeOplock(&oplock); @@ -2558,44 +2865,60 @@ NTSTATUS user_fs_request(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATI dprintf(" FSCTL_FILESYSTEM_GET_STATISTICS: \n"); FILESYSTEM_STATISTICS *fss = Irp->AssociatedIrp.SystemBuffer; - // btrfs: This is hideously wrong, but at least it stops SMB from breaking + // btrfs: This is hideously wrong, but at least it stops SMB + // from breaking - if (IrpSp->Parameters.FileSystemControl.OutputBufferLength < sizeof(FILESYSTEM_STATISTICS)) - return STATUS_BUFFER_TOO_SMALL; + if (IrpSp->Parameters.FileSystemControl.OutputBufferLength < + sizeof (FILESYSTEM_STATISTICS)) + return (STATUS_BUFFER_TOO_SMALL); - memset(fss, 0, sizeof(FILESYSTEM_STATISTICS)); + memset(fss, 0, sizeof (FILESYSTEM_STATISTICS)); fss->Version = 1; fss->FileSystemType = FILESYSTEM_STATISTICS_TYPE_NTFS; - fss->SizeOfCompleteStructure = sizeof(FILESYSTEM_STATISTICS); + fss->SizeOfCompleteStructure = sizeof (FILESYSTEM_STATISTICS); - Irp->IoStatus.Information = sizeof(FILESYSTEM_STATISTICS); + Irp->IoStatus.Information = sizeof (FILESYSTEM_STATISTICS); Status = STATUS_SUCCESS; break; case FSCTL_QUERY_DEPENDENT_VOLUME: dprintf(" FSCTL_QUERY_DEPENDENT_VOLUME: \n"); - STORAGE_QUERY_DEPENDENT_VOLUME_REQUEST *req = Irp->AssociatedIrp.SystemBuffer; - dprintf("RequestLevel %d: RequestFlags 0x%x\n", req->RequestLevel, req->RequestFlags); -//#define QUERY_DEPENDENT_VOLUME_REQUEST_FLAG_HOST_VOLUMES 0x1 -//#define QUERY_DEPENDENT_VOLUME_REQUEST_FLAG_GUEST_VOLUMES 0x2 - STORAGE_QUERY_DEPENDENT_VOLUME_LEV1_ENTRY *lvl1 = Irp->AssociatedIrp.SystemBuffer; - STORAGE_QUERY_DEPENDENT_VOLUME_LEV2_ENTRY *lvl2 = Irp->AssociatedIrp.SystemBuffer; + STORAGE_QUERY_DEPENDENT_VOLUME_REQUEST *req = + Irp->AssociatedIrp.SystemBuffer; + dprintf("RequestLevel %d: RequestFlags 0x%x\n", + req->RequestLevel, req->RequestFlags); +// #define QUERY_DEPENDENT_VOLUME_REQUEST_FLAG_HOST_VOLUMES 0x1 +// #define QUERY_DEPENDENT_VOLUME_REQUEST_FLAG_GUEST_VOLUMES 0x2 + STORAGE_QUERY_DEPENDENT_VOLUME_LEV1_ENTRY *lvl1 = + Irp->AssociatedIrp.SystemBuffer; + STORAGE_QUERY_DEPENDENT_VOLUME_LEV2_ENTRY *lvl2 = + Irp->AssociatedIrp.SystemBuffer; switch (req->RequestLevel) { case 1: - if (IrpSp->Parameters.FileSystemControl.OutputBufferLength < sizeof(STORAGE_QUERY_DEPENDENT_VOLUME_LEV1_ENTRY)) - return STATUS_BUFFER_TOO_SMALL; - memset(lvl1, 0, sizeof(STORAGE_QUERY_DEPENDENT_VOLUME_LEV1_ENTRY)); - lvl1->EntryLength = sizeof(STORAGE_QUERY_DEPENDENT_VOLUME_LEV1_ENTRY); - Irp->IoStatus.Information = sizeof(STORAGE_QUERY_DEPENDENT_VOLUME_LEV1_ENTRY); + if (IrpSp-> + Parameters.FileSystemControl.OutputBufferLength < + sizeof (STORAGE_QUERY_DEPENDENT_VOLUME_LEV1_ENTRY)) + return (STATUS_BUFFER_TOO_SMALL); + memset(lvl1, 0, + sizeof (STORAGE_QUERY_DEPENDENT_VOLUME_LEV1_ENTRY)); + lvl1->EntryLength = + sizeof (STORAGE_QUERY_DEPENDENT_VOLUME_LEV1_ENTRY); + Irp->IoStatus.Information = + sizeof (STORAGE_QUERY_DEPENDENT_VOLUME_LEV1_ENTRY); Status = STATUS_SUCCESS; break; case 2: - if (IrpSp->Parameters.FileSystemControl.OutputBufferLength < sizeof(STORAGE_QUERY_DEPENDENT_VOLUME_LEV2_ENTRY)) - return STATUS_BUFFER_TOO_SMALL; - memset(lvl2, 0, sizeof(STORAGE_QUERY_DEPENDENT_VOLUME_LEV2_ENTRY)); - lvl2->EntryLength = sizeof(STORAGE_QUERY_DEPENDENT_VOLUME_LEV2_ENTRY); - Irp->IoStatus.Information = sizeof(STORAGE_QUERY_DEPENDENT_VOLUME_LEV2_ENTRY); + if (IrpSp-> + Parameters.FileSystemControl.OutputBufferLength < + sizeof (STORAGE_QUERY_DEPENDENT_VOLUME_LEV2_ENTRY)) + return (STATUS_BUFFER_TOO_SMALL); + memset(lvl2, 0, + sizeof (STORAGE_QUERY_DEPENDENT_VOLUME_LEV2_ENTRY)); + lvl2->EntryLength = + sizeof (STORAGE_QUERY_DEPENDENT_VOLUME_LEV2_ENTRY); + Irp->IoStatus.Information = + sizeof (STORAGE_QUERY_DEPENDENT_VOLUME_LEV2_ENTRY); Status = STATUS_SUCCESS; break; default: @@ -2605,19 +2928,25 @@ NTSTATUS user_fs_request(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATI break; default: - dprintf("* %s: unknown class 0x%x\n", __func__, IrpSp->Parameters.FileSystemControl.FsControlCode); + dprintf("* %s: unknown class 0x%x\n", __func__, + IrpSp->Parameters.FileSystemControl.FsControlCode); break; } - return Status; + return (Status); } -NTSTATUS query_directory_FileFullDirectoryInformation(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +query_directory_FileFullDirectoryInformation(PDEVICE_OBJECT DeviceObject, + PIRP Irp, PIO_STACK_LOCATION IrpSp) { - //FILE_FULL_DIR_INFORMATION *outptr = Irp->UserBuffer; - int flag_index_specified = IrpSp->Flags & SL_INDEX_SPECIFIED ? 1 : 0; - int flag_restart_scan = IrpSp->Flags & SL_RESTART_SCAN ? 1 : 0; - int flag_return_single_entry = IrpSp->Flags & SL_RETURN_SINGLE_ENTRY ? 1 : 0; + // FILE_FULL_DIR_INFORMATION *outptr = Irp->UserBuffer; + int flag_index_specified = + IrpSp->Flags & SL_INDEX_SPECIFIED ? 1 : 0; + int flag_restart_scan = + IrpSp->Flags & SL_RESTART_SCAN ? 1 : 0; + int flag_return_single_entry = + IrpSp->Flags & SL_RETURN_SINGLE_ENTRY ? 1 : 0; int bytes_out = 0; int index = 0; uio_t *uio; @@ -2629,39 +2958,40 @@ NTSTATUS query_directory_FileFullDirectoryInformation(PDEVICE_OBJECT DeviceObjec NTSTATUS Status = STATUS_NO_SUCH_FILE; if ((Irp->UserBuffer == NULL && Irp->MdlAddress == NULL) || - IrpSp->Parameters.QueryDirectory.Length <= 0) - return STATUS_INSUFFICIENT_RESOURCES; + IrpSp->Parameters.QueryDirectory.Length <= 0) + return (STATUS_INSUFFICIENT_RESOURCES); - if (IrpSp->FileObject == NULL || - IrpSp->FileObject->FsContext == NULL || // vnode - IrpSp->FileObject->FsContext2 == NULL) // ccb - return STATUS_INVALID_PARAMETER; + if (IrpSp->FileObject == NULL || + IrpSp->FileObject->FsContext == NULL || // vnode + IrpSp->FileObject->FsContext2 == NULL) // ccb + return (STATUS_INVALID_PARAMETER); struct vnode *dvp = IrpSp->FileObject->FsContext; zfs_dirlist_t *zccb = IrpSp->FileObject->FsContext2; if (zccb->magic != ZFS_DIRLIST_MAGIC) - return STATUS_INVALID_PARAMETER; + return (STATUS_INVALID_PARAMETER); // Restarting listing? Clear EOF if (flag_restart_scan) { zccb->dir_eof = 0; zccb->uio_offset = 0; if (zccb->searchname.Buffer != NULL) - kmem_free(zccb->searchname.Buffer, zccb->searchname.MaximumLength); + kmem_free(zccb->searchname.Buffer, + zccb->searchname.MaximumLength); zccb->searchname.Buffer = NULL; zccb->searchname.MaximumLength = 0; } // Did last call complete listing? if (zccb->dir_eof) - return STATUS_NO_MORE_FILES; + return (STATUS_NO_MORE_FILES); - uio = uio_create(1, zccb->uio_offset, UIO_SYSSPACE, UIO_READ); + uio = uio_create(1, zccb->uio_offset, UIO_SYSSPACE, UIO_READ); void *SystemBuffer = MapUserBuffer(Irp); - uio_addiov(uio, (user_addr_t)SystemBuffer, - IrpSp->Parameters.QueryDirectory.Length); + uio_addiov(uio, (user_addr_t)SystemBuffer, + IrpSp->Parameters.QueryDirectory.Length); // Grab the root zp zmo = DeviceObject->DeviceExtension; @@ -2669,54 +2999,71 @@ NTSTATUS query_directory_FileFullDirectoryInformation(PDEVICE_OBJECT DeviceObjec zfsvfs = vfs_fsprivate(zmo); // or from zp - if (!zfsvfs) return STATUS_INTERNAL_ERROR; + if (!zfsvfs) + return (STATUS_INTERNAL_ERROR); - dprintf("%s: starting vp %p Search pattern '%wZ' type %d: saved search '%wZ'\n", __func__, dvp, - IrpSp->Parameters.QueryDirectory.FileName, - IrpSp->Parameters.QueryDirectory.FileInformationClass, - &zccb->searchname); + dprintf("%s: starting vp %p Search pattern '%wZ' type %d: " + "saved search '%wZ'\n", __func__, dvp, + IrpSp->Parameters.QueryDirectory.FileName, + IrpSp->Parameters.QueryDirectory.FileInformationClass, + &zccb->searchname); if (IrpSp->Parameters.QueryDirectory.FileName && - IrpSp->Parameters.QueryDirectory.FileName->Buffer && - IrpSp->Parameters.QueryDirectory.FileName->Length != 0 && - wcsncmp(IrpSp->Parameters.QueryDirectory.FileName->Buffer, L"*", 1) != 0) { - // Save the pattern in the zccb, as it is only given in the first call (citation needed) + IrpSp->Parameters.QueryDirectory.FileName->Buffer && + IrpSp->Parameters.QueryDirectory.FileName->Length != 0 && + wcsncmp(IrpSp->Parameters.QueryDirectory.FileName->Buffer, + L"*", 1) != 0) { + // Save the pattern in the zccb, as it is only given in the + // first call (citation needed) // If exists, we should free? if (zccb->searchname.Buffer != NULL) - kmem_free(zccb->searchname.Buffer, zccb->searchname.MaximumLength); - - zccb->ContainsWildCards = - FsRtlDoesNameContainWildCards(IrpSp->Parameters.QueryDirectory.FileName); - zccb->searchname.MaximumLength = IrpSp->Parameters.QueryDirectory.FileName->Length + 2; // Make room for terminator, if needed - zccb->searchname.Length = IrpSp->Parameters.QueryDirectory.FileName->Length; - zccb->searchname.Buffer = kmem_alloc(zccb->searchname.MaximumLength, KM_SLEEP); + kmem_free(zccb->searchname.Buffer, + zccb->searchname.MaximumLength); + + zccb->ContainsWildCards = FsRtlDoesNameContainWildCards( + IrpSp->Parameters.QueryDirectory.FileName); + zccb->searchname.MaximumLength = + IrpSp->Parameters.QueryDirectory.FileName->Length + 2; + zccb->searchname.Length = + IrpSp->Parameters.QueryDirectory.FileName->Length; + zccb->searchname.Buffer = + kmem_alloc(zccb->searchname.MaximumLength, + KM_SLEEP); if (zccb->ContainsWildCards) { - Status = RtlUpcaseUnicodeString(&zccb->searchname, IrpSp->Parameters.QueryDirectory.FileName, FALSE); + Status = RtlUpcaseUnicodeString(&zccb->searchname, + IrpSp->Parameters.QueryDirectory.FileName, FALSE); } else { - RtlCopyMemory(zccb->searchname.Buffer, IrpSp->Parameters.QueryDirectory.FileName->Buffer, zccb->searchname.Length); + RtlCopyMemory(zccb->searchname.Buffer, + IrpSp->Parameters.QueryDirectory.FileName->Buffer, + zccb->searchname.Length); } - dprintf("%s: setting up search '%wZ' (wildcards: %d) status 0x%x\n", __func__, - &zccb->searchname, zccb->ContainsWildCards, Status); + dprintf("%s: setting up search '%wZ' (wildcards: %d) " + "status 0x%x\n", __func__, + &zccb->searchname, zccb->ContainsWildCards, Status); } VN_HOLD(dvp); - ret = zfs_readdir(dvp, uio, NULL, zccb, IrpSp->Flags, IrpSp->Parameters.QueryDirectory.FileInformationClass, &numdirent); + ret = zfs_readdir(dvp, uio, NULL, zccb, IrpSp->Flags, + IrpSp->Parameters.QueryDirectory.FileInformationClass, &numdirent); VN_RELE(dvp); if (ret == 0) { // Set correct buffer size returned. - Irp->IoStatus.Information = IrpSp->Parameters.QueryDirectory.Length - uio_resid(uio); + Irp->IoStatus.Information = + IrpSp->Parameters.QueryDirectory.Length - uio_resid(uio); - dprintf("dirlist information in %d out size %d\n", - IrpSp->Parameters.QueryDirectory.Length, Irp->IoStatus.Information); + dprintf("dirlist information in %d out size %d\n", + IrpSp->Parameters.QueryDirectory.Length, + Irp->IoStatus.Information); - // Return saying there are entries in buffer, or, ] - // if we sent same data previously, but now EOF send NO MORE, - // or if there was nothing sent at all (search pattern failed), send NO SUCH +// Return saying there are entries in buffer, or, ] +// if we sent same data previously, but now EOF send NO MORE, +// or if there was nothing sent at all (search pattern failed), send NO SUCH if (Irp->IoStatus.Information == 0) - Status = (zccb->uio_offset == 0) ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES; + Status = (zccb->uio_offset == 0) ? STATUS_NO_SUCH_FILE : + STATUS_NO_MORE_FILES; else Status = STATUS_SUCCESS; @@ -2728,17 +3075,20 @@ NTSTATUS query_directory_FileFullDirectoryInformation(PDEVICE_OBJECT DeviceObjec // Release uio uio_free(uio); - return Status; + return (Status); } -NTSTATUS query_directory(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +query_directory(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp) { NTSTATUS Status = STATUS_NOT_IMPLEMENTED; switch (IrpSp->Parameters.QueryDirectory.FileInformationClass) { - // The type is now passed into zfs_vnop.c/zfs_readdir() so check there for support + // The type is now passed into zfs_vnop.c/zfs_readdir() + // so check there for support case FileBothDirectoryInformation: case FileDirectoryInformation: case FileFullDirectoryInformation: // *** @@ -2746,23 +3096,31 @@ NTSTATUS query_directory(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATI case FileIdFullDirectoryInformation: case FileNamesInformation: case FileObjectIdInformation: - Status = query_directory_FileFullDirectoryInformation(DeviceObject, Irp, IrpSp); + Status = + query_directory_FileFullDirectoryInformation(DeviceObject, + Irp, IrpSp); break; case FileQuotaInformation: - dprintf(" %s FileQuotaInformation *NotImplemented\n", __func__); + dprintf(" %s FileQuotaInformation *NotImplemented\n", + __func__); break; case FileReparsePointInformation: - dprintf(" %s FileReparsePointInformation *NotImplemented\n", __func__); + dprintf(" %s FileReparsePointInformation *NotImplemented\n", + __func__); break; default: - dprintf(" %s unknown 0x%x *NotImplemented\n", __func__, IrpSp->Parameters.QueryDirectory.FileInformationClass); + dprintf(" %s unknown 0x%x *NotImplemented\n", + __func__, + IrpSp->Parameters.QueryDirectory.FileInformationClass); break; } - return Status; + return (Status); } -NTSTATUS notify_change_directory(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +notify_change_directory(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp) { PFILE_OBJECT fileObject = IrpSp->FileObject; mount_t *zmo; @@ -2771,7 +3129,7 @@ NTSTATUS notify_change_directory(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STAC zmo = DeviceObject->DeviceExtension; ASSERT(zmo != NULL); if (zmo->type != MOUNT_TYPE_VCB) { - return STATUS_INVALID_PARAMETER; + return (STATUS_INVALID_PARAMETER); } struct vnode *vp = fileObject->FsContext; @@ -2783,48 +3141,58 @@ NTSTATUS notify_change_directory(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STAC if (!vnode_isdir(vp)) { VN_RELE(vp); - return STATUS_INVALID_PARAMETER; + return (STATUS_INVALID_PARAMETER); } if (zccb && zccb->deleteonclose) { VN_RELE(vp); - return STATUS_DELETE_PENDING; + return (STATUS_DELETE_PENDING); } ASSERT(zmo->NotifySync != NULL); - dprintf("%s: '%s' for %wZ\n", __func__, zp&&zp->z_name_cache?zp->z_name_cache:"", &fileObject->FileName); + dprintf("%s: '%s' for %wZ\n", __func__, + zp&&zp->z_name_cache?zp->z_name_cache:"", &fileObject->FileName); FsRtlNotifyFullChangeDirectory( - zmo->NotifySync, &zmo->DirNotifyList, zp, (PSTRING)&fileObject->FileName, - (IrpSp->Flags & SL_WATCH_TREE) ? TRUE : FALSE, FALSE, - IrpSp->Parameters.NotifyDirectory.CompletionFilter, Irp, NULL, NULL); + zmo->NotifySync, &zmo->DirNotifyList, zp, + (PSTRING)&fileObject->FileName, + (IrpSp->Flags & SL_WATCH_TREE) ? TRUE : FALSE, FALSE, + IrpSp->Parameters.NotifyDirectory.CompletionFilter, Irp, + NULL, NULL); VN_RELE(vp); - return STATUS_PENDING; + return (STATUS_PENDING); } -NTSTATUS set_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +set_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp) { NTSTATUS Status = STATUS_NOT_IMPLEMENTED; Irp->IoStatus.Information = 0; switch (IrpSp->Parameters.SetFile.FileInformationClass) { - case FileAllocationInformation: + case FileAllocationInformation: if (IrpSp->FileObject && IrpSp->FileObject->FsContext) { - FILE_ALLOCATION_INFORMATION *feofi = Irp->AssociatedIrp.SystemBuffer; - dprintf("* SET FileAllocationInformation %u\n", feofi->AllocationSize.QuadPart); - // This is a noop at the moment. It makes Windows Explorer and apps not crash - // From the documentation, setting the allocation size smaller than EOF should shrink it: - // https://msdn.microsoft.com/en-us/library/windows/desktop/aa364214(v=vs.85).aspx - // However, NTFS doesn't do that! It keeps the size the same. - // Setting a FileAllocationInformation larger than current EOF size does not have a observable affect from user space. + FILE_ALLOCATION_INFORMATION *feofi = + Irp->AssociatedIrp.SystemBuffer; + dprintf("* SET FileAllocationInformation %u\n", + feofi->AllocationSize.QuadPart); +// This is a noop at the moment. It makes Windows Explorer and apps not crash +// From the documentation, setting the allocation size smaller than EOF +// should shrink it: +// msdn.microsoft.com/en-us/library/windows/desktop/aa364214(v=vs.85).aspx +// However, NTFS doesn't do that! It keeps the size the same. +// Setting a FileAllocationInformation larger than current EOF size does +// not have a observable affect from user space. Status = STATUS_SUCCESS; } break; case FileBasicInformation: // chmod dprintf("* SET FileBasicInformation\n"); if (IrpSp->FileObject && IrpSp->FileObject->FsContext) { - FILE_BASIC_INFORMATION *fbi = Irp->AssociatedIrp.SystemBuffer; + FILE_BASIC_INFORMATION *fbi = + Irp->AssociatedIrp.SystemBuffer; struct vnode *vp = IrpSp->FileObject->FsContext; VN_HOLD(vp); @@ -2832,35 +3200,47 @@ NTSTATUS set_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATI vattr_t va = { 0 }; uint64_t unixtime[2] = { 0 }; - // can request that the file system not update .. LastAccessTime, LastWriteTime, and ChangeTime .. setting the appropriate members to -1. - // ie, LastAccessTime = -1 -> atime = disabled - not implemented - // LastAccessTime = -2 -> cancel the disable (-1), return to normal. - // a value of "0" means to keep existing value. +// can request that the file system not update .. LastAccessTime, +// LastWriteTime, and ChangeTime .. setting the appropriate members to -1. +// ie, LastAccessTime = -1 -> atime = disabled - not implemented +// LastAccessTime = -2 -> cancel the disable (-1), return to normal. +// a value of "0" means to keep existing value. if (fbi->ChangeTime.QuadPart > 0) { - TIME_WINDOWS_TO_UNIX(fbi->ChangeTime.QuadPart, unixtime); - va.va_change_time.tv_sec = unixtime[0]; va.va_change_time.tv_nsec = unixtime[1]; + TIME_WINDOWS_TO_UNIX(fbi->ChangeTime.QuadPart, + unixtime); + va.va_change_time.tv_sec = unixtime[0]; + va.va_change_time.tv_nsec = unixtime[1]; va.va_active |= ATTR_CTIME; } if (fbi->LastWriteTime.QuadPart > 0) { - TIME_WINDOWS_TO_UNIX(fbi->LastWriteTime.QuadPart, unixtime); - va.va_modify_time.tv_sec = unixtime[0]; va.va_modify_time.tv_nsec = unixtime[1]; + TIME_WINDOWS_TO_UNIX( + fbi->LastWriteTime.QuadPart, + unixtime); + va.va_modify_time.tv_sec = unixtime[0]; + va.va_modify_time.tv_nsec = unixtime[1]; va.va_active |= ATTR_MTIME; } if (fbi->CreationTime.QuadPart > 0) { - TIME_WINDOWS_TO_UNIX(fbi->CreationTime.QuadPart, unixtime); - va.va_create_time.tv_sec = unixtime[0]; va.va_create_time.tv_nsec = unixtime[1]; + TIME_WINDOWS_TO_UNIX(fbi->CreationTime.QuadPart, + unixtime); + va.va_create_time.tv_sec = unixtime[0]; + va.va_create_time.tv_nsec = unixtime[1]; va.va_active |= ATTR_CRTIME; // ATTR_CRTIME } - if (fbi->LastAccessTime.QuadPart > 0) - TIME_WINDOWS_TO_UNIX(fbi->LastAccessTime.QuadPart, zp->z_atime); + if (fbi->LastAccessTime.QuadPart > 0) + TIME_WINDOWS_TO_UNIX( + fbi->LastAccessTime.QuadPart, + zp->z_atime); if (fbi->FileAttributes) - if (zfs_setwinflags(VTOZ(vp), fbi->FileAttributes)) + if (zfs_setwinflags(VTOZ(vp), + fbi->FileAttributes)) va.va_active |= ATTR_MODE; Status = zfs_setattr(zp, &va, 0, NULL); - // zfs_setattr will turn ARCHIVE back on, when perhaps it is set off by this call + // zfs_setattr will turn ARCHIVE back on, when perhaps + // it is set off by this call if (fbi->FileAttributes) zfs_setwinflags(zp, fbi->FileAttributes); @@ -2881,31 +3261,33 @@ NTSTATUS set_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATI dprintf("* SET FilePositionInformation NOTIMPLEMENTED\n"); break; case FileRenameInformation: // vnop_rename - case FileRenameInformationEx: + case FileRenameInformationEx: Status = file_rename_information(DeviceObject, Irp, IrpSp); break; case FileValidDataLengthInformation: // truncate? - dprintf("* SET FileValidDataLengthInformation NOTIMPLEMENTED\n"); + dprintf("* SET FileValidDataLengthInformation NOTIMP\n"); break; case FileDispositionInformationEx: - Status = file_disposition_information_ex(DeviceObject, Irp, IrpSp); + Status = file_disposition_information_ex(DeviceObject, Irp, + IrpSp); break; default: dprintf("* %s: unknown type NOTIMPLEMENTED\n", __func__); break; } - return Status; + return (Status); } -NTSTATUS fs_read(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +fs_read(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) { PFILE_OBJECT fileObject; ULONG bufferLength; LARGE_INTEGER byteOffset; NTSTATUS Status = STATUS_SUCCESS; - int error; + int error; int nocache = Irp->Flags & IRP_NOCACHE; int pagingio = FlagOn(Irp->Flags, IRP_PAGING_IO); int releaselock = 0; @@ -2917,37 +3299,41 @@ NTSTATUS fs_read(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp CcMdlReadComplete(IrpSp->FileObject, Irp->MdlAddress); // Mdl is now deallocated. Irp->MdlAddress = NULL; - return STATUS_SUCCESS; + return (STATUS_SUCCESS); } #if 0 - dprintf(" %s minor type %d flags 0x%x mdl %d System %d User %d paging %d\n", __func__, IrpSp->MinorFunction, - DeviceObject->Flags, (Irp->MdlAddress != 0), (Irp->AssociatedIrp.SystemBuffer != 0), - (Irp->UserBuffer != 0), - FlagOn(Irp->Flags, IRP_PAGING_IO)); + dprintf(" %s minor type %d flags 0x%x mdl %d System %d " + "User %d paging %d\n", __func__, IrpSp->MinorFunction, + DeviceObject->Flags, (Irp->MdlAddress != 0), + (Irp->AssociatedIrp.SystemBuffer != 0), + (Irp->UserBuffer != 0), + FlagOn(Irp->Flags, IRP_PAGING_IO)); #endif if (zfs_disable_wincache) nocache = 1; bufferLength = IrpSp->Parameters.Read.Length; if (bufferLength == 0) - return STATUS_SUCCESS; + return (STATUS_SUCCESS); fileObject = IrpSp->FileObject; - // File may have been closed, but CC mgr setting section will ask to read + // File may have been closed, but CC mgr setting section + // will ask to read if (fileObject == NULL || fileObject->FsContext == NULL) { dprintf(" fileObject == NULL\n"); - //ASSERT0("fileobject == NULL"); - return STATUS_INVALID_PARAMETER; + // ASSERT0("fileobject == NULL"); + return (STATUS_INVALID_PARAMETER); } struct vnode *vp = fileObject->FsContext; VN_HOLD(vp); znode_t *zp = VTOZ(vp); - if (IrpSp->Parameters.Read.ByteOffset.LowPart == FILE_USE_FILE_POINTER_POSITION && - IrpSp->Parameters.Read.ByteOffset.HighPart == -1) { + if (IrpSp->Parameters.Read.ByteOffset.LowPart == + FILE_USE_FILE_POINTER_POSITION && + IrpSp->Parameters.Read.ByteOffset.HighPart == -1) { byteOffset = fileObject->CurrentByteOffset; } else { byteOffset = IrpSp->Parameters.Read.ByteOffset; @@ -2968,21 +3354,23 @@ NTSTATUS fs_read(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp // nocache transfer, make sure we flush first. if (!pagingio && nocache && fileObject->SectionObjectPointer && - (fileObject->SectionObjectPointer->DataSectionObject != NULL)) { + (fileObject->SectionObjectPointer->DataSectionObject != NULL)) { IO_STATUS_BLOCK IoStatus = { 0 }; - ExAcquireResourceExclusiveLite(vp->FileHeader.PagingIoResource, TRUE); + ExAcquireResourceExclusiveLite(vp->FileHeader.PagingIoResource, + TRUE); CcFlushCache(fileObject->SectionObjectPointer, - &byteOffset, - bufferLength, - &IoStatus); + &byteOffset, + bufferLength, + &IoStatus); ExReleaseResourceLite(vp->FileHeader.PagingIoResource); VERIFY0(IoStatus.Status); } // Grab lock if paging if (pagingio) { - ExAcquireResourceSharedLite(vp->FileHeader.PagingIoResource, TRUE); + ExAcquireResourceSharedLite(vp->FileHeader.PagingIoResource, + TRUE); releaselock = 1; - } + } void *SystemBuffer = MapUserBuffer(Irp); @@ -3007,24 +3395,25 @@ NTSTATUS fs_read(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp if (!FlagOn(IrpSp->MinorFunction, IRP_MN_MDL)) { vnode_pager_setsize(vp, zp->z_size); - CcSetFileSizes(IrpSp->FileObject, (PCC_FILE_SIZES)&vp->FileHeader.AllocationSize); + CcSetFileSizes(IrpSp->FileObject, + (PCC_FILE_SIZES)&vp->FileHeader.AllocationSize); vnode_setsizechange(vp, 0); #if (NTDDI_VERSION >= NTDDI_WIN8) if (!CcCopyReadEx(fileObject, - &byteOffset, - bufferLength, - TRUE, - SystemBuffer, - &Irp->IoStatus, - Irp->Tail.Overlay.Thread)) { + &byteOffset, + bufferLength, + TRUE, + SystemBuffer, + &Irp->IoStatus, + Irp->Tail.Overlay.Thread)) { #else if (!CcCopyRead(fileObject, - &byteOffset, - bufferLength, - TRUE, - SystemBuffer, - &Irp->IoStatus)) { + &byteOffset, + bufferLength, + TRUE, + SystemBuffer, + &Irp->IoStatus)) { #endif dprintf("CcCopyReadEx error\n"); } @@ -3037,10 +3426,10 @@ NTSTATUS fs_read(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp // MDL read CcMdlRead(fileObject, - &byteOffset, - bufferLength, - &Irp->MdlAddress, - &Irp->IoStatus); + &byteOffset, + bufferLength, + &Irp->MdlAddress, + &Irp->IoStatus); Status = Irp->IoStatus.Status; goto out; } // mdl @@ -3055,7 +3444,8 @@ NTSTATUS fs_read(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp ASSERT(SystemBuffer != NULL); uio_addiov(uio, (user_addr_t)SystemBuffer, bufferLength); - dprintf("%s: offset %llx size %lx\n", __func__, byteOffset.QuadPart, bufferLength); + dprintf("%s: offset %llx size %lx\n", __func__, + byteOffset.QuadPart, bufferLength); error = zfs_read(vp, uio, 0, NULL); @@ -3073,23 +3463,26 @@ NTSTATUS fs_read(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp VN_RELE(vp); // Update the file offset if ((Status == STATUS_SUCCESS) && - (fileObject->Flags & FO_SYNCHRONOUS_IO) && - !(Irp->Flags & IRP_PAGING_IO)) { - // update current byte offset only when synchronous IO and not pagind IO + (fileObject->Flags & FO_SYNCHRONOUS_IO) && + !(Irp->Flags & IRP_PAGING_IO)) { + // update current byte offset only when synchronous IO + // and not pagind IO fileObject->CurrentByteOffset.QuadPart = - byteOffset.QuadPart + Irp->IoStatus.Information; + byteOffset.QuadPart + Irp->IoStatus.Information; } if (releaselock) ExReleaseResourceLite(vp->FileHeader.PagingIoResource); -// dprintf(" FileName: %wZ offset 0x%llx len 0x%lx mdl %p System %p\n", &fileObject->FileName, - // byteOffset.QuadPart, bufferLength, Irp->MdlAddress, Irp->AssociatedIrp.SystemBuffer); +// dprintf(" FileName: %wZ offset 0x%llx len 0x%lx mdl %p System %p\n", +// &fileObject->FileName, byteOffset.QuadPart, +// bufferLength, Irp->MdlAddress, Irp->AssociatedIrp.SystemBuffer); - return Status; + return (Status); } -NTSTATUS fs_write(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +fs_write(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) { PFILE_OBJECT fileObject; ULONG bufferLength; @@ -3106,29 +3499,32 @@ NTSTATUS fs_write(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpS if (FlagOn(IrpSp->MinorFunction, IRP_MN_COMPLETE)) { dprintf("%s: IRP_MN_COMPLETE\n", __func__); - CcMdlWriteComplete(IrpSp->FileObject, &IrpSp->Parameters.Write.ByteOffset, Irp->MdlAddress); + CcMdlWriteComplete(IrpSp->FileObject, + &IrpSp->Parameters.Write.ByteOffset, Irp->MdlAddress); // Mdl is now deallocated. Irp->MdlAddress = NULL; - return STATUS_SUCCESS; + return (STATUS_SUCCESS); } -// dprintf(" %s paging %d\n", __func__, FlagOn(Irp->Flags, IRP_PAGING_IO)); + #if 0 - xprintf(" %s minor type %d flags 0x%x mdl %d System %d User %d paging %d\n", __func__, IrpSp->MinorFunction, - DeviceObject->Flags, (Irp->MdlAddress != 0), (Irp->AssociatedIrp.SystemBuffer != 0), - (Irp->UserBuffer != 0), - FlagOn(Irp->Flags, IRP_PAGING_IO)); + xprintf(" %s minor type %d flags 0x%x mdl %d System %d " + "User %d paging %d\n", __func__, IrpSp->MinorFunction, + DeviceObject->Flags, (Irp->MdlAddress != 0), + (Irp->AssociatedIrp.SystemBuffer != 0), + (Irp->UserBuffer != 0), + FlagOn(Irp->Flags, IRP_PAGING_IO)); #endif bufferLength = IrpSp->Parameters.Write.Length; if (bufferLength == 0) - return STATUS_SUCCESS; + return (STATUS_SUCCESS); fileObject = IrpSp->FileObject; if (fileObject == NULL || fileObject->FsContext == NULL) { dprintf(" fileObject == NULL\n"); ASSERT0("fileObject == NULL"); - return STATUS_INVALID_PARAMETER; + return (STATUS_INVALID_PARAMETER); } struct vnode *vp = fileObject->FsContext; @@ -3140,9 +3536,11 @@ NTSTATUS fs_write(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpS // Special encoding byteOffset = IrpSp->Parameters.Write.ByteOffset; if (IrpSp->Parameters.Write.ByteOffset.HighPart == -1) { - if (IrpSp->Parameters.Write.ByteOffset.LowPart == FILE_USE_FILE_POINTER_POSITION) { + if (IrpSp->Parameters.Write.ByteOffset.LowPart == + FILE_USE_FILE_POINTER_POSITION) { byteOffset = fileObject->CurrentByteOffset; - } else if (IrpSp->Parameters.Write.ByteOffset.LowPart == FILE_WRITE_TO_END_OF_FILE) { // APPEND + } else if (IrpSp->Parameters.Write.ByteOffset.LowPart == + FILE_WRITE_TO_END_OF_FILE) { // APPEND byteOffset.QuadPart = zp->z_size; } } @@ -3157,9 +3555,9 @@ NTSTATUS fs_write(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpS if (byteOffset.QuadPart + bufferLength > zp->z_size) bufferLength = zp->z_size - byteOffset.QuadPart; - //ASSERT(fileObject->PrivateCacheMap != NULL); + // ASSERT(fileObject->PrivateCacheMap != NULL); } - + if (!nocache && !CcCanIWrite(fileObject, bufferLength, TRUE, FALSE)) { Status = STATUS_PENDING; DbgBreakPoint(); @@ -3167,12 +3565,14 @@ NTSTATUS fs_write(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpS } if (nocache && !pagingio && fileObject->SectionObjectPointer && - fileObject->SectionObjectPointer->DataSectionObject) { + fileObject->SectionObjectPointer->DataSectionObject) { IO_STATUS_BLOCK iosb; - ExAcquireResourceExclusiveLite(vp->FileHeader.PagingIoResource, TRUE); + ExAcquireResourceExclusiveLite(vp->FileHeader.PagingIoResource, + TRUE); - CcFlushCache(fileObject->SectionObjectPointer, &byteOffset, bufferLength, &iosb); + CcFlushCache(fileObject->SectionObjectPointer, &byteOffset, + bufferLength, &iosb); if (!NT_SUCCESS(iosb.Status)) { ExReleaseResourceLite(vp->FileHeader.PagingIoResource); @@ -3180,7 +3580,8 @@ NTSTATUS fs_write(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpS goto out; } - CcPurgeCacheSection(fileObject->SectionObjectPointer, &byteOffset, bufferLength, FALSE); + CcPurgeCacheSection(fileObject->SectionObjectPointer, + &byteOffset, bufferLength, FALSE); ExReleaseResourceLite(vp->FileHeader.PagingIoResource); } @@ -3195,79 +3596,84 @@ NTSTATUS fs_write(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpS vnode_setsizechange(vp, 0); zfs_init_cache(fileObject, vp); - //CcSetReadAheadGranularity(fileObject, READ_AHEAD_GRANULARITY); + // CcSetReadAheadGranularity(fileObject, + // READ_AHEAD_GRANULARITY); } - // If beyond valid data, zero between to expand (this is cachedfile, not paging io, extend ok) + // If beyond valid data, zero between to expand + // (this is cachedfile, not paging io, extend ok) if (byteOffset.QuadPart + bufferLength > zp->z_size) { #if 0 LARGE_INTEGER ZeroStart, BeyondZeroEnd; ZeroStart.QuadPart = zp->z_size; - BeyondZeroEnd.QuadPart = IrpSp->Parameters.Write.ByteOffset.QuadPart + IrpSp->Parameters.Write.Length; + BeyondZeroEnd.QuadPart = + IrpSp->Parameters.Write.ByteOffset.QuadPart + + IrpSp->Parameters.Write.Length; dprintf("%s: growing file\n", __func__); - //CACHE_MANAGER(34) + // CACHE_MANAGER(34) // See the comment for FAT_FILE_SYSTEM(0x23) if (!CcZeroData(fileObject, - &ZeroStart, &BeyondZeroEnd, - TRUE)) { + &ZeroStart, &BeyondZeroEnd, + TRUE)) { dprintf("%s: CcZeroData failed\n", __func__); } #endif - // We have written "Length" into the "file" by the way of cache, so we need - // zp->z_size to reflect the new length, so we extend the file on disk, even though - // the actual writes will come later (from CcMgr). +// We have written "Length" into the "file" by the way of cache, so we need +// zp->z_size to reflect the new length, so we extend the file on disk, +// even though the actual writes will come later (from CcMgr). dprintf("%s: growing file\n", __func__); // zfs_freesp() calls vnode_pager_setsize(); Status = zfs_freesp(zp, - byteOffset.QuadPart, bufferLength, - FWRITE, B_TRUE); + byteOffset.QuadPart, bufferLength, + FWRITE, B_TRUE); ASSERT0(Status); - // Confirm size grown - //ASSERT(byteOffset.QuadPart + bufferLength == zp->z_size); } else { - //vnode_pager_setsize(vp, zp->z_size); + // vnode_pager_setsize(vp, zp->z_size); } // DO A NORMAL CACHED WRITE, if the MDL bit is not set, if (!FlagOn(IrpSp->MinorFunction, IRP_MN_MDL)) { - // Since we may have grown the filesize, we need to give CcMgr a head's up. +// Since we may have grown the filesize, we need to give CcMgr a head's up. vnode_pager_setsize(vp, zp->z_size); - CcSetFileSizes(fileObject, (PCC_FILE_SIZES)&vp->FileHeader.AllocationSize); + CcSetFileSizes(fileObject, + (PCC_FILE_SIZES)&vp->FileHeader.AllocationSize); vnode_setsizechange(vp, 0); - dprintf("CcWrite: offset [ 0x%llx - 0x%llx ] len 0x%lx\n", - byteOffset.QuadPart, byteOffset.QuadPart + bufferLength, bufferLength); + dprintf("CcWrite: offset [ 0x%llx - 0x%llx ] " + "len 0x%lx\n", byteOffset.QuadPart, + byteOffset.QuadPart + bufferLength, + bufferLength); #if (NTDDI_VERSION >= NTDDI_WIN8) if (!CcCopyWriteEx(fileObject, - &byteOffset, - bufferLength, - TRUE, - SystemBuffer, - Irp->Tail.Overlay.Thread)) { + &byteOffset, + bufferLength, + TRUE, + SystemBuffer, + Irp->Tail.Overlay.Thread)) { #else if (!CcCopyWrite(fileObject, - &byteOffset, - bufferLength, - TRUE, - SystemBuffer)) { + &byteOffset, + bufferLength, + TRUE, + SystemBuffer)) { #endif dprintf("Could not wait\n"); ASSERT0("failed copy"); } - //Irp->IoStatus.Status = STATUS_SUCCESS; + // Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = bufferLength; Status = STATUS_SUCCESS; goto out; } else { // DO AN MDL WRITE CcPrepareMdlWrite(fileObject, - &byteOffset, - bufferLength, - &Irp->MdlAddress, - &Irp->IoStatus); + &byteOffset, + bufferLength, + &Irp->MdlAddress, + &Irp->IoStatus); Status = Irp->IoStatus.Status; goto out; @@ -3278,17 +3684,20 @@ NTSTATUS fs_write(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpS uio = uio_create(1, byteOffset.QuadPart, UIO_SYSSPACE, UIO_WRITE); uio_addiov(uio, (user_addr_t)SystemBuffer, bufferLength); - //dprintf("%s: offset %llx size %lx\n", __func__, byteOffset.QuadPart, bufferLength); + // dprintf("%s: offset %llx size %lx\n", __func__, + // byteOffset.QuadPart, bufferLength); - dprintf("ZfsWrite: offset [ 0x%llx - 0x%llx ] len 0x%lx\n", - byteOffset.QuadPart, byteOffset.QuadPart + bufferLength, bufferLength); + dprintf("ZfsWrite: offset [ 0x%llx - 0x%llx ] len 0x%lx\n", + byteOffset.QuadPart, byteOffset.QuadPart + bufferLength, + bufferLength); if (FlagOn(Irp->Flags, IRP_PAGING_IO)) - error = zfs_write(vp, uio, 0, NULL); // Should we call vnop_pageout instead? + // Should we call vnop_pageout instead? + error = zfs_write(vp, uio, 0, NULL); else error = zfs_write(vp, uio, 0, NULL); - //if (error == 0) + // if (error == 0) // zp->z_pflags |= ZFS_ARCHIVE; // EOF? @@ -3303,38 +3712,45 @@ NTSTATUS fs_write(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpS // Update the file offset out: if ((Status == STATUS_SUCCESS) && - (fileObject->Flags & FO_SYNCHRONOUS_IO) && - !(Irp->Flags & IRP_PAGING_IO)) { + (fileObject->Flags & FO_SYNCHRONOUS_IO) && + !(Irp->Flags & IRP_PAGING_IO)) { fileObject->CurrentByteOffset.QuadPart = - byteOffset.QuadPart + Irp->IoStatus.Information; + byteOffset.QuadPart + Irp->IoStatus.Information; } VN_RELE(vp); -// dprintf(" FileName: %wZ offset 0x%llx len 0x%lx mdl %p System %p\n", &fileObject->FileName, -// byteOffset.QuadPart, bufferLength, Irp->MdlAddress, Irp->AssociatedIrp.SystemBuffer); +// dprintf(" FileName: %wZ offset 0x%llx len 0x%lx mdl %p System %p\n", +// &fileObject->FileName, byteOffset.QuadPart, bufferLength, +// Irp->MdlAddress, Irp->AssociatedIrp.SystemBuffer); // Unset the size-change, as we handled it directly in here vnode_setsizechange(vp, 0); - return Status; + return (Status); } /* * The lifetime of a delete. - * 1) If a file open is marked DELETE_ON_CLOSE in zfs_vnop_lookup() we will call - * vnode_setdeleteonclose(vp) to signal the intent. This is so file_standard_information - * can return DeletePending correctly (as well as a few more) - * 2) Upon IRP_MJ_CLEANUP (closing a file handle) we are expected to remove the file - * (as tested by IFStest.exe) we will call vnode_setdeleted(vp), this will: - * 3) Make zfs_vnop_lookup() return ENOENT when "setdeleted" is set. Making it appear - * as if the file was deleted - but retaining vp and zp as required by Windows. - * 4) Eventually IRP_MJ_CLOSE is called, and if final, we can release vp and zp, and - * if "setdeleted" was active, we can finally call delete_entry() to remove the file. + * 1) If a file open is marked DELETE_ON_CLOSE in zfs_vnop_lookup() we will + * call vnode_setdeleteonclose(vp) to signal the intent. This is so + * file_standard_information can return DeletePending correctly + * (as well as a few more) + * 2) Upon IRP_MJ_CLEANUP (closing a file handle) we are expected to remove + * the file (as tested by IFStest.exe) we will call vnode_setdeleted(vp), + * this will: + * 3) Make zfs_vnop_lookup() return ENOENT when "setdeleted" is set. + * Making it appear as if the file was deleted - but retaining vp and zp + * as required by Windows. + * 4) Eventually IRP_MJ_CLOSE is called, and if final, we can release + * vp and zp, and if "setdeleted" was active, we can finally call + * delete_entry() to remove the file. */ -NTSTATUS delete_entry(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +delete_entry(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) { - // In Unix, both zfs_unlink and zfs_rmdir expect a filename, and we do not have that here + // In Unix, both zfs_unlink and zfs_rmdir expect a filename, + // and we do not have that here struct vnode *vp = NULL, *dvp = NULL; int error; char filename[MAXNAMELEN]; @@ -3342,10 +3758,11 @@ NTSTATUS delete_entry(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION znode_t *zp = NULL; if (IrpSp->FileObject->FsContext == NULL || - IrpSp->FileObject->FileName.Buffer == NULL || - IrpSp->FileObject->FileName.Length == 0) { - dprintf("%s: called with missing arguments, can't delete\n", __func__); - return STATUS_INSTANCE_NOT_AVAILABLE; // FIXME + IrpSp->FileObject->FileName.Buffer == NULL || + IrpSp->FileObject->FileName.Length == 0) { + dprintf("%s: called with missing arguments, can't delete\n", + __func__); + return (STATUS_INSTANCE_NOT_AVAILABLE); // FIXME } vp = IrpSp->FileObject->FsContext; @@ -3358,26 +3775,27 @@ NTSTATUS delete_entry(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION // No dvp, lookup parent VERIFY(sa_lookup(zp->z_sa_hdl, SA_ZPL_PARENT(zp->z_zfsvfs), - &parent, sizeof(parent)) == 0); + &parent, sizeof (parent)) == 0); error = zfs_zget(zp->z_zfsvfs, parent, &dzp); if (error) - return STATUS_INSTANCE_NOT_AVAILABLE; // FIXME + return (STATUS_INSTANCE_NOT_AVAILABLE); // FIXME dvp = ZTOV(dzp); // Unfortunately, filename is littered with "\", clean it up, // or search based on ID to get name? dprintf("%s: deleting '%.*S'\n", __func__, - IrpSp->FileObject->FileName.Length / sizeof(WCHAR), - IrpSp->FileObject->FileName.Buffer); + IrpSp->FileObject->FileName.Length / sizeof (WCHAR), + IrpSp->FileObject->FileName.Buffer); error = RtlUnicodeToUTF8N(filename, MAXNAMELEN, &outlen, - IrpSp->FileObject->FileName.Buffer, IrpSp->FileObject->FileName.Length); - + IrpSp->FileObject->FileName.Buffer, + IrpSp->FileObject->FileName.Length); + if (error != STATUS_SUCCESS && - error != STATUS_SOME_NOT_MAPPED) { + error != STATUS_SOME_NOT_MAPPED) { VN_RELE(dvp); dprintf("%s: some illegal characters\n", __func__); - return STATUS_ILLEGAL_CHARACTER; + return (STATUS_ILLEGAL_CHARACTER); } while (outlen > 0 && filename[outlen - 1] == '\\') outlen--; filename[outlen] = 0; @@ -3397,7 +3815,7 @@ NTSTATUS delete_entry(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION vp = NULL; if (isdir) { - + error = zfs_rmdir(VTOZ(dvp), finalname, NULL, NULL, 0); } else { @@ -3413,19 +3831,19 @@ NTSTATUS delete_entry(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION VN_RELE(dvp); dprintf("%s: returning %d\n", __func__, error); - return error; + return (error); } -NTSTATUS flush_buffers(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +flush_buffers(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) { - PFILE_OBJECT FileObject = IrpSp->FileObject; NTSTATUS Status = 0; dprintf("%s: \n", __func__); if (FileObject == NULL || FileObject->FsContext == NULL) - return STATUS_INVALID_PARAMETER; + return (STATUS_INVALID_PARAMETER); struct vnode *vp = FileObject->FsContext; if (VN_HOLD(vp) == 0) { @@ -3434,10 +3852,11 @@ NTSTATUS flush_buffers(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION Status = zfs_vnop_ioctl_fullfsync(vp, NULL, zfsvfs); VN_RELE(vp); } - return Status; + return (Status); } -NTSTATUS query_security(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +query_security(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) { PFILE_OBJECT FileObject = IrpSp->FileObject; NTSTATUS Status; @@ -3445,7 +3864,7 @@ NTSTATUS query_security(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATIO dprintf("%s: \n", __func__); if (FileObject == NULL || FileObject->FsContext == NULL) - return STATUS_INVALID_PARAMETER; + return (STATUS_INVALID_PARAMETER); void *buf = MapUserBuffer(Irp); @@ -3455,25 +3874,27 @@ NTSTATUS query_security(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATIO sd = vnode_security(vp); ULONG buflen = IrpSp->Parameters.QuerySecurity.Length; Status = SeQuerySecurityDescriptorInfo( - &IrpSp->Parameters.QuerySecurity.SecurityInformation, - buf, - &buflen, - &sd); + &IrpSp->Parameters.QuerySecurity.SecurityInformation, + buf, + &buflen, + &sd); VN_RELE(vp); if (Status == STATUS_BUFFER_TOO_SMALL) { Status = STATUS_BUFFER_OVERFLOW; Irp->IoStatus.Information = buflen; } else if (NT_SUCCESS(Status)) { - Irp->IoStatus.Information = IrpSp->Parameters.QuerySecurity.Length; + Irp->IoStatus.Information = + IrpSp->Parameters.QuerySecurity.Length; } else { Irp->IoStatus.Information = 0; } - return Status; + return (Status); } -NTSTATUS set_security(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +set_security(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) { PFILE_OBJECT FileObject = IrpSp->FileObject; NTSTATUS Status = STATUS_SUCCESS; @@ -3481,7 +3902,7 @@ NTSTATUS set_security(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION dprintf("%s: \n", __func__); if (FileObject == NULL || FileObject->FsContext == NULL) - return STATUS_INVALID_PARAMETER; + return (STATUS_INVALID_PARAMETER); struct vnode *vp = FileObject->FsContext; VN_HOLD(vp); @@ -3497,12 +3918,12 @@ NTSTATUS set_security(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION goto err; } - Status = SeSetSecurityDescriptorInfo(NULL, - &IrpSp->Parameters.SetSecurity.SecurityInformation, - IrpSp->Parameters.SetSecurity.SecurityDescriptor, - (void **)&vp->security_descriptor, - PagedPool, - IoGetFileObjectGenericMapping()); + Status = SeSetSecurityDescriptorInfo(NULL, + &IrpSp->Parameters.SetSecurity.SecurityInformation, + IrpSp->Parameters.SetSecurity.SecurityDescriptor, + (void **)&vp->security_descriptor, + PagedPool, + IoGetFileObjectGenericMapping()); if (!NT_SUCCESS(Status)) goto err; @@ -3514,22 +3935,24 @@ NTSTATUS set_security(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION vattr.va_mask = 0; BOOLEAN defaulted; - if (IrpSp->Parameters.SetSecurity.SecurityInformation & OWNER_SECURITY_INFORMATION) { + if (IrpSp->Parameters.SetSecurity.SecurityInformation & + OWNER_SECURITY_INFORMATION) { PSID owner; - Status = RtlGetOwnerSecurityDescriptor(vnode_security(vp), &owner, &defaulted); + Status = RtlGetOwnerSecurityDescriptor(vnode_security(vp), + &owner, &defaulted); if (Status == STATUS_SUCCESS) { vattr.va_uid = zfs_sid2uid(owner); vattr.va_mask |= ATTR_UID; } -/* else - zp->z_uid = UID_NOBODY; -*/ } - if (IrpSp->Parameters.SetSecurity.SecurityInformation & GROUP_SECURITY_INFORMATION) { + if (IrpSp->Parameters.SetSecurity.SecurityInformation & + GROUP_SECURITY_INFORMATION) { PSID group; - Status = RtlGetGroupSecurityDescriptor(vnode_security(vp), &group, &defaulted); + Status = RtlGetGroupSecurityDescriptor(vnode_security(vp), + &group, &defaulted); if (Status == STATUS_SUCCESS) { - vattr.va_gid = zfs_sid2uid(group); // uid/gid reverse is identical + // uid/gid reverse is identical + vattr.va_gid = zfs_sid2uid(group); vattr.va_mask |= ATTR_GID; } } @@ -3542,25 +3965,31 @@ NTSTATUS set_security(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION Irp->IoStatus.Information = 0; zfs_send_notify(zfsvfs, zp->z_name_cache, zp->z_name_offset, - FILE_NOTIFY_CHANGE_SECURITY, - FILE_ACTION_MODIFIED); + FILE_NOTIFY_CHANGE_SECURITY, + FILE_ACTION_MODIFIED); err: VN_RELE(vp); - return Status; + return (Status); } -//#define IOCTL_VOLUME_BASE ((DWORD) 'V') -//#define IOCTL_VOLUME_GET_GPT_ATTRIBUTES CTL_CODE(IOCTL_VOLUME_BASE,14,METHOD_BUFFERED,FILE_ANY_ACCESS) +// #define IOCTL_VOLUME_BASE ((DWORD) 'V') +// #define IOCTL_VOLUME_GET_GPT_ATTRIBUTES +// CTL_CODE(IOCTL_VOLUME_BASE,14,METHOD_BUFFERED,FILE_ANY_ACCESS) -#define IOCTL_VOLUME_POST_ONLINE CTL_CODE(IOCTL_VOLUME_BASE, 25, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) +#define IOCTL_VOLUME_POST_ONLINE \ + CTL_CODE(IOCTL_VOLUME_BASE, 25, METHOD_BUFFERED, \ + FILE_READ_ACCESS | FILE_WRITE_ACCESS) -NTSTATUS ioctl_storage_get_device_number(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +ioctl_storage_get_device_number(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp) { - if (IrpSp->Parameters.QueryFile.Length < sizeof(STORAGE_DEVICE_NUMBER)) { - Irp->IoStatus.Information = sizeof(STORAGE_DEVICE_NUMBER); - return STATUS_BUFFER_TOO_SMALL; + if (IrpSp->Parameters.QueryFile.Length < + sizeof (STORAGE_DEVICE_NUMBER)) { + Irp->IoStatus.Information = sizeof (STORAGE_DEVICE_NUMBER); + return (STATUS_BUFFER_TOO_SMALL); } PSTORAGE_DEVICE_NUMBER sdn = Irp->AssociatedIrp.SystemBuffer; @@ -3568,89 +3997,98 @@ NTSTATUS ioctl_storage_get_device_number(PDEVICE_OBJECT DeviceObject, PIRP Irp, sdn->DeviceType = FILE_DEVICE_VIRTUAL_DISK; sdn->PartitionNumber = -1; // -1 means can't be partitioned - Irp->IoStatus.Information = sizeof(STORAGE_DEVICE_NUMBER); - return STATUS_SUCCESS; + Irp->IoStatus.Information = sizeof (STORAGE_DEVICE_NUMBER); + return (STATUS_SUCCESS); } -NTSTATUS ioctl_volume_get_volume_disk_extents(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +ioctl_volume_get_volume_disk_extents(PDEVICE_OBJECT DeviceObject, + PIRP Irp, PIO_STACK_LOCATION IrpSp) { VOLUME_DISK_EXTENTS *vde = Irp->AssociatedIrp.SystemBuffer; - if (IrpSp->Parameters.QueryFile.Length < sizeof(VOLUME_DISK_EXTENTS)) { - Irp->IoStatus.Information = sizeof(VOLUME_DISK_EXTENTS); - return STATUS_BUFFER_TOO_SMALL; + if (IrpSp->Parameters.QueryFile.Length < sizeof (VOLUME_DISK_EXTENTS)) { + Irp->IoStatus.Information = sizeof (VOLUME_DISK_EXTENTS); + return (STATUS_BUFFER_TOO_SMALL); } - Irp->IoStatus.Information = sizeof(VOLUME_DISK_EXTENTS); - RtlZeroMemory(vde, sizeof(VOLUME_DISK_EXTENTS)); + Irp->IoStatus.Information = sizeof (VOLUME_DISK_EXTENTS); + RtlZeroMemory(vde, sizeof (VOLUME_DISK_EXTENTS)); vde->NumberOfDiskExtents = 1; - return STATUS_SUCCESS; + return (STATUS_SUCCESS); } -NTSTATUS volume_create(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +volume_create(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) { mount_t *zmo = DeviceObject->DeviceExtension; - // This is also called from fsContext when IRP_MJ_CREATE FileName is NULL + // This is also called from fsContext when IRP_MJ_CREATE + // FileName is NULL /* VERIFY(zmo->type == MOUNT_TYPE_DCB); */ if (zmo->vpb != NULL) IrpSp->FileObject->Vpb = zmo->vpb; else IrpSp->FileObject->Vpb = DeviceObject->Vpb; - // dprintf("Setting FileObject->Vpb to %p\n", IrpSp->FileObject->Vpb); - //SetFileObjectForVCB(IrpSp->FileObject, zmo); - //IrpSp->FileObject->SectionObjectPointer = &zmo->SectionObjectPointers; - //IrpSp->FileObject->FsContext = &zmo->VolumeFileHeader; + // dprintf("Setting FileObject->Vpb to %p\n", IrpSp->FileObject->Vpb); + // SetFileObjectForVCB(IrpSp->FileObject, zmo); + // IrpSp->FileObject->SectionObjectPointer = + // &zmo->SectionObjectPointers; + // IrpSp->FileObject->FsContext = &zmo->VolumeFileHeader; - /* - * Check the ShareAccess requested: - * 0 : exclusive - * FILE_SHARE_READ : The file can be opened for read access by other threads - * FILE_SHARE_WRITE : The file can be opened for write access by other threads - * FILE_SHARE_DELETE : The file can be opened for delete access by other threads - */ +/* + * Check the ShareAccess requested: + * 0 : exclusive + * FILE_SHARE_READ : The file can be opened for read access by other threads + * FILE_SHARE_WRITE : The file can be opened for write access by other threads + * FILE_SHARE_DELETE : The file can be opened for del access by other threads + */ if ((IrpSp->Parameters.Create.ShareAccess == 0) && - zmo->volume_opens != 0) { + zmo->volume_opens != 0) { dprintf("%s: sharing violation\n", __func__); - return STATUS_SHARING_VIOLATION; + return (STATUS_SHARING_VIOLATION); } atomic_inc_64(&zmo->volume_opens); Irp->IoStatus.Information = FILE_OPENED; - return STATUS_SUCCESS; + return (STATUS_SUCCESS); } -NTSTATUS volume_close(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +volume_close(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) { mount_t *zmo = DeviceObject->DeviceExtension; VERIFY(zmo->type == MOUNT_TYPE_DCB); atomic_dec_64(&zmo->volume_opens); - return STATUS_SUCCESS; + return (STATUS_SUCCESS); } /* - * IRP_MJ_CLEANUP - sent when Windows is done with FileObject HANDLE (one of many) - * the vp is not released here, just decrease a count of vp. + * IRP_MJ_CLEANUP - sent when Windows is done with FileObject HANDLE + * (one of many) + * the vp is not released here, just decrease a count of vp. */ -int zfs_fileobject_cleanup(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp, - vnode_t **hold_vp) +int +zfs_fileobject_cleanup(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp, vnode_t **hold_vp) { int Status = STATUS_SUCCESS; mount_t *zmo = NULL; if (IrpSp->FileObject && IrpSp->FileObject->FsContext) { - struct vnode* vp = IrpSp->FileObject->FsContext; - zfs_dirlist_t* zccb = IrpSp->FileObject->FsContext2; + struct vnode *vp = IrpSp->FileObject->FsContext; + zfs_dirlist_t *zccb = IrpSp->FileObject->FsContext2; - znode_t* zp = VTOZ(vp); // zp for notify removal + znode_t *zp = VTOZ(vp); // zp for notify removal vnode_rele(vp); // Release longterm hold finally. dprintf("IRP_MJ_CLEANUP: '%s' iocount %u usecount %u\n", - zp && zp->z_name_cache ? zp->z_name_cache : "", vp->v_iocount, vp->v_usecount); + zp && zp->z_name_cache ? zp->z_name_cache : "", + vp->v_iocount, vp->v_usecount); vnode_lock(vp); IoRemoveShareAccess(IrpSp->FileObject, &vp->share_access); @@ -3664,41 +4102,58 @@ int zfs_fileobject_cleanup(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCA if (zp != NULL) { if (!isdir) { - if (vnode_flushcache(vp, IrpSp->FileObject, FALSE)) - dprintf("cleanup: flushcache said no?\n"); + if (vnode_flushcache(vp, IrpSp->FileObject, + FALSE)) + dprintf( + "cleanup: flushcache said no?\n"); } - /* Technically, this should only be called on the FileObject which - * opened the file with DELETE_ON_CLOSE - in fastfat, that is stored - * in the ccb (context) set in FsContext2, which holds data for each - * FileObject context. Possibly, we should as well. (We do for dirs) - */ +/* + * Technically, this should only be called on the FileObject which + * opened the file with DELETE_ON_CLOSE - in fastfat, that is stored + * in the ccb (context) set in FsContext2, which holds data for each + * FileObject context. Possibly, we should as well. (We do for dirs) + */ if (zccb && zccb->deleteonclose) { - zfsvfs_t* zfsvfs = vfs_fsprivate(zmo); + zfsvfs_t *zfsvfs = vfs_fsprivate(zmo); zccb->deleteonclose = 0; if (zp->z_name_cache != NULL) { if (isdir) { - dprintf("sending DIR notify: FileDeleted '%s' name '%s'\n", zp->z_name_cache, &zp->z_name_cache[zp->z_name_offset]); - zfs_send_notify(zfsvfs, zp->z_name_cache, zp->z_name_offset, - FILE_NOTIFY_CHANGE_DIR_NAME, - FILE_ACTION_REMOVED); + dprintf("DIR: FileDelete " + "'%s' name '%s'\n", + zp->z_name_cache, + &zp->z_name_cache[ + zp->z_name_offset]); + zfs_send_notify(zfsvfs, + zp->z_name_cache, + zp->z_name_offset, + FILE_NOTIFY_CHANGE_DIR_NAME, + FILE_ACTION_REMOVED); } else { - dprintf("sending FILE notify: FileDeleted '%s' name '%s'\n", zp->z_name_cache, &zp->z_name_cache[zp->z_name_offset]); - zfs_send_notify(zfsvfs, zp->z_name_cache, zp->z_name_offset, - FILE_NOTIFY_CHANGE_FILE_NAME, - FILE_ACTION_REMOVED); + dprintf("FILE: FileDelete " + "'%s' name '%s'\n", + zp->z_name_cache, + &zp->z_name_cache[ + zp->z_name_offset]); + zfs_send_notify(zfsvfs, + zp->z_name_cache, + zp->z_name_offset, + FILE_NOTIFY_CHANGE_FILE_NAME, + FILE_ACTION_REMOVED); } } - // Windows needs us to unlink it now, since CLOSE can be delayed - // and parent deletions might fail (ENOTEMPTY). + // Windows needs us to unlink it now, since CLOSE + // can be delayed and parent deletions might + // fail (ENOTEMPTY). - // This releases zp! + // This releases zp! Status = delete_entry(DeviceObject, Irp, IrpSp); if (Status != 0) - dprintf("Deletion failed: %d\n", Status); + dprintf("Deletion failed: %d\n", + Status); zp = NULL; @@ -3707,50 +4162,59 @@ int zfs_fileobject_cleanup(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCA Status = STATUS_SUCCESS; - // FILE_CLEANUP_UNKNOWN FILE_CLEANUP_WRONG_DEVICE FILE_CLEANUP_FILE_REMAINS - // FILE_CLEANUP_FILE_DELETED FILE_CLEANUP_LINK_DELETED FILE_CLEANUP_STREAM_DELETED - // FILE_CLEANUP_POSIX_STYLE_DELETE -#if defined (ZFS_FS_ATTRIBUTE_CLEANUP_INFO) && defined(ZFS_FS_ATTRIBUTE_POSIX) - Irp->IoStatus.Information = FILE_CLEANUP_FILE_DELETED | FILE_CLEANUP_POSIX_STYLE_DELETE; -#elif defined (ZFS_FS_ATTRIBUTE_CLEANUP_INFO) - Irp->IoStatus.Information = FILE_CLEANUP_FILE_DELETED; +// FILE_CLEANUP_UNKNOWN FILE_CLEANUP_WRONG_DEVICE FILE_CLEANUP_FILE_REMAINS +// FILE_CLEANUP_FILE_DELETED FILE_CLEANUP_LINK_DELETED +// FILE_CLEANUP_STREAM_DELETED FILE_CLEANUP_POSIX_STYLE_DELETE +#if defined(ZFS_FS_ATTRIBUTE_CLEANUP_INFO) && defined(ZFS_FS_ATTRIBUTE_POSIX) + Irp->IoStatus.Information = + FILE_CLEANUP_FILE_DELETED | + FILE_CLEANUP_POSIX_STYLE_DELETE; +#elif defined(ZFS_FS_ATTRIBUTE_CLEANUP_INFO) + Irp->IoStatus.Information = + FILE_CLEANUP_FILE_DELETED; #endif } else { - // fastfat zeros end of file here if last open closed + // fastfat zeros end of file here if last + // open closed } } /* The use of "zp" is only used as identity, not referenced. */ if (isdir) { - dprintf("Removing all notifications for directory: %p\n", zp); - FsRtlNotifyCleanup(zmo->NotifySync, &zmo->DirNotifyList, zp); + dprintf("Removing all notifications for " + "directory: %p\n", zp); + FsRtlNotifyCleanup(zmo->NotifySync, &zmo->DirNotifyList, + zp); } // Finish with Notifications dprintf("Removing notifications for file\n"); - FsRtlNotifyFullChangeDirectory(zmo->NotifySync, &zmo->DirNotifyList, - zp, NULL, FALSE, FALSE, 0, NULL, NULL, NULL); + FsRtlNotifyFullChangeDirectory(zmo->NotifySync, + &zmo->DirNotifyList, zp, NULL, FALSE, FALSE, 0, NULL, + NULL, NULL); - //dprintf("cleanup: vp %p attempt to ditch CCMgr\n", vp); - //if (vnode_flushcache(vp, IrpSp->FileObject, TRUE) == 1) { + // dprintf("cleanup: vp %p attempt to ditch CCMgr\n", vp); + // if (vnode_flushcache(vp, IrpSp->FileObject, TRUE) == 1) { // dprintf("vp %p clearing out FsContext\n", vp); - // IrpSp->FileObject->FsContext = NULL; - //} + // IrpSp->FileObject->FsContext = NULL; + // } // vnode_fileobject_remove(vp, IrpSp->FileObject); - //zfs_decouplefileobject(vp, IrpSp->FileObject); + // zfs_decouplefileobject(vp, IrpSp->FileObject); IrpSp->FileObject->Flags |= FO_CLEANUP_COMPLETE; Status = STATUS_SUCCESS; } - return Status; + return (Status); } /* - * IRP_MJ_CLOSE - sent when Windows is done with FileObject, and we can free memory. + * IRP_MJ_CLOSE - sent when Windows is done with FileObject, and we can + * free memory. */ -int zfs_fileobject_close(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp, - vnode_t **hold_vp) +int +zfs_fileobject_close(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp, vnode_t **hold_vp) { int Status = STATUS_SUCCESS; @@ -3758,22 +4222,25 @@ int zfs_fileobject_close(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATI if (IrpSp->FileObject) { - // Careful not to print something before vnode_fileobject_remove - - // if print is swapped out, we think fileobject is still valid. - //dprintf("IRP_MJ_CLOSE: '%wZ' \n", &IrpSp->FileObject->FileName); +// Careful not to print something before vnode_fileobject_remove - +// if print is swapped out, we think fileobject is still valid. +// dprintf("IRP_MJ_CLOSE: '%wZ' \n", &IrpSp->FileObject->FileName); if (IrpSp->FileObject->FsContext) { - //dprintf("CLOSE clearing FsContext of FO 0x%llx\n", IrpSp->FileObject); - // Mark vnode for cleanup, we grab a HOLD to make sure it isn't - // released right here, but marked to be released upon reaching 0 count +// dprintf("CLOSE clearing FsContext of FO 0x%llx\n", +// IrpSp->FileObject); +// Mark vnode for cleanup, we grab a HOLD to make sure it isn't +// released right here, but marked to be released upon +// reaching 0 count vnode_t *vp = IrpSp->FileObject->FsContext; znode_t *zp = (VTOZ(vp)); int isdir = vnode_isdir(vp); - /* - * First encourage Windows to release the FileObject, CcMgr etc, flush everything. - */ +/* + * First encourage Windows to release the FileObject, CcMgr etc, + * flush everything. + */ // FileObject should/could no longer point to vp. zfs_decouplefileobject(vp, IrpSp->FileObject); @@ -3782,27 +4249,32 @@ int zfs_fileobject_close(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATI if (isdir) { CcUninitializeCacheMap(IrpSp->FileObject, NULL, NULL); - // fastfat also flushes while(parent) dir here, if !iocount +// fastfat also flushes while(parent) dir here, if !iocount } - /* - * If we can release now, do so. - * If the reference count for the per-file context structure reaches zero - * and both the ImageSectionObject and DataSectionObject of the SectionObjectPointers - * field from the FILE_OBJECT is zero, the filter driver may then delete the per-file context data. - * - */ +/* + * If we can release now, do so. + * If the reference count for the per-file context structure reaches zero + * and both the ImageSectionObject and DataSectionObject of the + * SectionObjectPointers field from the FILE_OBJECT is zero, the + * filter driver may then delete the per-file context data. + * + */ if (!vnode_isvroot(vp)) { - /* Take hold from dispatcher, we will try to release in recycle */ +/* Take hold from dispatcher, try to release in recycle */ *hold_vp = NULL; - // Release vp - vnode_recycle expects iocount==1 - // we don't recycle root (unmount does) or RELE on recycle error - if (vnode_isvroot(vp) || (vnode_recycle(vp) != 0)) { - // If recycle failed, manually release dispatcher's HOLD - dprintf("IRP_CLOSE failed to recycle. is_empty %d\n", vnode_fileobject_empty(vp, 1)); +// Release vp - vnode_recycle expects iocount==1 +// we don't recycle root (unmount does) or RELE on +// recycle error + if (vnode_isvroot(vp) || + (vnode_recycle(vp) != 0)) { +// If recycle failed, manually release dispatcher's HOLD + dprintf("IRP_CLOSE failed to recycle. " + "is_empty %d\n", + vnode_fileobject_empty(vp, 1)); VN_RELE(vp); } @@ -3816,22 +4288,25 @@ int zfs_fileobject_close(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATI } } - return Status; + return (Status); } /* - * We received a long-lived ioctl, so lets setup a taskq to handle it, and return pending + * We received a long-lived ioctl, so lets setup a taskq to handle it, + * and return pending + * This code was proof-of-concept, and is NOT used. */ -void zfsdev_async_thread(void *arg) +void +zfsdev_async_thread(void *arg) { NTSTATUS Status; PIRP Irp; Irp = (PIRP)arg; - + dprintf("%s: starting ioctl\n", __func__); /* Use FKIOCTL to make sure it calls bcopy instead */ - Status = zfsdev_ioctl(NULL, Irp, FKIOCTL); + Status = zfsdev_ioctl(NULL, Irp, FKIOCTL); dprintf("%s: finished ioctl %d\n", __func__, Status); @@ -3846,10 +4321,13 @@ void zfsdev_async_thread(void *arg) ZwClose(Irp->Tail.Overlay.DriverContext[2]); } - IoCompleteRequest(Irp, Status == STATUS_SUCCESS ? IO_DISK_INCREMENT : IO_NO_INCREMENT); + IoCompleteRequest(Irp, + Status == STATUS_SUCCESS ? IO_DISK_INCREMENT : IO_NO_INCREMENT); } -NTSTATUS zfsdev_async(PDEVICE_OBJECT DeviceObject, PIRP Irp) +/* Not used */ +NTSTATUS +zfsdev_async(PDEVICE_OBJECT DeviceObject, PIRP Irp) { int error; PMDL mdl = NULL; @@ -3861,81 +4339,93 @@ NTSTATUS zfsdev_async(PDEVICE_OBJECT DeviceObject, PIRP Irp) IoMarkIrpPending(Irp); - /* - * A separate thread to the one that called us may not access the buffer from userland, - * So we have to map the in/out buffer, and put that address in its place. + /* + * A separate thread to the one that called us may not access the + * buffer from userland, So we have to map the in/out buffer, + * and put that address in its place. */ - error = ddi_copysetup(IrpSp->Parameters.DeviceIoControl.Type3InputBuffer, sizeof(zfs_cmd_t), - &IrpSp->Parameters.DeviceIoControl.Type3InputBuffer, &mdl); - if (error) return error; + error = ddi_copysetup( + IrpSp->Parameters.DeviceIoControl.Type3InputBuffer, + sizeof (zfs_cmd_t), + &IrpSp->Parameters.DeviceIoControl.Type3InputBuffer, &mdl); + if (error) + return (error); /* Save the MDL so we can free it once done */ Irp->Tail.Overlay.DriverContext[0] = mdl; - /* We would also need to handle zc->zc_nvlist_src and zc->zc_nvlist_dst - * which is tricker, since they are unpacked into nvlists deep in zfsdev_ioctl + /* + * We would also need to handle zc->zc_nvlist_src and zc->zc_nvlist_dst + * which is tricker, since they are unpacked into nvlists deep + * in zfsdev_ioctl + * The same problem happens for the filedescriptor from userland, + * also needs to be kernelMode */ - - /* The same problem happens for the filedescriptor from userland, also needs to be kernelMode */ zc = IrpSp->Parameters.DeviceIoControl.Type3InputBuffer; if (zc->zc_cookie) { - error = ObReferenceObjectByHandle((HANDLE)zc->zc_cookie, 0, 0, KernelMode, &fp, 0); - if (error != STATUS_SUCCESS) goto out; + error = ObReferenceObjectByHandle((HANDLE)zc->zc_cookie, 0, 0, + KernelMode, &fp, 0); + if (error != STATUS_SUCCESS) + goto out; Irp->Tail.Overlay.DriverContext[1] = fp; HANDLE h = NULL; - error = ObOpenObjectByPointer(fp, OBJ_FORCE_ACCESS_CHECK | OBJ_KERNEL_HANDLE, NULL, GENERIC_READ|GENERIC_WRITE, *IoFileObjectType, KernelMode, &h); - if (error != STATUS_SUCCESS) goto out; + error = ObOpenObjectByPointer(fp, + OBJ_FORCE_ACCESS_CHECK | OBJ_KERNEL_HANDLE, NULL, + GENERIC_READ|GENERIC_WRITE, *IoFileObjectType, + KernelMode, &h); + if (error != STATUS_SUCCESS) + goto out; dprintf("mapped filed is 0x%x\n", h); zc->zc_cookie = (uint64_t)h; Irp->Tail.Overlay.DriverContext[2] = h; } taskq_dispatch(system_taskq, zfsdev_async_thread, (void*)Irp, TQ_SLEEP); + return (STATUS_PENDING); - return STATUS_PENDING; -out: +out: if (mdl) { UnlockAndFreeMdl(mdl); } if (fp) { ObDereferenceObject(fp); } - return error; + return (error); } /* - * This is the ioctl handler for ioctl done directly on /dev/zfs node. This means - * all the internal ZFS ioctls, like ZFS_IOC_SEND etc. But, we will also get - * general Windows ioctls, not specific to volumes, or filesystems. + * This is the ioctl handler for ioctl done directly on /dev/zfs node. + * This means all the internal ZFS ioctls, like ZFS_IOC_SEND etc. + * But, we will also get general Windows ioctls, not specific to + * volumes, or filesystems. + * Incidentally, cstyle is confused about the function_class */ _Function_class_(DRIVER_DISPATCH) -static NTSTATUS -ioctlDispatcher( - _In_ PDEVICE_OBJECT DeviceObject, - _Inout_ PIRP Irp, - PIO_STACK_LOCATION IrpSp -) + static NTSTATUS + ioctlDispatcher(_In_ PDEVICE_OBJECT DeviceObject, _Inout_ PIRP Irp, + PIO_STACK_LOCATION IrpSp) { NTSTATUS Status; PAGED_CODE(); - dprintf(" %s: enter: major %d: minor %d: %s ioctlDeviceObject\n", __func__, IrpSp->MajorFunction, IrpSp->MinorFunction, - major2str(IrpSp->MajorFunction, IrpSp->MinorFunction)); - + dprintf(" %s: enter: major %d: minor %d: %s ioctlDeviceObject\n", + __func__, IrpSp->MajorFunction, IrpSp->MinorFunction, + major2str(IrpSp->MajorFunction, IrpSp->MinorFunction)); Status = STATUS_NOT_IMPLEMENTED; switch (IrpSp->MajorFunction) { case IRP_MJ_CREATE: - dprintf("IRP_MJ_CREATE: zfsdev FileObject %p name '%wZ' length %u flags 0x%x\n", - IrpSp->FileObject, IrpSp->FileObject->FileName, - IrpSp->FileObject->FileName.Length, IrpSp->Flags); + dprintf("IRP_MJ_CREATE: zfsdev FileObject %p name '%wZ' " + "length %u flags 0x%x\n", + IrpSp->FileObject, IrpSp->FileObject->FileName, + IrpSp->FileObject->FileName.Length, IrpSp->Flags); Status = zfsdev_open(IrpSp->FileObject, Irp); break; case IRP_MJ_CLOSE: @@ -3944,7 +4434,8 @@ ioctlDispatcher( case IRP_MJ_DEVICE_CONTROL: { /* Is it a ZFS ioctl? */ - u_long cmd = IrpSp->Parameters.DeviceIoControl.IoControlCode; + ulong_t cmd = + IrpSp->Parameters.DeviceIoControl.IoControlCode; if ((DEVICE_TYPE_FROM_CTL_CODE(cmd) == ZFSIOCTL_TYPE)) { @@ -3954,32 +4445,36 @@ ioctlDispatcher( cmd -= ZFSIOCTL_BASE; - /* Some IOCTL are very long-living, so we will put them in the - * background and return PENDING. Possibly we should always do - * this logic, but some ioctls are really short lived. - */ +/* + * Some IOCTL are very long-living, so we will put them in the + * background and return PENDING. Possibly we should always do + * this logic, but some ioctls are really short lived. + */ switch (cmd) { case ZFS_IOC_UNREGISTER_FS: - // We abuse returnedBytes to send back busy - Irp->IoStatus.Information = zfs_ioc_unregister_fs(); +// We abuse returnedBytes to send back busy + Irp->IoStatus.Information = + zfs_ioc_unregister_fs(); Status = STATUS_SUCCESS; break; - /* - * So to do ioctl in async mode is a hassle, we have to do the copyin/copyout - * MDL work in *this* thread, as the thread we spawn does not have access. - * This would also include zc->zc_nvlist_src / zc->zc_nvlist_dst, so - * zfsdev_ioctl() would need to be changed quite a bit. The file-descriptor - * passed in (zfs send/recv) also needs to be opened for kernel mode. This - * code is left here as an example on how it can be done (without zc->zc_nvlist_*) - * but we currently do not use it. Everything is handled synchronously. - * - case ZFS_IOC_SEND: - Status = zfsdev_async(DeviceObject, Irp); - break; - * - */ +/* + * So to do ioctl in async mode is a hassle, we have to do the copyin/copyout + * MDL work in *this* thread, as the thread we spawn does not have access. + * This would also include zc->zc_nvlist_src / zc->zc_nvlist_dst, so + * zfsdev_ioctl() would need to be changed quite a bit. The file-descriptor + * passed in (zfs send/recv) also needs to be opened for kernel mode. This + * code is left here as an example on how it can be done + * (without zc->zc_nvlist_*) but we currently do not use it. + * Everything is handled synchronously. + * + * case ZFS_IOC_SEND: + * Status = zfsdev_async(DeviceObject, Irp); + * break; + * + */ default: - Status = zfsdev_ioctl(DeviceObject, Irp, 0); + Status = zfsdev_ioctl( + DeviceObject, Irp, 0); } // switch cmd for async break; } @@ -3992,18 +4487,21 @@ ioctlDispatcher( break; case IOCTL_MOUNTDEV_QUERY_DEVICE_NAME: dprintf("IOCTL_MOUNTDEV_QUERY_DEVICE_NAME\n"); - Status = ioctl_query_device_name(DeviceObject, Irp, IrpSp); + Status = ioctl_query_device_name(DeviceObject, + Irp, IrpSp); break; case IOCTL_MOUNTDEV_QUERY_UNIQUE_ID: dprintf("IOCTL_MOUNTDEV_QUERY_UNIQUE_ID\n"); - Status = ioctl_query_unique_id(DeviceObject, Irp, IrpSp); + Status = ioctl_query_unique_id(DeviceObject, + Irp, IrpSp); break; case IOCTL_MOUNTDEV_QUERY_STABLE_GUID: dprintf("IOCTL_MOUNTDEV_QUERY_STABLE_GUID\n"); - Status = ioctl_query_stable_guid(DeviceObject, Irp, IrpSp); + Status = ioctl_query_stable_guid(DeviceObject, + Irp, IrpSp); break; case IOCTL_MOUNTDEV_QUERY_SUGGESTED_LINK_NAME: - dprintf("IOCTL_MOUNTDEV_QUERY_SUGGESTED_LINK_NAME\n"); + dprintf("IOCTL_MOUNTDEV_QUERY_SUGGESTED_LINK_NAME\n"); break; case IOCTL_VOLUME_ONLINE: dprintf("IOCTL_VOLUME_ONLINE\n"); @@ -4028,20 +4526,24 @@ ioctlDispatcher( /* kstat ioctls */ case KSTAT_IOC_CHAIN_ID: dprintf("KSTAT_IOC_CHAIN_ID\n"); - Status = spl_kstat_chain_id(DeviceObject, Irp, IrpSp); + Status = spl_kstat_chain_id(DeviceObject, Irp, + IrpSp); break; case KSTAT_IOC_READ: dprintf("KSTAT_IOC_READ\n"); - Status = spl_kstat_read(DeviceObject, Irp, IrpSp); + Status = spl_kstat_read(DeviceObject, Irp, + IrpSp); break; case KSTAT_IOC_WRITE: dprintf("KSTAT_IOC_WRITE\n"); - Status = spl_kstat_write(DeviceObject, Irp, IrpSp); + Status = spl_kstat_write(DeviceObject, Irp, + IrpSp); break; default: - dprintf("**** unknown Windows IOCTL: 0x%lx\n", cmd); + dprintf("**** unknown Windows IOCTL: 0x%lx\n", + cmd); } - + } break; @@ -4096,7 +4598,7 @@ ioctlDispatcher( } - return Status; + return (Status); } /* @@ -4106,29 +4608,31 @@ ioctlDispatcher( * /dev/diskX node directly). */ _Function_class_(DRIVER_DISPATCH) -static NTSTATUS -diskDispatcher( - _In_ PDEVICE_OBJECT DeviceObject, - _Inout_ PIRP Irp, - PIO_STACK_LOCATION IrpSp -) + static NTSTATUS + diskDispatcher( + _In_ PDEVICE_OBJECT DeviceObject, + _Inout_ PIRP Irp, + PIO_STACK_LOCATION IrpSp) { NTSTATUS Status; PAGED_CODE(); - dprintf(" %s: enter: major %d: minor %d: %s diskDeviceObject\n", __func__, IrpSp->MajorFunction, IrpSp->MinorFunction, - major2str(IrpSp->MajorFunction, IrpSp->MinorFunction)); - + dprintf(" %s: enter: major %d: minor %d: %s diskDeviceObject\n", + __func__, IrpSp->MajorFunction, IrpSp->MinorFunction, + major2str(IrpSp->MajorFunction, IrpSp->MinorFunction)); Status = STATUS_NOT_IMPLEMENTED; switch (IrpSp->MajorFunction) { case IRP_MJ_CREATE: - dprintf("IRP_MJ_CREATE: volume FileObject %p related %p name '%wZ' flags 0x%x\n", - IrpSp->FileObject, IrpSp->FileObject ? IrpSp->FileObject->RelatedFileObject : NULL, - IrpSp->FileObject->FileName, IrpSp->Flags); + dprintf("IRP_MJ_CREATE: volume FileObject %p related %p " + "name '%wZ' flags 0x%x\n", + IrpSp->FileObject, + IrpSp->FileObject ? + IrpSp->FileObject->RelatedFileObject : NULL, + IrpSp->FileObject->FileName, IrpSp->Flags); Status = volume_create(DeviceObject, Irp, IrpSp); break; @@ -4137,7 +4641,7 @@ diskDispatcher( break; case IRP_MJ_DEVICE_CONTROL: { - u_long cmd = IrpSp->Parameters.DeviceIoControl.IoControlCode; + ulong_t cmd = IrpSp->Parameters.DeviceIoControl.IoControlCode; /* Not ZFS ioctl, handle Windows ones */ switch (cmd) { case IOCTL_VOLUME_GET_GPT_ATTRIBUTES: @@ -4146,19 +4650,23 @@ diskDispatcher( break; case IOCTL_MOUNTDEV_QUERY_DEVICE_NAME: dprintf("IOCTL_MOUNTDEV_QUERY_DEVICE_NAME\n"); - Status = ioctl_query_device_name(DeviceObject, Irp, IrpSp); + Status = ioctl_query_device_name(DeviceObject, Irp, + IrpSp); break; case IOCTL_MOUNTDEV_QUERY_UNIQUE_ID: dprintf("IOCTL_MOUNTDEV_QUERY_UNIQUE_ID\n"); - Status = ioctl_query_unique_id(DeviceObject, Irp, IrpSp); + Status = ioctl_query_unique_id(DeviceObject, Irp, + IrpSp); break; case IOCTL_MOUNTDEV_QUERY_STABLE_GUID: dprintf("IOCTL_MOUNTDEV_QUERY_STABLE_GUID\n"); - Status = ioctl_mountdev_query_stable_guid(DeviceObject, Irp, IrpSp); + Status = ioctl_mountdev_query_stable_guid(DeviceObject, + Irp, IrpSp); break; case IOCTL_MOUNTDEV_QUERY_SUGGESTED_LINK_NAME: dprintf("IOCTL_MOUNTDEV_QUERY_SUGGESTED_LINK_NAME\n"); - Status = ioctl_mountdev_query_suggested_link_name(DeviceObject, Irp, IrpSp); + Status = ioctl_mountdev_query_suggested_link_name( + DeviceObject, Irp, IrpSp); break; case IOCTL_VOLUME_ONLINE: dprintf("IOCTL_VOLUME_ONLINE\n"); @@ -4187,19 +4695,23 @@ diskDispatcher( break; case IOCTL_STORAGE_GET_HOTPLUG_INFO: dprintf("IOCTL_STORAGE_GET_HOTPLUG_INFO\n"); - Status = ioctl_storage_get_hotplug_info(DeviceObject, Irp, IrpSp); + Status = ioctl_storage_get_hotplug_info(DeviceObject, + Irp, IrpSp); break; case IOCTL_STORAGE_QUERY_PROPERTY: dprintf("IOCTL_STORAGE_QUERY_PROPERTY\n"); - Status = ioctl_storage_query_property(DeviceObject, Irp, IrpSp); + Status = ioctl_storage_query_property(DeviceObject, Irp, + IrpSp); break; case IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS: dprintf("IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS\n"); - Status = ioctl_volume_get_volume_disk_extents(DeviceObject, Irp, IrpSp); + Status = ioctl_volume_get_volume_disk_extents( + DeviceObject, Irp, IrpSp); break; case IOCTL_STORAGE_GET_DEVICE_NUMBER: dprintf("IOCTL_STORAGE_GET_DEVICE_NUMBER\n"); - Status = ioctl_storage_get_device_number(DeviceObject, Irp, IrpSp); + Status = ioctl_storage_get_device_number(DeviceObject, + Irp, IrpSp); break; case IOCTL_DISK_CHECK_VERIFY: Status = STATUS_SUCCESS; @@ -4220,7 +4732,8 @@ diskDispatcher( dprintf("IOCTL_MOUNTDEV_LINK_CREATED\n"); Status = STATUS_SUCCESS; break; - case 0x4d0010: // Same as IOCTL_MOUNTDEV_LINK_CREATED but bit 14,15 are 0 (access permissions) + case 0x4d0010: +// Same as IOCTL_MOUNTDEV_LINK_CREATED but bit 14,15 are 0 (access permissions) dprintf("IOCTL_MOUNTDEV_LINK_CREATED v2\n"); Status = STATUS_SUCCESS; break; @@ -4228,20 +4741,24 @@ diskDispatcher( dprintf("IOCTL_MOUNTDEV_LINK_DELETED\n"); Status = STATUS_SUCCESS; break; - case 0x4d0014: // Same as IOCTL_MOUNTDEV_LINK_DELETED but bit 14,15 are 0 (access permissions) + case 0x4d0014: +// Same as IOCTL_MOUNTDEV_LINK_DELETED but bit 14,15 are 0 (access permissions) dprintf("IOCTL_MOUNTDEV_LINK_DELETED v2\n"); Status = STATUS_SUCCESS; break; case IOCTL_DISK_GET_PARTITION_INFO_EX: dprintf("IOCTL_DISK_GET_PARTITION_INFO_EX\n"); - Status = ioctl_disk_get_partition_info_ex(DeviceObject, Irp, IrpSp); + Status = ioctl_disk_get_partition_info_ex(DeviceObject, + Irp, IrpSp); break; case IOCTL_DISK_GET_DRIVE_GEOMETRY: dprintf("IOCTL_DISK_GET_DRIVE_GEOMETRY\n"); - Status = ioctl_disk_get_drive_geometry(DeviceObject, Irp, IrpSp); + Status = ioctl_disk_get_drive_geometry(DeviceObject, + Irp, IrpSp); break; default: - dprintf("**** unknown disk Windows IOCTL: 0x%lx\n", cmd); + dprintf("**** unknown disk Windows IOCTL: 0x%lx\n", + cmd); } } @@ -4251,8 +4768,8 @@ diskDispatcher( Status = STATUS_SUCCESS; break; - // Technically we don't really let them read from the virtual devices that - // hold the ZFS filesystem, so we just return all zeros. + // Technically we don't really let them read from the virtual + // devices that hold the ZFS filesystem, so we just return all zeros. case IRP_MJ_READ: dprintf("disk fake read\n"); uint64_t bufferLength; @@ -4275,7 +4792,7 @@ diskDispatcher( break; case IRP_MN_USER_FS_REQUEST: dprintf("IRP_MN_USER_FS_REQUEST: FsControlCode 0x%x\n", - IrpSp->Parameters.FileSystemControl.FsControlCode); + IrpSp->Parameters.FileSystemControl.FsControlCode); Status = user_fs_request(DeviceObject, Irp, IrpSp); break; default: @@ -4296,7 +4813,8 @@ diskDispatcher( break; case IRP_MN_QUERY_DEVICE_RELATIONS: Status = STATUS_NOT_IMPLEMENTED; - dprintf("DeviceRelations.Type 0x%x\n", IrpSp->Parameters.QueryDeviceRelations.Type); + dprintf("DeviceRelations.Type 0x%x\n", + IrpSp->Parameters.QueryDeviceRelations.Type); break; case IRP_MN_QUERY_ID: Status = pnp_query_id(DeviceObject, Irp, IrpSp); @@ -4325,7 +4843,7 @@ diskDispatcher( } - return Status; + return (Status); } /* @@ -4333,28 +4851,30 @@ diskDispatcher( * vnops happen and we handle everything with files and directories in ZFS. */ _Function_class_(DRIVER_DISPATCH) -static NTSTATUS -fsDispatcher( - _In_ PDEVICE_OBJECT DeviceObject, - _Inout_ PIRP Irp, - PIO_STACK_LOCATION IrpSp -) + static NTSTATUS + fsDispatcher( + _In_ PDEVICE_OBJECT DeviceObject, + _Inout_ PIRP Irp, + PIO_STACK_LOCATION IrpSp) { NTSTATUS Status; struct vnode *hold_vp = NULL; - + PAGED_CODE(); - dprintf(" %s: enter: major %d: minor %d: %s fsDeviceObject\n", __func__, IrpSp->MajorFunction, IrpSp->MinorFunction, - major2str(IrpSp->MajorFunction, IrpSp->MinorFunction)); + dprintf(" %s: enter: major %d: minor %d: %s fsDeviceObject\n", + __func__, IrpSp->MajorFunction, IrpSp->MinorFunction, + major2str(IrpSp->MajorFunction, IrpSp->MinorFunction)); #ifdef DEBUG_IOCOUNT int skiplock = 0; - /* - * Watch out for re-entrant calls! MJ_READ, can call CCMGR, which calls MJ_READ! - * This could be a bigger issue, in that any mutex calls in the zfs_read()/zfs_write stack - * could die - including rangelocks, rwlocks. Investigate. (+zfs_freesp/zfs_trunc) - */ +/* + * Watch out for re-entrant calls! MJ_READ, can call CCMGR, which calls + * MJ_READ! + * This could be a bigger issue, in that any mutex calls in the + * zfs_read()/zfs_write stack could die - including rangelocks, + * rwlocks. Investigate. (+zfs_freesp/zfs_trunc) + */ if (mutex_owned(&GIANT_SERIAL_LOCK)) skiplock = 1; else @@ -4363,25 +4883,30 @@ fsDispatcher( zfsvfs_t *zfsvfs = NULL; #endif - /* - * Like VFS layer in upstream, we hold the "vp" here before calling into the VNOP handlers. - * There is one special case, IRP_MJ_CREATE / zfs_vnop_lookup, which has no vp to start, - * and assigns the vp on success (held). - * We also pass "hold_vp" down to delete_entry, so it can release the last hold to delete - */ +/* + * Like VFS layer in upstream, we hold the "vp" here before calling into + * the VNOP handlers. + * There is one special case, IRP_MJ_CREATE / zfs_vnop_lookup, which has + * no vp to start, + * and assigns the vp on success (held). + * We also pass "hold_vp" down to delete_entry, so it can release the + * last hold to delete + */ if (IrpSp->FileObject && IrpSp->FileObject->FsContext) { hold_vp = IrpSp->FileObject->FsContext; if (VN_HOLD(hold_vp) != 0) { - // If we were given a vp, but can't hold the vp, we should fail this OP. + // If we were given a vp, but can't hold the vp, + // we should fail this OP. Irp->IoStatus.Information = 0; hold_vp = NULL; - return STATUS_INVALID_PARAMETER; + return (STATUS_INVALID_PARAMETER); } else { // Add FO to vp, if this is the first we've heard of it - vnode_fileobject_add(IrpSp->FileObject->FsContext, IrpSp->FileObject); + vnode_fileobject_add(IrpSp->FileObject->FsContext, + IrpSp->FileObject); // This is useful if you have iocount leaks, and do // only single-threaded operations @@ -4392,10 +4917,11 @@ fsDispatcher( #endif } } - /* Inside VNOP handlers, we no longer need to call VN_HOLD() on *this* vp - * (but might for dvp etc) and eventually that code will be removed, if this - * style works out. - */ +/* + * Inside VNOP handlers, we no longer need to call VN_HOLD() on *this* vp + * (but might for dvp etc) and eventually that code will be removed, if this + * style works out. + */ Status = STATUS_NOT_IMPLEMENTED; @@ -4403,23 +4929,40 @@ fsDispatcher( case IRP_MJ_CREATE: if (IrpSp->Parameters.Create.Options & FILE_OPEN_BY_FILE_ID) - dprintf("IRP_MJ_CREATE: FileObject %p related %p FileID 0x%llx flags 0x%x sharing 0x%x options 0x%x\n", - IrpSp->FileObject, IrpSp->FileObject ? IrpSp->FileObject->RelatedFileObject : NULL, - *((uint64_t *)IrpSp->FileObject->FileName.Buffer), IrpSp->Flags, IrpSp->Parameters.Create.ShareAccess, - IrpSp->Parameters.Create.Options); + dprintf("IRP_MJ_CREATE: FileObject %p related %p " + "FileID 0x%llx flags 0x%x sharing 0x%x options " + "0x%x\n", + IrpSp->FileObject, + IrpSp->FileObject ? + IrpSp->FileObject->RelatedFileObject : + NULL, + *((uint64_t *)IrpSp->FileObject->FileName.Buffer), + IrpSp->Flags, IrpSp->Parameters.Create.ShareAccess, + IrpSp->Parameters.Create.Options); else - dprintf("IRP_MJ_CREATE: FileObject %p related %p name '%wZ' flags 0x%x sharing 0x%x options %s attr 0x%x DesAcc 0x%x\n", - IrpSp->FileObject, IrpSp->FileObject ? IrpSp->FileObject->RelatedFileObject : NULL, - IrpSp->FileObject->FileName, IrpSp->Flags, IrpSp->Parameters.Create.ShareAccess, - create_options(IrpSp->Parameters.Create.Options), IrpSp->Parameters.Create.FileAttributes, IrpSp->Parameters.Create.SecurityContext->DesiredAccess); + dprintf("IRP_MJ_CREATE: FileObject %p related %p " + "name '%wZ' flags 0x%x sharing 0x%x options " + "%s attr 0x%x DesAcc 0x%x\n", + IrpSp->FileObject, + IrpSp->FileObject ? + IrpSp->FileObject->RelatedFileObject : + NULL, + IrpSp->FileObject->FileName, IrpSp->Flags, + IrpSp->Parameters.Create.ShareAccess, + create_options(IrpSp->Parameters.Create.Options), + IrpSp->Parameters.Create.FileAttributes, + IrpSp->Parameters.Create.SecurityContext-> + DesiredAccess); Irp->IoStatus.Information = FILE_OPENED; Status = STATUS_SUCCESS; #if 0 // Disallow autorun.inf for now - if (IrpSp && IrpSp->FileObject && IrpSp->FileObject->FileName.Buffer && - _wcsicmp(IrpSp->FileObject->FileName.Buffer, L"\\autorun.inf") == 0) { + if (IrpSp && IrpSp->FileObject && + IrpSp->FileObject->FileName.Buffer && + _wcsicmp(IrpSp->FileObject->FileName.Buffer, + L"\\autorun.inf") == 0) { Irp->IoStatus.Information = FILE_DOES_NOT_EXIST; Status = STATUS_OBJECT_NAME_NOT_FOUND; break; @@ -4432,14 +4975,15 @@ fsDispatcher( // // Check if we are opening the volume and not a file/directory. // We are opening the volume if the name is empty and there - // isn't a related file object. If there is a related file object - // then it is the Vcb itself. + // isn't a related file object. If there is a related + // file object then it is the Vcb itself. // // We have a name, so we are looking for something specific // Attempt to find the requested object - if (IrpSp && IrpSp->FileObject && /* IrpSp->FileObject->FileName.Buffer && */ - zmo) { + if (IrpSp && IrpSp->FileObject && + /* IrpSp->FileObject->FileName.Buffer && */ + zmo) { Status = zfs_vnop_lookup(Irp, IrpSp, zmo); @@ -4448,31 +4992,33 @@ fsDispatcher( } break; - /* - * CLEANUP comes before CLOSE. The IFSTEST.EXE on notifications - * require them to arrive at CLEANUP time, and deemed too late - * to be sent from CLOSE. It is required we act on DELETE_ON_CLOSE - * in CLEANUP, which means we have to call delete here. - * fastfat: - * Close is invoked whenever the last reference to a file object is deleted. - * Cleanup is invoked when the last handle to a file object is closed, and - * is called before close. - * The function of close is to completely tear down and remove the fcb/dcb/ccb - * structures associated with the file object. - * So for ZFS, CLEANUP will leave FsContext=vp around - to have it be freed in - * CLOSE. - */ - case IRP_MJ_CLEANUP: - Status = zfs_fileobject_cleanup(DeviceObject, Irp, IrpSp, &hold_vp); +/* + * CLEANUP comes before CLOSE. The IFSTEST.EXE on notifications + * require them to arrive at CLEANUP time, and deemed too late + * to be sent from CLOSE. It is required we act on DELETE_ON_CLOSE + * in CLEANUP, which means we have to call delete here. + * fastfat: + * Close is invoked whenever the last reference to a file object is deleted. + * Cleanup is invoked when the last handle to a file object is closed, and + * is called before close. + * The function of close is to completely tear down and remove the fcb/dcb/ccb + * structures associated with the file object. + * So for ZFS, CLEANUP will leave FsContext=vp around - to have it be freed in + * CLOSE. + */ + case IRP_MJ_CLEANUP: + Status = zfs_fileobject_cleanup(DeviceObject, Irp, IrpSp, + &hold_vp); break; case IRP_MJ_CLOSE: - Status = zfs_fileobject_close(DeviceObject, Irp, IrpSp, &hold_vp); + Status = zfs_fileobject_close(DeviceObject, Irp, IrpSp, + &hold_vp); break; case IRP_MJ_DEVICE_CONTROL: { - u_long cmd = IrpSp->Parameters.DeviceIoControl.IoControlCode; + ulong_t cmd = IrpSp->Parameters.DeviceIoControl.IoControlCode; /* Not ZFS ioctl, handle Windows ones */ switch (cmd) { case IOCTL_VOLUME_GET_GPT_ATTRIBUTES: @@ -4481,15 +5027,18 @@ fsDispatcher( break; case IOCTL_MOUNTDEV_QUERY_DEVICE_NAME: dprintf("IOCTL_MOUNTDEV_QUERY_DEVICE_NAME\n"); - Status = ioctl_query_device_name(DeviceObject, Irp, IrpSp); + Status = ioctl_query_device_name(DeviceObject, Irp, + IrpSp); break; case IOCTL_MOUNTDEV_QUERY_UNIQUE_ID: dprintf("IOCTL_MOUNTDEV_QUERY_UNIQUE_ID\n"); - Status = ioctl_query_unique_id(DeviceObject, Irp, IrpSp); + Status = ioctl_query_unique_id(DeviceObject, Irp, + IrpSp); break; case IOCTL_MOUNTDEV_QUERY_STABLE_GUID: dprintf("IOCTL_MOUNTDEV_QUERY_STABLE_GUID\n"); - Status = ioctl_query_stable_guid(DeviceObject, Irp, IrpSp); + Status = ioctl_query_stable_guid(DeviceObject, Irp, + IrpSp); break; case IOCTL_MOUNTDEV_QUERY_SUGGESTED_LINK_NAME: dprintf("IOCTL_MOUNTDEV_QUERY_SUGGESTED_LINK_NAME\n"); @@ -4524,43 +5073,53 @@ fsDispatcher( break; case IOCTL_DISK_GET_DRIVE_GEOMETRY: dprintf("IOCTL_DISK_GET_DRIVE_GEOMETRY\n"); - Status = ioctl_disk_get_drive_geometry(DeviceObject, Irp, IrpSp); + Status = ioctl_disk_get_drive_geometry(DeviceObject, + Irp, IrpSp); break; case IOCTL_DISK_GET_DRIVE_GEOMETRY_EX: dprintf("IOCTL_DISK_GET_DRIVE_GEOMETRY_EX\n"); - Status = ioctl_disk_get_drive_geometry_ex(DeviceObject, Irp, IrpSp); + Status = ioctl_disk_get_drive_geometry_ex(DeviceObject, + Irp, IrpSp); break; case IOCTL_DISK_GET_PARTITION_INFO: dprintf("IOCTL_DISK_GET_PARTITION_INFO\n"); - Status = ioctl_disk_get_partition_info(DeviceObject, Irp, IrpSp); + Status = ioctl_disk_get_partition_info(DeviceObject, + Irp, IrpSp); break; case IOCTL_DISK_GET_PARTITION_INFO_EX: dprintf("IOCTL_DISK_GET_PARTITION_INFO_EX\n"); - Status = ioctl_disk_get_partition_info_ex(DeviceObject, Irp, IrpSp); + Status = ioctl_disk_get_partition_info_ex(DeviceObject, + Irp, IrpSp); break; case IOCTL_VOLUME_IS_IO_CAPABLE: dprintf("IOCTL_VOLUME_IS_IO_CAPABLE\n"); - Status = ioctl_volume_is_io_capable(DeviceObject, Irp, IrpSp); + Status = ioctl_volume_is_io_capable(DeviceObject, Irp, + IrpSp); break; case IOCTL_STORAGE_GET_HOTPLUG_INFO: dprintf("IOCTL_STORAGE_GET_HOTPLUG_INFO\n"); - Status = ioctl_storage_get_hotplug_info(DeviceObject, Irp, IrpSp); + Status = ioctl_storage_get_hotplug_info(DeviceObject, + Irp, IrpSp); break; case IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS: dprintf("IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS\n"); - Status = ioctl_volume_get_volume_disk_extents(DeviceObject, Irp, IrpSp); + Status = ioctl_volume_get_volume_disk_extents( + DeviceObject, Irp, IrpSp); break; case IOCTL_DISK_GET_LENGTH_INFO: dprintf("IOCTL_DISK_GET_LENGTH_INFO\n"); - Status = ioctl_disk_get_length_info(DeviceObject, Irp, IrpSp); + Status = ioctl_disk_get_length_info(DeviceObject, Irp, + IrpSp); break; case IOCTL_STORAGE_GET_DEVICE_NUMBER: dprintf("IOCTL_STORAGE_GET_DEVICE_NUMBER\n"); - Status = ioctl_storage_get_device_number(DeviceObject, Irp, IrpSp); + Status = ioctl_storage_get_device_number(DeviceObject, + Irp, IrpSp); break; case IOCTL_STORAGE_QUERY_PROPERTY: dprintf("IOCTL_STORAGE_QUERY_PROPERTY\n"); - Status = ioctl_storage_query_property(DeviceObject, Irp, IrpSp); + Status = ioctl_storage_query_property(DeviceObject, Irp, + IrpSp); break; case FSCTL_DISMOUNT_VOLUME: @@ -4589,12 +5148,15 @@ fsDispatcher( case IRP_MN_USER_FS_REQUEST: Status = user_fs_request(DeviceObject, Irp, IrpSp); break; - case IRP_MN_KERNEL_CALL: // FSCTL_QUERY_VOLUME_CONTAINER_STATE 0x90930 - dprintf("IRP_MN_KERNEL_CALL: unknown 0x%x\n", IrpSp->Parameters.FileSystemControl.FsControlCode); + // FSCTL_QUERY_VOLUME_CONTAINER_STATE 0x90930 + case IRP_MN_KERNEL_CALL: + dprintf("IRP_MN_KERNEL_CALL: unknown 0x%x\n", + IrpSp->Parameters.FileSystemControl.FsControlCode); Status = STATUS_INVALID_DEVICE_REQUEST; break; default: - dprintf("IRP_MJ_FILE_SYSTEM_CONTROL: unknown 0x%x\n", IrpSp->MinorFunction); + dprintf("IRP_MJ_FILE_SYSTEM_CONTROL: unknown 0x%x\n", + IrpSp->MinorFunction); Status = STATUS_INVALID_DEVICE_REQUEST; } break; @@ -4607,32 +5169,35 @@ fsDispatcher( case IRP_MN_QUERY_DEVICE_RELATIONS: Status = STATUS_NOT_IMPLEMENTED; - if (IrpSp->Parameters.QueryDeviceRelations.Type == TargetDeviceRelation) { + if (IrpSp->Parameters.QueryDeviceRelations.Type == + TargetDeviceRelation) { PDEVICE_RELATIONS DeviceRelations; DeviceRelations = - (PDEVICE_RELATIONS)ExAllocatePool(PagedPool, - sizeof(DEVICE_RELATIONS)); + (PDEVICE_RELATIONS)ExAllocatePool(PagedPool, + sizeof (DEVICE_RELATIONS)); if (!DeviceRelations) { - dprintf(" can't allocate DeviceRelations\n"); + dprintf("enomem DeviceRelations\n"); Status = STATUS_INSUFFICIENT_RESOURCES; break; } - dprintf("DeviceRelations TargetDeviceRelations\n"); + dprintf("TargetDeviceRelations\n"); - /* The PnP manager will remove this when it is done with device */ +/* The PnP manager will remove this when it is done with device */ ObReferenceObject(DeviceObject); DeviceRelations->Count = 1; DeviceRelations->Objects[0] = DeviceObject; - Irp->IoStatus.Information = (ULONG_PTR)DeviceRelations; + Irp->IoStatus.Information = + (ULONG_PTR)DeviceRelations; Status = STATUS_SUCCESS; break; } - dprintf("DeviceRelations.Type 0x%x\n", IrpSp->Parameters.QueryDeviceRelations.Type); - break; + dprintf("DeviceRelations.Type 0x%x\n", + IrpSp->Parameters.QueryDeviceRelations.Type); + break; case IRP_MN_QUERY_ID: Status = pnp_query_id(DeviceObject, Irp, IrpSp); break; @@ -4672,7 +5237,8 @@ fsDispatcher( case IRP_MJ_DIRECTORY_CONTROL: switch (IrpSp->MinorFunction) { case IRP_MN_NOTIFY_CHANGE_DIRECTORY: - Status = notify_change_directory(DeviceObject, Irp, IrpSp); + Status = notify_change_directory(DeviceObject, Irp, + IrpSp); break; case IRP_MN_QUERY_DIRECTORY: Status = query_directory(DeviceObject, Irp, IrpSp); @@ -4709,18 +5275,25 @@ fsDispatcher( break; } - /* Re-check (since MJ_CREATE/vnop_lookup might have set it) vp here, to see if - * we should call setsize + /* + * Re-check (since MJ_CREATE/vnop_lookup might have set it) vp here, + * to see if we should call setsize */ if (IrpSp->FileObject && IrpSp->FileObject->FsContext) { struct vnode *vp = IrpSp->FileObject->FsContext; - /* vp "might" be held above, or not (vnop_lookup) so grab another just in case */ + /* + * vp "might" be held above, or not (vnop_lookup) so grab + * another just in case + */ if (vp && vnode_sizechange(vp) && - VN_HOLD(vp) == 0) { + VN_HOLD(vp) == 0) { if (CcIsFileCached(IrpSp->FileObject)) { - CcSetFileSizes(IrpSp->FileObject, (PCC_FILE_SIZES)&vp->FileHeader.AllocationSize); - dprintf("sizechanged, updated to %llx\n", vp->FileHeader.FileSize); + CcSetFileSizes(IrpSp->FileObject, + (PCC_FILE_SIZES) + &vp->FileHeader.AllocationSize); + dprintf("sizechanged, updated to %llx\n", + vp->FileHeader.FileSize); vnode_setsizechange(vp, 0); } VN_RELE(vp); @@ -4739,26 +5312,27 @@ fsDispatcher( // they are called async, outside IRP dispatcher. if (!skiplock) { // Wait for all async_rele to finish - if (zfsvfs) taskq_wait(dsl_pool_vnrele_taskq(dmu_objset_pool(zfsvfs->z_os))); + if (zfsvfs) + taskq_wait(dsl_pool_vnrele_taskq(dmu_objset_pool( + zfsvfs->z_os))); vnode_check_iocount(); mutex_exit(&GIANT_SERIAL_LOCK); } #endif - return Status; + return (Status); } /* - * ALL ioctl requests come in here, and we do the Windows specific work to handle IRPs - * then we sort out the type of request (ioctl, volume, filesystem) and call each - * respective handler. + * ALL ioctl requests come in here, and we do the Windows specific + * work to handle IRPs then we sort out the type of request + * (ioctl, volume, filesystem) and call each respective handler. */ _Function_class_(DRIVER_DISPATCH) -NTSTATUS -dispatcher( - _In_ PDEVICE_OBJECT DeviceObject, - _Inout_ PIRP Irp -) + NTSTATUS + dispatcher( + _In_ PDEVICE_OBJECT DeviceObject, + _Inout_ PIRP Irp) { BOOLEAN TopLevel = FALSE; BOOLEAN AtIrqlPassiveLevel; @@ -4766,10 +5340,11 @@ dispatcher( NTSTATUS Status = STATUS_NOT_IMPLEMENTED; uint64_t validity_check; - // Storport can call itself (and hence, ourselves) so this isn't always true. - //PAGED_CODE(); + // Storport can call itself (and hence, ourselves) so this isn't + // always true. + // PAGED_CODE(); - //dprintf("%s: enter\n", __func__); + // dprintf("%s: enter\n", __func__); // If we were called with our file system device object instead of a // volume device object, just complete this request with STATUS_SUCCESS @@ -4779,14 +5354,16 @@ dispatcher( Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = FILE_OPENED; IoCompleteRequest(Irp, IO_DISK_INCREMENT); - return STATUS_SUCCESS; + return (STATUS_SUCCESS); } #endif validity_check = *((uint64_t *)Irp); IrpSp = IoGetCurrentIrpStackLocation(Irp); - dprintf("%s: enter: major %d: minor %d: %s: type 0x%x: fo %p\n", __func__, IrpSp->MajorFunction, IrpSp->MinorFunction, - major2str(IrpSp->MajorFunction, IrpSp->MinorFunction), Irp->Type, IrpSp->FileObject); + dprintf("%s: enter: major %d: minor %d: %s: type 0x%x: fo %p\n", + __func__, IrpSp->MajorFunction, IrpSp->MinorFunction, + major2str(IrpSp->MajorFunction, IrpSp->MinorFunction), + Irp->Type, IrpSp->FileObject); AtIrqlPassiveLevel = (KeGetCurrentIrql() == PASSIVE_LEVEL); if (AtIrqlPassiveLevel) { @@ -4800,13 +5377,14 @@ dispatcher( if (DeviceObject == ioctlDeviceObject) Status = ioctlDispatcher(DeviceObject, Irp, IrpSp); else { - mount_t * zmo = DeviceObject->DeviceExtension; + mount_t *zmo = DeviceObject->DeviceExtension; if (zmo && zmo->type == MOUNT_TYPE_DCB) Status = diskDispatcher(DeviceObject, Irp, IrpSp); else if (zmo && zmo->type == MOUNT_TYPE_VCB) Status = fsDispatcher(DeviceObject, Irp, IrpSp); else { - extern PDRIVER_DISPATCH STOR_MajorFunction[IRP_MJ_MAXIMUM_FUNCTION + 1]; + extern PDRIVER_DISPATCH + STOR_MajorFunction[IRP_MJ_MAXIMUM_FUNCTION + 1]; if (STOR_MajorFunction[IrpSp->MajorFunction] != NULL) { if (TopLevel) { IoSetTopLevelIrp(NULL); @@ -4814,8 +5392,9 @@ dispatcher( if (AtIrqlPassiveLevel) { FsRtlExitFileSystem(); } - //dprintf("Relaying IRP to STORport\n"); - return STOR_MajorFunction[IrpSp->MajorFunction](DeviceObject, Irp); + // dprintf("Relaying IRP to STORport\n"); + return (STOR_MajorFunction[IrpSp->MajorFunction] + (DeviceObject, Irp)); } // Got a request we don't care about? @@ -4838,58 +5417,48 @@ dispatcher( break; default: ASSERT(validity_check == *((uint64_t *)Irp)); - dprintf("%s: exit: 0x%x %s Information 0x%x : %s\n", __func__, Status, - common_status_str(Status), - Irp->IoStatus.Information, major2str(IrpSp->MajorFunction, IrpSp->MinorFunction)); + dprintf("%s: exit: 0x%x %s Information 0x%x : %s\n", + __func__, Status, + common_status_str(Status), + Irp->IoStatus.Information, + major2str(IrpSp->MajorFunction, IrpSp->MinorFunction)); } - // Complete the request if it isn't pending (ie, we called zfsdev_async()) - if (Status != STATUS_PENDING) - { + // Complete the request if it isn't pending (ie, we + // called zfsdev_async()) + if (Status != STATUS_PENDING) { if (validity_check == *((uint64_t *)Irp)) { // IOCTL_STORAGE_GET_HOTPLUG_INFO // IOCTL_DISK_CHECK_VERIFY // IOCTL_STORAGE_QUERY_PROPERTY Irp->IoStatus.Status = Status; - IoCompleteRequest(Irp, Status == STATUS_SUCCESS ? IO_DISK_INCREMENT : IO_NO_INCREMENT); - } - else + IoCompleteRequest(Irp, + Status == STATUS_SUCCESS ? IO_DISK_INCREMENT : + IO_NO_INCREMENT); + } else { KeBugCheckEx(INCONSISTENT_IRP, (ULONG_PTR)Irp, 0, 0, 0); + } } - return Status; + return (Status); } -NTSTATUS ZFSCallbackAcquireForCreateSection( +NTSTATUS +ZFSCallbackAcquireForCreateSection( IN PFS_FILTER_CALLBACK_DATA CallbackData, - OUT PVOID *CompletionContext -) -/*++ -Routine Description: -This is the callback routine for MM to use to acquire the file exclusively. -NOTE: This routine expects the default FSRTL routine to be used to release -the resource. If this routine is ever changed to acquire something -other than main, a corresponding release routine will be required. -Arguments: -FS_FILTER_CALLBACK_DATA - Filter based callback data that provides the file object we -want to acquire. -CompletionContext - Ignored. -Return Value: -On success we return STATUS_FSFILTER_OP_COMPLETED_SUCCESSFULLY. -If SyncType is SyncTypeCreateSection, we return a status that indicates whether there -are any writers to this file. Note that main is acquired, so new handles cannot be opened. ---*/ + OUT PVOID *CompletionContext) { - //ASSERT(CallbackData->Operation == FS_FILTER_ACQUIRE_FOR_SECTION_SYNCHRONIZATION); - ASSERT(CallbackData->SizeOfFsFilterCallbackData == sizeof(FS_FILTER_CALLBACK_DATA)); + ASSERT(CallbackData->SizeOfFsFilterCallbackData == + sizeof (FS_FILTER_CALLBACK_DATA)); - dprintf("%s: Operation 0x%x \n", __func__, - CallbackData->Operation); + dprintf("%s: Operation 0x%x \n", __func__, + CallbackData->Operation); struct vnode *vp; vp = CallbackData->FileObject->FsContext; ASSERT(vp != NULL); - if (vp == NULL) return STATUS_INVALID_PARAMETER; + if (vp == NULL) + return (STATUS_INVALID_PARAMETER); #ifdef DEBUG_IOCOUNT int nolock = 0; @@ -4908,32 +5477,29 @@ are any writers to this file. Note that main is acquired, so new handles cannot if (!nolock) mutex_exit(&GIANT_SERIAL_LOCK); #endif - return STATUS_INVALID_PARAMETER; + return (STATUS_INVALID_PARAMETER); } #ifdef DEBUG_IOCOUNT if (!nolock) mutex_exit(&GIANT_SERIAL_LOCK); #endif - if (CallbackData->Parameters.AcquireForSectionSynchronization.SyncType != SyncTypeCreateSection) { - - return STATUS_FSFILTER_OP_COMPLETED_SUCCESSFULLY; - + if (CallbackData-> + Parameters.AcquireForSectionSynchronization.SyncType != + SyncTypeCreateSection) { + return (STATUS_FSFILTER_OP_COMPLETED_SUCCESSFULLY); } else if (vp->share_access.Writers == 0) { - - return STATUS_FILE_LOCKED_WITH_ONLY_READERS; - + return (STATUS_FILE_LOCKED_WITH_ONLY_READERS); } else { - - return STATUS_FILE_LOCKED_WITH_WRITERS; + return (STATUS_FILE_LOCKED_WITH_WRITERS); } } -NTSTATUS ZFSCallbackReleaseForCreateSection( +NTSTATUS +ZFSCallbackReleaseForCreateSection( IN PFS_FILTER_CALLBACK_DATA CallbackData, - OUT PVOID *CompletionContext -) + OUT PVOID *CompletionContext) { struct vnode *vp; vp = CallbackData->FileObject->FsContext; @@ -4941,10 +5507,12 @@ NTSTATUS ZFSCallbackReleaseForCreateSection( dprintf("%s: vp %p\n", __func__, vp); ASSERT(vp != NULL); - if (vp == NULL) return STATUS_INVALID_PARAMETER; + if (vp == NULL) + return (STATUS_INVALID_PARAMETER); if (vp->FileHeader.Resource) { - dprintf("%s: unlocked: %p\n", __func__, vp->FileHeader.Resource); + dprintf("%s: unlocked: %p\n", + __func__, vp->FileHeader.Resource); ExReleaseResourceLite(vp->FileHeader.Resource); #ifdef DEBUG_IOCOUNT int nolock = 0; @@ -4963,10 +5531,11 @@ NTSTATUS ZFSCallbackReleaseForCreateSection( #endif } - return STATUS_FSFILTER_OP_COMPLETED_SUCCESSFULLY; + return (STATUS_FSFILTER_OP_COMPLETED_SUCCESSFULLY); } -void zfs_windows_vnops_callback(PDEVICE_OBJECT deviceObject) +void +zfs_windows_vnops_callback(PDEVICE_OBJECT deviceObject) { } @@ -4978,7 +5547,7 @@ zfs_vfsops_init(void) #ifdef DEBUG_IOCOUNT mutex_init(&GIANT_SERIAL_LOCK, NULL, MUTEX_DEFAULT, NULL); #endif - return 0; + return (0); } int @@ -4988,5 +5557,5 @@ zfs_vfsops_fini(void) #ifdef DEBUG_IOCOUNT mutex_destroy(&GIANT_SERIAL_LOCK); #endif - return 0; + return (0); } diff --git a/module/os/windows/zfs/zfs_vnops_windows_lib.c b/module/os/windows/zfs/zfs_vnops_windows_lib.c index 0f5ddcdcc5f..bf3c9ad95c9 100644 --- a/module/os/windows/zfs/zfs_vnops_windows_lib.c +++ b/module/os/windows/zfs/zfs_vnops_windows_lib.c @@ -21,15 +21,11 @@ /* * Copyright (c) 2017 Jorgen Lundman */ -#define INITGUID -//#include -//#include +#define INITGUID #include #include #include -//#include #include -//#include #include #include #include @@ -48,12 +44,9 @@ #include #include -//#include #include -//#include #include -#include #include #include @@ -73,13 +66,21 @@ typedef struct { UINT32 nums[8]; } sid_header; -static sid_header sid_BA = { 1, 2, SECURITY_NT_AUTHORITY, {32, 544} }; // BUILTIN\Administrators -static sid_header sid_SY = { 1, 1, SECURITY_NT_AUTHORITY, {18} }; // NT AUTHORITY\SYSTEM -static sid_header sid_BU = { 1, 2, SECURITY_NT_AUTHORITY, {32, 545} }; // BUILTIN\Users -static sid_header sid_AU = { 1, 1, SECURITY_NT_AUTHORITY, {11} }; // NT AUTHORITY\Authenticated Users - -static sid_header sid_MH = { 1, 1, SECURITY_MANDATORY_LABEL_AUTHORITY, {12288} }; // MandatoryLevel\High -static sid_header sid_ML = { 1, 1, SECURITY_MANDATORY_LABEL_AUTHORITY, {4096} }; // MandatoryLevel\Low +// BUILTIN\Administrators +static sid_header sid_BA = { 1, 2, SECURITY_NT_AUTHORITY, {32, 544} }; +// NT AUTHORITY\SYSTEM +static sid_header sid_SY = { 1, 1, SECURITY_NT_AUTHORITY, {18} }; +// BUILTIN\Users +static sid_header sid_BU = { 1, 2, SECURITY_NT_AUTHORITY, {32, 545} }; +// NT AUTHORITY\Authenticated Users +static sid_header sid_AU = { 1, 1, SECURITY_NT_AUTHORITY, {11} }; + +// MandatoryLevel\High +static sid_header sid_MH = + { 1, 1, SECURITY_MANDATORY_LABEL_AUTHORITY, {12288} }; +// MandatoryLevel\Low +static sid_header sid_ML = + { 1, 1, SECURITY_MANDATORY_LABEL_AUTHORITY, {4096} }; typedef struct { UCHAR flags; @@ -88,253 +89,264 @@ typedef struct { } dacl; /* - -Brand new ntfs: -F:\ BUILTIN\Administrators:(F) - BUILTIN\Administrators:(OI)(CI)(IO)(F) - NT AUTHORITY\SYSTEM:(F) - NT AUTHORITY\SYSTEM:(OI)(CI)(IO)(F) - NT AUTHORITY\Authenticated Users:(M) - NT AUTHORITY\Authenticated Users:(OI)(CI)(IO)(M) - BUILTIN\Users:(RX) - BUILTIN\Users:(OI)(CI)(IO)(GR,GE) -*/ + * + * Brand new ntfs: + * F:\ BUILTIN\Administrators:(F) + * BUILTIN\Administrators:(OI)(CI)(IO)(F) + * NT AUTHORITY\SYSTEM:(F) + * NT AUTHORITY\SYSTEM:(OI)(CI)(IO)(F) + * NT AUTHORITY\Authenticated Users:(M) + * NT AUTHORITY\Authenticated Users:(OI)(CI)(IO)(M) + * BUILTIN\Users:(RX) + * BUILTIN\Users:(OI)(CI)(IO)(GR,GE) + */ static dacl def_dacls[] = { // BUILTIN\Administrators:(F) { 0, FILE_ALL_ACCESS, &sid_BA }, // BUILTIN\Administrators:(OI)(CI)(IO)(F) - { OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE | INHERIT_ONLY_ACE, FILE_ALL_ACCESS, &sid_BA }, + { OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE | INHERIT_ONLY_ACE, + FILE_ALL_ACCESS, &sid_BA }, // NT AUTHORITY\SYSTEM:(F) { 0, FILE_ALL_ACCESS, &sid_SY }, // NT AUTHORITY\SYSTEM:(OI)(CI)(IO)(F) - { OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE | INHERIT_ONLY_ACE, FILE_ALL_ACCESS, &sid_SY }, + { OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE | INHERIT_ONLY_ACE, + FILE_ALL_ACCESS, &sid_SY }, // NT AUTHORITY\Authenticated Users:(M) - { 0, FILE_GENERIC_READ | FILE_GENERIC_WRITE | DELETE | FILE_GENERIC_EXECUTE, &sid_AU }, + { 0, FILE_GENERIC_READ | FILE_GENERIC_WRITE | DELETE | + FILE_GENERIC_EXECUTE, &sid_AU }, // NT AUTHORITY\Authenticated Users:(OI)(CI)(IO)(M) - { OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE | INHERIT_ONLY_ACE, FILE_GENERIC_READ | FILE_GENERIC_WRITE | DELETE | FILE_GENERIC_EXECUTE, &sid_AU }, + { OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE | INHERIT_ONLY_ACE, + FILE_GENERIC_READ | FILE_GENERIC_WRITE | DELETE | + FILE_GENERIC_EXECUTE, &sid_AU }, // BUILTIN\Users:(RX) { 0, FILE_GENERIC_READ | FILE_GENERIC_EXECUTE, &sid_BU }, // BUILTIN\Users:(OI)(CI)(IO)(GR,GE) - { OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE | INHERIT_ONLY_ACE, GENERIC_READ | GENERIC_EXECUTE, &sid_BU }, + { OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE | INHERIT_ONLY_ACE, + GENERIC_READ | GENERIC_EXECUTE, &sid_BU }, #if 0 // C: only? // Mandatory Label\High Mandatory Level:(OI)(NP)(IO)(NW) - { OBJECT_INHERIT_ACE | NO_PROPAGATE_INHERIT_ACE | INHERIT_ONLY_ACE, SYSTEM_MANDATORY_LABEL_NO_WRITE_UP, &sid_MH }, + { OBJECT_INHERIT_ACE | NO_PROPAGATE_INHERIT_ACE | INHERIT_ONLY_ACE, + SYSTEM_MANDATORY_LABEL_NO_WRITE_UP, &sid_MH }, #endif // END { 0, 0, NULL } }; -//#define USE_RECYCLE_ACL +// #define USE_RECYCLE_ACL #ifdef USE_RECYCLE_ACL /* -Brand new $Recycle.bin - -Owner: WDKRemoteUser -Group: None - -F : \$Recycle.bin BUILTIN\Administrators:(I)(F) - NT AUTHORITY\SYSTEM : (I)(F) - NT AUTHORITY\Authenticated Users : (I)(M) - BUILTIN\Users : (I)(RX) -*/ + * Brand new $Recycle.bin + * + * Owner: WDKRemoteUser + * Group: None + * + * F : \$Recycle.bin BUILTIN\Administrators:(I)(F) + * NT AUTHORITY\SYSTEM : (I)(F) + * NT AUTHORITY\Authenticated Users : (I)(M) + * BUILTIN\Users : (I)(RX) + */ static dacl recycle_dacls[] = { // BUILTIN\Administrators:(I)(F) { INHERITED_ACE, FILE_ALL_ACCESS, &sid_BA }, // NT AUTHORITY\SYSTEM : (I)(F) { INHERITED_ACE, FILE_ALL_ACCESS, &sid_SY }, // NT AUTHORITY\Authenticated Users : (I)(M) - { INHERITED_ACE, FILE_GENERIC_READ | FILE_GENERIC_WRITE | DELETE | FILE_GENERIC_EXECUTE, &sid_AU }, + { INHERITED_ACE, FILE_GENERIC_READ | FILE_GENERIC_WRITE | DELETE + | FILE_GENERIC_EXECUTE, &sid_AU }, // BUILTIN\Users : (I)(RX) { INHERITED_ACE, FILE_GENERIC_READ | FILE_GENERIC_EXECUTE, &sid_BU }, // END { 0, 0, NULL } }; -#endif +#endif -char *major2str(int major, int minor) +char * +major2str(int major, int minor) { switch (major) { case IRP_MJ_CREATE: - return "IRP_MJ_CREATE"; + return ("IRP_MJ_CREATE"); case IRP_MJ_CREATE_NAMED_PIPE: - return "IRP_MJ_CREATE_NAMED_PIPE"; + return ("IRP_MJ_CREATE_NAMED_PIPE"); case IRP_MJ_CLOSE: - return "IRP_MJ_CLOSE"; + return ("IRP_MJ_CLOSE"); case IRP_MJ_READ: - return "IRP_MJ_READ"; + return ("IRP_MJ_READ"); case IRP_MJ_WRITE: - return "IRP_MJ_WRITE"; + return ("IRP_MJ_WRITE"); case IRP_MJ_QUERY_INFORMATION: - return "IRP_MJ_QUERY_INFORMATION"; + return ("IRP_MJ_QUERY_INFORMATION"); case IRP_MJ_SET_INFORMATION: - return "IRP_MJ_SET_INFORMATION"; + return ("IRP_MJ_SET_INFORMATION"); case IRP_MJ_QUERY_EA: - return "IRP_MJ_QUERY_EA"; + return ("IRP_MJ_QUERY_EA"); case IRP_MJ_SET_EA: - return "IRP_MJ_SET_EA"; + return ("IRP_MJ_SET_EA"); case IRP_MJ_FLUSH_BUFFERS: - return "IRP_MJ_FLUSH_BUFFERS"; + return ("IRP_MJ_FLUSH_BUFFERS"); case IRP_MJ_QUERY_VOLUME_INFORMATION: - return "IRP_MJ_QUERY_VOLUME_INFORMATION"; + return ("IRP_MJ_QUERY_VOLUME_INFORMATION"); case IRP_MJ_SET_VOLUME_INFORMATION: - return "IRP_MJ_SET_VOLUME_INFORMATION"; + return ("IRP_MJ_SET_VOLUME_INFORMATION"); case IRP_MJ_DIRECTORY_CONTROL: switch (minor) { case IRP_MN_NOTIFY_CHANGE_DIRECTORY: - return "IRP_MJ_DIRECTORY_CONTROL(IRP_MN_NOTIFY_CHANGE_DIRECTORY)"; + return ("IRP_MJ_DIRECTORY_CONTROL(IRP_MN_NOTIFY_CHANGE_DIRECTORY)"); case IRP_MN_QUERY_DIRECTORY: - return "IRP_MJ_DIRECTORY_CONTROL(IRP_MN_QUERY_DIRECTORY)"; + return ("IRP_MJ_DIRECTORY_CONTROL(IRP_MN_QUERY_DIRECTORY)"); } - return "IRP_MJ_DIRECTORY_CONTROL"; + return ("IRP_MJ_DIRECTORY_CONTROL"); case IRP_MJ_FILE_SYSTEM_CONTROL: switch (minor) { case IRP_MN_KERNEL_CALL: - return "IRP_MJ_FILE_SYSTEM_CONTROL(IRP_MN_KERNEL_CALL)"; + return ("IRP_MJ_FILE_SYSTEM_CONTROL(IRP_MN_KERNEL_CALL)"); case IRP_MN_MOUNT_VOLUME: - return "IRP_MJ_FILE_SYSTEM_CONTROL(IRP_MN_MOUNT_VOLUME)"; + return ("IRP_MJ_FILE_SYSTEM_CONTROL(IRP_MN_MOUNT_VOLUME)"); case IRP_MN_USER_FS_REQUEST: - return "IRP_MJ_FILE_SYSTEM_CONTROL(IRP_MN_USER_FS_REQUEST)"; + return ("IRP_MJ_FILE_SYSTEM_CONTROL(IRP_MN_USER_FS_REQUEST)"); case IRP_MN_VERIFY_VOLUME: - return "IRP_MJ_FILE_SYSTEM_CONTROL(IRP_MN_VERIFY_VOLUME)"; + return ("IRP_MJ_FILE_SYSTEM_CONTROL(IRP_MN_VERIFY_VOLUME)"); case IRP_MN_LOAD_FILE_SYSTEM: - return "IRP_MJ_FILE_SYSTEM_CONTROL(IRP_MN_LOAD_FILE_SYSTEM)"; + return ("IRP_MJ_FILE_SYSTEM_CONTROL(IRP_MN_LOAD_FILE_SYSTEM)"); } - return "IRP_MJ_FILE_SYSTEM_CONTROL"; + return ("IRP_MJ_FILE_SYSTEM_CONTROL"); case IRP_MJ_DEVICE_CONTROL: - return "IRP_MJ_DEVICE_CONTROL"; + return ("IRP_MJ_DEVICE_CONTROL"); case IRP_MJ_INTERNAL_DEVICE_CONTROL: - return "IRP_MJ_INTERNAL_DEVICE_CONTROL"; + return ("IRP_MJ_INTERNAL_DEVICE_CONTROL"); case IRP_MJ_SHUTDOWN: - return "IRP_MJ_SHUTDOWN"; + return ("IRP_MJ_SHUTDOWN"); case IRP_MJ_LOCK_CONTROL: switch (minor) { case IRP_MN_LOCK: - return "IRP_MJ_LOCK_CONTROL(IRP_MN_LOCK)"; + return ("IRP_MJ_LOCK_CONTROL(IRP_MN_LOCK)"); case IRP_MN_UNLOCK_ALL: - return "IRP_MJ_LOCK_CONTROL(IRP_MN_UNLOCK_ALL)"; + return ("IRP_MJ_LOCK_CONTROL(IRP_MN_UNLOCK_ALL)"); case IRP_MN_UNLOCK_ALL_BY_KEY: - return "IRP_MJ_LOCK_CONTROL(IRP_MN_UNLOCK_ALL_BY_KEY)"; + return ("IRP_MJ_LOCK_CONTROL(IRP_MN_UNLOCK_ALL_BY_KEY)"); case IRP_MN_UNLOCK_SINGLE: - return "IRP_MJ_LOCK_CONTROL(IRP_MN_UNLOCK_SINGLE)"; + return ("IRP_MJ_LOCK_CONTROL(IRP_MN_UNLOCK_SINGLE)"); } - return "IRP_MJ_LOCK_CONTROL"; + return ("IRP_MJ_LOCK_CONTROL"); case IRP_MJ_CLEANUP: - return "IRP_MJ_CLEANUP"; + return ("IRP_MJ_CLEANUP"); case IRP_MJ_CREATE_MAILSLOT: - return "IRP_MJ_CREATE_MAILSLOT"; + return ("IRP_MJ_CREATE_MAILSLOT"); case IRP_MJ_QUERY_SECURITY: - return "IRP_MJ_QUERY_SECURITY"; + return ("IRP_MJ_QUERY_SECURITY"); case IRP_MJ_SET_SECURITY: - return "IRP_MJ_SET_SECURITY"; + return ("IRP_MJ_SET_SECURITY"); case IRP_MJ_POWER: - return "IRP_MJ_POWER"; + return ("IRP_MJ_POWER"); case IRP_MJ_SYSTEM_CONTROL: - return "IRP_MJ_SYSTEM_CONTROL"; + return ("IRP_MJ_SYSTEM_CONTROL"); case IRP_MJ_DEVICE_CHANGE: - return "IRP_MJ_DEVICE_CHANGE"; + return ("IRP_MJ_DEVICE_CHANGE"); case IRP_MJ_QUERY_QUOTA: - return "IRP_MJ_QUERY_QUOTA"; + return ("IRP_MJ_QUERY_QUOTA"); case IRP_MJ_SET_QUOTA: - return "IRP_MJ_SET_QUOTA"; + return ("IRP_MJ_SET_QUOTA"); case IRP_MJ_PNP: switch (minor) { case IRP_MN_START_DEVICE: - return "IRP_MJ_PNP(IRP_MN_START_DEVICE)"; + return ("IRP_MJ_PNP(IRP_MN_START_DEVICE)"); case IRP_MN_QUERY_REMOVE_DEVICE: - return "IRP_MJ_PNP(IRP_MN_QUERY_REMOVE_DEVICE)"; + return ("IRP_MJ_PNP(IRP_MN_QUERY_REMOVE_DEVICE)"); case IRP_MN_REMOVE_DEVICE: - return "IRP_MJ_PNP(IRP_MN_REMOVE_DEVICE)"; + return ("IRP_MJ_PNP(IRP_MN_REMOVE_DEVICE)"); case IRP_MN_CANCEL_REMOVE_DEVICE: - return "IRP_MJ_PNP(IRP_MN_CANCEL_REMOVE_DEVICE)"; + return ("IRP_MJ_PNP(IRP_MN_CANCEL_REMOVE_DEVICE)"); case IRP_MN_STOP_DEVICE: - return "IRP_MJ_PNP(IRP_MN_STOP_DEVICE)"; + return ("IRP_MJ_PNP(IRP_MN_STOP_DEVICE)"); case IRP_MN_QUERY_STOP_DEVICE: - return "IRP_MJ_PNP(IRP_MN_QUERY_STOP_DEVICE)"; + return ("IRP_MJ_PNP(IRP_MN_QUERY_STOP_DEVICE)"); case IRP_MN_CANCEL_STOP_DEVICE: - return "IRP_MJ_PNP(IRP_MN_CANCEL_STOP_DEVICE)"; + return ("IRP_MJ_PNP(IRP_MN_CANCEL_STOP_DEVICE)"); case IRP_MN_QUERY_DEVICE_RELATIONS: - return "IRP_MJ_PNP(IRP_MN_QUERY_DEVICE_RELATIONS)"; + return ("IRP_MJ_PNP(IRP_MN_QUERY_DEVICE_RELATIONS)"); case IRP_MN_QUERY_INTERFACE: - return "IRP_MJ_PNP(IRP_MN_QUERY_INTERFACE)"; + return ("IRP_MJ_PNP(IRP_MN_QUERY_INTERFACE)"); case IRP_MN_QUERY_RESOURCES: - return "IRP_MJ_PNP(IRP_MN_QUERY_RESOURCES)"; + return ("IRP_MJ_PNP(IRP_MN_QUERY_RESOURCES)"); case IRP_MN_QUERY_RESOURCE_REQUIREMENTS: - return "IRP_MJ_PNP(IRP_MN_QUERY_RESOURCE_REQUIREMENTS)"; + return ("IRP_MJ_PNP(IRP_MN_QUERY_RESOURCE_REQUIREMENTS)"); case IRP_MN_QUERY_CAPABILITIES: - return "IRP_MJ_PNP(IRP_MN_QUERY_CAPABILITIES)"; + return ("IRP_MJ_PNP(IRP_MN_QUERY_CAPABILITIES)"); case IRP_MN_QUERY_DEVICE_TEXT: - return "IRP_MJ_PNP(IRP_MN_QUERY_DEVICE_TEXT)"; + return ("IRP_MJ_PNP(IRP_MN_QUERY_DEVICE_TEXT)"); case IRP_MN_FILTER_RESOURCE_REQUIREMENTS: - return "IRP_MJ_PNP(IRP_MN_FILTER_RESOURCE_REQUIREMENTS)"; + return ("IRP_MJ_PNP(IRP_MN_FILTER_RESOURCE_REQUIREMENTS)"); case IRP_MN_READ_CONFIG: - return "IRP_MJ_PNP(IRP_MN_READ_CONFIG)"; + return ("IRP_MJ_PNP(IRP_MN_READ_CONFIG)"); case IRP_MN_WRITE_CONFIG: - return "IRP_MJ_PNP(IRP_MN_WRITE_CONFIG)"; + return ("IRP_MJ_PNP(IRP_MN_WRITE_CONFIG)"); case IRP_MN_EJECT: - return "IRP_MJ_PNP(IRP_MN_EJECT)"; + return ("IRP_MJ_PNP(IRP_MN_EJECT)"); case IRP_MN_SET_LOCK: - return "IRP_MJ_PNP(IRP_MN_SET_LOCK)"; + return ("IRP_MJ_PNP(IRP_MN_SET_LOCK)"); case IRP_MN_QUERY_ID: - return "IRP_MJ_PNP(IRP_MN_QUERY_ID)"; + return ("IRP_MJ_PNP(IRP_MN_QUERY_ID)"); case IRP_MN_QUERY_PNP_DEVICE_STATE: - return "IRP_MJ_PNP(IRP_MN_QUERY_PNP_DEVICE_STATE)"; + return ("IRP_MJ_PNP(IRP_MN_QUERY_PNP_DEVICE_STATE)"); case IRP_MN_QUERY_BUS_INFORMATION: - return "IRP_MJ_PNP(IRP_MN_QUERY_BUS_INFORMATION)"; + return ("IRP_MJ_PNP(IRP_MN_QUERY_BUS_INFORMATION)"); case IRP_MN_DEVICE_USAGE_NOTIFICATION: - return "IRP_MJ_PNP(IRP_MN_DEVICE_USAGE_NOTIFICATION)"; + return ("IRP_MJ_PNP(IRP_MN_DEVICE_USAGE_NOTIFICATION)"); case IRP_MN_SURPRISE_REMOVAL: // SUPPLIES! - return "IRP_MJ_PNP(IRP_MN_SURPRISE_REMOVAL)"; + return ("IRP_MJ_PNP(IRP_MN_SURPRISE_REMOVAL)"); } - return "IRP_MJ_PNP"; + return ("IRP_MJ_PNP"); default: break; } - return "Unknown"; + return ("Unknown"); } -char *common_status_str(NTSTATUS Status) +char * +common_status_str(NTSTATUS Status) { switch (Status) { case STATUS_SUCCESS: - return "OK"; + return ("OK"); case STATUS_BUFFER_OVERFLOW: - return "Overflow"; + return ("Overflow"); case STATUS_END_OF_FILE: - return "EOF"; + return ("EOF"); case STATUS_NO_MORE_FILES: - return "NoMoreFiles"; + return ("NoMoreFiles"); case STATUS_OBJECT_PATH_NOT_FOUND: - return "ObjectPathNotFound"; + return ("ObjectPathNotFound"); case STATUS_NO_SUCH_FILE: - return "NoSuchFile"; + return ("NoSuchFile"); case STATUS_ACCESS_DENIED: - return "AccessDenied"; + return ("AccessDenied"); case STATUS_NOT_IMPLEMENTED: - return "NotImplemented"; + return ("NotImplemented"); case STATUS_PENDING: - return "STATUS_PENDING"; + return ("STATUS_PENDING"); case STATUS_INVALID_PARAMETER: - return "STATUS_INVALID_PARAMETER"; + return ("STATUS_INVALID_PARAMETER"); case STATUS_OBJECT_NAME_NOT_FOUND: - return "STATUS_OBJECT_NAME_NOT_FOUND"; + return ("STATUS_OBJECT_NAME_NOT_FOUND"); case STATUS_OBJECT_NAME_COLLISION: - return "STATUS_OBJECT_NAME_COLLISION"; + return ("STATUS_OBJECT_NAME_COLLISION"); case STATUS_FILE_IS_A_DIRECTORY: - return "STATUS_FILE_IS_A_DIRECTORY"; + return ("STATUS_FILE_IS_A_DIRECTORY"); case STATUS_NOT_A_REPARSE_POINT: - return "STATUS_NOT_A_REPARSE_POINT"; + return ("STATUS_NOT_A_REPARSE_POINT"); case STATUS_NOT_FOUND: - return "STATUS_NOT_FOUND"; + return ("STATUS_NOT_FOUND"); case STATUS_NO_MORE_EAS: - return "STATUS_NO_MORE_EAS"; + return ("STATUS_NO_MORE_EAS"); case STATUS_NO_EAS_ON_FILE: - return "STATUS_NO_EAS_ON_FILE"; + return ("STATUS_NO_EAS_ON_FILE"); default: - return "<*****>"; + return ("<*****>"); } } -char *create_options(ULONG Options) +char * +create_options(ULONG Options) { static char out[256]; @@ -349,96 +361,99 @@ char *create_options(ULONG Options) DirectoryFile = BooleanFlagOn(Options, FILE_DIRECTORY_FILE); if (BooleanFlagOn(Options, FILE_DIRECTORY_FILE)) - strlcat(out, "DirectoryFile ", sizeof(out)); + strlcat(out, "DirectoryFile ", sizeof (out)); if (BooleanFlagOn(Options, FILE_NON_DIRECTORY_FILE)) - strlcat(out, "NonDirectoryFile ", sizeof(out)); + strlcat(out, "NonDirectoryFile ", sizeof (out)); if (BooleanFlagOn(Options, FILE_NO_INTERMEDIATE_BUFFERING)) - strlcat(out, "NoIntermediateBuffering ", sizeof(out)); + strlcat(out, "NoIntermediateBuffering ", sizeof (out)); if (BooleanFlagOn(Options, FILE_NO_EA_KNOWLEDGE)) - strlcat(out, "NoEaKnowledge ", sizeof(out)); + strlcat(out, "NoEaKnowledge ", sizeof (out)); if (BooleanFlagOn(Options, FILE_DELETE_ON_CLOSE)) - strlcat(out, "DeleteOnClose ", sizeof(out)); + strlcat(out, "DeleteOnClose ", sizeof (out)); if (BooleanFlagOn(Options, FILE_OPEN_BY_FILE_ID)) - strlcat(out, "FileOpenByFileId ", sizeof(out)); + strlcat(out, "FileOpenByFileId ", sizeof (out)); CreateDisposition = (Options >> 24) & 0x000000ff; switch (CreateDisposition) { case FILE_SUPERSEDE: - strlcat(out, "@FILE_SUPERSEDE ", sizeof(out)); + strlcat(out, "@FILE_SUPERSEDE ", sizeof (out)); break; case FILE_CREATE: - strlcat(out, "@FILE_CREATE ", sizeof(out)); + strlcat(out, "@FILE_CREATE ", sizeof (out)); break; case FILE_OPEN: - strlcat(out, "@FILE_OPEN ", sizeof(out)); + strlcat(out, "@FILE_OPEN ", sizeof (out)); break; case FILE_OPEN_IF: - strlcat(out, "@FILE_OPEN_IF ", sizeof(out)); + strlcat(out, "@FILE_OPEN_IF ", sizeof (out)); break; case FILE_OVERWRITE: - strlcat(out, "@FILE_OVERWRITE ", sizeof(out)); + strlcat(out, "@FILE_OVERWRITE ", sizeof (out)); break; case FILE_OVERWRITE_IF: - strlcat(out, "@FILE_OVERWRITE_IF ", sizeof(out)); + strlcat(out, "@FILE_OVERWRITE_IF ", sizeof (out)); break; } CreateDirectory = (BOOLEAN)(DirectoryFile && - ((CreateDisposition == FILE_CREATE) || - (CreateDisposition == FILE_OPEN_IF))); + ((CreateDisposition == FILE_CREATE) || + (CreateDisposition == FILE_OPEN_IF))); OpenDirectory = (BOOLEAN)(DirectoryFile && - ((CreateDisposition == FILE_OPEN) || - (CreateDisposition == FILE_OPEN_IF))); + ((CreateDisposition == FILE_OPEN) || + (CreateDisposition == FILE_OPEN_IF))); CreateFile = (BOOLEAN)( - ((CreateDisposition == FILE_CREATE) || - (CreateDisposition == FILE_OPEN_IF) || - (CreateDisposition == FILE_SUPERSEDE) || - (CreateDisposition == FILE_OVERWRITE_IF))); + ((CreateDisposition == FILE_CREATE) || + (CreateDisposition == FILE_OPEN_IF) || + (CreateDisposition == FILE_SUPERSEDE) || + (CreateDisposition == FILE_OVERWRITE_IF))); if (CreateDirectory) - strlcat(out, "#CreateDirectory ", sizeof(out)); + strlcat(out, "#CreateDirectory ", sizeof (out)); if (OpenDirectory) - strlcat(out, "#OpenDirectory ", sizeof(out)); + strlcat(out, "#OpenDirectory ", sizeof (out)); if (CreateFile) - strlcat(out, "#CreateFile ", sizeof(out)); + strlcat(out, "#CreateFile ", sizeof (out)); - return out; + return (out); } -char *create_reply(NTSTATUS status, ULONG reply) +char * +create_reply(NTSTATUS status, ULONG reply) { switch (reply) { case FILE_SUPERSEDED: - return "FILE_SUPERSEDED"; + return ("FILE_SUPERSEDED"); case FILE_OPENED: - return "FILE_OPENED"; + return ("FILE_OPENED"); case FILE_CREATED: - return "FILE_CREATED"; + return ("FILE_CREATED"); case FILE_OVERWRITTEN: - return "FILE_OVERWRITTEN"; + return ("FILE_OVERWRITTEN"); case FILE_EXISTS: - return "FILE_EXISTS"; + return ("FILE_EXISTS"); case FILE_DOES_NOT_EXIST: - return "FILE_DOES_NOT_EXIST"; + return ("FILE_DOES_NOT_EXIST"); default: if (status == STATUS_REPARSE) - return "ReparseTag"; - return "FileUnknown"; + return ("ReparseTag"); + return ("FileUnknown"); } } -int AsciiStringToUnicodeString(char *in, PUNICODE_STRING out) +int +AsciiStringToUnicodeString(char *in, PUNICODE_STRING out) { ANSI_STRING conv; conv.Buffer = in; conv.Length = strlen(in); conv.MaximumLength = PATH_MAX; - return RtlAnsiStringToUnicodeString(out, &conv, TRUE); + return (RtlAnsiStringToUnicodeString(out, &conv, TRUE)); } -void FreeUnicodeString(PUNICODE_STRING s) +void +FreeUnicodeString(PUNICODE_STRING s) { if (s->Buffer) ExFreePool(s->Buffer); s->Buffer = NULL; @@ -449,7 +464,7 @@ zfs_vnop_ioctl_fullfsync(struct vnode *vp, vfs_context_t *ct, zfsvfs_t *zfsvfs) { int error = 0; - // error = zfs_fsync(VTOZ(vp), /*syncflag*/0, NULL); + // error = zfs_fsync(VTOZ(vp), /* syncflag */ 0, NULL); return (error); } @@ -457,7 +472,7 @@ uint32_t zfs_getwinflags(znode_t *zp) { uint32_t winflags = 0; - uint64_t zflags=zp->z_pflags; + uint64_t zflags = zp->z_pflags; if (zflags & ZFS_HIDDEN) winflags |= FILE_ATTRIBUTE_HIDDEN; @@ -479,14 +494,14 @@ zfs_getwinflags(znode_t *zp) winflags = FILE_ATTRIBUTE_NORMAL; dprintf("%s: changing zfs 0x%08llx to win 0x%08lx\n", __func__, - zflags, winflags); + zflags, winflags); return (winflags); } -int +int zfs_setwinflags(znode_t *zp, uint32_t winflags) { - uint64_t zflags = 0; + uint64_t zflags = 0; zflags = zp->z_pflags; @@ -513,51 +528,58 @@ zfs_setwinflags(znode_t *zp, uint32_t winflags) if (zp->z_pflags != zflags) { zp->z_pflags = zflags; dprintf("%s changing win 0x%08lx to zfs 0x%08llx\n", __func__, - winflags, zflags); - return 1; + winflags, zflags); + return (1); } - return 0; + return (0); } // WSL uses special EAs to interact with uid/gid/mode/device major/minor // Returns: TRUE if the EA was stored in the vattr. -BOOLEAN vattr_apply_lx_ea(vattr_t *vap, PFILE_FULL_EA_INFORMATION ea) +BOOLEAN +vattr_apply_lx_ea(vattr_t *vap, PFILE_FULL_EA_INFORMATION ea) { BOOLEAN setVap = FALSE; if (ea->EaNameLength != 6 || strncmp(ea->EaName, "$LX", 3) != 0) - return FALSE; + return (FALSE); void *eaValue = &ea->EaName[0] + ea->EaNameLength + 1; - if (strncmp(ea->EaName, LX_FILE_METADATA_UID_EA_NAME, ea->EaNameLength) == 0) { + if (strncmp(ea->EaName, LX_FILE_METADATA_UID_EA_NAME, + ea->EaNameLength) == 0) { vap->va_uid = *(PUINT32)eaValue; vap->va_active |= ATTR_UID; setVap = TRUE; - } else if (strncmp(ea->EaName, LX_FILE_METADATA_GID_EA_NAME, ea->EaNameLength) == 0) { + } else if (strncmp(ea->EaName, LX_FILE_METADATA_GID_EA_NAME, + ea->EaNameLength) == 0) { vap->va_gid = *(PUINT32)eaValue; vap->va_active |= ATTR_GID; setVap = TRUE; - } else if (strncmp(ea->EaName, LX_FILE_METADATA_MODE_EA_NAME, ea->EaNameLength) == 0) { + } else if (strncmp(ea->EaName, LX_FILE_METADATA_MODE_EA_NAME, + ea->EaNameLength) == 0) { vap->va_mode = *(PUINT32)eaValue; vap->va_active |= ATTR_MODE; setVap = TRUE; - } else if (strncmp(ea->EaName, LX_FILE_METADATA_DEVICE_ID_EA_NAME, ea->EaNameLength) == 0) { + } else if (strncmp(ea->EaName, LX_FILE_METADATA_DEVICE_ID_EA_NAME, + ea->EaNameLength) == 0) { UINT32 *vu32 = (UINT32*)eaValue; vap->va_rdev = makedev(vu32[0], vu32[1]); vap->va_active |= VNODE_ATTR_va_rdev; setVap = TRUE; } - return setVap; + return (setVap); } -static int vnode_apply_single_ea(struct vnode *vp, struct vnode *xdvp, FILE_FULL_EA_INFORMATION *ea) +static int +vnode_apply_single_ea(struct vnode *vp, struct vnode *xdvp, + FILE_FULL_EA_INFORMATION *ea) { int error; struct vnode *xvp = NULL; dprintf("%s: xattr '%.*s' valuelen %u\n", __func__, - ea->EaNameLength, ea->EaName, ea->EaValueLength); + ea->EaNameLength, ea->EaName, ea->EaValueLength); if (ea->EaValueLength == 0) { @@ -567,8 +589,8 @@ static int vnode_apply_single_ea(struct vnode *vp, struct vnode *xdvp, FILE_FULL } else { // Add replace EA - error = zfs_obtain_xattr(VTOZ(xdvp), ea->EaName, VTOZ(vp)->z_mode, NULL, - &xvp, 0); + error = zfs_obtain_xattr(VTOZ(xdvp), ea->EaName, + VTOZ(vp)->z_mode, NULL, &xvp, 0); if (error) goto out; @@ -578,7 +600,8 @@ static int vnode_apply_single_ea(struct vnode *vp, struct vnode *xdvp, FILE_FULL /* Write data */ uio_t *uio; uio = uio_create(1, 0, UIO_SYSSPACE, UIO_WRITE); - uio_addiov(uio, ea->EaName + ea->EaNameLength + 1, ea->EaValueLength); + uio_addiov(uio, ea->EaName + ea->EaNameLength + 1, + ea->EaValueLength); error = zfs_write(xvp, uio, 0, NULL); uio_free(uio); } @@ -587,25 +610,30 @@ static int vnode_apply_single_ea(struct vnode *vp, struct vnode *xdvp, FILE_FULL if (xvp != NULL) VN_RELE(xvp); - return error; + return (error); } /* - * Apply a set of EAs to a vnode, while handling special Windows EAs that set UID/GID/Mode/rdev. + * Apply a set of EAs to a vnode, while handling special Windows EAs that + * set UID/GID/Mode/rdev. */ -NTSTATUS vnode_apply_eas(struct vnode *vp, PFILE_FULL_EA_INFORMATION eas, ULONG eaLength, PULONG pEaErrorOffset) +NTSTATUS +vnode_apply_eas(struct vnode *vp, PFILE_FULL_EA_INFORMATION eas, + ULONG eaLength, PULONG pEaErrorOffset) { NTSTATUS Status = STATUS_SUCCESS; - if (vp == NULL || eas == NULL) return STATUS_INVALID_PARAMETER; + if (vp == NULL || eas == NULL) + return (STATUS_INVALID_PARAMETER); // Optional: Check for validity if the caller wants it. if (pEaErrorOffset != NULL) { Status = IoCheckEaBufferValidity(eas, eaLength, pEaErrorOffset); if (!NT_SUCCESS(Status)) { - dprintf("%s: failed validity: 0x%x\n", __func__, Status); - return Status; + dprintf("%s: failed validity: 0x%x\n", + __func__, Status); + return (Status); } } @@ -614,21 +642,27 @@ NTSTATUS vnode_apply_eas(struct vnode *vp, PFILE_FULL_EA_INFORMATION eas, ULONG vattr_t vap = { 0 }; int error; PFILE_FULL_EA_INFORMATION ea; - for (ea = eas; ; ea = (PFILE_FULL_EA_INFORMATION)((uint8_t*)ea + ea->NextEntryOffset)) { + for (ea = eas; /* empty */; + ea = (PFILE_FULL_EA_INFORMATION) + ((uint8_t *)ea + ea->NextEntryOffset)) { if (vattr_apply_lx_ea(&vap, ea)) { - dprintf(" encountered special attrs EA '%.*s'\n", ea->EaNameLength, ea->EaName); + dprintf(" encountered special attrs EA '%.*s'\n", + ea->EaNameLength, ea->EaName); } else { - // optimization: defer creating an xattr dir until the first standard EA + // optimization: defer creating an xattr dir until + // the first standard EA if (xdvp == NULL) { // Open (or Create) the xattr directory - if (zfs_get_xattrdir(VTOZ(vp), &xdzp, NULL, CREATE_XATTR_DIR) != 0) { + if (zfs_get_xattrdir(VTOZ(vp), &xdzp, NULL, + CREATE_XATTR_DIR) != 0) { Status = STATUS_EA_CORRUPT_ERROR; goto out; } xdvp = ZTOV(xdzp); } error = vnode_apply_single_ea(vp, xdvp, ea); - if (error != 0) dprintf(" failed to process xattr: %d\n", error); + if (error != 0) + dprintf("failed to process xattr: %d\n", error); } if (ea->NextEntryOffset == 0) @@ -648,7 +682,7 @@ NTSTATUS vnode_apply_eas(struct vnode *vp, PFILE_FULL_EA_INFORMATION eas, ULONG VN_RELE(xdvp); } - return Status; + return (Status); } /* @@ -667,9 +701,9 @@ NTSTATUS vnode_apply_eas(struct vnode *vp, PFILE_FULL_EA_INFORMATION eas, ULONG */ int zfs_obtain_xattr(znode_t *dzp, const char *name, mode_t mode, cred_t *cr, - vnode_t **vpp, int flag) + vnode_t **vpp, int flag) { - int error=0; + int error = 0; znode_t *xzp = NULL; zfsvfs_t *zfsvfs = dzp->z_zfsvfs; zilog_t *zilog; @@ -681,16 +715,16 @@ zfs_obtain_xattr(znode_t *dzp, const char *name, mode_t mode, cred_t *cr, /* zfs_dirent_lock() expects a component name */ - ZFS_ENTER(zfsvfs); - ZFS_VERIFY_ZP(dzp); - zilog = zfsvfs->z_log; + ZFS_ENTER(zfsvfs); + ZFS_VERIFY_ZP(dzp); + zilog = zfsvfs->z_log; vattr.va_type = VREG; vattr.va_mode = mode & ~S_IFMT; vattr.va_mask = ATTR_TYPE | ATTR_MODE; if ((error = zfs_acl_ids_create(dzp, 0, - &vattr, cr, NULL, &acl_ids)) != 0) { + &vattr, cr, NULL, &acl_ids)) != 0) { ZFS_EXIT(zfsvfs); return (error); } @@ -698,11 +732,10 @@ zfs_obtain_xattr(znode_t *dzp, const char *name, mode_t mode, cred_t *cr, cn.pn_bufsize = strlen(name)+1; cn.pn_buf = (char *)kmem_zalloc(cn.pn_bufsize, KM_SLEEP); - - top: +top: /* Lock the attribute entry name. */ - if ( (error = zfs_dirent_lock(&dl, dzp, (char *)name, &xzp, flag, - NULL, &cn)) ) { + if ((error = zfs_dirent_lock(&dl, dzp, (char *)name, &xzp, flag, + NULL, &cn))) { goto out; } /* If the name already exists, we're done. */ @@ -720,7 +753,7 @@ zfs_obtain_xattr(znode_t *dzp, const char *name, mode_t mode, cred_t *cr, dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0, SPA_MAXBLOCKSIZE); } #endif - zfs_sa_upgrade_txholds(tx, dzp); + zfs_sa_upgrade_txholds(tx, dzp); error = dmu_tx_assign(tx, TXG_WAIT); if (error) { zfs_dirent_unlock(dl); @@ -735,12 +768,12 @@ zfs_obtain_xattr(znode_t *dzp, const char *name, mode_t mode, cred_t *cr, zfs_mknode(dzp, &vattr, tx, cr, 0, &xzp, &acl_ids); - /* - ASSERT(xzp->z_id == zoid); - */ + /* + * ASSERT(xzp->z_id == zoid); + */ (void) zfs_link_create(dl, xzp, tx, ZNEW); zfs_log_create(zilog, tx, TX_CREATE, dzp, xzp, (char *)name, - NULL /* vsecp */, 0 /*acl_ids.z_fuidp*/, &vattr); + NULL /* vsecp */, 0 /* acl_ids.z_fuidp */, &vattr); dmu_tx_commit(tx); /* @@ -749,7 +782,7 @@ zfs_obtain_xattr(znode_t *dzp, const char *name, mode_t mode, cred_t *cr, zfs_znode_getvnode(xzp, dzp, zfsvfs); zfs_dirent_unlock(dl); - out: +out: zfs_acl_ids_free(&acl_ids); if (cn.pn_buf) kmem_free(cn.pn_buf, cn.pn_bufsize); @@ -761,7 +794,7 @@ zfs_obtain_xattr(znode_t *dzp, const char *name, mode_t mode, cred_t *cr, if (xzp) *vpp = ZTOV(xzp); - ZFS_EXIT(zfsvfs); + ZFS_EXIT(zfsvfs); return (error); } @@ -776,8 +809,8 @@ zfs_obtain_xattr(znode_t *dzp, const char *name, mode_t mode, cred_t *cr, */ int ace_trivial_common(void *acep, int aclcnt, - uint64_t (*walk)(void *, uint64_t, int aclcnt, - uint16_t *, uint16_t *, uint32_t *)) + uint64_t (*walk)(void *, uint64_t, int aclcnt, + uint16_t *, uint16_t *, uint32_t *)) { uint16_t flags; uint32_t mask; @@ -796,8 +829,8 @@ ace_trivial_common(void *acep, int aclcnt, } if (flags & (ACE_FILE_INHERIT_ACE| - ACE_DIRECTORY_INHERIT_ACE|ACE_NO_PROPAGATE_INHERIT_ACE| - ACE_INHERIT_ONLY_ACE)) + ACE_DIRECTORY_INHERIT_ACE|ACE_NO_PROPAGATE_INHERIT_ACE| + ACE_INHERIT_ONLY_ACE)) return (1); /* @@ -807,7 +840,7 @@ ace_trivial_common(void *acep, int aclcnt, * attributes or a files ACL. */ if ((mask & (ACE_READ_ACL|ACE_READ_ATTRIBUTES)) && - (type == ACE_ACCESS_DENIED_ACE_TYPE)) + (type == ACE_ACCESS_DENIED_ACE_TYPE)) return (1); /* @@ -818,7 +851,7 @@ ace_trivial_common(void *acep, int aclcnt, /* * Child delete permission should be accompanied by write - */ + */ if ((mask & ACE_DELETE_CHILD) && !(mask & ACE_WRITE_DATA)) return (1); /* @@ -827,9 +860,9 @@ ace_trivial_common(void *acep, int aclcnt, */ if (type == ACE_ACCESS_ALLOWED_ACE_TYPE && - (!(flags & ACE_OWNER) && (mask & - (ACE_WRITE_OWNER|ACE_WRITE_ACL| ACE_WRITE_ATTRIBUTES| - ACE_WRITE_NAMED_ATTRS)))) + (!(flags & ACE_OWNER) && (mask & + (ACE_WRITE_OWNER|ACE_WRITE_ACL| ACE_WRITE_ATTRIBUTES| + ACE_WRITE_NAMED_ATTRS)))) return (1); } @@ -841,96 +874,97 @@ ace_trivial_common(void *acep, int aclcnt, void acl_trivial_access_masks(mode_t mode, boolean_t isdir, trivial_acl_t *masks) { - uint32_t read_mask = ACE_READ_DATA; - uint32_t write_mask = ACE_WRITE_DATA|ACE_APPEND_DATA; - uint32_t execute_mask = ACE_EXECUTE; + uint32_t read_mask = ACE_READ_DATA; + uint32_t write_mask = ACE_WRITE_DATA|ACE_APPEND_DATA; + uint32_t execute_mask = ACE_EXECUTE; if (isdir) write_mask |= ACE_DELETE_CHILD; - masks->deny1 = 0; - if (!(mode & S_IRUSR) && (mode & (S_IRGRP|S_IROTH))) - masks->deny1 |= read_mask; - if (!(mode & S_IWUSR) && (mode & (S_IWGRP|S_IWOTH))) - masks->deny1 |= write_mask; - if (!(mode & S_IXUSR) && (mode & (S_IXGRP|S_IXOTH))) - masks->deny1 |= execute_mask; - - masks->deny2 = 0; - if (!(mode & S_IRGRP) && (mode & S_IROTH)) - masks->deny2 |= read_mask; - if (!(mode & S_IWGRP) && (mode & S_IWOTH)) - masks->deny2 |= write_mask; - if (!(mode & S_IXGRP) && (mode & S_IXOTH)) - masks->deny2 |= execute_mask; - - masks->allow0 = 0; - if ((mode & S_IRUSR) && (!(mode & S_IRGRP) && (mode & S_IROTH))) - masks->allow0 |= read_mask; - if ((mode & S_IWUSR) && (!(mode & S_IWGRP) && (mode & S_IWOTH))) - masks->allow0 |= write_mask; - if ((mode & S_IXUSR) && (!(mode & S_IXGRP) && (mode & S_IXOTH))) - masks->allow0 |= execute_mask; - - masks->owner = ACE_WRITE_ATTRIBUTES|ACE_WRITE_OWNER|ACE_WRITE_ACL| - ACE_WRITE_NAMED_ATTRS|ACE_READ_ACL|ACE_READ_ATTRIBUTES| - ACE_READ_NAMED_ATTRS|ACE_SYNCHRONIZE; - if (mode & S_IRUSR) - masks->owner |= read_mask; - if (mode & S_IWUSR) - masks->owner |= write_mask; - if (mode & S_IXUSR) - masks->owner |= execute_mask; - - masks->group = ACE_READ_ACL|ACE_READ_ATTRIBUTES|ACE_READ_NAMED_ATTRS| - ACE_SYNCHRONIZE; - if (mode & S_IRGRP) - masks->group |= read_mask; - if (mode & S_IWGRP) - masks->group |= write_mask; - if (mode & S_IXGRP) - masks->group |= execute_mask; - - masks->everyone = ACE_READ_ACL|ACE_READ_ATTRIBUTES|ACE_READ_NAMED_ATTRS| - ACE_SYNCHRONIZE; - if (mode & S_IROTH) - masks->everyone |= read_mask; - if (mode & S_IWOTH) - masks->everyone |= write_mask; - if (mode & S_IXOTH) - masks->everyone |= execute_mask; -} - - - -#define KAUTH_DIR_WRITE (KAUTH_VNODE_ACCESS | KAUTH_VNODE_ADD_FILE | \ - KAUTH_VNODE_ADD_SUBDIRECTORY | \ - KAUTH_VNODE_DELETE_CHILD) - -#define KAUTH_DIR_READ (KAUTH_VNODE_ACCESS | KAUTH_VNODE_LIST_DIRECTORY) - -#define KAUTH_DIR_EXECUTE (KAUTH_VNODE_ACCESS | KAUTH_VNODE_SEARCH) - -#define KAUTH_FILE_WRITE (KAUTH_VNODE_ACCESS | KAUTH_VNODE_WRITE_DATA) - -#define KAUTH_FILE_READ (KAUTH_VNODE_ACCESS | KAUTH_VNODE_READ_DATA) - -#define KAUTH_FILE_EXECUTE (KAUTH_VNODE_ACCESS | KAUTH_VNODE_EXECUTE) + masks->deny1 = 0; + if (!(mode & S_IRUSR) && (mode & (S_IRGRP|S_IROTH))) + masks->deny1 |= read_mask; + if (!(mode & S_IWUSR) && (mode & (S_IWGRP|S_IWOTH))) + masks->deny1 |= write_mask; + if (!(mode & S_IXUSR) && (mode & (S_IXGRP|S_IXOTH))) + masks->deny1 |= execute_mask; + + masks->deny2 = 0; + if (!(mode & S_IRGRP) && (mode & S_IROTH)) + masks->deny2 |= read_mask; + if (!(mode & S_IWGRP) && (mode & S_IWOTH)) + masks->deny2 |= write_mask; + if (!(mode & S_IXGRP) && (mode & S_IXOTH)) + masks->deny2 |= execute_mask; + + masks->allow0 = 0; + if ((mode & S_IRUSR) && (!(mode & S_IRGRP) && (mode & S_IROTH))) + masks->allow0 |= read_mask; + if ((mode & S_IWUSR) && (!(mode & S_IWGRP) && (mode & S_IWOTH))) + masks->allow0 |= write_mask; + if ((mode & S_IXUSR) && (!(mode & S_IXGRP) && (mode & S_IXOTH))) + masks->allow0 |= execute_mask; + + masks->owner = ACE_WRITE_ATTRIBUTES|ACE_WRITE_OWNER|ACE_WRITE_ACL| + ACE_WRITE_NAMED_ATTRS|ACE_READ_ACL|ACE_READ_ATTRIBUTES| + ACE_READ_NAMED_ATTRS|ACE_SYNCHRONIZE; + if (mode & S_IRUSR) + masks->owner |= read_mask; + if (mode & S_IWUSR) + masks->owner |= write_mask; + if (mode & S_IXUSR) + masks->owner |= execute_mask; + + masks->group = ACE_READ_ACL|ACE_READ_ATTRIBUTES|ACE_READ_NAMED_ATTRS| + ACE_SYNCHRONIZE; + if (mode & S_IRGRP) + masks->group |= read_mask; + if (mode & S_IWGRP) + masks->group |= write_mask; + if (mode & S_IXGRP) + masks->group |= execute_mask; + + masks->everyone = ACE_READ_ACL|ACE_READ_ATTRIBUTES|ACE_READ_NAMED_ATTRS| + ACE_SYNCHRONIZE; + if (mode & S_IROTH) + masks->everyone |= read_mask; + if (mode & S_IWOTH) + masks->everyone |= write_mask; + if (mode & S_IXOTH) + masks->everyone |= execute_mask; +} + + + +#define KAUTH_DIR_WRITE (KAUTH_VNODE_ACCESS | KAUTH_VNODE_ADD_FILE | \ + KAUTH_VNODE_ADD_SUBDIRECTORY | \ + KAUTH_VNODE_DELETE_CHILD) + +#define KAUTH_DIR_READ (KAUTH_VNODE_ACCESS | KAUTH_VNODE_LIST_DIRECTORY) + +#define KAUTH_DIR_EXECUTE (KAUTH_VNODE_ACCESS | KAUTH_VNODE_SEARCH) + +#define KAUTH_FILE_WRITE (KAUTH_VNODE_ACCESS | KAUTH_VNODE_WRITE_DATA) + +#define KAUTH_FILE_READ (KAUTH_VNODE_ACCESS | KAUTH_VNODE_READ_DATA) + +#define KAUTH_FILE_EXECUTE (KAUTH_VNODE_ACCESS | KAUTH_VNODE_EXECUTE) /* * Compute the same user access value as getattrlist(2) */ -uint32_t getuseraccess(znode_t *zp, vfs_context_t ctx) +uint32_t +getuseraccess(znode_t *zp, vfs_context_t ctx) { uint32_t user_access = 0; #if 0 vnode_t *vp; int error = 0; - zfs_acl_phys_t acl_phys; + zfs_acl_phys_t acl_phys; /* Only take the expensive vnode_authorize path when we have an ACL */ - error = sa_lookup(zp->z_sa_hdl, SA_ZPL_ZNODE_ACL(zp->z_zfsvfs), - &acl_phys, sizeof (acl_phys)); + error = sa_lookup(zp->z_sa_hdl, SA_ZPL_ZNODE_ACL(zp->z_zfsvfs), + &acl_phys, sizeof (acl_phys)); if (error || acl_phys.z_acl_count == 0) { kauth_cred_t cred = vfs_context_ucred(ctx); @@ -942,12 +976,12 @@ uint32_t getuseraccess(znode_t *zp, vfs_context_t ctx) return (R_OK | W_OK | X_OK); } - sa_lookup(zp->z_sa_hdl, SA_ZPL_UID(zp->z_zfsvfs), - &obj_uid, sizeof (obj_uid)); - sa_lookup(zp->z_sa_hdl, SA_ZPL_MODE(zp->z_zfsvfs), - &obj_mode, sizeof (obj_mode)); + sa_lookup(zp->z_sa_hdl, SA_ZPL_UID(zp->z_zfsvfs), + &obj_uid, sizeof (obj_uid)); + sa_lookup(zp->z_sa_hdl, SA_ZPL_MODE(zp->z_zfsvfs), + &obj_mode, sizeof (obj_mode)); - //obj_uid = pzp->zp_uid; + // obj_uid = pzp->zp_uid; obj_mode = obj_mode & MODEMASK; if (obj_uid == UNKNOWNUID) { obj_uid = kauth_cred_getuid(cred); @@ -982,197 +1016,196 @@ uint32_t getuseraccess(znode_t *zp, vfs_context_t ctx) static unsigned char fingerprint[] = {0xab, 0xcd, 0xef, 0xab, 0xcd, 0xef, - 0xab, 0xcd, 0xef, 0xab, 0xcd, 0xef}; + 0xab, 0xcd, 0xef, 0xab, 0xcd, 0xef}; /* * Convert "Well Known" GUID to enum type. */ -int kauth_wellknown_guid(guid_t *guid) +int +kauth_wellknown_guid(guid_t *guid) { - uint32_t last = 0; + uint32_t last = 0; - if (memcmp(fingerprint, guid->g_guid, sizeof(fingerprint))) - return KAUTH_WKG_NOT; + if (memcmp(fingerprint, guid->g_guid, sizeof (fingerprint))) + return (KAUTH_WKG_NOT); - last = BE_32(*((uint32_t *)&guid->g_guid[12])); + last = BE_32(*((uint32_t *)&guid->g_guid[12])); - switch(last) { - case 0x0c: - return KAUTH_WKG_EVERYBODY; - case 0x0a: - return KAUTH_WKG_OWNER; - case 0x10: - return KAUTH_WKG_GROUP; - case 0xFFFFFFFE: - return KAUTH_WKG_NOBODY; - } + switch (last) { + case 0x0c: + return (KAUTH_WKG_EVERYBODY); + case 0x0a: + return (KAUTH_WKG_OWNER); + case 0x10: + return (KAUTH_WKG_GROUP); + case 0xFFFFFFFE: + return (KAUTH_WKG_NOBODY); + } - return KAUTH_WKG_NOT; + return (KAUTH_WKG_NOT); } /* * Set GUID to "well known" guid, based on enum type */ -void nfsacl_set_wellknown(int wkg, guid_t *guid) -{ - /* - * All WKGs begin with the same 12 bytes. - */ - bcopy(fingerprint, (void *)guid, 12); - /* - * The final 4 bytes are our code (in network byte order). - */ - switch (wkg) { - case 4: - *((uint32_t *)&guid->g_guid[12]) = BE_32(0x0000000c); - break; - case 3: - *((uint32_t *)&guid->g_guid[12]) = BE_32(0xfffffffe); - break; - case 1: - *((uint32_t *)&guid->g_guid[12]) = BE_32(0x0000000a); - break; - case 2: - *((uint32_t *)&guid->g_guid[12]) = BE_32(0x00000010); - }; +void +nfsacl_set_wellknown(int wkg, guid_t *guid) +{ + /* + * All WKGs begin with the same 12 bytes. + */ + bcopy(fingerprint, (void *)guid, 12); + /* + * The final 4 bytes are our code (in network byte order). + */ + switch (wkg) { + case 4: + *((uint32_t *)&guid->g_guid[12]) = BE_32(0x0000000c); + break; + case 3: + *((uint32_t *)&guid->g_guid[12]) = BE_32(0xfffffffe); + break; + case 1: + *((uint32_t *)&guid->g_guid[12]) = BE_32(0x0000000a); + break; + case 2: + *((uint32_t *)&guid->g_guid[12]) = BE_32(0x00000010); + }; } /* * Convert Darwin ACL list, into ZFS ACL "aces" list. */ -void aces_from_acl(ace_t *aces, int *nentries, struct kauth_acl *k_acl, - int *seen_type) +void +aces_from_acl(ace_t *aces, int *nentries, struct kauth_acl *k_acl, + int *seen_type) { #if 0 - int i; - ace_t *ace; - guid_t *guidp; - kauth_ace_rights_t *ace_rights; - uid_t who; - uint32_t mask = 0; - uint16_t flags = 0; - uint16_t type = 0; - uint32_t ace_flags; - int wkg; + int i; + ace_t *ace; + guid_t *guidp; + kauth_ace_rights_t *ace_rights; + uid_t who; + uint32_t mask = 0; + uint16_t flags = 0; + uint16_t type = 0; + uint32_t ace_flags; + int wkg; int err = 0; - *nentries = k_acl->acl_entrycount; - - //bzero(aces, sizeof(*aces) * *nentries); - - //*nentries = aclp->acl_cnt; + *nentries = k_acl->acl_entrycount; - for (i = 0; i < *nentries; i++) { - //entry = &(aclp->acl_entry[i]); + // bzero(aces, sizeof (*aces) * *nentries); - flags = 0; - mask = 0; + // *nentries = aclp->acl_cnt; + for (i = 0; i < *nentries; i++) { + // entry = &(aclp->acl_entry[i]); + flags = 0; + mask = 0; - ace = &(aces[i]); + ace = &(aces[i]); - /* Note Mac OS X GUID is a 128-bit identifier */ - guidp = &k_acl->acl_ace[i].ace_applicable; + /* Note Mac OS X GUID is a 128-bit identifier */ + guidp = &k_acl->acl_ace[i].ace_applicable; - who = -1; - wkg = kauth_wellknown_guid(guidp); + who = -1; + wkg = kauth_wellknown_guid(guidp); - switch(wkg) { - case KAUTH_WKG_OWNER: - flags |= ACE_OWNER; - if (seen_type) *seen_type |= ACE_OWNER; - break; - case KAUTH_WKG_GROUP: - flags |= ACE_GROUP|ACE_IDENTIFIER_GROUP; - if (seen_type) *seen_type |= ACE_GROUP; - break; - case KAUTH_WKG_EVERYBODY: - flags |= ACE_EVERYONE; - if (seen_type) *seen_type |= ACE_EVERYONE; - break; + switch (wkg) { + case KAUTH_WKG_OWNER: + flags |= ACE_OWNER; + if (seen_type) *seen_type |= ACE_OWNER; + break; + case KAUTH_WKG_GROUP: + flags |= ACE_GROUP|ACE_IDENTIFIER_GROUP; + if (seen_type) *seen_type |= ACE_GROUP; + break; + case KAUTH_WKG_EVERYBODY: + flags |= ACE_EVERYONE; + if (seen_type) *seen_type |= ACE_EVERYONE; + break; - case KAUTH_WKG_NOBODY: - default: - /* Try to get a uid from supplied guid */ - err = kauth_cred_guid2uid(guidp, &who); - if (err) { - err = kauth_cred_guid2gid(guidp, &who); - if (!err) { - flags |= ACE_IDENTIFIER_GROUP; + case KAUTH_WKG_NOBODY: + default: + /* Try to get a uid from supplied guid */ + err = kauth_cred_guid2uid(guidp, &who); + if (err) { + err = kauth_cred_guid2gid(guidp, &who); + if (!err) { + flags |= ACE_IDENTIFIER_GROUP; + } } - } - if (err) { - *nentries=0; - dprintf("ZFS: returning due to guid2gid\n"); - return; - } - - } // switch - - ace->a_who = who; - - ace_rights = k_acl->acl_ace[i].ace_rights; - if (ace_rights & KAUTH_VNODE_READ_DATA) - mask |= ACE_READ_DATA; - if (ace_rights & KAUTH_VNODE_WRITE_DATA) - mask |= ACE_WRITE_DATA; - if (ace_rights & KAUTH_VNODE_APPEND_DATA) - mask |= ACE_APPEND_DATA; - if (ace_rights & KAUTH_VNODE_READ_EXTATTRIBUTES) - mask |= ACE_READ_NAMED_ATTRS; - if (ace_rights & KAUTH_VNODE_WRITE_EXTATTRIBUTES) - mask |= ACE_WRITE_NAMED_ATTRS; - if (ace_rights & KAUTH_VNODE_EXECUTE) - mask |= ACE_EXECUTE; - if (ace_rights & KAUTH_VNODE_DELETE_CHILD) - mask |= ACE_DELETE_CHILD; - if (ace_rights & KAUTH_VNODE_READ_ATTRIBUTES) - mask |= ACE_READ_ATTRIBUTES; - if (ace_rights & KAUTH_VNODE_WRITE_ATTRIBUTES) - mask |= ACE_WRITE_ATTRIBUTES; - if (ace_rights & KAUTH_VNODE_DELETE) - mask |= ACE_DELETE; - if (ace_rights & KAUTH_VNODE_READ_SECURITY) - mask |= ACE_READ_ACL; - if (ace_rights & KAUTH_VNODE_WRITE_SECURITY) - mask |= ACE_WRITE_ACL; - if (ace_rights & KAUTH_VNODE_TAKE_OWNERSHIP) - mask |= ACE_WRITE_OWNER; - if (ace_rights & KAUTH_VNODE_SYNCHRONIZE) - mask |= ACE_SYNCHRONIZE; - ace->a_access_mask = mask; - - ace_flags = k_acl->acl_ace[i].ace_flags; - if (ace_flags & KAUTH_ACE_FILE_INHERIT) - flags |= ACE_FILE_INHERIT_ACE; - if (ace_flags & KAUTH_ACE_DIRECTORY_INHERIT) - flags |= ACE_DIRECTORY_INHERIT_ACE; - if (ace_flags & KAUTH_ACE_LIMIT_INHERIT) - flags |= ACE_NO_PROPAGATE_INHERIT_ACE; - if (ace_flags & KAUTH_ACE_ONLY_INHERIT) - flags |= ACE_INHERIT_ONLY_ACE; - ace->a_flags = flags; - - switch(ace_flags & KAUTH_ACE_KINDMASK) { - case KAUTH_ACE_PERMIT: - type = ACE_ACCESS_ALLOWED_ACE_TYPE; - break; - case KAUTH_ACE_DENY: - type = ACE_ACCESS_DENIED_ACE_TYPE; - break; - case KAUTH_ACE_AUDIT: - type = ACE_SYSTEM_AUDIT_ACE_TYPE; - break; - case KAUTH_ACE_ALARM: - type = ACE_SYSTEM_ALARM_ACE_TYPE; - break; - } - ace->a_type = type; - dprintf(" ACL: %d type %04x, mask %04x, flags %04x, who %d\n", - i, type, mask, flags, who); - } + if (err) { + *nentries = 0; + dprintf("ZFS: return to guid2gid\n"); + return; + } + } // switch + ace->a_who = who; + + ace_rights = k_acl->acl_ace[i].ace_rights; + if (ace_rights & KAUTH_VNODE_READ_DATA) + mask |= ACE_READ_DATA; + if (ace_rights & KAUTH_VNODE_WRITE_DATA) + mask |= ACE_WRITE_DATA; + if (ace_rights & KAUTH_VNODE_APPEND_DATA) + mask |= ACE_APPEND_DATA; + if (ace_rights & KAUTH_VNODE_READ_EXTATTRIBUTES) + mask |= ACE_READ_NAMED_ATTRS; + if (ace_rights & KAUTH_VNODE_WRITE_EXTATTRIBUTES) + mask |= ACE_WRITE_NAMED_ATTRS; + if (ace_rights & KAUTH_VNODE_EXECUTE) + mask |= ACE_EXECUTE; + if (ace_rights & KAUTH_VNODE_DELETE_CHILD) + mask |= ACE_DELETE_CHILD; + if (ace_rights & KAUTH_VNODE_READ_ATTRIBUTES) + mask |= ACE_READ_ATTRIBUTES; + if (ace_rights & KAUTH_VNODE_WRITE_ATTRIBUTES) + mask |= ACE_WRITE_ATTRIBUTES; + if (ace_rights & KAUTH_VNODE_DELETE) + mask |= ACE_DELETE; + if (ace_rights & KAUTH_VNODE_READ_SECURITY) + mask |= ACE_READ_ACL; + if (ace_rights & KAUTH_VNODE_WRITE_SECURITY) + mask |= ACE_WRITE_ACL; + if (ace_rights & KAUTH_VNODE_TAKE_OWNERSHIP) + mask |= ACE_WRITE_OWNER; + if (ace_rights & KAUTH_VNODE_SYNCHRONIZE) + mask |= ACE_SYNCHRONIZE; + ace->a_access_mask = mask; + + ace_flags = k_acl->acl_ace[i].ace_flags; + if (ace_flags & KAUTH_ACE_FILE_INHERIT) + flags |= ACE_FILE_INHERIT_ACE; + if (ace_flags & KAUTH_ACE_DIRECTORY_INHERIT) + flags |= ACE_DIRECTORY_INHERIT_ACE; + if (ace_flags & KAUTH_ACE_LIMIT_INHERIT) + flags |= ACE_NO_PROPAGATE_INHERIT_ACE; + if (ace_flags & KAUTH_ACE_ONLY_INHERIT) + flags |= ACE_INHERIT_ONLY_ACE; + ace->a_flags = flags; + + switch (ace_flags & KAUTH_ACE_KINDMASK) { + case KAUTH_ACE_PERMIT: + type = ACE_ACCESS_ALLOWED_ACE_TYPE; + break; + case KAUTH_ACE_DENY: + type = ACE_ACCESS_DENIED_ACE_TYPE; + break; + case KAUTH_ACE_AUDIT: + type = ACE_SYSTEM_AUDIT_ACE_TYPE; + break; + case KAUTH_ACE_ALARM: + type = ACE_SYSTEM_ALARM_ACE_TYPE; + break; + } + ace->a_type = type; + dprintf(" ACL: %d type %04x, mask %04x, flags %04x, who %d\n", + i, type, mask, flags, who); + } #endif } @@ -1180,7 +1213,7 @@ void aces_from_acl(ace_t *aces, int *nentries, struct kauth_acl *k_acl, int zpl_xattr_set_sa(struct vnode *vp, const char *name, const void *value, - size_t size, int flags, cred_t *cr) + size_t size, int flags, cred_t *cr) { znode_t *zp = VTOZ(vp); nvlist_t *nvl; @@ -1193,33 +1226,33 @@ zpl_xattr_set_sa(struct vnode *vp, const char *name, const void *value, if (value == NULL) { error = -nvlist_remove(nvl, name, DATA_TYPE_BYTE_ARRAY); if (error == -ENOENT) - return error; - //error = zpl_xattr_set_dir(vp, name, NULL, 0, flags, cr); - } else { - /* Limited to 32k to keep nvpair memory allocations small */ - if (size > DXATTR_MAX_ENTRY_SIZE) - return (-EFBIG); + return (error); + // error = zpl_xattr_set_dir(vp, name, NULL, 0, flags, cr); + } else { + /* Limited to 32k to keep nvpair memory allocations small */ + if (size > DXATTR_MAX_ENTRY_SIZE) + return (-EFBIG); - /* Prevent the DXATTR SA from consuming the entire SA region */ - error = -nvlist_size(nvl, &sa_size, NV_ENCODE_XDR); - if (error) - return (error); + /* Prevent the DXATTR SA from consuming the entire SA region */ + error = -nvlist_size(nvl, &sa_size, NV_ENCODE_XDR); + if (error) + return (error); - if (sa_size > DXATTR_MAX_SA_SIZE) - return (-EFBIG); - error = -nvlist_add_byte_array(nvl, name, - (uchar_t *)value, size); - if (error) - return (error); - } + if (sa_size > DXATTR_MAX_SA_SIZE) + return (-EFBIG); + error = -nvlist_add_byte_array(nvl, name, + (uchar_t *)value, size); + if (error) + return (error); + } - /* Update the SA for additions, modifications, and removals. */ - if (!error) - error = -zfs_sa_set_xattr(zp); + /* Update the SA for additions, modifications, and removals. */ + if (!error) + error = -zfs_sa_set_xattr(zp); - ASSERT3S(error, <=, 0); + ASSERT3S(error, <=, 0); - return (error); + return (error); } int @@ -1244,7 +1277,7 @@ zpl_xattr_get_sa(struct vnode *vp, const char *name, void *value, size_t size) ASSERT(zp->z_xattr_cached); error = -nvlist_lookup_byte_array(zp->z_xattr_cached, name, - &nv_value, &nv_size); + &nv_value, &nv_size); if (error) return (error); @@ -1300,10 +1333,10 @@ zfs_vfs_uuid_gen(const char *osname, uuid_t uuid) * UUID version 3 (MD5) namespace variant: * hash namespace (uuid) together with name */ - MD5Init( &md5c ); - MD5Update( &md5c, &namespace, sizeof (namespace)); - MD5Update( &md5c, osname, strlen(osname)); - MD5Final( uuid, &md5c ); + MD5Init(&md5c); + MD5Update(&md5c, &namespace, sizeof (namespace)); + MD5Update(&md5c, osname, strlen(osname)); + MD5Final(uuid, &md5c); /* * To make UUID version 3, twiddle a few bits: @@ -1316,7 +1349,7 @@ zfs_vfs_uuid_gen(const char *osname, uuid_t uuid) uuid[8] = (uuid[8] & 0x3F) | 0x80; /* Print all caps */ - //dprintf("%s UUIDgen: [%s](%ld)->" + // dprintf("%s UUIDgen: [%s](%ld)->" dprintf("%s UUIDgen: [%s](%ld) -> " "[%02X%02X%02X%02X-%02X%02X-%02X%02X-" "%02X%02X-%02X%02X%02X%02X%02X%02X]\n", @@ -1336,11 +1369,13 @@ zfs_vfs_uuid_gen(const char *osname, uuid_t uuid) * not NULL, it too should be held. * Returned is an allocated string (kmem_alloc) which should be freed * by caller (kmem_free(fullpath, returnsize)). - * If supplied, start_zp_offset, is the index into fullpath where the + * If supplied, start_zp_offset, is the index into fullpath where the * start_zp component name starts. (Point between start_parent/start_zp). * returnsize includes the final NULL, so it is strlen(fullpath)+1 */ -int zfs_build_path(znode_t *start_zp, znode_t *start_parent, char **fullpath, uint32_t *returnsize, uint32_t *start_zp_offset) +int +zfs_build_path(znode_t *start_zp, znode_t *start_parent, char **fullpath, + uint32_t *returnsize, uint32_t *start_zp_offset) { char *work; int index, size, part, error; @@ -1352,9 +1387,11 @@ int zfs_build_path(znode_t *start_zp, znode_t *start_parent, char **fullpath, ui zfsvfs_t *zfsvfs; char name[MAXPATHLEN]; // No output? nothing to do - if (!fullpath) return EINVAL; + if (!fullpath) + return (EINVAL); // No input? nothing to do - if (!start_zp) return EINVAL; + if (!start_zp) + return (EINVAL); zfsvfs = start_zp->z_zfsvfs; zp = start_zp; @@ -1367,7 +1404,7 @@ int zfs_build_path(znode_t *start_zp, znode_t *start_parent, char **fullpath, ui work[--index] = 0; size = 1; - while(1) { + while (1) { // Fetch parent if (start_parent) { @@ -1377,10 +1414,11 @@ int zfs_build_path(znode_t *start_zp, znode_t *start_parent, char **fullpath, ui start_parent = NULL; } else if (zp->z_sa_hdl != NULL) { VERIFY(sa_lookup(zp->z_sa_hdl, SA_ZPL_PARENT(zfsvfs), - &parent, sizeof(parent)) == 0); + &parent, sizeof (parent)) == 0); error = zfs_zget(zfsvfs, parent, &dzp); if (error) { - dprintf("%s: zget failed %d\n", __func__, error); + dprintf("%s: zget failed %d\n", + __func__, error); goto failed; } } @@ -1389,11 +1427,12 @@ int zfs_build_path(znode_t *start_zp, znode_t *start_parent, char **fullpath, ui // Find name if (zp->z_id == zfsvfs->z_root || zp->z_id == ZFSCTL_INO_ROOT) - strlcpy(name, "", MAXPATHLEN); // Empty string, as we add "\\" below + strlcpy(name, "", MAXPATHLEN); else - if ((error = zap_value_search(zfsvfs->z_os, parent, zp->z_id, - ZFS_DIRENT_OBJ(-1ULL), name)) != 0) { - dprintf("%s: zap_value_search failed %d\n", __func__, error); + if ((error = zap_value_search(zfsvfs->z_os, parent, + zp->z_id, ZFS_DIRENT_OBJ(-1ULL), name)) != 0) { + dprintf("%s: zap_value_search failed %d\n", + __func__, error); goto failed; } // Copy in name. @@ -1443,7 +1482,7 @@ int zfs_build_path(znode_t *start_zp, znode_t *start_parent, char **fullpath, ui memmove(*fullpath, &work[index], size); kmem_free(work, MAXPATHLEN * 2); dprintf("%s: set '%s' as name\n", __func__, *fullpath); - return 0; + return (0); failed: if (zp != NULL) @@ -1451,27 +1490,30 @@ int zfs_build_path(znode_t *start_zp, znode_t *start_parent, char **fullpath, ui if (dzp != NULL) VN_RELE(ZTOV(dzp)); kmem_free(work, MAXPATHLEN * 2); - return -1; + return (-1); } /* -* This is connected to IRP_MN_NOTIFY_DIRECTORY_CHANGE -* and sending the notifications of changes -*/ -void zfs_send_notify_stream(zfsvfs_t *zfsvfs, char *name, int nameoffset, ULONG FilterMatch, ULONG Action, char *stream) + * This is connected to IRP_MN_NOTIFY_DIRECTORY_CHANGE + * and sending the notifications of changes + */ +void +zfs_send_notify_stream(zfsvfs_t *zfsvfs, char *name, int nameoffset, + ULONG FilterMatch, ULONG Action, char *stream) { mount_t *zmo; zmo = zfsvfs->z_vfs; UNICODE_STRING ustr; UNICODE_STRING ustream; - if (name == NULL) return; + if (name == NULL) + return; AsciiStringToUnicodeString(name, &ustr); - dprintf("%s: '%wZ' part '%S' %u %u\n", __func__, &ustr, - /*&name[nameoffset],*/ &ustr.Buffer[nameoffset], - FilterMatch, Action); + dprintf("%s: '%wZ' part '%S' %u %u\n", __func__, &ustr, + /* &name[nameoffset], */ &ustr.Buffer[nameoffset], + FilterMatch, Action); if (stream != NULL) { AsciiStringToUnicodeString(stream, &ustream); @@ -1479,23 +1521,27 @@ void zfs_send_notify_stream(zfsvfs_t *zfsvfs, char *name, int nameoffset, ULONG } FsRtlNotifyFullReportChange(zmo->NotifySync, &zmo->DirNotifyList, - (PSTRING)&ustr, nameoffset * sizeof(WCHAR), - stream == NULL ? NULL : (PSTRING)&ustream , // StreamName - NULL, // NormalizedParentName - FilterMatch, Action, - NULL); // TargetContext + (PSTRING)&ustr, nameoffset * sizeof (WCHAR), + stream == NULL ? NULL : (PSTRING)&ustream, // StreamName + NULL, // NormalizedParentName + FilterMatch, Action, + NULL); // TargetContext FreeUnicodeString(&ustr); if (stream != NULL) FreeUnicodeString(&ustream); } -void zfs_send_notify(zfsvfs_t *zfsvfs, char *name, int nameoffset, ULONG FilterMatch, ULONG Action) +void +zfs_send_notify(zfsvfs_t *zfsvfs, char *name, int nameoffset, + ULONG FilterMatch, ULONG Action) { - zfs_send_notify_stream(zfsvfs, name, nameoffset, FilterMatch, Action, NULL); + zfs_send_notify_stream(zfsvfs, name, nameoffset, FilterMatch, + Action, NULL); } -void zfs_uid2sid(uint64_t uid, SID **sid) +void +zfs_uid2sid(uint64_t uid, SID **sid) { int num; SID *tmp; @@ -1506,7 +1552,7 @@ void zfs_uid2sid(uint64_t uid, SID **sid) num = (uid == 0) ? 1 : 2; tmp = ExAllocatePoolWithTag(PagedPool, - offsetof(SID, SubAuthority) + (num * sizeof(ULONG)), 'zsid'); + offsetof(SID, SubAuthority) + (num * sizeof (ULONG)), 'zsid'); tmp->Revision = 1; tmp->SubAuthorityCount = num; @@ -1528,26 +1574,36 @@ void zfs_uid2sid(uint64_t uid, SID **sid) *sid = tmp; } -uint64_t zfs_sid2uid(SID *sid) +uint64_t +zfs_sid2uid(SID *sid) { // Root - if (sid->Revision == 1 && sid->SubAuthorityCount == 1 && - sid->IdentifierAuthority.Value[0] == 0 && sid->IdentifierAuthority.Value[1] == 0 && sid->IdentifierAuthority.Value[2] == 0 && - sid->IdentifierAuthority.Value[3] == 0 && sid->IdentifierAuthority.Value[4] == 0 && sid->IdentifierAuthority.Value[5] == 18) - return 0; + if (sid->Revision == 1 && sid->SubAuthorityCount == 1 && + sid->IdentifierAuthority.Value[0] == 0 && + sid->IdentifierAuthority.Value[1] == 0 && + sid->IdentifierAuthority.Value[2] == 0 && + sid->IdentifierAuthority.Value[3] == 0 && + sid->IdentifierAuthority.Value[4] == 0 && + sid->IdentifierAuthority.Value[5] == 18) + return (0); // Samba's SID scheme: S-1-22-1-X if (sid->Revision == 1 && sid->SubAuthorityCount == 2 && - sid->IdentifierAuthority.Value[0] == 0 && sid->IdentifierAuthority.Value[1] == 0 && sid->IdentifierAuthority.Value[2] == 0 && - sid->IdentifierAuthority.Value[3] == 0 && sid->IdentifierAuthority.Value[4] == 0 && sid->IdentifierAuthority.Value[5] == 22 && - sid->SubAuthority[0] == 1) - return sid->SubAuthority[1]; - - return UID_NOBODY; + sid->IdentifierAuthority.Value[0] == 0 && + sid->IdentifierAuthority.Value[1] == 0 && + sid->IdentifierAuthority.Value[2] == 0 && + sid->IdentifierAuthority.Value[3] == 0 && + sid->IdentifierAuthority.Value[4] == 0 && + sid->IdentifierAuthority.Value[5] == 22 && + sid->SubAuthority[0] == 1) + return (sid->SubAuthority[1]); + + return (UID_NOBODY); } -void zfs_gid2sid(uint64_t gid, SID **sid) +void +zfs_gid2sid(uint64_t gid, SID **sid) { int num = 2; SID *tmp; @@ -1555,7 +1611,7 @@ void zfs_gid2sid(uint64_t gid, SID **sid) ASSERT(sid != NULL); tmp = ExAllocatePoolWithTag(PagedPool, - offsetof(SID, SubAuthority) + (num * sizeof(ULONG)), 'zsid'); + offsetof(SID, SubAuthority) + (num * sizeof (ULONG)), 'zsid'); tmp->Revision = 1; tmp->SubAuthorityCount = num; @@ -1572,7 +1628,8 @@ void zfs_gid2sid(uint64_t gid, SID **sid) *sid = tmp; } -void zfs_freesid(SID *sid) +void +zfs_freesid(SID *sid) { ASSERT(sid != NULL); ExFreePool(sid); @@ -1580,23 +1637,24 @@ void zfs_freesid(SID *sid) static ACL * -zfs_set_acl(dacl *dacls) +zfs_set_acl(dacl *dacls) { int size, i; ACL *acl = NULL; ACCESS_ALLOWED_ACE *aaa; - size = sizeof(ACL); + size = sizeof (ACL); i = 0; while (dacls[i].sid) { - size += sizeof(ACCESS_ALLOWED_ACE); - size += 8 + (dacls[i].sid->elements * sizeof(UINT32)) - sizeof(ULONG); + size += sizeof (ACCESS_ALLOWED_ACE); + size += 8 + (dacls[i].sid->elements * sizeof (UINT32)) - + sizeof (ULONG); i++; } acl = ExAllocatePoolWithTag(PagedPool, size, 'zacl'); - if (!acl) - return NULL; + if (!acl) + return (NULL); acl->AclRevision = ACL_REVISION; acl->Sbz1 = 0; @@ -1609,20 +1667,24 @@ zfs_set_acl(dacl *dacls) while (dacls[i].sid) { aaa->Header.AceType = ACCESS_ALLOWED_ACE_TYPE; aaa->Header.AceFlags = dacls[i].flags; - aaa->Header.AceSize = sizeof(ACCESS_ALLOWED_ACE) - sizeof(ULONG) + 8 + (dacls[i].sid->elements * sizeof(UINT32)); + aaa->Header.AceSize = sizeof (ACCESS_ALLOWED_ACE) - + sizeof (ULONG) + 8 + + (dacls[i].sid->elements * sizeof (UINT32)); aaa->Mask = dacls[i].mask; - RtlCopyMemory(&aaa->SidStart, dacls[i].sid, 8 + (dacls[i].sid->elements * sizeof(UINT32))); + RtlCopyMemory(&aaa->SidStart, dacls[i].sid, + 8 + (dacls[i].sid->elements * sizeof (UINT32))); aaa = (ACCESS_ALLOWED_ACE*)((UINT8*)aaa + aaa->Header.AceSize); i++; } - return acl; + return (acl); } -void zfs_set_security_root(struct vnode *vp) +void +zfs_set_security_root(struct vnode *vp) { SECURITY_DESCRIPTOR sd; SID *usersid = NULL, *groupsid = NULL; @@ -1632,7 +1694,8 @@ void zfs_set_security_root(struct vnode *vp) ACL *acl = NULL; Status = RtlCreateSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION); - if (Status != STATUS_SUCCESS) goto err; + if (Status != STATUS_SUCCESS) + goto err; acl = def_dacls; @@ -1644,21 +1707,23 @@ void zfs_set_security_root(struct vnode *vp) acl = zfs_set_acl(acl); - if (acl) + if (acl) Status = RtlSetDaclSecurityDescriptor(&sd, TRUE, acl, FALSE); ULONG buflen = 0; Status = RtlAbsoluteToSelfRelativeSD(&sd, NULL, &buflen); if (Status != STATUS_SUCCESS && - Status != STATUS_BUFFER_TOO_SMALL) goto err; + Status != STATUS_BUFFER_TOO_SMALL) + goto err; ASSERT(buflen != 0); void *tmp = ExAllocatePoolWithTag(PagedPool, buflen, 'ZSEC'); - if (tmp == NULL) goto err; + if (tmp == NULL) + goto err; Status = RtlAbsoluteToSelfRelativeSD(&sd, tmp, &buflen); - + vnode_setsecurity(vp, tmp); err: @@ -1670,15 +1735,18 @@ void zfs_set_security_root(struct vnode *vp) zfs_freesid(groupsid); } -void zfs_set_security(struct vnode *vp, struct vnode *dvp) +void +zfs_set_security(struct vnode *vp, struct vnode *dvp) { SECURITY_SUBJECT_CONTEXT subjcont; NTSTATUS Status; SID *usersid = NULL, *groupsid = NULL; - if (vp == NULL) return; + if (vp == NULL) + return; - if (vp->security_descriptor != NULL) return; + if (vp->security_descriptor != NULL) + return; znode_t *zp = VTOZ(vp); zfsvfs_t *zfsvfs = zp->z_zfsvfs; @@ -1698,16 +1766,16 @@ void zfs_set_security(struct vnode *vp, struct vnode *dvp) znode_t *dzp = NULL; if (dvp == NULL) { if (zp->z_sa_hdl != NULL) { - uint64_t parent; - if (sa_lookup(zp->z_sa_hdl, SA_ZPL_PARENT(zfsvfs), - &parent, sizeof(parent)) != 0) { - goto err; - } - if (zfs_zget(zfsvfs, parent, &dzp)) { - dvp = NULL; - goto err; - } - dvp = ZTOV(dzp); + uint64_t parent; + if (sa_lookup(zp->z_sa_hdl, SA_ZPL_PARENT(zfsvfs), + &parent, sizeof (parent)) != 0) { + goto err; + } + if (zfs_zget(zfsvfs, parent, &dzp)) { + dvp = NULL; + goto err; + } + dvp = ZTOV(dzp); } // What to do if no sa_hdl ? } else { VN_HOLD(dvp); @@ -1720,11 +1788,12 @@ void zfs_set_security(struct vnode *vp, struct vnode *dvp) SeCaptureSubjectContext(&subjcont); void *sd = NULL; - Status = SeAssignSecurityEx(vnode_security(dvp), NULL, (void**)&sd, NULL, - vnode_isdir(vp)?TRUE:FALSE, - SEF_DACL_AUTO_INHERIT, &subjcont, IoGetFileObjectGenericMapping(), PagedPool); + Status = SeAssignSecurityEx(vnode_security(dvp), NULL, (void**)&sd, + NULL, vnode_isdir(vp)?TRUE:FALSE, SEF_DACL_AUTO_INHERIT, + &subjcont, IoGetFileObjectGenericMapping(), PagedPool); - if (Status != STATUS_SUCCESS) goto err; + if (Status != STATUS_SUCCESS) + goto err; vnode_setsecurity(vp, sd); @@ -1745,33 +1814,36 @@ void zfs_set_security(struct vnode *vp, struct vnode *dvp) } // return true if a XATTR name should be skipped -int xattr_protected(char *name) +int +xattr_protected(char *name) { - return 0; + return (0); } // return true if xattr is a stream (name ends with ":$DATA") -int xattr_stream(char *name) +int +xattr_stream(char *name) { char tail[] = ":$DATA"; - int taillen = sizeof(tail); + int taillen = sizeof (tail); int len; if (name == NULL) - return 0; + return (0); len = strlen(name); if (len < taillen) - return 0; + return (0); if (strcmp(&name[len - taillen + 1], tail) == 0) - return 1; + return (1); - return 0; + return (0); } // Get the size needed for EA, check first if it is // cached in vnode. Otherwise, compute it and set. -uint64_t xattr_getsize(struct vnode *vp) +uint64_t +xattr_getsize(struct vnode *vp) { uint64_t ret = 0; struct vnode *xdvp = NULL, *xvp = NULL; @@ -1781,22 +1853,23 @@ uint64_t xattr_getsize(struct vnode *vp) zap_attribute_t za; objset_t *os; - if (vp == NULL) return 0; + if (vp == NULL) + return (0); // Cached? Easy, use it if (vnode_easize(vp, &ret)) - return ret; + return (ret); zp = VTOZ(vp); zfsvfs = zp->z_zfsvfs; - /* - * Iterate through all the xattrs, adding up namelengths and value sizes. - * There was some suggestion that this should be 4 + (5 + name + valuelen) - * but that no longer appears to be true. The returned value is used directly - * with IRP_MJ_QUERY_EA and we will have to return short. - * We will return the true space needed. - */ +/* + * Iterate through all the xattrs, adding up namelengths and value sizes. + * There was some suggestion that this should be 4 + (5 + name + valuelen) + * but that no longer appears to be true. The returned value is used directly + * with IRP_MJ_QUERY_EA and we will have to return short. + * We will return the true space needed. + */ if (zfs_get_xattrdir(zp, &xdzp, NULL, 0) != 0) { goto out; } @@ -1804,16 +1877,18 @@ uint64_t xattr_getsize(struct vnode *vp) os = zfsvfs->z_os; for (zap_cursor_init(&zc, os, VTOZ(xdvp)->z_id); - zap_cursor_retrieve(&zc, &za) == 0; zap_cursor_advance(&zc)) { + zap_cursor_retrieve(&zc, &za) == 0; zap_cursor_advance(&zc)) { if (xattr_protected(za.za_name)) continue; /* skip */ if (xattr_stream(za.za_name)) continue; /* skip */ - if (zfs_dirlook(VTOZ(xdvp), za.za_name, &xvp, 0, NULL, NULL) == 0) { + if (zfs_dirlook(VTOZ(xdvp), za.za_name, &xvp, 0, NULL, + NULL) == 0) { ret = ((ret + 3) & ~3); // aligned to 4 bytes. - ret += offsetof(FILE_FULL_EA_INFORMATION, EaName) + strlen(za.za_name) + 1 + VTOZ(xvp)->z_size; + ret += offsetof(FILE_FULL_EA_INFORMATION, EaName) + + strlen(za.za_name) + 1 + VTOZ(xvp)->z_size; VN_RELE(xvp); } } @@ -1824,14 +1899,15 @@ uint64_t xattr_getsize(struct vnode *vp) // Cache result, even if failure (cached as 0). vnode_set_easize(vp, ret); - return ret; + return (ret); } /* * Call vnode_setunlink if zfs_zaccess_delete() allows it * TODO: provide credentials */ -NTSTATUS zfs_setunlink(FILE_OBJECT *fo, vnode_t *dvp) +NTSTATUS +zfs_setunlink(FILE_OBJECT *fo, vnode_t *dvp) { vnode_t *vp = NULL; NTSTATUS Status = STATUS_UNSUCCESSFUL; @@ -1864,14 +1940,14 @@ NTSTATUS zfs_setunlink(FILE_OBJECT *fo, vnode_t *dvp) } if (zfsvfs->z_rdonly || vfs_isrdonly(zfsvfs->z_vfs) || - !spa_writeable(dmu_objset_spa(zfsvfs->z_os))) { + !spa_writeable(dmu_objset_spa(zfsvfs->z_os))) { Status = STATUS_MEDIA_WRITE_PROTECTED; goto err; } // Cannot delete a user mapped image. if (!MmFlushImageSection(&vp->SectionObjectPointers, - MmFlushForDelete)) { + MmFlushForDelete)) { Status = STATUS_CANNOT_DELETE; goto err; } @@ -1882,7 +1958,7 @@ NTSTATUS zfs_setunlink(FILE_OBJECT *fo, vnode_t *dvp) uint64_t parent; if (sa_lookup(zp->z_sa_hdl, SA_ZPL_PARENT(zfsvfs), - &parent, sizeof(parent)) != 0) { + &parent, sizeof (parent)) != 0) { goto err; } if (zfs_zget(zfsvfs, parent, &dzp)) { @@ -1890,8 +1966,7 @@ NTSTATUS zfs_setunlink(FILE_OBJECT *fo, vnode_t *dvp) goto err; } dvp = ZTOV(dzp); - } - else { + } else { dzp = VTOZ(dvp); VN_HOLD(dvp); } @@ -1917,12 +1992,11 @@ NTSTATUS zfs_setunlink(FILE_OBJECT *fo, vnode_t *dvp) int error = zfs_zaccess_delete(dzp, zp, 0); if (error == 0) { - ASSERT3P(zccb, != , NULL); + ASSERT3P(zccb, !=, NULL); zccb->deleteonclose = 1; fo->DeletePending = TRUE; Status = STATUS_SUCCESS; - } - else { + } else { Status = STATUS_ACCESS_DENIED; } @@ -1937,7 +2011,7 @@ NTSTATUS zfs_setunlink(FILE_OBJECT *fo, vnode_t *dvp) dvp = NULL; } - return Status; + return (Status); } int @@ -1963,12 +2037,14 @@ dmu_buf_try_add_ref(dmu_buf_t *db, objset_t *os, uint64_t object, /* IRP_MJ_SET_INFORMATION helpers */ -NTSTATUS file_disposition_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +file_disposition_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp) { NTSTATUS Status = STATUS_SUCCESS; if (IrpSp->FileObject == NULL || IrpSp->FileObject->FsContext == NULL) - return STATUS_INVALID_PARAMETER; + return (STATUS_INVALID_PARAMETER); PFILE_OBJECT FileObject = IrpSp->FileObject; struct vnode *vp = FileObject->FsContext; @@ -1980,8 +2056,8 @@ NTSTATUS file_disposition_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO if (vp) { dprintf("Deletion %s on '%wZ'\n", - fdi->DeleteFile ? "set" : "unset", - IrpSp->FileObject->FileName); + fdi->DeleteFile ? "set" : "unset", + IrpSp->FileObject->FileName); Status = STATUS_SUCCESS; if (fdi->DeleteFile) { Status = zfs_setunlink(IrpSp->FileObject, NULL); @@ -1989,20 +2065,24 @@ NTSTATUS file_disposition_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO if (zccb) zccb->deleteonclose = 0; FileObject->DeletePending = FALSE; } - // Dirs marked for Deletion should release all pending Notify events + // Dirs marked for Deletion should release all + // pending Notify events if (Status == STATUS_SUCCESS && fdi->DeleteFile) { - FsRtlNotifyCleanup(zmo->NotifySync, &zmo->DirNotifyList, VTOZ(vp)); + FsRtlNotifyCleanup(zmo->NotifySync, + &zmo->DirNotifyList, VTOZ(vp)); } } - return Status; + return (Status); } -NTSTATUS file_disposition_information_ex(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +file_disposition_information_ex(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp) { NTSTATUS Status = STATUS_SUCCESS; if (IrpSp->FileObject == NULL || IrpSp->FileObject->FsContext == NULL) - return STATUS_INVALID_PARAMETER; + return (STATUS_INVALID_PARAMETER); PFILE_OBJECT FileObject = IrpSp->FileObject; struct vnode *vp = FileObject->FsContext; @@ -2023,23 +2103,28 @@ NTSTATUS file_disposition_information_ex(PDEVICE_OBJECT DeviceObject, PIRP Irp, Status = zfs_setunlink(FileObject, NULL); else if (zccb) zccb->deleteonclose = 0; - + // Do we care about FILE_DISPOSITION_POSIX_SEMANTICS ? - // Dirs marked for Deletion should release all pending Notify events - if (Status == STATUS_SUCCESS && (fdie->Flags | FILE_DISPOSITION_DELETE)) { - FsRtlNotifyCleanup(zmo->NotifySync, &zmo->DirNotifyList, VTOZ(vp)); + // Dirs marked for Deletion should release all + // pending Notify events + if (Status == STATUS_SUCCESS && + (fdie->Flags | FILE_DISPOSITION_DELETE)) { + FsRtlNotifyCleanup(zmo->NotifySync, &zmo->DirNotifyList, + VTOZ(vp)); } } - return Status; + return (Status); } -NTSTATUS file_endoffile_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +file_endoffile_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp) { NTSTATUS Status = STATUS_SUCCESS; if (IrpSp->FileObject == NULL || IrpSp->FileObject->FsContext == NULL) - return STATUS_INVALID_PARAMETER; + return (STATUS_INVALID_PARAMETER); PFILE_OBJECT FileObject = IrpSp->FileObject; struct vnode *vp = FileObject->FsContext; @@ -2050,7 +2135,7 @@ NTSTATUS file_endoffile_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_S int changed = 0; if (zfsvfs == NULL) - return STATUS_INVALID_PARAMETER; + return (STATUS_INVALID_PARAMETER); dprintf("* File_EndOfFile_Information:\n"); @@ -2062,15 +2147,15 @@ NTSTATUS file_endoffile_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_S // extra work. BOOLEAN CacheMapInitialized = FALSE; if (FileObject && FileObject->SectionObjectPointer && - (FileObject->SectionObjectPointer->DataSectionObject != NULL) && - (FileObject->SectionObjectPointer->SharedCacheMap == NULL) && - !FlagOn(Irp->Flags, IRP_PAGING_IO)) { + (FileObject->SectionObjectPointer->DataSectionObject != NULL) && + (FileObject->SectionObjectPointer->SharedCacheMap == NULL) && + !FlagOn(Irp->Flags, IRP_PAGING_IO)) { vnode_pager_setsize(vp, zp->z_size); CcInitializeCacheMap(FileObject, - (PCC_FILE_SIZES)&vp->FileHeader.AllocationSize, - FALSE, - &CacheManagerCallbacks, vp); - CcSetAdditionalCacheAttributes(FileObject, TRUE, TRUE); // FIXME: for now + (PCC_FILE_SIZES)&vp->FileHeader.AllocationSize, + FALSE, + &CacheManagerCallbacks, vp); + CcSetAdditionalCacheAttributes(FileObject, TRUE, TRUE); CacheMapInitialized = TRUE; } @@ -2084,7 +2169,9 @@ NTSTATUS file_endoffile_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_S // Advance only? if (IrpSp->Parameters.SetFile.AdvanceOnly) { if (feofi->EndOfFile.QuadPart > zp->z_size) { - Status = zfs_freesp(zp, feofi->EndOfFile.QuadPart, 0, 0, TRUE); + Status = zfs_freesp(zp, + feofi->EndOfFile.QuadPart, + 0, 0, TRUE); changed = 1; } dprintf("%s: AdvanceOnly\n", __func__); @@ -2093,8 +2180,10 @@ NTSTATUS file_endoffile_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_S // Truncation? if (zp->z_size > feofi->EndOfFile.QuadPart) { // Are we able to truncate? - if (FileObject->SectionObjectPointer && !MmCanFileBeTruncated(FileObject->SectionObjectPointer, - &feofi->EndOfFile)) { + if (FileObject->SectionObjectPointer && + !MmCanFileBeTruncated( + FileObject->SectionObjectPointer, + &feofi->EndOfFile)) { Status = STATUS_USER_MAPPED_FILE; goto out; } @@ -2102,7 +2191,8 @@ NTSTATUS file_endoffile_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_S } // Set new size - Status = zfs_freesp(zp, feofi->EndOfFile.QuadPart, 0, 0, TRUE); // Len = 0 is truncate + Status = zfs_freesp(zp, feofi->EndOfFile.QuadPart, + 0, 0, TRUE); // Len = 0 is truncate changed = 1; } @@ -2114,16 +2204,18 @@ NTSTATUS file_endoffile_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_S dprintf("%s: new size 0x%llx set\n", __func__, zp->z_size); - // zfs_freesp() calls vnode_paget_setsize(), but we need to update it here. + // zfs_freesp() calls vnode_paget_setsize(), but we need + // xto update it here. if (FileObject->SectionObjectPointer) CcSetFileSizes(FileObject, - (PCC_FILE_SIZES)&vp->FileHeader.AllocationSize); + (PCC_FILE_SIZES)&vp->FileHeader.AllocationSize); // No notify for XATTR/Stream for now if (!(zp->z_pflags & ZFS_XATTR)) { - zfs_send_notify(zfsvfs, zp->z_name_cache, zp->z_name_offset, - FILE_NOTIFY_CHANGE_SIZE, - FILE_ACTION_MODIFIED); + zfs_send_notify(zfsvfs, zp->z_name_cache, + zp->z_name_offset, + FILE_NOTIFY_CHANGE_SIZE, + FILE_ACTION_MODIFIED); } } @@ -2136,30 +2228,33 @@ NTSTATUS file_endoffile_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_S // We handled setsize in here. vnode_setsizechange(vp, 0); - return Status; + return (Status); } // create hardlink by calling zfs_create -NTSTATUS file_link_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +file_link_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp) { NTSTATUS Status; /* - typedef struct _FILE_LINK_INFORMATION { - BOOLEAN ReplaceIfExists; - HANDLE RootDirectory; - ULONG FileNameLength; - WCHAR FileName[1]; - } FILE_LINK_INFORMATION, *PFILE_LINK_INFORMATION; - */ + * typedef struct _FILE_LINK_INFORMATION { + * BOOLEAN ReplaceIfExists; + * HANDLE RootDirectory; + * ULONG FileNameLength; + * WCHAR FileName[1]; + * } FILE_LINK_INFORMATION, *PFILE_LINK_INFORMATION; + */ FILE_LINK_INFORMATION *link = Irp->AssociatedIrp.SystemBuffer; - dprintf("* FileLinkInformation: %.*S\n", link->FileNameLength / sizeof(WCHAR), link->FileName); + dprintf("* FileLinkInformation: %.*S\n", + link->FileNameLength / sizeof (WCHAR), link->FileName); // So, use FileObject to get VP. // Use VP to lookup parent. // Use Filename to find destonation dvp, and vp if it exists. if (IrpSp->FileObject == NULL || IrpSp->FileObject->FsContext == NULL) - return STATUS_INVALID_PARAMETER; + return (STATUS_INVALID_PARAMETER); FILE_OBJECT *RootFileObject = NULL; PFILE_OBJECT FileObject = IrpSp->FileObject; @@ -2177,52 +2272,54 @@ NTSTATUS file_link_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_ // If given a RootDirectory Handle, lookup tdvp if (link->RootDirectory != 0) { if (ObReferenceObjectByHandle(link->RootDirectory, - GENERIC_READ, *IoFileObjectType, KernelMode, - &RootFileObject, NULL) != STATUS_SUCCESS) { - return STATUS_INVALID_PARAMETER; + GENERIC_READ, *IoFileObjectType, KernelMode, + &RootFileObject, NULL) != STATUS_SUCCESS) { + return (STATUS_INVALID_PARAMETER); } tdvp = RootFileObject->FsContext; VN_HOLD(tdvp); - } - else { - // Name can be absolute, if so use name, otherwise, use vp's parent. + } else { + // Name can be absolute, if so use name, otherwise, + // use vp's parent. } // Convert incoming filename to utf8 error = RtlUnicodeToUTF8N(buffer, MAXNAMELEN, &outlen, - link->FileName, link->FileNameLength); + link->FileName, link->FileNameLength); if (error != STATUS_SUCCESS && - error != STATUS_SOME_NOT_MAPPED) { + error != STATUS_SOME_NOT_MAPPED) { if (tdvp) VN_RELE(tdvp); if (RootFileObject) ObDereferenceObject(RootFileObject); - return STATUS_ILLEGAL_CHARACTER; + return (STATUS_ILLEGAL_CHARACTER); } // Output string is only null terminated if input is, so do so now. buffer[outlen] = 0; filename = buffer; - // Filename is often "\??\E:\name" so we want to eat everything up to the "\name" + // Filename is often "\??\E:\name" so we want to eat everything + // up to the "\name" if ((filename[0] == '\\') && - (filename[1] == '?') && - (filename[2] == '?') && - (filename[3] == '\\') && - /* [4] drive letter */ - (filename[5] == ':') && - (filename[6] == '\\')) + (filename[1] == '?') && + (filename[2] == '?') && + (filename[3] == '\\') && + /* [4] drive letter */ + (filename[5] == ':') && + (filename[6] == '\\')) filename = &filename[6]; - error = zfs_find_dvp_vp(zfsvfs, filename, 1, 0, &remainder, &tdvp, &tvp, 0); + error = zfs_find_dvp_vp(zfsvfs, filename, 1, 0, &remainder, &tdvp, + &tvp, 0); if (error) { if (tdvp) VN_RELE(tdvp); if (RootFileObject) ObDereferenceObject(RootFileObject); - return STATUS_OBJECTID_NOT_FOUND; + return (STATUS_OBJECTID_NOT_FOUND); } // Fetch parent VERIFY(sa_lookup(zp->z_sa_hdl, SA_ZPL_PARENT(zfsvfs), - &parent, sizeof(parent)) == 0); + &parent, sizeof (parent)) == 0); // Fetch fdvp error = zfs_zget(zfsvfs, parent, &dzp); @@ -2243,7 +2340,8 @@ NTSTATUS file_link_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_ // What about link->ReplaceIfExist ? - error = zfs_link(VTOZ(tdvp), VTOZ(fvp), remainder ? remainder : filename, NULL, 0); + error = zfs_link(VTOZ(tdvp), VTOZ(fvp), + remainder ? remainder : filename, NULL, 0); if (error == 0) { @@ -2252,10 +2350,12 @@ NTSTATUS file_link_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_ // Release fromname, and lookup new name kmem_free(zp->z_name_cache, zp->z_name_len); zp->z_name_cache = NULL; - if (zfs_build_path(zp, VTOZ(tdvp), &zp->z_name_cache, &zp->z_name_len, &zp->z_name_offset) == 0) { - zfs_send_notify(zfsvfs, zp->z_name_cache, zp->z_name_offset, - FILE_NOTIFY_CHANGE_CREATION, - FILE_ACTION_ADDED); + if (zfs_build_path(zp, VTOZ(tdvp), &zp->z_name_cache, + &zp->z_name_len, &zp->z_name_offset) == 0) { + zfs_send_notify(zfsvfs, zp->z_name_cache, + zp->z_name_offset, + FILE_NOTIFY_CHANGE_CREATION, + FILE_ACTION_ADDED); } #endif } @@ -2267,35 +2367,48 @@ NTSTATUS file_link_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_ if (fvp) VN_RELE(fvp); if (tvp) VN_RELE(tvp); - return error; + return (error); } -NTSTATUS file_rename_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +file_rename_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp) { NTSTATUS Status; - boolean_t ExVariant = IrpSp->Parameters.SetFile.FileInformationClass == FileRenameInformationEx; - /* - The file name string in the FileName member must be specified in one of the following forms. - A simple file name. (The RootDirectory member is NULL.) In this case, the file is simply renamed within the same directory. - That is, the rename operation changes the name of the file but not its location. - - A fully qualified file name. (The RootDirectory member is NULL.) In this case, the rename operation changes the name and location of the file. - - A relative file name. In this case, the RootDirectory member contains a handle to the target directory for the rename operation. The file name itself must be a simple file name. - - NOTE: The RootDirectory handle thing never happens, and no sample source (including fastfat) handles it. - */ + boolean_t ExVariant = + IrpSp->Parameters.SetFile.FileInformationClass == + FileRenameInformationEx; +/* + * The file name string in the FileName member must be specified in + * one of the following forms. + * A simple file name. (The RootDirectory member is NULL.) In this case, + * the file is simply renamed within the same directory. + * That is, the rename operation changes the name of the file but not its + * location. + * + * A fully qualified file name. (The RootDirectory member is NULL.) + * In this case, the rename operation changes the name and location + * of the file. + * + * A relative file name. In this case, the RootDirectory member contains + * a handle to the target directory for the rename operation. The file + * name itself must be a simple file name. + * + * NOTE: The RootDirectory handle thing never happens, and no sample + * source (including fastfat) handles it. + */ FILE_RENAME_INFORMATION *ren = Irp->AssociatedIrp.SystemBuffer; - dprintf("* FileRenameInformation: %.*S\n", ren->FileNameLength / sizeof(WCHAR), ren->FileName); + dprintf("* FileRenameInformation: %.*S\n", + ren->FileNameLength / sizeof (WCHAR), ren->FileName); - //ASSERT(ren->RootDirectory == NULL); + // ASSERT(ren->RootDirectory == NULL); // So, use FileObject to get VP. // Use VP to lookup parent. // Use Filename to find destonation dvp, and vp if it exists. if (IrpSp->FileObject == NULL || IrpSp->FileObject->FsContext == NULL) - return STATUS_INVALID_PARAMETER; + return (STATUS_INVALID_PARAMETER); PFILE_OBJECT FileObject = IrpSp->FileObject; struct vnode *fvp = FileObject->FsContext; @@ -2314,76 +2427,80 @@ NTSTATUS file_rename_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STAC // Convert incoming filename to utf8 error = RtlUnicodeToUTF8N(buffer, MAXNAMELEN, &outlen, - ren->FileName, ren->FileNameLength); + ren->FileName, ren->FileNameLength); if (error != STATUS_SUCCESS && - error != STATUS_SOME_NOT_MAPPED) { - return STATUS_ILLEGAL_CHARACTER; + error != STATUS_SOME_NOT_MAPPED) { + return (STATUS_ILLEGAL_CHARACTER); } // Output string is only null terminated if input is, so do so now. buffer[outlen] = 0; filename = buffer; - // Filename is often "\??\E:\lower\name" - and "/lower" might be another dataset - // so we need to drive a lookup, with SL_OPEN_TARGET_DIRECTORY set so we get - // the parent of where we are renaming to. This will give us "tdvp", and + // Filename is often "\??\E:\lower\name" - and "/lower" might be + // another dataset so we need to drive a lookup, with + // SL_OPEN_TARGET_DIRECTORY set so we get the parent of where + // we are renaming to. This will give us "tdvp", and // possibly "tvp" is we are to rename over an item. #if 0 if ((filename[0] == '\\') && - (filename[1] == '?') && - (filename[2] == '?') && - (filename[3] == '\\') && - /* [4] drive letter */ - (filename[5] == ':') && - (filename[6] == '\\')) + (filename[1] == '?') && + (filename[2] == '?') && + (filename[3] == '\\') && + /* [4] drive letter */ + (filename[5] == ':') && + (filename[6] == '\\')) filename = &filename[6]; #endif - // If it starts with "\" drive the lookup, if it is just a name like "HEAD", assume - // tdvp is same as fdvp. + // If it starts with "\" drive the lookup, if it is just a name + // like "HEAD", assume tdvp is same as fdvp. if ((filename[0] == '\\')) { OBJECT_ATTRIBUTES oa; IO_STATUS_BLOCK ioStatus; UNICODE_STRING uFileName; - //RtlInitEmptyUnicodeString(&uFileName, ren->FileName, ren->FileNameLength); // doesn't set length + // RtlInitEmptyUnicodeString(&uFileName, ren->FileName, + // ren->FileNameLength); // doesn't set length // Is there really no offical wrapper to do this? - uFileName.Length = uFileName.MaximumLength = ren->FileNameLength; + uFileName.Length = uFileName.MaximumLength = + ren->FileNameLength; uFileName.Buffer = ren->FileName; - InitializeObjectAttributes(&oa, &uFileName, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, - NULL, NULL); - + InitializeObjectAttributes(&oa, &uFileName, + OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, + NULL, NULL); + Status = IoCreateFile( - &destParentHandle, - FILE_READ_DATA, - &oa, - &ioStatus, - NULL, - 0, - FILE_SHARE_READ, - FILE_OPEN, - FILE_OPEN_FOR_BACKUP_INTENT, - NULL, - 0, - CreateFileTypeNone, - NULL, - IO_FORCE_ACCESS_CHECK | IO_OPEN_TARGET_DIRECTORY | IO_NO_PARAMETER_CHECKING - ); + &destParentHandle, + FILE_READ_DATA, + &oa, + &ioStatus, + NULL, + 0, + FILE_SHARE_READ, + FILE_OPEN, + FILE_OPEN_FOR_BACKUP_INTENT, + NULL, + 0, + CreateFileTypeNone, + NULL, + IO_FORCE_ACCESS_CHECK | IO_OPEN_TARGET_DIRECTORY | + IO_NO_PARAMETER_CHECKING); if (!NT_SUCCESS(Status)) - return STATUS_INVALID_PARAMETER; + return (STATUS_INVALID_PARAMETER); // We have the targetdirectoryparent - get FileObject. Status = ObReferenceObjectByHandle(destParentHandle, - STANDARD_RIGHTS_REQUIRED, - *IoFileObjectType, - KernelMode, - &dFileObject, - NULL); + STANDARD_RIGHTS_REQUIRED, + *IoFileObjectType, + KernelMode, + &dFileObject, + NULL); if (!NT_SUCCESS(Status)) { ZwClose(destParentHandle); - return STATUS_INVALID_PARAMETER; + return (STATUS_INVALID_PARAMETER); } // All exits need to go through "out:" at this point on. @@ -2395,7 +2512,8 @@ NTSTATUS file_rename_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STAC // Hold it VERIFY0(VN_HOLD(tdvp)); - // Filename is '\??\E:\dir\dir\file' and we only care about the last part. + // Filename is '\??\E:\dir\dir\file' and we only care about + // the last part. char *r = strrchr(filename, '\\'); if (r == NULL) r = strrchr(filename, '/'); @@ -2404,7 +2522,8 @@ NTSTATUS file_rename_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STAC filename = r; } - error = zfs_find_dvp_vp(zfsvfs, filename, 1, 0, &remainder, &tdvp, &tvp, 0); + error = zfs_find_dvp_vp(zfsvfs, filename, 1, 0, &remainder, + &tdvp, &tvp, 0); if (error) { Status = STATUS_OBJECTID_NOT_FOUND; goto out; @@ -2422,13 +2541,13 @@ NTSTATUS file_rename_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STAC error = STATUS_OBJECT_NAME_COLLISION; goto out; } - if (tvp && ExVariant && !(ren->Flags&FILE_RENAME_REPLACE_IF_EXISTS) ) { + if (tvp && ExVariant && !(ren->Flags&FILE_RENAME_REPLACE_IF_EXISTS)) { error = STATUS_OBJECT_NAME_COLLISION; goto out; } VERIFY(sa_lookup(zp->z_sa_hdl, SA_ZPL_PARENT(zfsvfs), - &parent, sizeof(parent)) == 0); + &parent, sizeof (parent)) == 0); // Fetch fdvp error = zfs_zget(zfsvfs, parent, &dzp); @@ -2453,34 +2572,36 @@ NTSTATUS file_rename_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STAC error = zfs_rename(VTOZ(fdvp), &zp->z_name_cache[zp->z_name_offset], - VTOZ(tdvp), remainder ? remainder : filename, - NULL, 0); + VTOZ(tdvp), remainder ? remainder : filename, NULL, 0); if (error == 0) { // TODO: rename file in same directory, send OLD_NAME, NEW_NAME - // Moving to different directory, send: FILE_ACTION_REMOVED, FILE_ACTION_ADDED + // Moving to different directory, send: + // FILE_ACTION_REMOVED, FILE_ACTION_ADDED // send CHANGE_LAST_WRITE zfs_send_notify(zfsvfs, zp->z_name_cache, zp->z_name_offset, - vnode_isdir(fvp) ? - FILE_NOTIFY_CHANGE_DIR_NAME : - FILE_NOTIFY_CHANGE_FILE_NAME, - FILE_ACTION_RENAMED_OLD_NAME); + vnode_isdir(fvp) ? + FILE_NOTIFY_CHANGE_DIR_NAME : + FILE_NOTIFY_CHANGE_FILE_NAME, + FILE_ACTION_RENAMED_OLD_NAME); // Release fromname, and lookup new name kmem_free(zp->z_name_cache, zp->z_name_len); zp->z_name_cache = NULL; - if (zfs_build_path(zp, VTOZ(tdvp), &zp->z_name_cache, &zp->z_name_len, &zp->z_name_offset) == 0) { - zfs_send_notify(zfsvfs, zp->z_name_cache, zp->z_name_offset, - vnode_isdir(fvp) ? - FILE_NOTIFY_CHANGE_DIR_NAME : - FILE_NOTIFY_CHANGE_FILE_NAME, - FILE_ACTION_RENAMED_NEW_NAME); + if (zfs_build_path(zp, VTOZ(tdvp), &zp->z_name_cache, + &zp->z_name_len, &zp->z_name_offset) == 0) { + zfs_send_notify(zfsvfs, zp->z_name_cache, + zp->z_name_offset, + vnode_isdir(fvp) ? + FILE_NOTIFY_CHANGE_DIR_NAME : + FILE_NOTIFY_CHANGE_FILE_NAME, + FILE_ACTION_RENAMED_NEW_NAME); } znode_t *tdzp = VTOZ(tdvp); zfs_send_notify(zfsvfs, tdzp->z_name_cache, tdzp->z_name_offset, - FILE_NOTIFY_CHANGE_LAST_WRITE, FILE_ACTION_MODIFIED); + FILE_NOTIFY_CHANGE_LAST_WRITE, FILE_ACTION_MODIFIED); } // Release all holds @@ -2494,19 +2615,22 @@ NTSTATUS file_rename_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STAC if (fvp) VN_RELE(fvp); if (tvp) VN_RELE(tvp); - return error; + return (error); } /* IRP_MJ_QUERY_INFORMATION helpers */ -NTSTATUS file_attribute_tag_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp, - FILE_ATTRIBUTE_TAG_INFORMATION *tag) +NTSTATUS +file_attribute_tag_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp, FILE_ATTRIBUTE_TAG_INFORMATION *tag) { - if (IrpSp->Parameters.QueryFile.Length < sizeof(FILE_ATTRIBUTE_TAG_INFORMATION)) { - Irp->IoStatus.Information = sizeof(FILE_ATTRIBUTE_TAG_INFORMATION); - return STATUS_BUFFER_TOO_SMALL; + if (IrpSp->Parameters.QueryFile.Length < + sizeof (FILE_ATTRIBUTE_TAG_INFORMATION)) { + Irp->IoStatus.Information = + sizeof (FILE_ATTRIBUTE_TAG_INFORMATION); + return (STATUS_BUFFER_TOO_SMALL); } if (IrpSp->FileObject && IrpSp->FileObject->FsContext) { @@ -2520,45 +2644,52 @@ NTSTATUS file_attribute_tag_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, P uio_t *uio; REPARSE_DATA_BUFFER tagdata; uio = uio_create(1, 0, UIO_SYSSPACE, UIO_READ); - uio_addiov(uio, (user_addr_t)&tagdata, sizeof(tagdata)); + uio_addiov(uio, (user_addr_t)&tagdata, + sizeof (tagdata)); err = zfs_readlink(vp, uio, NULL); tag->ReparseTag = tagdata.ReparseTag; dprintf("Returning tag 0x%x\n", tag->ReparseTag); uio_free(uio); } - Irp->IoStatus.Information = sizeof(FILE_ATTRIBUTE_TAG_INFORMATION); + Irp->IoStatus.Information = + sizeof (FILE_ATTRIBUTE_TAG_INFORMATION); ASSERT(tag->FileAttributes != 0); - return STATUS_SUCCESS; + return (STATUS_SUCCESS); } - return STATUS_INVALID_PARAMETER; + return (STATUS_INVALID_PARAMETER); } -NTSTATUS file_internal_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp, - FILE_INTERNAL_INFORMATION *infernal) +NTSTATUS +file_internal_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp, FILE_INTERNAL_INFORMATION *infernal) { - if (IrpSp->Parameters.QueryFile.Length < sizeof(FILE_INTERNAL_INFORMATION)) { - Irp->IoStatus.Information = sizeof(FILE_INTERNAL_INFORMATION); - return STATUS_BUFFER_TOO_SMALL; + if (IrpSp->Parameters.QueryFile.Length < + sizeof (FILE_INTERNAL_INFORMATION)) { + Irp->IoStatus.Information = sizeof (FILE_INTERNAL_INFORMATION); + return (STATUS_BUFFER_TOO_SMALL); } if (IrpSp->FileObject && IrpSp->FileObject->FsContext) { struct vnode *vp = IrpSp->FileObject->FsContext; znode_t *zp = VTOZ(vp); infernal->IndexNumber.QuadPart = zp->z_id; - Irp->IoStatus.Information = sizeof(FILE_INTERNAL_INFORMATION); - return STATUS_SUCCESS; + Irp->IoStatus.Information = sizeof (FILE_INTERNAL_INFORMATION); + return (STATUS_SUCCESS); } - return STATUS_NO_SUCH_FILE; + return (STATUS_NO_SUCH_FILE); } -NTSTATUS file_basic_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp, FILE_BASIC_INFORMATION *basic) +NTSTATUS +file_basic_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp, FILE_BASIC_INFORMATION *basic) { dprintf(" %s\n", __func__); - if (IrpSp->Parameters.QueryFile.Length < sizeof(FILE_BASIC_INFORMATION)) { - Irp->IoStatus.Information = sizeof(FILE_BASIC_INFORMATION); - return STATUS_BUFFER_TOO_SMALL; + if (IrpSp->Parameters.QueryFile.Length < + sizeof (FILE_BASIC_INFORMATION)) { + Irp->IoStatus.Information = sizeof (FILE_BASIC_INFORMATION); + return (STATUS_BUFFER_TOO_SMALL); } if (IrpSp->FileObject && IrpSp->FileObject->FsContext) { @@ -2571,69 +2702,81 @@ NTSTATUS file_basic_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK uint64_t mtime[2]; uint64_t ctime[2]; uint64_t crtime[2]; - SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, &mtime, 16); - SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, &ctime, 16); - SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CRTIME(zfsvfs), NULL, &crtime, 16); + SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), + NULL, &mtime, 16); + SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), + NULL, &ctime, 16); + SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CRTIME(zfsvfs), + NULL, &crtime, 16); sa_bulk_lookup(zp->z_sa_hdl, bulk, count); - TIME_UNIX_TO_WINDOWS(mtime, basic->LastWriteTime.QuadPart); - TIME_UNIX_TO_WINDOWS(ctime, basic->ChangeTime.QuadPart); - TIME_UNIX_TO_WINDOWS(crtime, basic->CreationTime.QuadPart); - TIME_UNIX_TO_WINDOWS(zp->z_atime, basic->LastAccessTime.QuadPart); + TIME_UNIX_TO_WINDOWS(mtime, + basic->LastWriteTime.QuadPart); + TIME_UNIX_TO_WINDOWS(ctime, + basic->ChangeTime.QuadPart); + TIME_UNIX_TO_WINDOWS(crtime, + basic->CreationTime.QuadPart); + TIME_UNIX_TO_WINDOWS(zp->z_atime, + basic->LastAccessTime.QuadPart); basic->FileAttributes = zfs_getwinflags(zp); VN_RELE(vp); } - Irp->IoStatus.Information = sizeof(FILE_BASIC_INFORMATION); - return STATUS_SUCCESS; + Irp->IoStatus.Information = sizeof (FILE_BASIC_INFORMATION); + return (STATUS_SUCCESS); } // This can be called from diskDispatcher, referring to the volume. // if so, make something up. Is this the right thing to do? if (IrpSp->FileObject && IrpSp->FileObject->FsContext == NULL) { - LARGE_INTEGER JanOne1980 = { 0xe1d58000,0x01a8e79f }; + LARGE_INTEGER JanOne1980 = { 0xe1d58000, 0x01a8e79f }; ExLocalTimeToSystemTime(&JanOne1980, - &basic->LastWriteTime); - basic->CreationTime = basic->LastAccessTime = basic->LastWriteTime; + &basic->LastWriteTime); + basic->CreationTime = basic->LastAccessTime = + basic->LastWriteTime; basic->FileAttributes = FILE_ATTRIBUTE_NORMAL; - Irp->IoStatus.Information = sizeof(FILE_BASIC_INFORMATION); - return STATUS_SUCCESS; + Irp->IoStatus.Information = sizeof (FILE_BASIC_INFORMATION); + return (STATUS_SUCCESS); } ASSERT(basic->FileAttributes != 0); dprintf(" %s failing\n", __func__); - return STATUS_OBJECT_NAME_NOT_FOUND; + return (STATUS_OBJECT_NAME_NOT_FOUND); } -uint64_t zfs_blksz(znode_t *zp) +uint64_t +zfs_blksz(znode_t *zp) { if (zp->z_blksz) - return zp->z_blksz; + return (zp->z_blksz); if (zp->z_sa_hdl) { uint32_t blksize; uint64_t nblks; sa_object_size(zp->z_sa_hdl, &blksize, &nblks); if (blksize) - return (uint64_t)blksize; + return ((uint64_t)blksize); } if (zp->z_zfsvfs->z_max_blksz) - return zp->z_zfsvfs->z_max_blksz; - return 512ULL; + return (zp->z_zfsvfs->z_max_blksz); + return (512ULL); } -NTSTATUS file_standard_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp, FILE_STANDARD_INFORMATION *standard) +NTSTATUS +file_standard_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp, FILE_STANDARD_INFORMATION *standard) { dprintf(" %s\n", __func__); - if (IrpSp->Parameters.QueryFile.Length < sizeof(FILE_STANDARD_INFORMATION)) { - Irp->IoStatus.Information = sizeof(FILE_STANDARD_INFORMATION); - return STATUS_BUFFER_TOO_SMALL; + if (IrpSp->Parameters.QueryFile.Length < + sizeof (FILE_STANDARD_INFORMATION)) { + Irp->IoStatus.Information = sizeof (FILE_STANDARD_INFORMATION); + return (STATUS_BUFFER_TOO_SMALL); } standard->Directory = TRUE; - standard->AllocationSize.QuadPart = 512; // space taken on disk, multiples of block size - standard->EndOfFile.QuadPart = 512; // byte size of file + standard->AllocationSize.QuadPart = 512; + standard->EndOfFile.QuadPart = 512; standard->DeletePending = FALSE; standard->NumberOfLinks = 1; if (IrpSp->FileObject && IrpSp->FileObject->FsContext) { @@ -2642,46 +2785,55 @@ NTSTATUS file_standard_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_ST VN_HOLD(vp); znode_t *zp = VTOZ(vp); standard->Directory = vnode_isdir(vp) ? TRUE : FALSE; - // sa_object_size(zp->z_sa_hdl, &blksize, &nblks); + // sa_object_size(zp->z_sa_hdl, &blksize, &nblks); uint64_t blk = zfs_blksz(zp); - standard->AllocationSize.QuadPart = P2ROUNDUP(zp->z_size ? zp->z_size : 1, blk); // space taken on disk, multiples of block size - //standard->AllocationSize.QuadPart = zp->z_size; // space taken on disk, multiples of block size - standard->EndOfFile.QuadPart = vnode_isdir(vp) ? 0 : zp->z_size; // byte size of file + // space taken on disk, multiples of block size + standard->AllocationSize.QuadPart = + P2ROUNDUP(zp->z_size ? zp->z_size : 1, blk); + standard->EndOfFile.QuadPart = vnode_isdir(vp) ? 0 : zp->z_size; standard->NumberOfLinks = zp->z_links; - standard->DeletePending = zccb && zccb->deleteonclose ? TRUE : FALSE; + standard->DeletePending = zccb && + zccb->deleteonclose ? TRUE : FALSE; VN_RELE(vp); dprintf("Returning size %llu and allocsize %llu\n", - standard->EndOfFile.QuadPart, standard->AllocationSize.QuadPart); - Irp->IoStatus.Information = sizeof(FILE_STANDARD_INFORMATION); - return STATUS_SUCCESS; + standard->EndOfFile.QuadPart, + standard->AllocationSize.QuadPart); + Irp->IoStatus.Information = sizeof (FILE_STANDARD_INFORMATION); + return (STATUS_SUCCESS); } - return STATUS_OBJECT_NAME_NOT_FOUND; + return (STATUS_OBJECT_NAME_NOT_FOUND); } -NTSTATUS file_position_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp, FILE_POSITION_INFORMATION *position) +NTSTATUS +file_position_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp, FILE_POSITION_INFORMATION *position) { dprintf(" %s\n", __func__); - if (IrpSp->Parameters.QueryFile.Length < sizeof(FILE_POSITION_INFORMATION)) { - Irp->IoStatus.Information = sizeof(FILE_POSITION_INFORMATION); - return STATUS_BUFFER_TOO_SMALL; + if (IrpSp->Parameters.QueryFile.Length < + sizeof (FILE_POSITION_INFORMATION)) { + Irp->IoStatus.Information = sizeof (FILE_POSITION_INFORMATION); + return (STATUS_BUFFER_TOO_SMALL); } if (IrpSp->FileObject) - position->CurrentByteOffset.QuadPart = IrpSp->FileObject->CurrentByteOffset.QuadPart; + position->CurrentByteOffset.QuadPart = + IrpSp->FileObject->CurrentByteOffset.QuadPart; - Irp->IoStatus.Information = sizeof(FILE_POSITION_INFORMATION); - return STATUS_SUCCESS; + Irp->IoStatus.Information = sizeof (FILE_POSITION_INFORMATION); + return (STATUS_SUCCESS); } -NTSTATUS file_ea_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp, FILE_EA_INFORMATION *ea) +NTSTATUS +file_ea_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp, FILE_EA_INFORMATION *ea) { NTSTATUS Status = STATUS_INVALID_PARAMETER; dprintf(" %s\n", __func__); - if (IrpSp->Parameters.QueryFile.Length < sizeof(FILE_EA_INFORMATION)) { - Irp->IoStatus.Information = sizeof(FILE_EA_INFORMATION); - return STATUS_BUFFER_TOO_SMALL; + if (IrpSp->Parameters.QueryFile.Length < sizeof (FILE_EA_INFORMATION)) { + Irp->IoStatus.Information = sizeof (FILE_EA_INFORMATION); + return (STATUS_BUFFER_TOO_SMALL); } ea->EaSize = 0; @@ -2692,22 +2844,26 @@ NTSTATUS file_ea_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LO ea->EaSize = xattr_getsize(vp); dprintf("%s: returning size %d / 0x%x\n", __func__, - ea->EaSize, ea->EaSize); + ea->EaSize, ea->EaSize); - Irp->IoStatus.Information = sizeof(FILE_EA_INFORMATION); - return STATUS_SUCCESS; + Irp->IoStatus.Information = sizeof (FILE_EA_INFORMATION); + return (STATUS_SUCCESS); } - return STATUS_INVALID_PARAMETER; + return (STATUS_INVALID_PARAMETER); } -NTSTATUS file_network_open_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp, FILE_NETWORK_OPEN_INFORMATION *netopen) +NTSTATUS +file_network_open_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp, FILE_NETWORK_OPEN_INFORMATION *netopen) { dprintf(" %s\n", __func__); - if (IrpSp->Parameters.QueryFile.Length < sizeof(FILE_NETWORK_OPEN_INFORMATION)) { - Irp->IoStatus.Information = sizeof(FILE_NETWORK_OPEN_INFORMATION); - return STATUS_BUFFER_TOO_SMALL; + if (IrpSp->Parameters.QueryFile.Length < + sizeof (FILE_NETWORK_OPEN_INFORMATION)) { + Irp->IoStatus.Information = + sizeof (FILE_NETWORK_OPEN_INFORMATION); + return (STATUS_BUFFER_TOO_SMALL); } if (IrpSp->FileObject && IrpSp->FileObject->FsContext) { @@ -2719,34 +2875,47 @@ NTSTATUS file_network_open_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PI uint64_t mtime[2]; uint64_t ctime[2]; uint64_t crtime[2]; - SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, &mtime, 16); - SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, &ctime, 16); - SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CRTIME(zfsvfs), NULL, &crtime, 16); + SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, + &mtime, 16); + SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, + &ctime, 16); + SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CRTIME(zfsvfs), NULL, + &crtime, 16); sa_bulk_lookup(zp->z_sa_hdl, bulk, count); - TIME_UNIX_TO_WINDOWS(mtime, netopen->LastWriteTime.QuadPart); - TIME_UNIX_TO_WINDOWS(ctime, netopen->ChangeTime.QuadPart); - TIME_UNIX_TO_WINDOWS(crtime, netopen->CreationTime.QuadPart); - TIME_UNIX_TO_WINDOWS(zp->z_atime, netopen->LastAccessTime.QuadPart); - netopen->AllocationSize.QuadPart = P2ROUNDUP(zp->z_size, zfs_blksz(zp)); + TIME_UNIX_TO_WINDOWS(mtime, + netopen->LastWriteTime.QuadPart); + TIME_UNIX_TO_WINDOWS(ctime, + netopen->ChangeTime.QuadPart); + TIME_UNIX_TO_WINDOWS(crtime, + netopen->CreationTime.QuadPart); + TIME_UNIX_TO_WINDOWS(zp->z_atime, + netopen->LastAccessTime.QuadPart); + netopen->AllocationSize.QuadPart = + P2ROUNDUP(zp->z_size, zfs_blksz(zp)); netopen->EndOfFile.QuadPart = vnode_isdir(vp) ? 0 : zp->z_size; netopen->FileAttributes = zfs_getwinflags(zp); - Irp->IoStatus.Information = sizeof(FILE_NETWORK_OPEN_INFORMATION); - return STATUS_SUCCESS; + Irp->IoStatus.Information = + sizeof (FILE_NETWORK_OPEN_INFORMATION); + return (STATUS_SUCCESS); } - return STATUS_OBJECT_PATH_NOT_FOUND; + return (STATUS_OBJECT_PATH_NOT_FOUND); } -NTSTATUS file_standard_link_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp, FILE_STANDARD_LINK_INFORMATION *fsli) +NTSTATUS +file_standard_link_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp, FILE_STANDARD_LINK_INFORMATION *fsli) { PFILE_OBJECT FileObject = IrpSp->FileObject; dprintf(" %s\n", __func__); - if (IrpSp->Parameters.QueryFile.Length < sizeof(FILE_STANDARD_LINK_INFORMATION)) { - Irp->IoStatus.Information = sizeof(FILE_STANDARD_LINK_INFORMATION); - return STATUS_BUFFER_TOO_SMALL; + if (IrpSp->Parameters.QueryFile.Length < + sizeof (FILE_STANDARD_LINK_INFORMATION)) { + Irp->IoStatus.Information = + sizeof (FILE_STANDARD_LINK_INFORMATION); + return (STATUS_BUFFER_TOO_SMALL); } if (IrpSp->FileObject && IrpSp->FileObject->FsContext) { @@ -2757,22 +2926,25 @@ NTSTATUS file_standard_link_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, P fsli->NumberOfAccessibleLinks = zp->z_links; fsli->TotalNumberOfLinks = zp->z_links; - fsli->DeletePending = zccb && zccb->deleteonclose ? TRUE : FALSE; + fsli->DeletePending = zccb && + zccb->deleteonclose ? TRUE : FALSE; fsli->Directory = S_ISDIR(zp->z_mode); } - Irp->IoStatus.Information = sizeof(FILE_STANDARD_LINK_INFORMATION); - return STATUS_SUCCESS; + Irp->IoStatus.Information = sizeof (FILE_STANDARD_LINK_INFORMATION); + return (STATUS_SUCCESS); } -NTSTATUS file_id_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp, FILE_ID_INFORMATION *fii) +NTSTATUS +file_id_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp, FILE_ID_INFORMATION *fii) { PFILE_OBJECT FileObject = IrpSp->FileObject; dprintf(" %s\n", __func__); - if (IrpSp->Parameters.QueryFile.Length < sizeof(FILE_ID_INFORMATION)) { - Irp->IoStatus.Information = sizeof(FILE_ID_INFORMATION); - return STATUS_BUFFER_TOO_SMALL; + if (IrpSp->Parameters.QueryFile.Length < sizeof (FILE_ID_INFORMATION)) { + Irp->IoStatus.Information = sizeof (FILE_ID_INFORMATION); + return (STATUS_BUFFER_TOO_SMALL); } struct vnode *vp = FileObject->FsContext; @@ -2782,23 +2954,28 @@ NTSTATUS file_id_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LO fii->VolumeSerialNumber = 0x19831116; - RtlCopyMemory(&fii->FileId.Identifier[0], &zp->z_id, sizeof(UINT64)); + RtlCopyMemory(&fii->FileId.Identifier[0], &zp->z_id, sizeof (UINT64)); uint64_t guid = dmu_objset_fsid_guid(zfsvfs->z_os); - RtlCopyMemory(&fii->FileId.Identifier[sizeof(UINT64)], &guid, sizeof(UINT64)); + RtlCopyMemory(&fii->FileId.Identifier[sizeof (UINT64)], + &guid, sizeof (UINT64)); - Irp->IoStatus.Information = sizeof(FILE_ID_INFORMATION); - return STATUS_SUCCESS; + Irp->IoStatus.Information = sizeof (FILE_ID_INFORMATION); + return (STATUS_SUCCESS); } -NTSTATUS file_case_sensitive_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp, FILE_CASE_SENSITIVE_INFORMATION *fcsi) +NTSTATUS +file_case_sensitive_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp, FILE_CASE_SENSITIVE_INFORMATION *fcsi) { PFILE_OBJECT FileObject = IrpSp->FileObject; dprintf(" %s\n", __func__); - if (IrpSp->Parameters.QueryFile.Length < sizeof(FILE_CASE_SENSITIVE_INFORMATION)) { - Irp->IoStatus.Information = sizeof(FILE_CASE_SENSITIVE_INFORMATION); - return STATUS_BUFFER_TOO_SMALL; + if (IrpSp->Parameters.QueryFile.Length < + sizeof (FILE_CASE_SENSITIVE_INFORMATION)) { + Irp->IoStatus.Information = + sizeof (FILE_CASE_SENSITIVE_INFORMATION); + return (STATUS_BUFFER_TOO_SMALL); } struct vnode *vp = FileObject->FsContext; @@ -2810,12 +2987,14 @@ NTSTATUS file_case_sensitive_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, if (zfsvfs->z_case == ZFS_CASE_SENSITIVE) fcsi->Flags |= FILE_CS_FLAG_CASE_SENSITIVE_DIR; - Irp->IoStatus.Information = sizeof(FILE_CASE_SENSITIVE_INFORMATION); + Irp->IoStatus.Information = sizeof (FILE_CASE_SENSITIVE_INFORMATION); - return STATUS_SUCCESS; + return (STATUS_SUCCESS); } -NTSTATUS file_stat_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp, FILE_STAT_INFORMATION *fsi) +NTSTATUS +file_stat_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp, FILE_STAT_INFORMATION *fsi) { PFILE_OBJECT FileObject = IrpSp->FileObject; @@ -2834,9 +3013,12 @@ NTSTATUS file_stat_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_ uint64_t mtime[2]; uint64_t ctime[2]; uint64_t crtime[2]; - SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, &mtime, 16); - SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, &ctime, 16); - SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CRTIME(zfsvfs), NULL, &crtime, 16); + SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, + &mtime, 16); + SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, + &ctime, 16); + SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CRTIME(zfsvfs), NULL, + &crtime, 16); sa_bulk_lookup(zp->z_sa_hdl, bulk, count); fsi->FileId.QuadPart = zp->z_id; @@ -2844,7 +3026,8 @@ NTSTATUS file_stat_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_ TIME_UNIX_TO_WINDOWS(zp->z_atime, fsi->LastAccessTime.QuadPart); TIME_UNIX_TO_WINDOWS(mtime, fsi->LastWriteTime.QuadPart); TIME_UNIX_TO_WINDOWS(ctime, fsi->ChangeTime.QuadPart); - fsi->AllocationSize.QuadPart = P2ROUNDUP(zp->z_size, zfs_blksz(zp)); + fsi->AllocationSize.QuadPart = + P2ROUNDUP(zp->z_size, zfs_blksz(zp)); fsi->EndOfFile.QuadPart = zp->z_size; fsi->FileAttributes = zfs_getwinflags(zp); fsi->ReparseTag = 0; @@ -2852,11 +3035,12 @@ NTSTATUS file_stat_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_ fsi->EffectiveAccess = GENERIC_ALL; } - return STATUS_SUCCESS; + return (STATUS_SUCCESS); } // Convert ZFS (Unix) mode to Windows mode. -ULONG ZMODE2WMODE(mode_t z) +ULONG +ZMODE2WMODE(mode_t z) { ULONG w = 0; @@ -2875,10 +3059,12 @@ ULONG ZMODE2WMODE(mode_t z) if ((z&S_IROTH) == S_IROTH) w |= 0x0004; // if ((z&S_IWOTH) == S_IWOTH) w |= 0x0002; // if ((z&S_IXOTH) == S_IXOTH) w |= 0x0001; // - return w; + return (w); } -NTSTATUS file_stat_lx_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp, FILE_STAT_LX_INFORMATION *fsli) +NTSTATUS +file_stat_lx_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp, FILE_STAT_LX_INFORMATION *fsli) { PFILE_OBJECT FileObject = IrpSp->FileObject; @@ -2896,48 +3082,63 @@ NTSTATUS file_stat_lx_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STA uint64_t mtime[2]; uint64_t ctime[2]; uint64_t crtime[2]; - SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, &mtime, 16); - SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, &ctime, 16); - SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CRTIME(zfsvfs), NULL, &crtime, 16); + SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, + &mtime, 16); + SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, + &ctime, 16); + SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CRTIME(zfsvfs), NULL, + &crtime, 16); sa_bulk_lookup(zp->z_sa_hdl, bulk, count); fsli->FileId.QuadPart = zp->z_id; - TIME_UNIX_TO_WINDOWS(crtime, fsli->CreationTime.QuadPart); - TIME_UNIX_TO_WINDOWS(zp->z_atime, fsli->LastAccessTime.QuadPart); - TIME_UNIX_TO_WINDOWS(mtime, fsli->LastWriteTime.QuadPart); - TIME_UNIX_TO_WINDOWS(ctime, fsli->ChangeTime.QuadPart); - fsli->AllocationSize.QuadPart = P2ROUNDUP(zp->z_size, zfs_blksz(zp)); + TIME_UNIX_TO_WINDOWS(crtime, + fsli->CreationTime.QuadPart); + TIME_UNIX_TO_WINDOWS(zp->z_atime, + fsli->LastAccessTime.QuadPart); + TIME_UNIX_TO_WINDOWS(mtime, + fsli->LastWriteTime.QuadPart); + TIME_UNIX_TO_WINDOWS(ctime, + fsli->ChangeTime.QuadPart); + fsli->AllocationSize.QuadPart = + P2ROUNDUP(zp->z_size, zfs_blksz(zp)); fsli->EndOfFile.QuadPart = zp->z_size; fsli->FileAttributes = zfs_getwinflags(zp); fsli->ReparseTag = 0; fsli->NumberOfLinks = zp->z_links; - fsli->EffectiveAccess = SPECIFIC_RIGHTS_ALL | ACCESS_SYSTEM_SECURITY; - fsli->LxFlags = LX_FILE_METADATA_HAS_UID | LX_FILE_METADATA_HAS_GID | LX_FILE_METADATA_HAS_MODE; - if (zfsvfs->z_case == ZFS_CASE_SENSITIVE) fsli->LxFlags |= LX_FILE_CASE_SENSITIVE_DIR; + fsli->EffectiveAccess = + SPECIFIC_RIGHTS_ALL | ACCESS_SYSTEM_SECURITY; + fsli->LxFlags = LX_FILE_METADATA_HAS_UID | + LX_FILE_METADATA_HAS_GID | LX_FILE_METADATA_HAS_MODE; + if (zfsvfs->z_case == ZFS_CASE_SENSITIVE) + fsli->LxFlags |= LX_FILE_CASE_SENSITIVE_DIR; fsli->LxUid = zp->z_uid; fsli->LxGid = zp->z_gid; fsli->LxMode = ZMODE2WMODE(zp->z_mode); fsli->LxDeviceIdMajor = 0; fsli->LxDeviceIdMinor = 0; } - return STATUS_SUCCESS; + return (STATUS_SUCCESS); } // // If overflow, set Information to input_size and NameLength to required size. // -NTSTATUS file_name_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp, FILE_NAME_INFORMATION *name, PULONG usedspace, int normalize) +NTSTATUS +file_name_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp, FILE_NAME_INFORMATION *name, + PULONG usedspace, int normalize) { PFILE_OBJECT FileObject = IrpSp->FileObject; dprintf("* %s: (normalize %d)\n", __func__, normalize); if (FileObject == NULL || FileObject->FsContext == NULL) - return STATUS_INVALID_PARAMETER; + return (STATUS_INVALID_PARAMETER); - if (IrpSp->Parameters.QueryFile.Length < (ULONG)FIELD_OFFSET(FILE_NAME_INFORMATION, FileName[0])) { - Irp->IoStatus.Information = sizeof(FILE_NAME_INFORMATION); - return STATUS_BUFFER_TOO_SMALL; + if (IrpSp->Parameters.QueryFile.Length < + (ULONG)FIELD_OFFSET(FILE_NAME_INFORMATION, FileName[0])) { + Irp->IoStatus.Information = sizeof (FILE_NAME_INFORMATION); + return (STATUS_BUFFER_TOO_SMALL); } struct vnode *vp = FileObject->FsContext; @@ -2960,100 +3161,116 @@ NTSTATUS file_name_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_ // Should never be unset! if (zp->z_name_cache == NULL) { dprintf("%s: name not set path taken\n", __func__); - if (zfs_build_path(zp, NULL, &zp->z_name_cache, &zp->z_name_len, &zp->z_name_offset) == -1) { - dprintf("%s: failed to build fullpath\n", __func__); - return STATUS_OBJECT_PATH_NOT_FOUND; + if (zfs_build_path(zp, NULL, &zp->z_name_cache, + &zp->z_name_len, &zp->z_name_offset) == -1) { + dprintf("%s: failed to build fullpath\n", + __func__); + return (STATUS_OBJECT_PATH_NOT_FOUND); } } // Safety if (zp->z_name_cache != NULL) { strlcpy(strname, zp->z_name_cache, - MAXPATHLEN); + MAXPATHLEN); - // If it is a DIR, make sure it ends with "\", except for - // root, that is just "\" + // If it is a DIR, make sure it ends with "\", + // except for root, that is just "\" if (S_ISDIR(zp->z_mode)) strlcat(strname, "\\", - MAXPATHLEN); + MAXPATHLEN); } } VN_RELE(vp); // Convert name, setting FileNameLength to how much we need - error = RtlUTF8ToUnicodeN(NULL, 0, &name->FileNameLength, strname, strlen(strname)); - //ASSERT(strlen(strname)*2 == name->FileNameLength); - dprintf("%s: remaining space %d str.len %d struct size %d\n", __func__, IrpSp->Parameters.QueryFile.Length, - name->FileNameLength, sizeof(FILE_NAME_INFORMATION)); + error = RtlUTF8ToUnicodeN(NULL, 0, &name->FileNameLength, + strname, strlen(strname)); + + dprintf("%s: remaining space %d str.len %d struct size %d\n", + __func__, IrpSp->Parameters.QueryFile.Length, + name->FileNameLength, sizeof (FILE_NAME_INFORMATION)); // CHECK ERROR here. - // Calculate how much room there is for filename, after the struct and its first wchar - int space = IrpSp->Parameters.QueryFile.Length - FIELD_OFFSET(FILE_NAME_INFORMATION, FileName); + // Calculate how much room there is for filename, after + // the struct and its first wchar + int space = IrpSp->Parameters.QueryFile.Length - + FIELD_OFFSET(FILE_NAME_INFORMATION, FileName); space = MIN(space, name->FileNameLength); ASSERT(space >= 0); // Copy over as much as we can, including the first wchar - error = RtlUTF8ToUnicodeN(name->FileName, space /* + sizeof(name->FileName) */, NULL, strname, strlen(strname)); + error = RtlUTF8ToUnicodeN(name->FileName, + space /* + sizeof (name->FileName) */, + NULL, strname, strlen(strname)); if (space < name->FileNameLength) Status = STATUS_BUFFER_OVERFLOW; else Status = STATUS_SUCCESS; - // Return how much of the filename we copied after the first wchar - // which is used with sizeof(struct) to work out how much bigger the return is. - if (usedspace) *usedspace = space; // Space will always be 2 or more, since struct has room for 1 wchar + // which is used with sizeof (struct) to work out how much + // bigger the return is. + if (usedspace) *usedspace = space; + // Space will always be 2 or more, since struct has room for 1 wchar - dprintf("* %s: %s name of '%.*S' struct size 0x%x and FileNameLength 0x%x Usedspace 0x%x\n", __func__, - Status == STATUS_BUFFER_OVERFLOW ? "partial" : "", - space / 2, name->FileName, - sizeof(FILE_NAME_INFORMATION), name->FileNameLength, space); + dprintf("* %s: %s name of '%.*S' struct size 0x%x and " + "FileNameLength 0x%x Usedspace 0x%x\n", __func__, + Status == STATUS_BUFFER_OVERFLOW ? "partial" : "", + space / 2, name->FileName, + sizeof (FILE_NAME_INFORMATION), name->FileNameLength, space); - return Status; + return (Status); } // This function is not used - left in as example. If you think // something is not working due to missing FileRemoteProtocolInformation // then think again. This is not the problem. -NTSTATUS file_remote_protocol_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp, FILE_REMOTE_PROTOCOL_INFORMATION *frpi) +NTSTATUS +file_remote_protocol_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp, FILE_REMOTE_PROTOCOL_INFORMATION *frpi) { dprintf(" %s\n", __func__); - if (IrpSp->Parameters.QueryFile.Length < sizeof(FILE_REMOTE_PROTOCOL_INFORMATION)) { - Irp->IoStatus.Information = sizeof(FILE_REMOTE_PROTOCOL_INFORMATION); - return STATUS_BUFFER_TOO_SMALL; + if (IrpSp->Parameters.QueryFile.Length < + sizeof (FILE_REMOTE_PROTOCOL_INFORMATION)) { + Irp->IoStatus.Information = + sizeof (FILE_REMOTE_PROTOCOL_INFORMATION); + return (STATUS_BUFFER_TOO_SMALL); } frpi->StructureVersion = 4; - frpi->StructureSize = sizeof(FILE_REMOTE_PROTOCOL_INFORMATION); + frpi->StructureSize = sizeof (FILE_REMOTE_PROTOCOL_INFORMATION); frpi->Protocol = WNNC_NET_GOOGLE; frpi->ProtocolMajorVersion = 1; frpi->ProtocolMinorVersion = 0; frpi->ProtocolRevision = 3; frpi->Flags = REMOTE_PROTOCOL_FLAG_LOOPBACK; - Irp->IoStatus.Information = sizeof(FILE_REMOTE_PROTOCOL_INFORMATION); - return STATUS_SUCCESS; + Irp->IoStatus.Information = sizeof (FILE_REMOTE_PROTOCOL_INFORMATION); + return (STATUS_SUCCESS); } // Insert a streamname into an output buffer, if there is room, // StreamNameLength is always the FULL name length, even when we only // fit partial. // Return 0 for OK, 1 for overflow. -int zfswin_insert_streamname(char *streamname, uint8_t *outbuffer, DWORD **lastNextEntryOffset, - uint64_t availablebytes, uint64_t *spaceused, uint64_t streamsize) +int +zfswin_insert_streamname(char *streamname, uint8_t *outbuffer, + DWORD **lastNextEntryOffset, uint64_t availablebytes, + uint64_t *spaceused, uint64_t streamsize) { /* - typedef struct _FILE_STREAM_INFO { - DWORD NextEntryOffset; - DWORD StreamNameLength; - LARGE_INTEGER StreamSize; - LARGE_INTEGER StreamAllocationSize; - WCHAR StreamName[1]; - } FILE_STREAM_INFO, *PFILE_STREAM_INFO; - */ - // The first stream struct we assume is already aligned, but further ones - // should be padded here. + * typedef struct _FILE_STREAM_INFO { + * DWORD NextEntryOffset; + * DWORD StreamNameLength; + * LARGE_INTEGER StreamSize; + * LARGE_INTEGER StreamAllocationSize; + * WCHAR StreamName[1]; + * } FILE_STREAM_INFO, *PFILE_STREAM_INFO; + */ + // The first stream struct we assume is already aligned, + // but further ones should be padded here. FILE_STREAM_INFORMATION *stream = NULL; int overflow = 0; @@ -3065,18 +3282,19 @@ int zfswin_insert_streamname(char *streamname, uint8_t *outbuffer, DWORD **lastN int error; // Check error? Do we care about convertion errors? - error = RtlUTF8ToUnicodeN(NULL, 0, &needed_streamnamelen, streamname, strlen(streamname)); + error = RtlUTF8ToUnicodeN(NULL, 0, &needed_streamnamelen, + streamname, strlen(streamname)); // Is there room? We have to add the struct if there is room for it // and fill it out as much as possible, and copy in as much of the name // as we can. - if (*spaceused + sizeof(FILE_STREAM_INFORMATION) <= availablebytes) { + if (*spaceused + sizeof (FILE_STREAM_INFORMATION) <= availablebytes) { stream = (FILE_STREAM_INFORMATION *)&outbuffer[*spaceused]; // Room for one more struct, update privious's next ptr if (*lastNextEntryOffset != NULL) { - // Update previous structure to point to this one. + // Update previous structure to point to this one. **lastNextEntryOffset = (DWORD)*spaceused; } @@ -3084,15 +3302,18 @@ int zfswin_insert_streamname(char *streamname, uint8_t *outbuffer, DWORD **lastN // Directly set next to 0, assuming this will be last record stream->NextEntryOffset = 0; - // remember this struct's NextEntry, so the next one can fill it in. + // remember this struct's NextEntry, so the next one can + // fill it in. *lastNextEntryOffset = &stream->NextEntryOffset; // Set all the fields now stream->StreamSize.QuadPart = streamsize; - stream->StreamAllocationSize.QuadPart = P2ROUNDUP(streamsize, 512); + stream->StreamAllocationSize.QuadPart = + P2ROUNDUP(streamsize, 512); // Return the total name length - stream->StreamNameLength = needed_streamnamelen + 1 * sizeof(WCHAR); // + ":" + stream->StreamNameLength = + needed_streamnamelen + 1 * sizeof (WCHAR); // + ":" // Consume the space of the struct *spaceused += FIELD_OFFSET(FILE_STREAM_INFORMATION, StreamName); @@ -3100,8 +3321,7 @@ int zfswin_insert_streamname(char *streamname, uint8_t *outbuffer, DWORD **lastN uint64_t roomforname; if (*spaceused + stream->StreamNameLength <= availablebytes) { roomforname = stream->StreamNameLength; - } - else { + } else { roomforname = availablebytes - *spaceused; overflow = 1; } @@ -3113,26 +3333,29 @@ int zfswin_insert_streamname(char *streamname, uint8_t *outbuffer, DWORD **lastN // We need to real full length in StreamNameLength // There is always room for 1 char stream->StreamName[0] = L':'; - roomforname -= sizeof(WCHAR); + roomforname -= sizeof (WCHAR); // Convert as much as we can, accounting for the start ":" - error = RtlUTF8ToUnicodeN(&stream->StreamName[1], roomforname, NULL, streamname, strlen(streamname)); + error = RtlUTF8ToUnicodeN(&stream->StreamName[1], roomforname, + NULL, streamname, strlen(streamname)); dprintf("%s: added %s streamname '%s'\n", __func__, - overflow ? "(partial)" : "", streamname); - } - else { + overflow ? "(partial)" : "", streamname); + } else { dprintf("%s: no room for '%s'\n", __func__, streamname); overflow = 1; } - return overflow; + return (overflow); } // // If overflow, set Information to input_size and NameLength to required size. // -NTSTATUS file_stream_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp, FILE_STREAM_INFORMATION *stream, PULONG usedspace) +NTSTATUS +file_stream_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp, FILE_STREAM_INFORMATION *stream, + PULONG usedspace) { PFILE_OBJECT FileObject = IrpSp->FileObject; NTSTATUS Status; @@ -3144,11 +3367,12 @@ NTSTATUS file_stream_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STAC dprintf("%s: \n", __func__); if (FileObject == NULL || FileObject->FsContext == NULL) - return STATUS_INVALID_PARAMETER; + return (STATUS_INVALID_PARAMETER); - if (IrpSp->Parameters.QueryFile.Length < sizeof(FILE_STREAM_INFORMATION)) { - Irp->IoStatus.Information = sizeof(FILE_STREAM_INFORMATION); - return STATUS_BUFFER_TOO_SMALL; + if (IrpSp->Parameters.QueryFile.Length < + sizeof (FILE_STREAM_INFORMATION)) { + Irp->IoStatus.Information = sizeof (FILE_STREAM_INFORMATION); + return (STATUS_BUFFER_TOO_SMALL); } struct vnode *vp = FileObject->FsContext, *xvp = NULL; @@ -3168,9 +3392,11 @@ NTSTATUS file_stream_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STAC // Iterate the xattrs. - // Add a record for this name, if there is room. Keep a - // count of how much space would need. insert_xattrname adds first ":" and ":$DATA" - overflow = zfswin_insert_streamname(":$DATA", outbuffer, &lastNextEntryOffset, availablebytes, &spaceused, zp->z_size); + // Add a record for this name, if there is room. Keep a + // count of how much space would need. + // insert_xattrname adds first ":" and ":$DATA" + overflow = zfswin_insert_streamname(":$DATA", outbuffer, + &lastNextEntryOffset, availablebytes, &spaceused, zp->z_size); /* Grab the hidden attribute directory vnode. */ if (zfs_get_xattrdir(zp, &xdzp, cr, 0) != 0) { @@ -3181,16 +3407,18 @@ NTSTATUS file_stream_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STAC os = zfsvfs->z_os; for (zap_cursor_init(&zc, os, VTOZ(xdvp)->z_id); - zap_cursor_retrieve(&zc, &za) == 0; zap_cursor_advance(&zc)) { + zap_cursor_retrieve(&zc, &za) == 0; zap_cursor_advance(&zc)) { if (!xattr_stream(za.za_name)) continue; /* skip */ // We need to lookup the size of the xattr. - int error = zfs_dirlook(VTOZ(xdvp), za.za_name, &xvp, 0, NULL, NULL); + int error = zfs_dirlook(VTOZ(xdvp), za.za_name, &xvp, 0, + NULL, NULL); - overflow += zfswin_insert_streamname(za.za_name, outbuffer, &lastNextEntryOffset, availablebytes, &spaceused, - xvp ? VTOZ(xvp)->z_size : 0); + overflow += zfswin_insert_streamname(za.za_name, outbuffer, + &lastNextEntryOffset, availablebytes, &spaceused, + xvp ? VTOZ(xvp)->z_size : 0); if (error == 0) VN_RELE(xvp); @@ -3213,14 +3441,15 @@ NTSTATUS file_stream_information(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STAC // Set to how space we used. Irp->IoStatus.Information = spaceused; - return Status; + return (Status); } /* IRP_MJ_DEVICE_CONTROL helpers */ - -NTSTATUS QueryCapabilities(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +QueryCapabilities(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp) { NTSTATUS Status; PDEVICE_CAPABILITIES DeviceCapabilities; @@ -3230,40 +3459,48 @@ NTSTATUS QueryCapabilities(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCA DeviceCapabilities->EjectSupported = TRUE; DeviceCapabilities->Removable = FALSE; // XX DeviceCapabilities->DockDevice = FALSE; - DeviceCapabilities->D1Latency = DeviceCapabilities->D2Latency = DeviceCapabilities->D3Latency = 0; + DeviceCapabilities->D1Latency = + DeviceCapabilities->D2Latency = + DeviceCapabilities->D3Latency = 0; DeviceCapabilities->NoDisplayInUI = 0; - Irp->IoStatus.Information = sizeof(DEVICE_CAPABILITIES); + Irp->IoStatus.Information = sizeof (DEVICE_CAPABILITIES); - return STATUS_SUCCESS; + return (STATUS_SUCCESS); } // -// If overflow, set Information to sizeof(MOUNTDEV_NAME), and NameLength to required size. +// If overflow, set Information to sizeof (MOUNTDEV_NAME), and +// NameLength to required size. // -NTSTATUS ioctl_query_device_name(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +ioctl_query_device_name(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp) { // Return name in MOUNTDEV_NAME PMOUNTDEV_NAME name; mount_t *zmo; NTSTATUS Status; - if (IrpSp->Parameters.DeviceIoControl.OutputBufferLength < sizeof(MOUNTDEV_NAME)) { - Irp->IoStatus.Information = sizeof(MOUNTDEV_NAME); - return STATUS_BUFFER_TOO_SMALL; + if (IrpSp->Parameters.DeviceIoControl.OutputBufferLength < + sizeof (MOUNTDEV_NAME)) { + Irp->IoStatus.Information = sizeof (MOUNTDEV_NAME); + return (STATUS_BUFFER_TOO_SMALL); } zmo = (mount_t *)DeviceObject->DeviceExtension; name = Irp->AssociatedIrp.SystemBuffer; - int space = IrpSp->Parameters.DeviceIoControl.OutputBufferLength - sizeof(MOUNTDEV_NAME); + int space = IrpSp->Parameters.DeviceIoControl.OutputBufferLength - + sizeof (MOUNTDEV_NAME); #if 1 space = MIN(space, zmo->device_name.Length); name->NameLength = zmo->device_name.Length; - RtlCopyMemory(name->Name, zmo->device_name.Buffer, space + sizeof(name->Name)); - Irp->IoStatus.Information = sizeof(MOUNTDEV_NAME) + space; + RtlCopyMemory(name->Name, zmo->device_name.Buffer, + space + sizeof (name->Name)); + Irp->IoStatus.Information = sizeof (MOUNTDEV_NAME) + space; - if (space < zmo->device_name.Length - sizeof(name->Name)) + if (space < zmo->device_name.Length - sizeof (name->Name)) Status = STATUS_BUFFER_OVERFLOW; else Status = STATUS_SUCCESS; @@ -3275,46 +3512,52 @@ NTSTATUS ioctl_query_device_name(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STAC space = MIN(space, zmo->device_name.Length); name->NameLength = zmo->device_name.Length; - RtlCopyMemory(name->Name, zmo->device_name.Buffer, space + sizeof(name->Name)); - Irp->IoStatus.Information = sizeof(MOUNTDEV_NAME) + space; + RtlCopyMemory(name->Name, zmo->device_name.Buffer, + space + sizeof (name->Name)); + Irp->IoStatus.Information = sizeof (MOUNTDEV_NAME) + space; - if (space < zmo->device_name.Length - sizeof(name->Name)) + if (space < zmo->device_name.Length - sizeof (name->Name)) Status = STATUS_BUFFER_OVERFLOW; else Status = STATUS_SUCCESS; #endif - ASSERT(Irp->IoStatus.Information <= IrpSp->Parameters.DeviceIoControl.OutputBufferLength); + ASSERT(Irp->IoStatus.Information <= + IrpSp->Parameters.DeviceIoControl.OutputBufferLength); - dprintf("replying with '%.*S'\n", space + sizeof(name->Name) / sizeof(WCHAR), name->Name); + dprintf("replying with '%.*S'\n", + space + sizeof (name->Name) / sizeof (WCHAR), name->Name); - return Status; + return (Status); } -NTSTATUS ioctl_disk_get_drive_geometry(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +ioctl_disk_get_drive_geometry(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp) { dprintf("%s: \n", __func__); - if (IrpSp->Parameters.DeviceIoControl.OutputBufferLength < sizeof(DISK_GEOMETRY)) { - Irp->IoStatus.Information = sizeof(DISK_GEOMETRY); - return STATUS_BUFFER_TOO_SMALL; + if (IrpSp->Parameters.DeviceIoControl.OutputBufferLength < + sizeof (DISK_GEOMETRY)) { + Irp->IoStatus.Information = sizeof (DISK_GEOMETRY); + return (STATUS_BUFFER_TOO_SMALL); } mount_t *zmo = DeviceObject->DeviceExtension; if (!zmo || - (zmo->type != MOUNT_TYPE_VCB && - zmo->type != MOUNT_TYPE_DCB)) { - return STATUS_INVALID_PARAMETER; + (zmo->type != MOUNT_TYPE_VCB && + zmo->type != MOUNT_TYPE_DCB)) { + return (STATUS_INVALID_PARAMETER); } zfsvfs_t *zfsvfs = vfs_fsprivate(zmo); if (zfsvfs == NULL) - return STATUS_INVALID_PARAMETER; + return (STATUS_INVALID_PARAMETER); ZFS_ENTER(zfsvfs); // This returns EIO if fail uint64_t refdbytes, availbytes, usedobjs, availobjs; dmu_objset_space(zfsvfs->z_os, - &refdbytes, &availbytes, &usedobjs, &availobjs); + &refdbytes, &availbytes, &usedobjs, &availobjs); DISK_GEOMETRY *geom = Irp->AssociatedIrp.SystemBuffer; @@ -3325,8 +3568,8 @@ NTSTATUS ioctl_disk_get_drive_geometry(PDEVICE_OBJECT DeviceObject, PIRP Irp, PI geom->MediaType = FixedMedia; ZFS_EXIT(zfsvfs); - Irp->IoStatus.Information = sizeof(DISK_GEOMETRY); - return STATUS_SUCCESS; + Irp->IoStatus.Information = sizeof (DISK_GEOMETRY); + return (STATUS_SUCCESS); } // This is how Windows Samples handle it @@ -3337,30 +3580,33 @@ typedef struct _DISK_GEOMETRY_EX_INTERNAL { DISK_DETECTION_INFO Detection; } DISK_GEOMETRY_EX_INTERNAL, *PDISK_GEOMETRY_EX_INTERNAL; -NTSTATUS ioctl_disk_get_drive_geometry_ex(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +ioctl_disk_get_drive_geometry_ex(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp) { dprintf("%s: \n", __func__); - if (IrpSp->Parameters.DeviceIoControl.OutputBufferLength < FIELD_OFFSET(DISK_GEOMETRY_EX, Data)) { - Irp->IoStatus.Information = sizeof(DISK_GEOMETRY_EX); - return STATUS_BUFFER_TOO_SMALL; + if (IrpSp->Parameters.DeviceIoControl.OutputBufferLength < + FIELD_OFFSET(DISK_GEOMETRY_EX, Data)) { + Irp->IoStatus.Information = sizeof (DISK_GEOMETRY_EX); + return (STATUS_BUFFER_TOO_SMALL); } mount_t *zmo = DeviceObject->DeviceExtension; if (!zmo || - (zmo->type != MOUNT_TYPE_VCB && - zmo->type != MOUNT_TYPE_DCB)) { - return STATUS_INVALID_PARAMETER; + (zmo->type != MOUNT_TYPE_VCB && + zmo->type != MOUNT_TYPE_DCB)) { + return (STATUS_INVALID_PARAMETER); } zfsvfs_t *zfsvfs = vfs_fsprivate(zmo); if (zfsvfs == NULL) - return STATUS_INVALID_PARAMETER; + return (STATUS_INVALID_PARAMETER); ZFS_ENTER(zfsvfs); // This returns EIO if fail uint64_t refdbytes, availbytes, usedobjs, availobjs; dmu_objset_space(zfsvfs->z_os, - &refdbytes, &availbytes, &usedobjs, &availobjs); + &refdbytes, &availbytes, &usedobjs, &availobjs); DISK_GEOMETRY_EX_INTERNAL *geom = Irp->AssociatedIrp.SystemBuffer; @@ -3368,46 +3614,52 @@ NTSTATUS ioctl_disk_get_drive_geometry_ex(PDEVICE_OBJECT DeviceObject, PIRP Irp, geom->Geometry.BytesPerSector = 512; geom->Geometry.MediaType = FixedMedia; - if (IrpSp->Parameters.DeviceIoControl.OutputBufferLength >= FIELD_OFFSET(DISK_GEOMETRY_EX_INTERNAL, Detection)) { - geom->Partition.SizeOfPartitionInfo = sizeof(geom->Partition); + if (IrpSp->Parameters.DeviceIoControl.OutputBufferLength >= + FIELD_OFFSET(DISK_GEOMETRY_EX_INTERNAL, Detection)) { + geom->Partition.SizeOfPartitionInfo = sizeof (geom->Partition); geom->Partition.PartitionStyle = PARTITION_STYLE_GPT; - //geom->Partition.Gpt.DiskId = 0; + // geom->Partition.Gpt.DiskId = 0; } - if (IrpSp->Parameters.DeviceIoControl.OutputBufferLength >= sizeof(DISK_GEOMETRY_EX_INTERNAL)) { - geom->Detection.SizeOfDetectInfo = sizeof(geom->Detection); - + if (IrpSp->Parameters.DeviceIoControl.OutputBufferLength >= + sizeof (DISK_GEOMETRY_EX_INTERNAL)) { + geom->Detection.SizeOfDetectInfo = sizeof (geom->Detection); } ZFS_EXIT(zfsvfs); - Irp->IoStatus.Information = MIN(IrpSp->Parameters.DeviceIoControl.OutputBufferLength, sizeof(DISK_GEOMETRY_EX_INTERNAL)); - return STATUS_SUCCESS; + Irp->IoStatus.Information = + MIN(IrpSp->Parameters.DeviceIoControl.OutputBufferLength, + sizeof (DISK_GEOMETRY_EX_INTERNAL)); + return (STATUS_SUCCESS); } -NTSTATUS ioctl_disk_get_partition_info(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +ioctl_disk_get_partition_info(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp) { dprintf("%s: \n", __func__); - if (IrpSp->Parameters.DeviceIoControl.OutputBufferLength < sizeof(PARTITION_INFORMATION)) { - Irp->IoStatus.Information = sizeof(PARTITION_INFORMATION); - return STATUS_BUFFER_TOO_SMALL; + if (IrpSp->Parameters.DeviceIoControl.OutputBufferLength < + sizeof (PARTITION_INFORMATION)) { + Irp->IoStatus.Information = sizeof (PARTITION_INFORMATION); + return (STATUS_BUFFER_TOO_SMALL); } mount_t *zmo = DeviceObject->DeviceExtension; if (!zmo || - (zmo->type != MOUNT_TYPE_VCB && - zmo->type != MOUNT_TYPE_DCB)) { - return STATUS_INVALID_PARAMETER; + (zmo->type != MOUNT_TYPE_VCB && + zmo->type != MOUNT_TYPE_DCB)) { + return (STATUS_INVALID_PARAMETER); } zfsvfs_t *zfsvfs = vfs_fsprivate(zmo); if (zfsvfs == NULL) - return STATUS_INVALID_PARAMETER; + return (STATUS_INVALID_PARAMETER); ZFS_ENTER(zfsvfs); // This returns EIO if fail uint64_t refdbytes, availbytes, usedobjs, availobjs; dmu_objset_space(zfsvfs->z_os, - &refdbytes, &availbytes, &usedobjs, &availobjs); + &refdbytes, &availbytes, &usedobjs, &availobjs); PARTITION_INFORMATION *part = Irp->AssociatedIrp.SystemBuffer; @@ -3422,36 +3674,39 @@ NTSTATUS ioctl_disk_get_partition_info(PDEVICE_OBJECT DeviceObject, PIRP Irp, PI ZFS_EXIT(zfsvfs); - Irp->IoStatus.Information = sizeof(PARTITION_INFORMATION); + Irp->IoStatus.Information = sizeof (PARTITION_INFORMATION); - return STATUS_SUCCESS; + return (STATUS_SUCCESS); } -NTSTATUS ioctl_disk_get_partition_info_ex(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +ioctl_disk_get_partition_info_ex(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp) { dprintf("%s: \n", __func__); - if (IrpSp->Parameters.DeviceIoControl.OutputBufferLength < sizeof(PARTITION_INFORMATION_EX)) { - Irp->IoStatus.Information = sizeof(PARTITION_INFORMATION_EX); - return STATUS_BUFFER_TOO_SMALL; + if (IrpSp->Parameters.DeviceIoControl.OutputBufferLength < + sizeof (PARTITION_INFORMATION_EX)) { + Irp->IoStatus.Information = sizeof (PARTITION_INFORMATION_EX); + return (STATUS_BUFFER_TOO_SMALL); } mount_t *zmo = DeviceObject->DeviceExtension; if (!zmo || - (zmo->type != MOUNT_TYPE_VCB && - zmo->type != MOUNT_TYPE_DCB)) { - return STATUS_INVALID_PARAMETER; + (zmo->type != MOUNT_TYPE_VCB && + zmo->type != MOUNT_TYPE_DCB)) { + return (STATUS_INVALID_PARAMETER); } zfsvfs_t *zfsvfs = vfs_fsprivate(zmo); if (zfsvfs == NULL) - return STATUS_INVALID_PARAMETER; + return (STATUS_INVALID_PARAMETER); ZFS_ENTER(zfsvfs); // This returns EIO if fail uint64_t refdbytes, availbytes, usedobjs, availobjs; dmu_objset_space(zfsvfs->z_os, - &refdbytes, &availbytes, &usedobjs, &availobjs); + &refdbytes, &availbytes, &usedobjs, &availobjs); PARTITION_INFORMATION_EX *part = Irp->AssociatedIrp.SystemBuffer; @@ -3467,74 +3722,84 @@ NTSTATUS ioctl_disk_get_partition_info_ex(PDEVICE_OBJECT DeviceObject, PIRP Irp, ZFS_EXIT(zfsvfs); - Irp->IoStatus.Information = sizeof(PARTITION_INFORMATION_EX); + Irp->IoStatus.Information = sizeof (PARTITION_INFORMATION_EX); - return STATUS_SUCCESS; + return (STATUS_SUCCESS); } -NTSTATUS ioctl_disk_get_length_info(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +ioctl_disk_get_length_info(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp) { dprintf("%s: \n", __func__); - if (IrpSp->Parameters.DeviceIoControl.OutputBufferLength < sizeof(GET_LENGTH_INFORMATION)) { - Irp->IoStatus.Information = sizeof(GET_LENGTH_INFORMATION); - return STATUS_BUFFER_TOO_SMALL; + if (IrpSp->Parameters.DeviceIoControl.OutputBufferLength < + sizeof (GET_LENGTH_INFORMATION)) { + Irp->IoStatus.Information = sizeof (GET_LENGTH_INFORMATION); + return (STATUS_BUFFER_TOO_SMALL); } mount_t *zmo = DeviceObject->DeviceExtension; if (!zmo || - (zmo->type != MOUNT_TYPE_VCB && - zmo->type != MOUNT_TYPE_DCB)) { - return STATUS_INVALID_PARAMETER; + (zmo->type != MOUNT_TYPE_VCB && + zmo->type != MOUNT_TYPE_DCB)) { + return (STATUS_INVALID_PARAMETER); } zfsvfs_t *zfsvfs = vfs_fsprivate(zmo); if (zfsvfs == NULL) - return STATUS_INVALID_PARAMETER; + return (STATUS_INVALID_PARAMETER); ZFS_ENTER(zfsvfs); // This returns EIO if fail uint64_t refdbytes, availbytes, usedobjs, availobjs; dmu_objset_space(zfsvfs->z_os, - &refdbytes, &availbytes, &usedobjs, &availobjs); + &refdbytes, &availbytes, &usedobjs, &availobjs); GET_LENGTH_INFORMATION *gli = Irp->AssociatedIrp.SystemBuffer; gli->Length.QuadPart = availbytes + refdbytes; ZFS_EXIT(zfsvfs); - Irp->IoStatus.Information = sizeof(GET_LENGTH_INFORMATION); + Irp->IoStatus.Information = sizeof (GET_LENGTH_INFORMATION); - return STATUS_SUCCESS; + return (STATUS_SUCCESS); } -NTSTATUS ioctl_volume_is_io_capable(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +ioctl_volume_is_io_capable(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp) { dprintf("%s: \n", __func__); - return STATUS_SUCCESS; + return (STATUS_SUCCESS); } -NTSTATUS ioctl_storage_get_hotplug_info(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +ioctl_storage_get_hotplug_info(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp) { dprintf("%s: \n", __func__); - if (IrpSp->Parameters.DeviceIoControl.OutputBufferLength < sizeof(STORAGE_HOTPLUG_INFO)) { - Irp->IoStatus.Information = sizeof(STORAGE_HOTPLUG_INFO); - return STATUS_BUFFER_TOO_SMALL; + if (IrpSp->Parameters.DeviceIoControl.OutputBufferLength < + sizeof (STORAGE_HOTPLUG_INFO)) { + Irp->IoStatus.Information = sizeof (STORAGE_HOTPLUG_INFO); + return (STATUS_BUFFER_TOO_SMALL); } STORAGE_HOTPLUG_INFO *hot = Irp->AssociatedIrp.SystemBuffer; - hot->Size = sizeof(STORAGE_HOTPLUG_INFO); + hot->Size = sizeof (STORAGE_HOTPLUG_INFO); hot->MediaRemovable = FALSE; // XX hot->DeviceHotplug = TRUE; hot->MediaHotplug = FALSE; hot->WriteCacheEnableOverride = FALSE; - Irp->IoStatus.Information = sizeof(STORAGE_HOTPLUG_INFO); - return STATUS_SUCCESS; + Irp->IoStatus.Information = sizeof (STORAGE_HOTPLUG_INFO); + return (STATUS_SUCCESS); } -NTSTATUS ioctl_storage_query_property(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +ioctl_storage_query_property(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp) { NTSTATUS status; ULONG outputLength; @@ -3542,9 +3807,9 @@ NTSTATUS ioctl_storage_query_property(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO dprintf("%s: \n", __func__); outputLength = IrpSp->Parameters.DeviceIoControl.OutputBufferLength; - if (outputLength < sizeof(STORAGE_PROPERTY_QUERY)) { - Irp->IoStatus.Information = sizeof(STORAGE_PROPERTY_QUERY); - return STATUS_BUFFER_TOO_SMALL; + if (outputLength < sizeof (STORAGE_PROPERTY_QUERY)) { + Irp->IoStatus.Information = sizeof (STORAGE_PROPERTY_QUERY); + return (STATUS_BUFFER_TOO_SMALL); } STORAGE_PROPERTY_QUERY *spq = Irp->AssociatedIrp.SystemBuffer; @@ -3558,20 +3823,20 @@ NTSTATUS ioctl_storage_query_property(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO switch (spq->PropertyId) { case StorageDeviceUniqueIdProperty: - dprintf(" PropertyExistsQuery StorageDeviceUniqueIdProperty\n"); +dprintf(" PropertyExistsQuery StorageDeviceUniqueIdProperty\n"); status = STATUS_SUCCESS; break; case StorageDeviceWriteCacheProperty: case StorageAdapterProperty: - dprintf(" PropertyExistsQuery Not implemented 0x%x\n", spq->PropertyId); +dprintf(" PropertyExistsQuery Not implemented 0x%x\n", spq->PropertyId); status = STATUS_NOT_IMPLEMENTED; break; case StorageDeviceAttributesProperty: - dprintf(" PropertyExistsQuery StorageDeviceAttributesProperty\n"); +dprintf(" PropertyExistsQuery StorageDeviceAttributesProperty\n"); status = STATUS_SUCCESS; break; default: - dprintf(" PropertyExistsQuery unknown 0x%x\n", spq->PropertyId); +dprintf(" PropertyExistsQuery unknown 0x%x\n", spq->PropertyId); status = STATUS_NOT_IMPLEMENTED; break; } // switch PropertyId @@ -3582,9 +3847,10 @@ NTSTATUS ioctl_storage_query_property(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO switch (spq->PropertyId) { case StorageDeviceProperty: - dprintf(" PropertyStandardQuery StorageDeviceProperty\n"); - Irp->IoStatus.Information = sizeof(STORAGE_DEVICE_DESCRIPTOR); - if (outputLength < sizeof(STORAGE_DEVICE_DESCRIPTOR)) { +dprintf(" PropertyStandardQuery StorageDeviceProperty\n"); + Irp->IoStatus.Information = + sizeof (STORAGE_DEVICE_DESCRIPTOR); + if (outputLength < sizeof (STORAGE_DEVICE_DESCRIPTOR)) { status = STATUS_BUFFER_TOO_SMALL; break; } @@ -3593,47 +3859,57 @@ NTSTATUS ioctl_storage_query_property(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO status = STATUS_SUCCESS; break; case StorageAdapterProperty: - dprintf(" PropertyStandardQuery Not implemented 0x%x\n", spq->PropertyId); +dprintf(" PropertyStandardQuery Not implemented 0x%x\n", spq->PropertyId); status = STATUS_NOT_IMPLEMENTED; break; case StorageDeviceAttributesProperty: - dprintf(" PropertyStandardQuery StorageDeviceAttributesProperty\n"); - Irp->IoStatus.Information = sizeof(STORAGE_DEVICE_ATTRIBUTES_DESCRIPTOR); - if (outputLength < sizeof(STORAGE_DEVICE_ATTRIBUTES_DESCRIPTOR)) { +dprintf(" PropertyStandardQuery StorageDeviceAttributesProperty\n"); + Irp->IoStatus.Information = + sizeof (STORAGE_DEVICE_ATTRIBUTES_DESCRIPTOR); + if (outputLength < + sizeof (STORAGE_DEVICE_ATTRIBUTES_DESCRIPTOR)) { status = STATUS_BUFFER_TOO_SMALL; break; } STORAGE_DEVICE_ATTRIBUTES_DESCRIPTOR *sdad; sdad = Irp->AssociatedIrp.SystemBuffer; sdad->Version = 1; - sdad->Size = sizeof(STORAGE_DEVICE_ATTRIBUTES_DESCRIPTOR); - sdad->Attributes = STORAGE_ATTRIBUTE_BYTE_ADDRESSABLE_IO; + sdad->Size = + sizeof (STORAGE_DEVICE_ATTRIBUTES_DESCRIPTOR); + sdad->Attributes = + STORAGE_ATTRIBUTE_BYTE_ADDRESSABLE_IO; status = STATUS_SUCCESS; break; default: - dprintf(" PropertyStandardQuery unknown 0x%x\n", spq->PropertyId); + dprintf(" PropertyStandardQuery unknown 0x%x\n", + spq->PropertyId); status = STATUS_NOT_IMPLEMENTED; break; } // switch propertyId break; default: - dprintf("%s: unknown Querytype: 0x%x\n", __func__, spq->QueryType); + dprintf("%s: unknown Querytype: 0x%x\n", + __func__, spq->QueryType); status = STATUS_NOT_IMPLEMENTED; break; } - Irp->IoStatus.Information = sizeof(STORAGE_PROPERTY_QUERY); - return status; + Irp->IoStatus.Information = sizeof (STORAGE_PROPERTY_QUERY); + return (status); } // Query Unique id uses 1 byte chars. -// If overflow, set Information to sizeof(MOUNTDEV_UNIQUE_ID), and NameLength to required size. +// If overflow, set Information to sizeof (MOUNTDEV_UNIQUE_ID), +// and NameLength to required size. // -NTSTATUS ioctl_query_unique_id(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +ioctl_query_unique_id(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp) { PMOUNTDEV_UNIQUE_ID uniqueId; - ULONG bufferLength = IrpSp->Parameters.DeviceIoControl.OutputBufferLength; + ULONG bufferLength = + IrpSp->Parameters.DeviceIoControl.OutputBufferLength; mount_t *zmo; char osname[MAXNAMELEN]; ULONG len; @@ -3642,150 +3918,151 @@ NTSTATUS ioctl_query_unique_id(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_ zmo = (mount_t *)DeviceObject->DeviceExtension; - if (bufferLength < sizeof(MOUNTDEV_UNIQUE_ID)) { - Irp->IoStatus.Information = sizeof(MOUNTDEV_UNIQUE_ID); - return STATUS_BUFFER_TOO_SMALL; + if (bufferLength < sizeof (MOUNTDEV_UNIQUE_ID)) { + Irp->IoStatus.Information = sizeof (MOUNTDEV_UNIQUE_ID); + return (STATUS_BUFFER_TOO_SMALL); } - RtlUnicodeToUTF8N(osname, MAXPATHLEN, &len, zmo->name.Buffer, zmo->name.Length); + RtlUnicodeToUTF8N(osname, MAXPATHLEN, &len, zmo->name.Buffer, + zmo->name.Length); osname[len] = 0; - // uniqueId appears to be CHARS not WCHARS, so this might need correcting? + // uniqueId appears to be CHARS not WCHARS, + // so this might need correcting? uniqueId = (PMOUNTDEV_UNIQUE_ID)Irp->AssociatedIrp.SystemBuffer; uniqueId->UniqueIdLength = strlen(osname); - if (sizeof(USHORT) + uniqueId->UniqueIdLength < bufferLength) { - RtlCopyMemory((PCHAR)uniqueId->UniqueId, osname, uniqueId->UniqueIdLength); - Irp->IoStatus.Information = FIELD_OFFSET(MOUNTDEV_UNIQUE_ID, UniqueId[0]) + - uniqueId->UniqueIdLength; - dprintf("replying with '%.*s'\n", uniqueId->UniqueIdLength, uniqueId->UniqueId); - return STATUS_SUCCESS; - } - else { - Irp->IoStatus.Information = sizeof(MOUNTDEV_UNIQUE_ID); - return STATUS_BUFFER_OVERFLOW; + if (sizeof (USHORT) + uniqueId->UniqueIdLength < bufferLength) { + RtlCopyMemory((PCHAR)uniqueId->UniqueId, osname, + uniqueId->UniqueIdLength); + Irp->IoStatus.Information = + FIELD_OFFSET(MOUNTDEV_UNIQUE_ID, UniqueId[0]) + + uniqueId->UniqueIdLength; + dprintf("replying with '%.*s'\n", + uniqueId->UniqueIdLength, uniqueId->UniqueId); + return (STATUS_SUCCESS); + } else { + Irp->IoStatus.Information = sizeof (MOUNTDEV_UNIQUE_ID); + return (STATUS_BUFFER_OVERFLOW); } } -NTSTATUS ioctl_query_stable_guid(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +ioctl_query_stable_guid(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp) { PMOUNTDEV_STABLE_GUID mountGuid; - ULONG bufferLength = IrpSp->Parameters.DeviceIoControl.OutputBufferLength; + ULONG bufferLength = + IrpSp->Parameters.DeviceIoControl.OutputBufferLength; mount_t *zmo; dprintf("%s: \n", __func__); zmo = (mount_t *)DeviceObject->DeviceExtension; - if (bufferLength < sizeof(MOUNTDEV_STABLE_GUID)) { - Irp->IoStatus.Information = sizeof(MOUNTDEV_STABLE_GUID); - return STATUS_BUFFER_TOO_SMALL; + if (bufferLength < sizeof (MOUNTDEV_STABLE_GUID)) { + Irp->IoStatus.Information = sizeof (MOUNTDEV_STABLE_GUID); + return (STATUS_BUFFER_TOO_SMALL); } mountGuid = (PMOUNTDEV_STABLE_GUID)Irp->AssociatedIrp.SystemBuffer; - RtlZeroMemory(&mountGuid->StableGuid, sizeof(mountGuid->StableGuid)); + RtlZeroMemory(&mountGuid->StableGuid, sizeof (mountGuid->StableGuid)); zfsvfs_t *zfsvfs = vfs_fsprivate(zmo); if (zfsvfs) { uint64_t guid = dmu_objset_fsid_guid(zfsvfs->z_os); - RtlCopyMemory(&mountGuid->StableGuid, &guid, sizeof(guid)); - Irp->IoStatus.Information = sizeof(MOUNTDEV_STABLE_GUID); - return STATUS_SUCCESS; + RtlCopyMemory(&mountGuid->StableGuid, &guid, sizeof (guid)); + Irp->IoStatus.Information = sizeof (MOUNTDEV_STABLE_GUID); + return (STATUS_SUCCESS); } - return STATUS_NOT_FOUND; + return (STATUS_NOT_FOUND); } -NTSTATUS ioctl_mountdev_query_suggested_link_name(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +ioctl_mountdev_query_suggested_link_name(PDEVICE_OBJECT DeviceObject, + PIRP Irp, PIO_STACK_LOCATION IrpSp) { MOUNTDEV_SUGGESTED_LINK_NAME *linkName; - ULONG bufferLength = IrpSp->Parameters.DeviceIoControl.OutputBufferLength; + ULONG bufferLength = + IrpSp->Parameters.DeviceIoControl.OutputBufferLength; // UNICODE_STRING MountPoint; mount_t *zmo = (mount_t *)DeviceObject->DeviceExtension; dprintf("%s: \n", __func__); - if (bufferLength < sizeof(MOUNTDEV_SUGGESTED_LINK_NAME)) { - Irp->IoStatus.Information = sizeof(MOUNTDEV_SUGGESTED_LINK_NAME); - return STATUS_BUFFER_TOO_SMALL; + if (bufferLength < sizeof (MOUNTDEV_SUGGESTED_LINK_NAME)) { + Irp->IoStatus.Information = + sizeof (MOUNTDEV_SUGGESTED_LINK_NAME); + return (STATUS_BUFFER_TOO_SMALL); } // We only reply to strict driveletter mounts, not paths... if (!zmo->justDriveLetter) - return STATUS_NOT_FOUND; + return (STATUS_NOT_FOUND); // If "?:" then just let windows pick drive letter if (zmo->mountpoint.Buffer[4] == L'?') - return STATUS_NOT_FOUND; + return (STATUS_NOT_FOUND); // This code works, for driveletters. // The mountpoint string is "\\??\\f:" so change // that to DosDevicesF: - DECLARE_UNICODE_STRING_SIZE(MountPoint, ZFS_MAX_DATASET_NAME_LEN); // 36(uuid) + 6 (punct) + 6 (Volume) - RtlUnicodeStringPrintf(&MountPoint, L"\\DosDevices\\%wc:", towupper(zmo->mountpoint.Buffer[4])); // "\??\F:" + DECLARE_UNICODE_STRING_SIZE(MountPoint, + ZFS_MAX_DATASET_NAME_LEN); // 36(uuid) + 6 (punct) + 6 (Volume) + RtlUnicodeStringPrintf(&MountPoint, L"\\DosDevices\\%wc:", + towupper(zmo->mountpoint.Buffer[4])); // "\??\F:" - //RtlInitUnicodeString(&MountPoint, L"\\DosDevices\\G:"); + // RtlInitUnicodeString(&MountPoint, L"\\DosDevices\\G:"); - linkName = (PMOUNTDEV_SUGGESTED_LINK_NAME)Irp->AssociatedIrp.SystemBuffer; + linkName = + (PMOUNTDEV_SUGGESTED_LINK_NAME)Irp->AssociatedIrp.SystemBuffer; linkName->UseOnlyIfThereAreNoOtherLinks = FALSE; linkName->NameLength = MountPoint.Length; - if (sizeof(USHORT) + linkName->NameLength <= bufferLength) { + if (sizeof (USHORT) + linkName->NameLength <= bufferLength) { RtlCopyMemory((PCHAR)linkName->Name, MountPoint.Buffer, - linkName->NameLength); + linkName->NameLength); Irp->IoStatus.Information = - FIELD_OFFSET(MOUNTDEV_SUGGESTED_LINK_NAME, Name[0]) + - linkName->NameLength; + FIELD_OFFSET(MOUNTDEV_SUGGESTED_LINK_NAME, Name[0]) + + linkName->NameLength; dprintf(" LinkName %wZ (%d)\n", MountPoint, MountPoint.Length); - return STATUS_SUCCESS; + return (STATUS_SUCCESS); } - Irp->IoStatus.Information = sizeof(MOUNTDEV_SUGGESTED_LINK_NAME); - return STATUS_BUFFER_OVERFLOW; - - //return STATUS_NOT_FOUND; + Irp->IoStatus.Information = sizeof (MOUNTDEV_SUGGESTED_LINK_NAME); + return (STATUS_BUFFER_OVERFLOW); } -NTSTATUS ioctl_mountdev_query_stable_guid(PDEVICE_OBJECT DeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp) +NTSTATUS +ioctl_mountdev_query_stable_guid(PDEVICE_OBJECT DeviceObject, PIRP Irp, + PIO_STACK_LOCATION IrpSp) { MOUNTDEV_STABLE_GUID *guid = Irp->UserBuffer; - ULONG bufferLength = IrpSp->Parameters.DeviceIoControl.OutputBufferLength; + ULONG bufferLength = + IrpSp->Parameters.DeviceIoControl.OutputBufferLength; mount_t *zmo = (mount_t *)DeviceObject->DeviceExtension; dprintf("%s: \n", __func__); - if (bufferLength < sizeof(MOUNTDEV_STABLE_GUID)) { - Irp->IoStatus.Information = sizeof(MOUNTDEV_STABLE_GUID); - return STATUS_BUFFER_TOO_SMALL; + if (bufferLength < sizeof (MOUNTDEV_STABLE_GUID)) { + Irp->IoStatus.Information = sizeof (MOUNTDEV_STABLE_GUID); + return (STATUS_BUFFER_TOO_SMALL); } zfsvfs_t *zfsvfs = vfs_fsprivate(zmo); if (zfsvfs == NULL) - return STATUS_INVALID_PARAMETER; + return (STATUS_INVALID_PARAMETER); extern int zfs_vfs_uuid_gen(const char *osname, uuid_t uuid); // A bit naughty - zfs_vfs_uuid_gen(spa_name(dmu_objset_spa(zfsvfs->z_os)), (char *)&guid->StableGuid); + zfs_vfs_uuid_gen(spa_name(dmu_objset_spa(zfsvfs->z_os)), + (char *)&guid->StableGuid); - Irp->IoStatus.Information = sizeof(MOUNTDEV_STABLE_GUID); - return STATUS_SUCCESS; + Irp->IoStatus.Information = sizeof (MOUNTDEV_STABLE_GUID); + return (STATUS_SUCCESS); } - -// FFFF9284A054B080: * user_fs_request: unknown class 0x903bc: CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 238, - -// 0x2d118c - MASS_STORAGE 0x463 -// disk Windows IOCTL: 0x530018 - -// fsWindows IOCTL: 0x534058 -// FFFF9284A14A9040: **** unknown fsWindows IOCTL: 0x534058 function 0x16 -// VOLSNAPCONTROLTYPE : - -/* - (open Extend\$Reparse:$R:$INDEX_ALLOCATION and use ZwQueryDirectoryFile on that handle to get - reparse info). It gives you the FileReference (file id) and tag value of all the reparse - points on the volume (see ntifs.h for FILE_REPARSE_POINT_INFORMATION). - */ diff --git a/module/os/windows/zfs/zfs_vnops_windows_mount.c b/module/os/windows/zfs/zfs_vnops_windows_mount.c index d2358cd426b..ed93e625c62 100644 --- a/module/os/windows/zfs/zfs_vnops_windows_mount.c +++ b/module/os/windows/zfs/zfs_vnops_windows_mount.c @@ -21,15 +21,11 @@ /* * Copyright (c) 2019 Jorgen Lundman */ -#define INITGUID -//#include -//#include +#define INITGUID #include #include #include -//#include #include -//#include #include #include #include @@ -47,12 +43,9 @@ #include #include -//#include #include -//#include #include -#include #include #include @@ -69,47 +62,56 @@ uint64_t zfs_disable_removablemedia = 0; /* -* Jump through the hoops needed to make a mount happen. -* -* Create a new Volume name -* Register a new unknown device -* Assign volume name -* Register device as disk -* fill in disk information -* broadcast information -*/ - -NTSTATUS mountmgr_add_drive_letter(PDEVICE_OBJECT mountmgr, PUNICODE_STRING devpath) + * Jump through the hoops needed to make a mount happen. + * + * Create a new Volume name + * Register a new unknown device + * Assign volume name + * Register device as disk + * fill in disk information + * broadcast information + */ + +NTSTATUS +mountmgr_add_drive_letter(PDEVICE_OBJECT mountmgr, PUNICODE_STRING devpath) { NTSTATUS Status; ULONG mmdltsize; MOUNTMGR_DRIVE_LETTER_TARGET* mmdlt; MOUNTMGR_DRIVE_LETTER_INFORMATION mmdli; - mmdltsize = offsetof(MOUNTMGR_DRIVE_LETTER_TARGET, DeviceName[0]) + devpath->Length; + mmdltsize = offsetof(MOUNTMGR_DRIVE_LETTER_TARGET, DeviceName[0]) + + devpath->Length; mmdlt = kmem_alloc(mmdltsize, KM_SLEEP); mmdlt->DeviceNameLength = devpath->Length; RtlCopyMemory(&mmdlt->DeviceName, devpath->Buffer, devpath->Length); - dprintf("mmdlt = %.*S\n", mmdlt->DeviceNameLength / sizeof(WCHAR), mmdlt->DeviceName); + dprintf("mmdlt = %.*S\n", + mmdlt->DeviceNameLength / sizeof (WCHAR), mmdlt->DeviceName); - Status = dev_ioctl(mountmgr, IOCTL_MOUNTMGR_NEXT_DRIVE_LETTER, mmdlt, mmdltsize, &mmdli, sizeof(MOUNTMGR_DRIVE_LETTER_INFORMATION), FALSE, NULL); + Status = dev_ioctl(mountmgr, IOCTL_MOUNTMGR_NEXT_DRIVE_LETTER, + mmdlt, mmdltsize, &mmdli, + sizeof (MOUNTMGR_DRIVE_LETTER_INFORMATION), FALSE, NULL); if (!NT_SUCCESS(Status)) - dprintf("IOCTL_MOUNTMGR_NEXT_DRIVE_LETTER returned %08x\n", Status); + dprintf("IOCTL_MOUNTMGR_NEXT_DRIVE_LETTER returned %08x\n", + Status); else - dprintf("DriveLetterWasAssigned = %u, CurrentDriveLetter = %c\n", mmdli.DriveLetterWasAssigned, mmdli.CurrentDriveLetter); + dprintf("DriveLetterWasAssigned = %u, " + "CurrentDriveLetter = %c\n", + mmdli.DriveLetterWasAssigned, mmdli.CurrentDriveLetter); kmem_free(mmdlt, mmdltsize); - return Status; + return (Status); } /* * check if valid mountpoint, like \DosDevices\X: */ -BOOLEAN MOUNTMGR_IS_DRIVE_LETTER_A(char *mountpoint) +BOOLEAN +MOUNTMGR_IS_DRIVE_LETTER_A(char *mountpoint) { UNICODE_STRING wc_mpt; wchar_t buf[PATH_MAX]; @@ -121,7 +123,8 @@ BOOLEAN MOUNTMGR_IS_DRIVE_LETTER_A(char *mountpoint) /* * check if valid mountpoint, like \??\Volume{abc} */ -BOOLEAN MOUNTMGR_IS_VOLUME_NAME_A(char *mountpoint) +BOOLEAN +MOUNTMGR_IS_VOLUME_NAME_A(char *mountpoint) { UNICODE_STRING wc_mpt; wchar_t buf[PATH_MAX]; @@ -138,9 +141,10 @@ BOOLEAN MOUNTMGR_IS_VOLUME_NAME_A(char *mountpoint) * MOUNTMGR_IS_VOLUME_NAME and discarded if not valid * only_driveletter and only_volume_name are mutual exclusive */ -NTSTATUS mountmgr_get_mountpoint(PDEVICE_OBJECT mountmgr, - PUNICODE_STRING devpath, char *savename, BOOLEAN only_driveletter, - BOOLEAN only_volume_name) +NTSTATUS +mountmgr_get_mountpoint(PDEVICE_OBJECT mountmgr, + PUNICODE_STRING devpath, char *savename, BOOLEAN only_driveletter, + BOOLEAN only_volume_name) { MOUNTMGR_MOUNT_POINT point = { 0 }; MOUNTMGR_MOUNT_POINTS points; @@ -149,69 +153,92 @@ NTSTATUS mountmgr_get_mountpoint(PDEVICE_OBJECT mountmgr, NTSTATUS Status; if (only_driveletter && only_volume_name) - return STATUS_INVALID_PARAMETER; + return (STATUS_INVALID_PARAMETER); ppoints = &points; - Status = dev_ioctl(mountmgr, IOCTL_MOUNTMGR_QUERY_POINTS, &point, sizeof(MOUNTMGR_MOUNT_POINT), ppoints, sizeof(MOUNTMGR_MOUNT_POINTS), FALSE, NULL); + Status = dev_ioctl(mountmgr, IOCTL_MOUNTMGR_QUERY_POINTS, + &point, sizeof (MOUNTMGR_MOUNT_POINT), ppoints, + sizeof (MOUNTMGR_MOUNT_POINTS), FALSE, NULL); if (Status == STATUS_BUFFER_OVERFLOW) { len = points.Size; ppoints = kmem_alloc(len, KM_SLEEP); - Status = dev_ioctl(mountmgr, IOCTL_MOUNTMGR_QUERY_POINTS, &point, sizeof(MOUNTMGR_MOUNT_POINT), ppoints, len, FALSE, NULL); + Status = dev_ioctl(mountmgr, IOCTL_MOUNTMGR_QUERY_POINTS, + &point, sizeof (MOUNTMGR_MOUNT_POINT), + ppoints, len, FALSE, NULL); } - dprintf("IOCTL_MOUNTMGR_QUERY_POINTS return %x - looking for '%wZ'\n", Status, - devpath); + dprintf("IOCTL_MOUNTMGR_QUERY_POINTS return %x - looking for '%wZ'\n", + Status, devpath); if (Status == STATUS_SUCCESS) { for (int Index = 0; - Index < ppoints->NumberOfMountPoints; - Index++) { - PMOUNTMGR_MOUNT_POINT ipoint = ppoints->MountPoints + Index; - PWCHAR DeviceName = (PWCHAR)((PUCHAR)ppoints + ipoint->DeviceNameOffset); - PWCHAR SymbolicLinkName = (PWCHAR)((PUCHAR)ppoints + ipoint->SymbolicLinkNameOffset); - - // Why is this hackery needed, we should be able to lookup the drive letter from volume name + Index < ppoints->NumberOfMountPoints; + Index++) { + PMOUNTMGR_MOUNT_POINT ipoint = + ppoints->MountPoints + Index; + PWCHAR DeviceName = + (PWCHAR)((PUCHAR)ppoints + + ipoint->DeviceNameOffset); + PWCHAR SymbolicLinkName = + (PWCHAR)((PUCHAR)ppoints + + ipoint->SymbolicLinkNameOffset); + + // Why is this hackery needed, we should be able + // to lookup the drive letter from volume name dprintf(" point %d: '%.*S' '%.*S'\n", Index, - ipoint->DeviceNameLength / sizeof(WCHAR), DeviceName, - ipoint->SymbolicLinkNameLength / sizeof(WCHAR), SymbolicLinkName); - if (wcsncmp(DeviceName, devpath->Buffer, ipoint->DeviceNameLength / sizeof(WCHAR)) == 0) { + ipoint->DeviceNameLength / sizeof (WCHAR), + DeviceName, + ipoint->SymbolicLinkNameLength / sizeof (WCHAR), + SymbolicLinkName); + if (wcsncmp(DeviceName, devpath->Buffer, + ipoint->DeviceNameLength / sizeof (WCHAR)) == 0) { ULONG length = 0; - RtlUnicodeToUTF8N(savename, MAXPATHLEN, &length, SymbolicLinkName, ipoint->SymbolicLinkNameLength); + RtlUnicodeToUTF8N(savename, MAXPATHLEN, &length, + SymbolicLinkName, + ipoint->SymbolicLinkNameLength); savename[length] = 0; - if (only_driveletter && !MOUNTMGR_IS_DRIVE_LETTER_A(savename)) + if (only_driveletter && + !MOUNTMGR_IS_DRIVE_LETTER_A(savename)) savename[0] = 0; - else if (only_volume_name && !MOUNTMGR_IS_VOLUME_NAME_A(savename)) + else if (only_volume_name && + !MOUNTMGR_IS_VOLUME_NAME_A(savename)) savename[0] = 0; } } } if (ppoints != NULL) kmem_free(ppoints, len); - return STATUS_SUCCESS; + return (STATUS_SUCCESS); } /* -* Returns the last valid mountpoint of the device according to MOUNTMGR_IS_DRIVE_LETTER() -*/ -NTSTATUS mountmgr_get_drive_letter( PDEVICE_OBJECT mountmgr, - PUNICODE_STRING devpath, char *savename) + * Returns the last valid mountpoint of the device according + * to MOUNTMGR_IS_DRIVE_LETTER() + */ +NTSTATUS +mountmgr_get_drive_letter(DEVICE_OBJECT *mountmgr, + PUNICODE_STRING devpath, char *savename) { - return mountmgr_get_mountpoint(mountmgr, devpath, savename, TRUE, FALSE); + return (mountmgr_get_mountpoint(mountmgr, devpath, savename, + TRUE, FALSE)); } /* -* Returns the last valid mountpoint of the device according to MOUNTMGR_IS_VOLUME_NAME() -*/ -NTSTATUS mountmgr_get_volume_name_mountpoint(PDEVICE_OBJECT mountmgr, - PUNICODE_STRING devpath, char *savename) + * Returns the last valid mountpoint of the device according + * to MOUNTMGR_IS_VOLUME_NAME() + */ +NTSTATUS +mountmgr_get_volume_name_mountpoint(PDEVICE_OBJECT mountmgr, + PUNICODE_STRING devpath, char *savename) { - return mountmgr_get_mountpoint(mountmgr, devpath, savename, FALSE, TRUE); + return (mountmgr_get_mountpoint(mountmgr, devpath, savename, + FALSE, TRUE)); } NTSTATUS - SendIoctlToMountManager(__in ULONG IoControlCode, __in PVOID InputBuffer, - __in ULONG Length, __out PVOID OutputBuffer, - __in ULONG OutputLength) +SendIoctlToMountManager(__in ULONG IoControlCode, __in PVOID InputBuffer, + __in ULONG Length, __out PVOID OutputBuffer, + __in ULONG OutputLength) { NTSTATUS status; UNICODE_STRING mountManagerName; @@ -223,29 +250,31 @@ NTSTATUS RtlInitUnicodeString(&mountManagerName, MOUNTMGR_DEVICE_NAME); - status = IoGetDeviceObjectPointer(&mountManagerName, FILE_READ_ATTRIBUTES, - &mountFileObject, &mountDeviceObject); + status = IoGetDeviceObjectPointer(&mountManagerName, + FILE_READ_ATTRIBUTES, + &mountFileObject, &mountDeviceObject); if (!NT_SUCCESS(status)) { dprintf(" IoGetDeviceObjectPointer failed: 0x%x\n", status); - return status; + return (status); } KeInitializeEvent(&driverEvent, NotificationEvent, FALSE); irp = IoBuildDeviceIoControlRequest(IoControlCode, mountDeviceObject, - InputBuffer, Length, OutputBuffer, - OutputLength, FALSE, &driverEvent, &iosb); + InputBuffer, Length, OutputBuffer, + OutputLength, FALSE, &driverEvent, &iosb); if (irp == NULL) { dprintf(" IoBuildDeviceIoControlRequest failed\n"); - return STATUS_INSUFFICIENT_RESOURCES; + return (STATUS_INSUFFICIENT_RESOURCES); } status = IoCallDriver(mountDeviceObject, irp); if (status == STATUS_PENDING) { - KeWaitForSingleObject(&driverEvent, Executive, KernelMode, FALSE, NULL); + KeWaitForSingleObject(&driverEvent, Executive, KernelMode, + FALSE, NULL); } status = iosb.Status; @@ -254,28 +283,27 @@ NTSTATUS if (NT_SUCCESS(status)) { dprintf(" IoCallDriver success\n"); - } - else { + } else { dprintf(" IoCallDriver failed: 0x%x\n", status); } - return status; + return (status); } -NTSTATUS MountMgrChangeNotify(void) +NTSTATUS +MountMgrChangeNotify(void) { - NTSTATUS status; - ULONG length; + NTSTATUS status; + ULONG length; MOUNTMGR_CHANGE_NOTIFY_INFO chinfo_in; MOUNTMGR_CHANGE_NOTIFY_INFO chinfo_out; - dprintf("=> MountMgrChangeNotify\n"); - length = sizeof(MOUNTMGR_CHANGE_NOTIFY_INFO); + length = sizeof (MOUNTMGR_CHANGE_NOTIFY_INFO); - status = SendIoctlToMountManager( - IOCTL_MOUNTMGR_CHANGE_NOTIFY, &chinfo_in, length, &chinfo_out, length); + status = SendIoctlToMountManager(IOCTL_MOUNTMGR_CHANGE_NOTIFY, + &chinfo_in, length, &chinfo_out, length); if (NT_SUCCESS(status)) dprintf(" IoCallDriver success\n"); @@ -290,27 +318,29 @@ NTSTATUS MountMgrChangeNotify(void) NTSTATUS SendVolumeArrivalNotification(PUNICODE_STRING DeviceName) { - NTSTATUS status; + NTSTATUS status; PMOUNTMGR_TARGET_NAME targetName; - ULONG length; + ULONG length; dprintf("=> SendVolumeArrivalNotification: '%wZ'\n", DeviceName); - length = sizeof(MOUNTMGR_TARGET_NAME) + DeviceName->Length - 1; + length = sizeof (MOUNTMGR_TARGET_NAME) + DeviceName->Length - 1; targetName = ExAllocatePool(PagedPool, length); if (targetName == NULL) { dprintf(" can't allocate MOUNTMGR_TARGET_NAME\n"); - return STATUS_INSUFFICIENT_RESOURCES; + return (STATUS_INSUFFICIENT_RESOURCES); } RtlZeroMemory(targetName, length); targetName->DeviceNameLength = DeviceName->Length; - RtlCopyMemory(targetName->DeviceName, DeviceName->Buffer, DeviceName->Length); + RtlCopyMemory(targetName->DeviceName, DeviceName->Buffer, + DeviceName->Length); status = SendIoctlToMountManager( - IOCTL_MOUNTMGR_VOLUME_ARRIVAL_NOTIFICATION, targetName, length, NULL, 0); + IOCTL_MOUNTMGR_VOLUME_ARRIVAL_NOTIFICATION, + targetName, length, NULL, 0); if (NT_SUCCESS(status)) { dprintf(" IoCallDriver success\n"); @@ -322,51 +352,53 @@ SendVolumeArrivalNotification(PUNICODE_STRING DeviceName) dprintf("<= SendVolumeArrivalNotification\n"); - return status; + return (status); } NTSTATUS RegisterDeviceInterface(__in PDRIVER_OBJECT DriverObject, - __in PDEVICE_OBJECT DeviceObject, __in mount_t *Dcb) + __in PDEVICE_OBJECT DeviceObject, __in mount_t *Dcb) { PDEVICE_OBJECT pnpDeviceObject = NULL; NTSTATUS status; status = IoReportDetectedDevice( - DriverObject, - InterfaceTypeUndefined, - 0xFFFFFFFF, // 0 - 0xFFFFFFFF, // 0 - NULL, - NULL, - FALSE, - &pnpDeviceObject); + DriverObject, + InterfaceTypeUndefined, + 0xFFFFFFFF, // 0 + 0xFFFFFFFF, // 0 + NULL, + NULL, + FALSE, + &pnpDeviceObject); if (NT_SUCCESS(status)) { dprintf(" IoReportDetectedDevice success\n"); } else { dprintf(" IoReportDetectedDevice failed: 0x%x\n", status); - return status; + return (status); } - if (IoAttachDeviceToDeviceStack(pnpDeviceObject, DeviceObject) != NULL) { + if (IoAttachDeviceToDeviceStack(pnpDeviceObject, + DeviceObject) != NULL) { dprintf(" IoAttachDeviceToDeviceStack success\n"); } else { dprintf(" IoAttachDeviceToDeviceStack failed\n"); } status = IoRegisterDeviceInterface( - pnpDeviceObject, - &GUID_DEVINTERFACE_DISK, - NULL, - &Dcb->device_name); // device_name checks out + pnpDeviceObject, + &GUID_DEVINTERFACE_DISK, + NULL, + &Dcb->device_name); // device_name checks out if (NT_SUCCESS(status)) { - dprintf(" IoRegisterDeviceInterface success: %wZ\n", &Dcb->device_name); + dprintf(" IoRegisterDeviceInterface success: %wZ\n", + &Dcb->device_name); } else { dprintf(" IoRegisterDeviceInterface failed: 0x%x\n", status); - return status; + return (status); } status = IoSetDeviceInterfaceState(&Dcb->device_name, TRUE); @@ -375,20 +407,21 @@ RegisterDeviceInterface(__in PDRIVER_OBJECT DriverObject, dprintf(" IoSetDeviceInterfaceState success\n"); } else { dprintf(" IoSetDeviceInterfaceState failed: 0x%x\n", status); - return status; + return (status); } status = IoRegisterDeviceInterface( - pnpDeviceObject, - &MOUNTDEV_MOUNTED_DEVICE_GUID, - NULL, - &Dcb->fs_name); + pnpDeviceObject, + &MOUNTDEV_MOUNTED_DEVICE_GUID, + NULL, + &Dcb->fs_name); if (NT_SUCCESS(status)) { - dprintf(" IoRegisterDeviceInterface success: %wZ\n", &Dcb->fs_name); + dprintf(" IoRegisterDeviceInterface success: %wZ\n", + &Dcb->fs_name); } else { dprintf(" IoRegisterDeviceInterface failed: 0x%x\n", status); - return status; + return (status); } status = IoSetDeviceInterfaceState(&Dcb->fs_name, TRUE); @@ -397,15 +430,15 @@ RegisterDeviceInterface(__in PDRIVER_OBJECT DriverObject, dprintf(" IoSetDeviceInterfaceState success\n"); } else { dprintf(" IoSetDeviceInterfaceState failed: 0x%x\n", status); - return status; + return (status); } - return status; + return (status); } NTSTATUS SendVolumeCreatePoint(__in PUNICODE_STRING DeviceName, - __in PUNICODE_STRING MountPoint) + __in PUNICODE_STRING MountPoint) { NTSTATUS status; PMOUNTMGR_CREATE_POINT_INPUT point; @@ -413,32 +446,33 @@ SendVolumeCreatePoint(__in PUNICODE_STRING DeviceName, dprintf("=> SendVolumeCreatePoint\n"); - length = sizeof(MOUNTMGR_CREATE_POINT_INPUT) + MountPoint->Length + - DeviceName->Length; + length = sizeof (MOUNTMGR_CREATE_POINT_INPUT) + MountPoint->Length + + DeviceName->Length; point = ExAllocatePool(PagedPool, length); if (point == NULL) { dprintf(" can't allocate MOUNTMGR_CREATE_POINT_INPUT\n"); - return STATUS_INSUFFICIENT_RESOURCES; + return (STATUS_INSUFFICIENT_RESOURCES); } RtlZeroMemory(point, length); dprintf(" DeviceName: %wZ\n", DeviceName); - point->DeviceNameOffset = sizeof(MOUNTMGR_CREATE_POINT_INPUT); + point->DeviceNameOffset = sizeof (MOUNTMGR_CREATE_POINT_INPUT); point->DeviceNameLength = DeviceName->Length; - RtlCopyMemory((PCHAR)point + point->DeviceNameOffset, DeviceName->Buffer, - DeviceName->Length); + RtlCopyMemory((PCHAR)point + point->DeviceNameOffset, + DeviceName->Buffer, + DeviceName->Length); dprintf(" MountPoint: %wZ\n", MountPoint); point->SymbolicLinkNameOffset = - point->DeviceNameOffset + point->DeviceNameLength; + point->DeviceNameOffset + point->DeviceNameLength; point->SymbolicLinkNameLength = MountPoint->Length; RtlCopyMemory((PCHAR)point + point->SymbolicLinkNameOffset, - MountPoint->Buffer, MountPoint->Length); - + MountPoint->Buffer, MountPoint->Length); + status = SendIoctlToMountManager(IOCTL_MOUNTMGR_CREATE_POINT, point, - length, NULL, 0); + length, NULL, 0); if (NT_SUCCESS(status)) { dprintf(" IoCallDriver success\n"); @@ -450,12 +484,12 @@ SendVolumeCreatePoint(__in PUNICODE_STRING DeviceName, dprintf("<= SendVolumeCreatePoint\n"); - return status; + return (status); } NTSTATUS SendVolumeDeletePoints(__in PUNICODE_STRING MountPoint, - __in PUNICODE_STRING DeviceName) + __in PUNICODE_STRING DeviceName) { NTSTATUS status; PMOUNTMGR_MOUNT_POINT point; @@ -467,10 +501,10 @@ SendVolumeDeletePoints(__in PUNICODE_STRING MountPoint, if (_wcsnicmp(L"\\DosDevices\\", MountPoint->Buffer, 12)) { dprintf("Not a drive letter, skipping\n"); - return STATUS_SUCCESS; + return (STATUS_SUCCESS); } - length = sizeof(MOUNTMGR_MOUNT_POINT) + MountPoint->Length; + length = sizeof (MOUNTMGR_MOUNT_POINT) + MountPoint->Length; if (DeviceName != NULL) { length += DeviceName->Length; } @@ -478,43 +512,45 @@ SendVolumeDeletePoints(__in PUNICODE_STRING MountPoint, if (point == NULL) { dprintf(" can't allocate MOUNTMGR_CREATE_POINT_INPUT\n"); - return STATUS_INSUFFICIENT_RESOURCES; + return (STATUS_INSUFFICIENT_RESOURCES); } - olength = sizeof(MOUNTMGR_MOUNT_POINTS) + 1024; + olength = sizeof (MOUNTMGR_MOUNT_POINTS) + 1024; deletedPoints = kmem_alloc(olength, KM_SLEEP); if (deletedPoints == NULL) { dprintf(" can't allocate PMOUNTMGR_MOUNT_POINTS\n"); kmem_free(point, length); - return STATUS_INSUFFICIENT_RESOURCES; + return (STATUS_INSUFFICIENT_RESOURCES); } - RtlZeroMemory(point, length); //kmem_zalloc + RtlZeroMemory(point, length); // kmem_zalloc RtlZeroMemory(deletedPoints, olength); dprintf(" MountPoint: %wZ\n", MountPoint); - point->SymbolicLinkNameOffset = sizeof(MOUNTMGR_MOUNT_POINT); + point->SymbolicLinkNameOffset = sizeof (MOUNTMGR_MOUNT_POINT); point->SymbolicLinkNameLength = MountPoint->Length; RtlCopyMemory((PCHAR)point + point->SymbolicLinkNameOffset, - MountPoint->Buffer, MountPoint->Length); + MountPoint->Buffer, MountPoint->Length); if (DeviceName != NULL) { dprintf(" DeviceName: %wZ\n", DeviceName); point->DeviceNameOffset = - point->SymbolicLinkNameOffset + point->SymbolicLinkNameLength; + point->SymbolicLinkNameOffset + + point->SymbolicLinkNameLength; point->DeviceNameLength = DeviceName->Length; - RtlCopyMemory((PCHAR)point + point->DeviceNameOffset, DeviceName->Buffer, - DeviceName->Length); + RtlCopyMemory((PCHAR)point + point->DeviceNameOffset, + DeviceName->Buffer, DeviceName->Length); } - // Only symbolic link can be deleted with IOCTL_MOUNTMGR_DELETE_POINTS. - // If any other entry is specified, the mount manager will ignore subsequent - // IOCTL_MOUNTMGR_VOLUME_ARRIVAL_NOTIFICATION for the same volume ID. + // Only symbolic link can be deleted with IOCTL_MOUNTMGR_DELETE_POINTS. + // If any other entry is specified, the mount manager will ignore + // subsequent IOCTL_MOUNTMGR_VOLUME_ARRIVAL_NOTIFICATION for the + // same volume ID. status = SendIoctlToMountManager(IOCTL_MOUNTMGR_DELETE_POINTS, point, - length, deletedPoints, olength); + length, deletedPoints, olength); if (NT_SUCCESS(status)) { dprintf(" IoCallDriver success, %d mount points deleted.\n", - deletedPoints->NumberOfMountPoints); + deletedPoints->NumberOfMountPoints); } else { dprintf(" IoCallDriver failed: 0x%x\n", status); } @@ -524,10 +560,11 @@ SendVolumeDeletePoints(__in PUNICODE_STRING MountPoint, dprintf("<= SendVolumeDeletePoints\n"); - return status; + return (status); } -void zfs_release_mount(mount_t *zmo) +void +zfs_release_mount(mount_t *zmo) { FreeUnicodeString(&zmo->symlink_name); FreeUnicodeString(&zmo->device_name); @@ -542,7 +579,8 @@ void zfs_release_mount(mount_t *zmo) } } -int zfs_windows_mount(zfs_cmd_t *zc) +int +zfs_windows_mount(zfs_cmd_t *zc) { dprintf("%s: '%s' '%s'\n", __func__, zc->zc_name, zc->zc_value); NTSTATUS status; @@ -561,63 +599,67 @@ int zfs_windows_mount(zfs_cmd_t *zc) */ int mplen = strlen(zc->zc_value); if ((mplen < 6) || - strncmp("\\??\\", zc->zc_value, 4)) { - dprintf("%s: mountpoint '%s' does not start with \\??\\x:", __func__, zc->zc_value); - return EINVAL; + strncmp("\\??\\", zc->zc_value, 4)) { + dprintf("%s: mountpoint '%s' does not start with \\??\\x:", + __func__, zc->zc_value); + return (EINVAL); } zfs_vfs_uuid_gen(zc->zc_name, uuid); zfs_vfs_uuid_unparse(uuid, uuid_a); char buf[PATH_MAX]; - //snprintf(buf, sizeof(buf), "\\Device\\ZFS{%s}", uuid_a); - WCHAR diskDeviceNameBuf[MAXIMUM_FILENAME_LENGTH]; // L"\\Device\\Volume" - WCHAR fsDeviceNameBuf[MAXIMUM_FILENAME_LENGTH]; // L"\\Device\\ZFS" - WCHAR symbolicLinkNameBuf[MAXIMUM_FILENAME_LENGTH]; // L"\\DosDevices\\Global\\Volume" - UNICODE_STRING diskDeviceName; - UNICODE_STRING fsDeviceName; - UNICODE_STRING symbolicLinkTarget; + // snprintf(buf, sizeof (buf), "\\Device\\ZFS{%s}", uuid_a); + WCHAR diskDeviceNameBuf[MAXIMUM_FILENAME_LENGTH]; // L"\\Device\\Volume" + WCHAR fsDeviceNameBuf[MAXIMUM_FILENAME_LENGTH]; // L"\\Device\\ZFS" + // L"\\DosDevices\\Global\\Volume" + WCHAR symbolicLinkNameBuf[MAXIMUM_FILENAME_LENGTH]; + UNICODE_STRING diskDeviceName; + UNICODE_STRING fsDeviceName; + UNICODE_STRING symbolicLinkTarget; ANSI_STRING pants; - ULONG deviceCharacteristics; + ULONG deviceCharacteristics; deviceCharacteristics = 0; // FILE_DEVICE_IS_MOUNTED; /* Allow $recycle.bin - don't set removable. */ if (!zfs_disable_removablemedia) deviceCharacteristics |= FILE_REMOVABLE_MEDIA; - snprintf(buf, sizeof(buf), "\\Device\\Volume{%s}", uuid_a); - // snprintf(buf, sizeof(buf), "\\Device\\ZFS_%s", zc->zc_name); + snprintf(buf, sizeof (buf), "\\Device\\Volume{%s}", uuid_a); + // snprintf(buf, sizeof (buf), "\\Device\\ZFS_%s", zc->zc_name); pants.Buffer = buf; pants.Length = strlen(buf); pants.MaximumLength = PATH_MAX; status = RtlAnsiStringToUnicodeString(&diskDeviceName, &pants, TRUE); dprintf("%s: new devstring '%wZ'\n", __func__, &diskDeviceName); - status = IoCreateDeviceSecure(WIN_DriverObject, // DriverObject - sizeof(mount_t), // DeviceExtensionSize - &diskDeviceName, - FILE_DEVICE_DISK,// DeviceType - deviceCharacteristics, // DeviceCharacteristics - FALSE, // Not Exclusive - &SDDL_DEVOBJ_SYS_ALL_ADM_RWX_WORLD_RW_RES_R, // Default SDDL String - NULL, // Device Class GUID - &diskDeviceObject); // DeviceObject + status = IoCreateDeviceSecure(WIN_DriverObject, + sizeof (mount_t), + &diskDeviceName, + FILE_DEVICE_DISK, + deviceCharacteristics, + FALSE, + &SDDL_DEVOBJ_SYS_ALL_ADM_RWX_WORLD_RW_RES_R, + NULL, + &diskDeviceObject); if (status != STATUS_SUCCESS) { dprintf("IoCreateDeviceSecure returned %08x\n", status); - return status; + return (status); } diskDeviceObject->Flags |= DO_BUS_ENUMERATED_DEVICE; mount_t *zmo_dcb = diskDeviceObject->DeviceExtension; zmo_dcb->type = MOUNT_TYPE_DCB; - zmo_dcb->size = sizeof(mount_t); + zmo_dcb->size = sizeof (mount_t); vfs_setfsprivate(zmo_dcb, NULL); - dprintf("%s: created dcb at %p asked for size %d\n", __func__, zmo_dcb, sizeof(mount_t)); + dprintf("%s: created dcb at %p asked for size %d\n", + __func__, zmo_dcb, sizeof (mount_t)); AsciiStringToUnicodeString(uuid_a, &zmo_dcb->uuid); - // Should we keep the name with slashes like "BOOM/lower" or just "lower". - // Turns out the name in Explorer only works for 4 chars or lower. Why? + // Should we keep the name with slashes like "BOOM/lower" or + // just "lower". Turns out the name in Explorer only + // works for 4 chars or lower. Why? #if 0 char *r; if ((r = strrchr(zc->zc_name, '/')) != NULL) @@ -629,19 +671,21 @@ int zfs_windows_mount(zfs_cmd_t *zc) AsciiStringToUnicodeString(zc->zc_name, &zmo_dcb->name); #endif AsciiStringToUnicodeString(buf, &zmo_dcb->device_name); - //strlcpy(zc->zc_value, buf, sizeof(zc->zc_value)); // Copy to userland + // strlcpy(zc->zc_value, buf, sizeof (zc->zc_value)); zmo_dcb->deviceObject = diskDeviceObject; - dprintf("New device %p has extension %p\n", diskDeviceObject, zmo_dcb); + dprintf("New device %p has extension %p\n", + diskDeviceObject, zmo_dcb); - snprintf(buf, sizeof(buf), "\\DosDevices\\Global\\Volume{%s}", uuid_a); + snprintf(buf, sizeof (buf), "\\DosDevices\\Global\\Volume{%s}", uuid_a); pants.Buffer = buf; pants.Length = strlen(buf); pants.MaximumLength = PATH_MAX; - status = RtlAnsiStringToUnicodeString(&symbolicLinkTarget, &pants, TRUE); + status = RtlAnsiStringToUnicodeString(&symbolicLinkTarget, &pants, + TRUE); dprintf("%s: new symlink '%wZ'\n", __func__, &symbolicLinkTarget); AsciiStringToUnicodeString(buf, &zmo_dcb->symlink_name); - snprintf(buf, sizeof(buf), "\\Device\\ZFS{%s}", uuid_a); + snprintf(buf, sizeof (buf), "\\Device\\ZFS{%s}", uuid_a); pants.Buffer = buf; pants.Length = strlen(buf); pants.MaximumLength = PATH_MAX; @@ -657,22 +701,22 @@ int zfs_windows_mount(zfs_cmd_t *zc) if (!NT_SUCCESS(status)) { IoDeleteDevice(diskDeviceObject); dprintf(" IoCreateSymbolicLink returned 0x%x\n", status); - return status; + return (status); } - //InsertMountEntry(WIN_DriverObject, NULL, FALSE); + // InsertMountEntry(WIN_DriverObject, NULL, FALSE); // Call ZFS and have it setup a mount "zfsvfs" // we don7t have the vcb yet, but we want to find out mount // problems early. struct zfs_mount_args mnt_args; - mnt_args.struct_size = sizeof(struct zfs_mount_args); + mnt_args.struct_size = sizeof (struct zfs_mount_args); mnt_args.optlen = 0; mnt_args.mflag = 0; // Set flags mnt_args.fspec = zc->zc_name; - // Mount will temporarily be pointing to "dcb" until the + // Mount will temporarily be pointing to "dcb" until the // zfs_vnop_mount() below corrects it to "vcb". status = zfs_vfs_mount(zmo_dcb, NULL, (user_addr_t)&mnt_args, NULL); dprintf("%s: zfs_vfs_mount() returns %d\n", __func__, status); @@ -680,16 +724,16 @@ int zfs_windows_mount(zfs_cmd_t *zc) if (status) { zfs_release_mount(zmo_dcb); IoDeleteDevice(diskDeviceObject); - return status; + return (status); } // Check if we are to mount with driveletter, or path - // We already check that path is "\\??\\" above, and + // We already check that path is "\\??\\" above, and // at least 6 chars. Seventh char can be zero, or "/" // then zero, for drive only mount. if ((zc->zc_value[6] == 0) || - ((zc->zc_value[6] == '/') && - (zc->zc_value[7] == 0))) { + ((zc->zc_value[6] == '/') && + (zc->zc_value[7] == 0))) { zmo_dcb->justDriveLetter = B_TRUE; } else { zmo_dcb->justDriveLetter = B_FALSE; @@ -698,10 +742,12 @@ int zfs_windows_mount(zfs_cmd_t *zc) // Remember mountpoint path AsciiStringToUnicodeString(zc->zc_value, &zmo_dcb->mountpoint); - dprintf("%s: driveletter %d '%wZ'\n", __func__, zmo_dcb->justDriveLetter, &zmo_dcb->mountpoint); + dprintf("%s: driveletter %d '%wZ'\n", + __func__, zmo_dcb->justDriveLetter, &zmo_dcb->mountpoint); // Return volume name to userland - snprintf(zc->zc_value, sizeof(zc->zc_value), "\\DosDevices\\Global\\Volume{%s}", uuid_a); + snprintf(zc->zc_value, sizeof (zc->zc_value), + "\\DosDevices\\Global\\Volume{%s}", uuid_a); // Mark devices as initialized diskDeviceObject->Flags &= ~DO_DEVICE_INITIALIZING; @@ -711,52 +757,26 @@ int zfs_windows_mount(zfs_cmd_t *zc) IoVerifyVolume(diskDeviceObject, FALSE); status = STATUS_SUCCESS; - return status; + return (status); } -VOID InitVpb(__in PVPB Vpb, __in PDEVICE_OBJECT VolumeDevice) +void +InitVpb(__in PVPB Vpb, __in PDEVICE_OBJECT VolumeDevice) { if (Vpb != NULL) { Vpb->DeviceObject = VolumeDevice; - Vpb->VolumeLabelLength = (USHORT)wcslen(VOLUME_LABEL) * sizeof(WCHAR); + Vpb->VolumeLabelLength = + (USHORT)wcslen(VOLUME_LABEL) * sizeof (WCHAR); RtlStringCchCopyW(Vpb->VolumeLabel, - sizeof(Vpb->VolumeLabel) / sizeof(WCHAR), VOLUME_LABEL); + sizeof (Vpb->VolumeLabel) / sizeof (WCHAR), VOLUME_LABEL); Vpb->SerialNumber = 0x19831116; Vpb->Flags |= VPB_MOUNTED; } } - -/* - [ffff9284a0e84080 zpool.exe] -1de4.000b48 ffff9284a56db080 fffd57fc Blocked nt!KiSwapContext+0x76 - nt!KiSwapThread+0x3f2 - nt!KiCommitThreadWait+0x144 - nt!KeWaitForSingleObject+0x255 - nt!IopWaitForLockAlertable+0x48 - nt!IopMountVolume+0x106 - nt!IopCheckVpbMounted+0x1b3 - nt!IopParseDevice+0x31f - nt!ObpLookupObjectName+0x78f - nt!ObOpenObjectByNameEx+0x201 - nt!NtDeleteFile+0x114 - nt!KiSystemServiceCopyEnd+0x25 - nt!KiServiceLinkage - ZFSin!CreateReparsePoint+0x4c - ZFSin!zfs_vnop_mount_cont+0x3f8 - ZFSin!zfs_vnop_mount+0x424 - ZFSin!fsDispatcher+0xa15 - ZFSin!dispatcher+0x178 - nt!IofCallDriver+0x59 - +0xfffff804357c076e - +0xffff9284a03e9010 - +0xffff928400000000 - -* -* Justification: The LPCWSTR could be non-NULL terminated when passed and causes the buffer to be overran. -*/ -NTSTATUS CreateReparsePoint(POBJECT_ATTRIBUTES poa, PCUNICODE_STRING SubstituteName, - PCUNICODE_STRING PrintName) +NTSTATUS +CreateReparsePoint(POBJECT_ATTRIBUTES poa, PCUNICODE_STRING SubstituteName, + PCUNICODE_STRING PrintName) { HANDLE hFile; IO_STATUS_BLOCK iosb; @@ -764,42 +784,57 @@ NTSTATUS CreateReparsePoint(POBJECT_ATTRIBUTES poa, PCUNICODE_STRING SubstituteN dprintf("%s: \n", __func__); - status = ZwDeleteFile(poa); // this is stalled forever waiting for event of deletion - possibly ZFS doesnt send event? - if (status != STATUS_SUCCESS) dprintf("pre-rmdir failed 0x%x\n", status); + // this is stalled forever waiting for event of deletion - + // possibly ZFS doesnt send event? + status = ZwDeleteFile(poa); + if (status != STATUS_SUCCESS) + dprintf("pre-rmdir failed 0x%x\n", status); status = ZwCreateFile(&hFile, FILE_ALL_ACCESS, poa, &iosb, 0, 0, 0, - FILE_CREATE, FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, 0, 0); + FILE_CREATE, FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, + 0, 0); if (0 > status) - return status; + return (status); dprintf("%s: create ok\n", __func__); - USHORT cb = 2 * sizeof(WCHAR) + FIELD_OFFSET(REPARSE_DATA_BUFFER, MountPointReparseBuffer.PathBuffer) + SubstituteName->Length + PrintName->Length; + + USHORT cb = 2 * sizeof (WCHAR) + + FIELD_OFFSET(REPARSE_DATA_BUFFER, + MountPointReparseBuffer.PathBuffer) + + SubstituteName->Length + PrintName->Length; PREPARSE_DATA_BUFFER prdb = (PREPARSE_DATA_BUFFER)alloca(cb); RtlZeroMemory(prdb, cb); prdb->ReparseTag = IO_REPARSE_TAG_MOUNT_POINT; prdb->ReparseDataLength = cb - REPARSE_DATA_BUFFER_HEADER_SIZE; - prdb->MountPointReparseBuffer.SubstituteNameLength = SubstituteName->Length; + prdb->MountPointReparseBuffer.SubstituteNameLength = + SubstituteName->Length; prdb->MountPointReparseBuffer.PrintNameLength = PrintName->Length; - prdb->MountPointReparseBuffer.PrintNameOffset = SubstituteName->Length + sizeof(WCHAR); - memcpy(prdb->MountPointReparseBuffer.PathBuffer, SubstituteName->Buffer, SubstituteName->Length); - memcpy(RtlOffsetToPointer(prdb->MountPointReparseBuffer.PathBuffer, SubstituteName->Length + sizeof(WCHAR)), PrintName->Buffer, PrintName->Length); - status = ZwFsControlFile(hFile, 0, 0, 0, &iosb, FSCTL_SET_REPARSE_POINT, prdb, cb, 0, 0); + prdb->MountPointReparseBuffer.PrintNameOffset = + SubstituteName->Length + sizeof (WCHAR); + memcpy(prdb->MountPointReparseBuffer.PathBuffer, + SubstituteName->Buffer, SubstituteName->Length); + memcpy(RtlOffsetToPointer(prdb->MountPointReparseBuffer.PathBuffer, + SubstituteName->Length + sizeof (WCHAR)), + PrintName->Buffer, PrintName->Length); + status = ZwFsControlFile(hFile, 0, 0, 0, &iosb, + FSCTL_SET_REPARSE_POINT, prdb, cb, 0, 0); dprintf("%s: ControlFile %d / 0x%x\n", __func__, status, status); if (0 > status) { static FILE_DISPOSITION_INFORMATION fdi = { TRUE }; - ZwSetInformationFile(hFile, &iosb, &fdi, sizeof fdi, FileDispositionInformation); + ZwSetInformationFile(hFile, &iosb, &fdi, + sizeof (fdi), FileDispositionInformation); } ZwClose(hFile); - return status; + return (status); } - /* * go through all mointpoints (IOCTL_MOUNTMGR_QUERY_POINTS) * and check if our driveletter is in the list * return 1 if yes, otherwise 0 */ -NTSTATUS mountmgr_is_driveletter_assigned(PDEVICE_OBJECT mountmgr, - wchar_t driveletter, BOOLEAN *ret) +NTSTATUS +mountmgr_is_driveletter_assigned(PDEVICE_OBJECT mountmgr, + wchar_t driveletter, BOOLEAN *ret) { MOUNTMGR_MOUNT_POINT point = { 0 }; MOUNTMGR_MOUNT_POINTS points; @@ -810,41 +845,52 @@ NTSTATUS mountmgr_is_driveletter_assigned(PDEVICE_OBJECT mountmgr, ppoints = &points; Status = dev_ioctl(mountmgr, IOCTL_MOUNTMGR_QUERY_POINTS, &point, - sizeof(MOUNTMGR_MOUNT_POINT), ppoints, - sizeof(MOUNTMGR_MOUNT_POINTS), FALSE, NULL); + sizeof (MOUNTMGR_MOUNT_POINT), ppoints, + sizeof (MOUNTMGR_MOUNT_POINTS), FALSE, NULL); if (Status == STATUS_BUFFER_OVERFLOW) { len = points.Size; ppoints = kmem_alloc(len, KM_SLEEP); Status = dev_ioctl(mountmgr, IOCTL_MOUNTMGR_QUERY_POINTS, - &point, sizeof(MOUNTMGR_MOUNT_POINT), ppoints, - len, FALSE, NULL); + &point, sizeof (MOUNTMGR_MOUNT_POINT), ppoints, + len, FALSE, NULL); } - dprintf("IOCTL_MOUNTMGR_QUERY_POINTS return %x - looking for driveletter '%c'\n", - Status, driveletter); + dprintf("IOCTL_MOUNTMGR_QUERY_POINTS return %x - " + "looking for driveletter '%c'\n", + Status, driveletter); if (Status == STATUS_SUCCESS) { char mpt_name[PATH_MAX] = { 0 }; for (int Index = 0; - Index < ppoints->NumberOfMountPoints; - Index++) { - PMOUNTMGR_MOUNT_POINT ipoint = ppoints->MountPoints + Index; - PWCHAR DeviceName = (PWCHAR)((PUCHAR)ppoints + ipoint->DeviceNameOffset); - PWCHAR SymbolicLinkName = (PWCHAR)((PUCHAR)ppoints + ipoint->SymbolicLinkNameOffset); + Index < ppoints->NumberOfMountPoints; + Index++) { + PMOUNTMGR_MOUNT_POINT ipoint = + ppoints->MountPoints + Index; + PWCHAR DeviceName = + (PWCHAR)((PUCHAR)ppoints + + ipoint->DeviceNameOffset); + PWCHAR SymbolicLinkName = + (PWCHAR)((PUCHAR)ppoints + + ipoint->SymbolicLinkNameOffset); dprintf(" point %d: '%.*S' '%.*S'\n", Index, - ipoint->DeviceNameLength / sizeof(WCHAR), DeviceName, - ipoint->SymbolicLinkNameLength / sizeof(WCHAR), SymbolicLinkName); + ipoint->DeviceNameLength / sizeof (WCHAR), + DeviceName, + ipoint->SymbolicLinkNameLength / + sizeof (WCHAR), + SymbolicLinkName); ULONG length = 0; - RtlUnicodeToUTF8N(mpt_name, MAXPATHLEN, &length, SymbolicLinkName, - ipoint->SymbolicLinkNameLength); + RtlUnicodeToUTF8N(mpt_name, MAXPATHLEN, &length, + SymbolicLinkName, + ipoint->SymbolicLinkNameLength); mpt_name[length] = 0; char c_driveletter; wctomb(&c_driveletter, driveletter); - if (MOUNTMGR_IS_DRIVE_LETTER_A(mpt_name) && mpt_name[12] == c_driveletter) { + if (MOUNTMGR_IS_DRIVE_LETTER_A(mpt_name) && + mpt_name[12] == c_driveletter) { *ret = 1; if (ppoints != NULL) kmem_free(ppoints, len); - return STATUS_SUCCESS; + return (STATUS_SUCCESS); } } } @@ -856,8 +902,9 @@ NTSTATUS mountmgr_is_driveletter_assigned(PDEVICE_OBJECT mountmgr, /* * assign driveletter with IOCTL_MOUNTMGR_CREATE_POINT */ -NTSTATUS mountmgr_assign_driveletter(PUNICODE_STRING device_name, - wchar_t driveletter) +NTSTATUS +mountmgr_assign_driveletter(PUNICODE_STRING device_name, + wchar_t driveletter) { DECLARE_UNICODE_STRING_SIZE(mpt, 16); RtlUnicodeStringPrintf(&mpt, L"\\DosDevices\\%c:", driveletter); @@ -866,10 +913,12 @@ NTSTATUS mountmgr_assign_driveletter(PUNICODE_STRING device_name, /* - * assign next free driveletter (D..Z) if mountmgr is offended and refuses to do it + * assign next free driveletter (D..Z) if mountmgr is offended + * and refuses to do it */ -NTSTATUS SetNextDriveletterManually(PDEVICE_OBJECT mountmgr, - PUNICODE_STRING device_name) +NTSTATUS +SetNextDriveletterManually(PDEVICE_OBJECT mountmgr, + PUNICODE_STRING device_name) { NTSTATUS status; for (wchar_t c = 'D'; c <= 'Z'; c++) { @@ -879,41 +928,47 @@ NTSTATUS SetNextDriveletterManually(PDEVICE_OBJECT mountmgr, status = mountmgr_assign_driveletter(device_name, c); if (status == STATUS_SUCCESS) { - // prove it - status = mountmgr_is_driveletter_assigned(mountmgr, c, &ret); + // prove it + status = + mountmgr_is_driveletter_assigned(mountmgr, + c, &ret); if (status == STATUS_SUCCESS) { if (ret == 1) - return STATUS_SUCCESS; + return (STATUS_SUCCESS); else - return STATUS_VOLUME_DISMOUNTED; + return + (STATUS_VOLUME_DISMOUNTED); } else { - return status; + return (status); } } } } - return status; + return (status); } -void generateGUID(char* pguid) +void +generateGUID(char *pguid) { char *uuid_format = "xxxxxxxx-xxxx-4xxx-Nxxx-xxxxxxxxxxxx"; char *szHex = "0123456789ABCDEF-"; int len = strlen(uuid_format); - for (int i = 0; i < len + 1; i++) - { + for (int i = 0; i < len + 1; i++) { int r = rand() % 16; char c = ' '; - switch (uuid_format[i]) - { - case 'x': { c = szHex[r]; } break; - case 'N': { c = szHex[r & 0x03 | 0x08]; } break; - case '-': { c = '-'; } break; - case '4': { c = '4'; } break; + switch (uuid_format[i]) { + case 'x': { c = szHex[r]; } + break; + case 'N': { c = szHex[r & 0x03 | 0x08]; } + break; + case '-': { c = '-'; } + break; + case '4': { c = '4'; } + break; } pguid[i] = (i < len) ? c : 0x00; @@ -921,7 +976,8 @@ void generateGUID(char* pguid) } -void generateVolumeNameMountpoint(wchar_t *vol_mpt) +void +generateVolumeNameMountpoint(wchar_t *vol_mpt) { char GUID[50]; wchar_t wc_guid[50]; @@ -930,7 +986,8 @@ void generateVolumeNameMountpoint(wchar_t *vol_mpt) int len = _snwprintf(vol_mpt, 50, L"\\??\\Volume{%s}", wc_guid); } -int zfs_vnop_mount(PDEVICE_OBJECT DiskDevice, PIRP Irp, PIO_STACK_LOCATION IrpSp) +int +zfs_vnop_mount(PDEVICE_OBJECT DiskDevice, PIRP Irp, PIO_STACK_LOCATION IrpSp) { PDRIVER_OBJECT DriverObject = DiskDevice->DriverObject; PDEVICE_OBJECT volDeviceObject; @@ -948,20 +1005,22 @@ int zfs_vnop_mount(PDEVICE_OBJECT DiskDevice, PIRP Irp, PIO_STACK_LOCATION IrpSp MOUNTDEV_NAME *mdn2; mdn2 = kmem_alloc(256, KM_SLEEP); - status = dev_ioctl(pdo, IOCTL_MOUNTDEV_QUERY_DEVICE_NAME, NULL, 0, mdn2, 256, TRUE, NULL); + status = dev_ioctl(pdo, IOCTL_MOUNTDEV_QUERY_DEVICE_NAME, + NULL, 0, mdn2, 256, TRUE, NULL); if (NT_SUCCESS(status)) { dprintf("%s: given deviceName '%.*S'\n", __func__, - mdn2->NameLength / sizeof(WCHAR), mdn2->Name); + mdn2->NameLength / sizeof (WCHAR), mdn2->Name); delay(hz << 1); } while (IoGetLowerDeviceObject(pdo)) { pdo = IoGetLowerDeviceObject(pdo); dprintf(".. going deeper %p\n", pdo); - status = dev_ioctl(pdo, IOCTL_MOUNTDEV_QUERY_DEVICE_NAME, NULL, 0, mdn2, 256, TRUE, NULL); + status = dev_ioctl(pdo, IOCTL_MOUNTDEV_QUERY_DEVICE_NAME, + NULL, 0, mdn2, 256, TRUE, NULL); if (NT_SUCCESS(status)) { dprintf("%s: given deviceName '%.*S'\n", __func__, - mdn2->NameLength / sizeof(WCHAR), mdn2->Name); + mdn2->NameLength / sizeof (WCHAR), mdn2->Name); delay(hz << 1); } } @@ -970,15 +1029,16 @@ int zfs_vnop_mount(PDEVICE_OBJECT DiskDevice, PIRP Irp, PIO_STACK_LOCATION IrpSp #else if (IrpSp->Parameters.MountVolume.DeviceObject == NULL) { dprintf("%s: MountVolume is NULL\n", __func__); - return STATUS_UNRECOGNIZED_VOLUME; + return (STATUS_UNRECOGNIZED_VOLUME); } - DeviceToMount = IoGetDeviceAttachmentBaseRef(IrpSp->Parameters.MountVolume.DeviceObject); + DeviceToMount = IoGetDeviceAttachmentBaseRef(IrpSp-> + Parameters.MountVolume.DeviceObject); dprintf("*** mount request for %p : minor\n", DeviceToMount); if (DeviceToMount == NULL) { dprintf("%s: DeviceToMount is NULL\n", __func__); - return STATUS_UNRECOGNIZED_VOLUME; + return (STATUS_UNRECOGNIZED_VOLUME); } // DeviceToMount must be released from here down @@ -998,33 +1058,34 @@ int zfs_vnop_mount(PDEVICE_OBJECT DiskDevice, PIRP Irp, PIO_STACK_LOCATION IrpSp status = STATUS_UNRECOGNIZED_VOLUME; goto out; } - + if ((dcb->type != MOUNT_TYPE_DCB) || - (dcb->size != sizeof(mount_t))) { - dprintf("%s: Not a ZFS dataset -- dcb %p ignoring: type 0x%x != 0x%x, size %d != %d\n", - __func__, dcb, - dcb->type, MOUNT_TYPE_DCB, dcb->size, sizeof(mount_t)); + (dcb->size != sizeof (mount_t))) { + dprintf("%s: Not a ZFS dataset -- dcb %p ignoring: " + "type 0x%x != 0x%x, size %d != %d\n", + __func__, dcb, + dcb->type, MOUNT_TYPE_DCB, dcb->size, sizeof (mount_t)); status = STATUS_UNRECOGNIZED_VOLUME; goto out; } // ZFS Dataset being mounted: - //dprintf("%s: mounting '%wZ'\n", __func__, dcb->name); + // dprintf("%s: mounting '%wZ'\n", __func__, dcb->name); // We created a DISK before, now we create a VOLUME - ULONG deviceCharacteristics; + ULONG deviceCharacteristics; deviceCharacteristics = 0; // FILE_DEVICE_IS_MOUNTED; /* Allow $recycle.bin - don't set removable. */ if (!zfs_disable_removablemedia) deviceCharacteristics |= FILE_REMOVABLE_MEDIA; - status = IoCreateDevice(DriverObject, // DriverObject - sizeof(mount_t), // DeviceExtensionSize - NULL, // DeviceName - FILE_DEVICE_DISK, // DeviceType FILE_DEVICE_DISK_FILE_SYSTEM - deviceCharacteristics, // DeviceCharacteristics - FALSE, // Not Exclusive - &volDeviceObject); // DeviceObject + status = IoCreateDevice(DriverObject, + sizeof (mount_t), + NULL, + FILE_DEVICE_DISK, + deviceCharacteristics, + FALSE, + &volDeviceObject); if (!NT_SUCCESS(status)) { dprintf("%s: IoCreateDevice failed: 0x%x\n", __func__, status); @@ -1033,7 +1094,7 @@ int zfs_vnop_mount(PDEVICE_OBJECT DiskDevice, PIRP Irp, PIO_STACK_LOCATION IrpSp mount_t *vcb = volDeviceObject->DeviceExtension; vcb->type = MOUNT_TYPE_VCB; - vcb->size = sizeof(mount_t); + vcb->size = sizeof (mount_t); volDeviceObject->Flags |= DO_BUS_ENUMERATED_DEVICE; @@ -1055,7 +1116,7 @@ int zfs_vnop_mount(PDEVICE_OBJECT DiskDevice, PIRP Irp, PIO_STACK_LOCATION IrpSp vcb->parent_device = dcb; // vcb is the ptr used in unmount, so set both devices here. - //vcb->diskDeviceObject = dcb->deviceObject; + // vcb->diskDeviceObject = dcb->deviceObject; vcb->deviceObject = volDeviceObject; RtlDuplicateUnicodeString(0, &dcb->fs_name, &vcb->fs_name); @@ -1071,7 +1132,7 @@ int zfs_vnop_mount(PDEVICE_OBJECT DiskDevice, PIRP Irp, PIO_STACK_LOCATION IrpSp FsRtlNotifyInitializeSync(&vcb->NotifySync); // FsRtlNotifyCleanup(vcb->NotifySync, &vcb->DirNotifyList, ccb); // VOID FsRtlNotifyCleanupAll( - //_In_ PNOTIFY_SYNC NotifySync, + // _In_ PNOTIFY_SYNC NotifySync, // _In_ PLIST_ENTRY NotifyList // ); @@ -1083,29 +1144,32 @@ int zfs_vnop_mount(PDEVICE_OBJECT DiskDevice, PIRP Irp, PIO_STACK_LOCATION IrpSp volDeviceObject->Flags |= DO_DIRECT_IO; volDeviceObject->Flags &= ~DO_DEVICE_INITIALIZING; - //SetLongFlag(vcb->Flags, VCB_MOUNTED); + // SetLongFlag(vcb->Flags, VCB_MOUNTED); ObReferenceObject(volDeviceObject); status = SendVolumeArrivalNotification(&dcb->device_name); if (!NT_SUCCESS(status)) { - dprintf(" SendVolumeArrivalNotification failed: 0x%x\n", status); + dprintf(" SendVolumeArrivalNotification failed: 0x%x\n", + status); } #if 0 UNICODE_STRING mountp; UNICODE_STRING devv; - //RtlInitUnicodeString(&mountp, L"\\DosDevices\\F:"); + // RtlInitUnicodeString(&mountp, L"\\DosDevices\\F:"); RtlInitUnicodeString(&mountp, L"\\DosDevices\\Global\\C:\\BOOM\\"); dprintf("Trying to connect %wZ with %wZ\n", &mountp, &dcb->device_name); status = IoCreateSymbolicLink(&mountp, &dcb->device_name); dprintf("Create symlink said %d / 0x%x\n", status, status); RtlInitUnicodeString(&mountp, L"\\DosDevices\\Global\\C:\\BOOM"); - dprintf("Trying to connect %wZ with %wZ\n", &mountp, &dcb->symlink_name); + dprintf("Trying to connect %wZ with %wZ\n", &mountp, + &dcb->symlink_name); status = IoCreateSymbolicLink(&mountp, &dcb->symlink_name); dprintf("Create symlink said %d / 0x%x\n", status, status); RtlInitUnicodeString(&mountp, L"\\DosDevices\\Global\\C:\\BOOM"); - RtlInitUnicodeString(&devv, L"\\Volume{0b1bb601-af0b-32e8-a1d2-54c167af6277}"); + RtlInitUnicodeString(&devv, + L"\\Volume{0b1bb601-af0b-32e8-a1d2-54c167af6277}"); dprintf("Trying to connect %wZ with %wZ\n", &mountp, &devv); status = IoCreateSymbolicLink(&mountp, &devv); dprintf("Create symlink said %d / 0x%x\n", status, status); @@ -1117,7 +1181,7 @@ int zfs_vnop_mount(PDEVICE_OBJECT DiskDevice, PIRP Irp, PIO_STACK_LOCATION IrpSp dprintf("Create symlink said %d / 0x%x\n", status, status); SendVolumeCreatePoint(&dcb->symlink_name, &mountp); - //gui 0x560000 + // gui 0x560000 // IOCTL_DISK_GET_PARTITION_INFO_EX 0x70048 #endif @@ -1128,8 +1192,10 @@ int zfs_vnop_mount(PDEVICE_OBJECT DiskDevice, PIRP Irp, PIO_STACK_LOCATION IrpSp UNICODE_STRING usStr; RtlInitUnicodeString(&usStr, L"\\??\\c:\\BOOM"); InitializeObjectAttributes(&poa, &usStr, OBJ_KERNEL_HANDLE, NULL, NULL); - //CreateReparsePoint(&poa, L"\\??\\Volume{7cc383a0-beac-11e7-b56d-02150b22a130}", L"AnyBOOM"); - CreateReparsePoint(&poa, L"\\??\\Volume{0b1bb601-af0b-32e8-a1d2-54c167af6277}", L"AnyBOOM"); + // CreateReparsePoint(&poa, + // L"\\??\\Volume{7cc383a0-beac-11e7-b56d-02150b22a130}", L"AnyBOOM"); + CreateReparsePoint(&poa, + L"\\??\\Volume{0b1bb601-af0b-32e8-a1d2-54c167af6277}", L"AnyBOOM"); #endif UNICODE_STRING name; PFILE_OBJECT fileObject; @@ -1137,69 +1203,98 @@ int zfs_vnop_mount(PDEVICE_OBJECT DiskDevice, PIRP Irp, PIO_STACK_LOCATION IrpSp // Query MntMgr for points, just informative RtlInitUnicodeString(&name, MOUNTMGR_DEVICE_NAME); - status = IoGetDeviceObjectPointer(&name, FILE_READ_ATTRIBUTES, &fileObject, - &mountmgr); + status = IoGetDeviceObjectPointer(&name, FILE_READ_ATTRIBUTES, + &fileObject, &mountmgr); char namex[PATH_MAX] = ""; status = mountmgr_get_drive_letter(mountmgr, &dcb->device_name, namex); // Check if we are to mount as path or just drive letter if (dcb->justDriveLetter) { - // If SendVolumeArrival was executed successfully we should have two mountpoints + // If SendVolumeArrival was executed successfully we should + // have two mountpoints // point 1: \Device\Volumes{abc} \DosDevices\X: // point 2: \Device\Volumes{abc} \??\Volume{xyz} - // but if we are in remount and removed the mountpoints for this volume manually before + // but if we are in remount and removed the mountpoints + // for this volume manually before // they won't get assigned by mountmgr automatically anymore. // So at least check if we got them and if not, try to create. if (!MOUNTMGR_IS_DRIVE_LETTER_A(namex)) { namex[0] = 0; - status = mountmgr_get_volume_name_mountpoint(mountmgr, &dcb->device_name, &namex); + status = mountmgr_get_volume_name_mountpoint(mountmgr, + &dcb->device_name, &namex); if (!MOUNTMGR_IS_VOLUME_NAME_A(namex)) { - // We have no volume name mountpoint for our device, - // so generate a valid GUID and mount the device + // We have no volume name mountpoint for our + // device, so generate a valid GUID and mount + // the device UNICODE_STRING vol_mpt; wchar_t buf[50]; generateVolumeNameMountpoint(&buf); RtlInitUnicodeString(&vol_mpt, buf); - status = SendVolumeCreatePoint(&dcb->device_name, &vol_mpt); + status = + SendVolumeCreatePoint(&dcb->device_name, + &vol_mpt); } - // If driveletter was provided, try to add it as mountpoint - if (dcb && dcb->mountpoint.Length > 0 && dcb->mountpoint.Buffer[4] != '?') { + // If driveletter was provided, try to add it + // as mountpoint + if (dcb && dcb->mountpoint.Length > 0 && + dcb->mountpoint.Buffer[4] != '?') { // check if driveletter is unassigned BOOLEAN ret; - status = mountmgr_is_driveletter_assigned(mountmgr, dcb->mountpoint.Buffer[4], &ret); + status = mountmgr_is_driveletter_assigned( + mountmgr, + dcb->mountpoint.Buffer[4], &ret); if (status == STATUS_SUCCESS && ret == 0) { - // driveletter is unassigned, try to add mountpoint - status = mountmgr_assign_driveletter(&dcb->device_name, dcb->mountpoint.Buffer[4]); + // driveletter is unassigned, try to + // add mountpoint + status = mountmgr_assign_driveletter( + &dcb->device_name, + dcb->mountpoint.Buffer[4]); } else { - // driveletter already assigned, find another one - SetNextDriveletterManually(mountmgr, &dcb->device_name); + // driveletter already assigned, + // find another one + SetNextDriveletterManually(mountmgr, + &dcb->device_name); } } else { - // user provided no driveletter, find one on our own - SetNextDriveletterManually(mountmgr, &dcb->device_name); + // user provided no driveletter, + // find one on our own + SetNextDriveletterManually(mountmgr, + &dcb->device_name); } } // !MOUNTMGR_IS_DRIVE_LETTER(&actualDriveletter) namex[0] = 0; - status = mountmgr_get_drive_letter(mountmgr, &dcb->device_name, namex); + status = mountmgr_get_drive_letter(mountmgr, + &dcb->device_name, namex); } else { OBJECT_ATTRIBUTES poa; - DECLARE_UNICODE_STRING_SIZE(volStr, ZFS_MAX_DATASET_NAME_LEN); // 36(uuid) + 6 (punct) + 6 (Volume) - RtlUnicodeStringPrintf(&volStr, L"\\??\\Volume{%wZ}", vcb->uuid); // "\??\Volume{0b1bb601-af0b-32e8-a1d2-54c167af6277}" - InitializeObjectAttributes(&poa, &dcb->mountpoint, OBJ_KERNEL_HANDLE, NULL, NULL); - dprintf("Creating reparse mountpoint on '%wZ' for volume '%wZ'\n", &dcb->mountpoint, &volStr); - CreateReparsePoint(&poa, &volStr, &vcb->name); // 3rd arg is visible in DOS box + // 36(uuid) + 6 (punct) + 6 (Volume) + DECLARE_UNICODE_STRING_SIZE(volStr, + ZFS_MAX_DATASET_NAME_LEN); + // "\??\Volume{0b1bb601-af0b-32e8-a1d2-54c167af6277}" + RtlUnicodeStringPrintf(&volStr, + L"\\??\\Volume{%wZ}", + vcb->uuid); + InitializeObjectAttributes(&poa, + &dcb->mountpoint, OBJ_KERNEL_HANDLE, NULL, NULL); + dprintf("Creating reparse mountpoint on '%wZ' for " + "volume '%wZ'\n", + &dcb->mountpoint, &volStr); + // 3rd arg is visible in DOS box + CreateReparsePoint(&poa, &volStr, &vcb->name); // Remove drive letter? - // RtlUnicodeStringPrintf(&volStr, L"\\DosDevices\\E:"); // FIXME - // RtlUnicodeStringPrintf(&volStr, L"%s", namex); // "\??\Volume{0b1bb601-af0b-32e8-a1d2-54c167af6277}" + // RtlUnicodeStringPrintf(&volStr, L"\\DosDevices\\E:"); + // RtlUnicodeStringPrintf(&volStr, L"%s", namex); + // "\??\Volume{0b1bb601-af0b-32e8-a1d2-54c167af6277}" ULONG lenx; - RtlUTF8ToUnicodeN(volStr.Buffer, ZFS_MAX_DATASET_NAME_LEN, &lenx, namex, strlen(namex)); + RtlUTF8ToUnicodeN(volStr.Buffer, ZFS_MAX_DATASET_NAME_LEN, + &lenx, namex, strlen(namex)); volStr.Length = lenx; status = SendVolumeDeletePoints(&volStr, &dcb->device_name); @@ -1210,13 +1305,16 @@ int zfs_vnop_mount(PDEVICE_OBJECT DiskDevice, PIRP Irp, PIO_STACK_LOCATION IrpSp ObDereferenceObject(fileObject); - // It seems likely we should announce our new filesystem, but when we do it stops working - // in explorer with "invalid function". But if we can set this, we can't call - // FSRTL_VOLUME_MOUNT below it, and more importantly, FSRTL_VOLUME_DISMOUNT + // It seems likely we should announce our new filesystem, but when + // we do it stops working in explorer with "invalid function". + // But if we can set this, we can't call + // FSRTL_VOLUME_MOUNT below it, and more importantly, + // FSRTL_VOLUME_DISMOUNT // before we umount. Need to figure out why. #if 0 - RegisterDeviceInterface(dcb->deviceObject->DriverObject, dcb->deviceObject, dcb); + RegisterDeviceInterface(dcb->deviceObject->DriverObject, + dcb->deviceObject, dcb); FILE_OBJECT *root_file; root_file = IoCreateStreamFileObject(NULL, dcb->deviceObject); @@ -1228,37 +1326,40 @@ int zfs_vnop_mount(PDEVICE_OBJECT DiskDevice, PIRP Irp, PIO_STACK_LOCATION IrpSp out: ObDereferenceObject(DeviceToMount); dprintf("%s: exit: 0x%x\n", __func__, status); - return status; + return (status); } -int zfs_remove_driveletter(mount_t *zmo) +int +zfs_remove_driveletter(mount_t *zmo) { UNICODE_STRING name; - PFILE_OBJECT fileObject; - PDEVICE_OBJECT mountmgr; + PFILE_OBJECT fileObject; + PDEVICE_OBJECT mountmgr; NTSTATUS Status; dprintf("%s: removing driveletter for '%wZ'\n", __func__, &zmo->name); // Query MntMgr for points, just informative RtlInitUnicodeString(&name, MOUNTMGR_DEVICE_NAME); - Status = IoGetDeviceObjectPointer(&name, FILE_READ_ATTRIBUTES, &fileObject, - &mountmgr); + Status = IoGetDeviceObjectPointer(&name, FILE_READ_ATTRIBUTES, + &fileObject, &mountmgr); ObDereferenceObject(fileObject); MOUNTMGR_MOUNT_POINT* mmp = NULL; ULONG mmpsize; MOUNTMGR_MOUNT_POINTS mmps1, *mmps2 = NULL; - mmpsize = sizeof(MOUNTMGR_MOUNT_POINT) + zmo->device_name.Length; + mmpsize = sizeof (MOUNTMGR_MOUNT_POINT) + zmo->device_name.Length; mmp = kmem_zalloc(mmpsize, KM_SLEEP); - - mmp->DeviceNameOffset = sizeof(MOUNTMGR_MOUNT_POINT); + + mmp->DeviceNameOffset = sizeof (MOUNTMGR_MOUNT_POINT); mmp->DeviceNameLength = zmo->device_name.Length; - RtlCopyMemory(&mmp[1], zmo->device_name.Buffer, zmo->device_name.Length); + RtlCopyMemory(&mmp[1], zmo->device_name.Buffer, + zmo->device_name.Length); - Status = dev_ioctl(mountmgr, IOCTL_MOUNTMGR_DELETE_POINTS, mmp, mmpsize, &mmps1, sizeof(MOUNTMGR_MOUNT_POINTS), FALSE, NULL); + Status = dev_ioctl(mountmgr, IOCTL_MOUNTMGR_DELETE_POINTS, + mmp, mmpsize, &mmps1, sizeof (MOUNTMGR_MOUNT_POINTS), FALSE, NULL); if (!NT_SUCCESS(Status) && Status != STATUS_BUFFER_OVERFLOW) { goto out; @@ -1271,9 +1372,10 @@ int zfs_remove_driveletter(mount_t *zmo) mmps2 = kmem_zalloc(mmps1.Size, KM_SLEEP); - Status = dev_ioctl(mountmgr, IOCTL_MOUNTMGR_DELETE_POINTS, mmp, mmpsize, mmps2, mmps1.Size, FALSE, NULL); + Status = dev_ioctl(mountmgr, IOCTL_MOUNTMGR_DELETE_POINTS, + mmp, mmpsize, mmps2, mmps1.Size, FALSE, NULL); - //if (!NT_SUCCESS(Status)) + // if (!NT_SUCCESS(Status)) // ERR("IOCTL_MOUNTMGR_DELETE_POINTS 2 returned %08x\n", Status); out: @@ -1285,28 +1387,31 @@ int zfs_remove_driveletter(mount_t *zmo) kmem_free(mmp, mmpsize); ObDereferenceObject(mountmgr); - return Status; + return (Status); } // Test increasingly more desperate things to unmount -void test(mount_t *zmo, zfs_cmd_t *zc) +void +test(mount_t *zmo, zfs_cmd_t *zc) { - ANSI_STRING AnsiFilespec; - UNICODE_STRING UnicodeFilespec; - OBJECT_ATTRIBUTES ObjectAttributes; + ANSI_STRING AnsiFilespec; + UNICODE_STRING UnicodeFilespec; + OBJECT_ATTRIBUTES ObjectAttributes; - SHORT UnicodeName[PATH_MAX]; - CHAR AnsiName[PATH_MAX]; - USHORT NameLength = 0; + SHORT UnicodeName[PATH_MAX]; + CHAR AnsiName[PATH_MAX]; + USHORT NameLength = 0; NTSTATUS ntstatus; - DECLARE_UNICODE_STRING_SIZE(volStr, ZFS_MAX_DATASET_NAME_LEN); // 36(uuid) + 6 (punct) + 6 (Volume) - //RtlUnicodeStringPrintf(&volStr, L"\\??\\E:", zmo->uuid); // "\??\Volume{0b1bb601-af0b-32e8-a1d2-54c167af6277}" - RtlUnicodeStringPrintf(&volStr, L"\\??\\Volume{%wZ}", zmo->uuid); // "\??\Volume{0b1bb601-af0b-32e8-a1d2-54c167af6277}" + // 36(uuid) + 6 (punct) + 6 (Volume) + DECLARE_UNICODE_STRING_SIZE(volStr, ZFS_MAX_DATASET_NAME_LEN); + // "\??\Volume{0b1bb601-af0b-32e8-a1d2-54c167af6277}" + // RtlUnicodeStringPrintf(&volStr, L"\\??\\E:", zmo->uuid); + RtlUnicodeStringPrintf(&volStr, L"\\??\\Volume{%wZ}", zmo->uuid); #if 0 - memset(UnicodeName, 0, sizeof(SHORT) * PATH_MAX); - memset(AnsiName, 0, sizeof(UCHAR) * PATH_MAX); + memset(UnicodeName, 0, sizeof (SHORT) * PATH_MAX); + memset(AnsiName, 0, sizeof (UCHAR) * PATH_MAX); NameLength = strlen(FileName); ASSERT(NameLength < PATH_MAX); @@ -1321,9 +1426,9 @@ void test(mount_t *zmo, zfs_cmd_t *zc) UnicodeFilespec.Buffer = (PWSTR)UnicodeName; #endif - ObjectAttributes.Length = sizeof(OBJECT_ATTRIBUTES); + ObjectAttributes.Length = sizeof (OBJECT_ATTRIBUTES); ObjectAttributes.RootDirectory = NULL; - ObjectAttributes.Attributes = /*OBJ_CASE_INSENSITIVE |*/ OBJ_KERNEL_HANDLE; + ObjectAttributes.Attributes = OBJ_KERNEL_HANDLE; ObjectAttributes.ObjectName = &volStr; ObjectAttributes.SecurityDescriptor = NULL; ObjectAttributes.SecurityQualityOfService = NULL; @@ -1331,53 +1436,53 @@ void test(mount_t *zmo, zfs_cmd_t *zc) HANDLE handle; #if 0 ntstatus = ZwCreateFile(&handle, - GENERIC_WRITE | SYNCHRONIZE, - &ObjectAttributes, - &iostatus, - 0, - FILE_ATTRIBUTE_NORMAL, - /* FILE_SHARE_WRITE | */ FILE_SHARE_READ, - FILE_OPEN, - FILE_SYNCHRONOUS_IO_NONALERT | FILE_NO_INTERMEDIATE_BUFFERING, - NULL, - 0); + GENERIC_WRITE | SYNCHRONIZE, + &ObjectAttributes, + &iostatus, + 0, + FILE_ATTRIBUTE_NORMAL, + /* FILE_SHARE_WRITE | */ FILE_SHARE_READ, + FILE_OPEN, + FILE_SYNCHRONOUS_IO_NONALERT | FILE_NO_INTERMEDIATE_BUFFERING, + NULL, + 0); #else ntstatus = ZwOpenFile(&handle, FILE_READ_ATTRIBUTES|FILE_WRITE_ATTRIBUTES, &ObjectAttributes, &iostatus, FILE_SHARE_READ|FILE_SHARE_WRITE, - FILE_NON_DIRECTORY_FILE|FILE_SYNCHRONOUS_IO_NONALERT ); + FILE_NON_DIRECTORY_FILE|FILE_SYNCHRONOUS_IO_NONALERT); #endif if (NT_SUCCESS(ntstatus)) { IO_STATUS_BLOCK IoStatus; - ntstatus = FsRtlNotifyVolumeEvent(handle, FSRTL_VOLUME_DISMOUNT); + ntstatus = FsRtlNotifyVolumeEvent(handle, + FSRTL_VOLUME_DISMOUNT); FILE_OBJECT *root_file; root_file = IoCreateStreamFileObject(handle, NULL); - ntstatus = FsRtlNotifyVolumeEvent(root_file, FSRTL_VOLUME_DISMOUNT); + ntstatus = FsRtlNotifyVolumeEvent(root_file, + FSRTL_VOLUME_DISMOUNT); ObDereferenceObject(root_file); #if 0 ntstatus = ZwDeviceIoControlFile(handle, - 0,0,0, &IoStatus, FSCTL_LOCK_VOLUME, 0,0,0,0); + 0, 0, 0, &IoStatus, FSCTL_LOCK_VOLUME, 0, 0, 0, 0); ntstatus = ZwDeviceIoControlFile(handle, - 0,0,0, &IoStatus, FSCTL_DISMOUNT_VOLUME, 0,0,0,0); + 0, 0, 0, &IoStatus, FSCTL_DISMOUNT_VOLUME, 0, 0, 0, 0); - // ntstatus = kernel_ioctl(handle, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0); + // ntstatus = kernel_ioctl(handle, FSCTL_LOCK_VOLUME, + // NULL, 0, NULL, 0); #endif ZwClose(handle); } - - } - - -int zfs_windows_unmount(zfs_cmd_t *zc) +int +zfs_windows_unmount(zfs_cmd_t *zc) { // IRP_MN_QUERY_REMOVE_DEVICE // IRP_MN_REMOVE_DEVICE @@ -1391,7 +1496,7 @@ int zfs_windows_unmount(zfs_cmd_t *zc) zfsvfs_t *zfsvfs; int error = EBUSY; znode_t *zp; - //int rdonly; + // int rdonly; if (getzfsvfs(zc->zc_name, &zfsvfs) == 0) { @@ -1402,10 +1507,12 @@ int zfs_windows_unmount(zfs_cmd_t *zc) // DbgBreakPoint(); #if 0 - // Try issuing DISMOUNT ... this wont work unless "attached" in RegisterDeviceInterface() + // Try issuing DISMOUNT ... this wont work unless + // "attached" in RegisterDeviceInterface() FILE_OBJECT *root_file; root_file = IoCreateStreamFileObject(NULL, zmo->deviceObject); - ntstatus = FsRtlNotifyVolumeEvent(root_file, FSRTL_VOLUME_DISMOUNT); + ntstatus = FsRtlNotifyVolumeEvent(root_file, + FSRTL_VOLUME_DISMOUNT); ObDereferenceObject(root_file); #endif // Try other desperate things @@ -1417,10 +1524,13 @@ int zfs_windows_unmount(zfs_cmd_t *zc) zfs_remove_driveletter(zmo); #if 1 - // Try issuing DISMOUNT ... this wont work unless "attached" in RegisterDeviceInterface() + // Try issuing DISMOUNT ... this wont work unless + // "attached" in RegisterDeviceInterface() FILE_OBJECT *root_file; - root_file = IoCreateStreamFileObject(NULL, zmo->deviceObject); - ntstatus = FsRtlNotifyVolumeEvent(root_file, FSRTL_VOLUME_DISMOUNT); + root_file = IoCreateStreamFileObject(NULL, + zmo->deviceObject); + ntstatus = FsRtlNotifyVolumeEvent(root_file, + FSRTL_VOLUME_DISMOUNT); ObDereferenceObject(root_file); #endif @@ -1430,18 +1540,22 @@ int zfs_windows_unmount(zfs_cmd_t *zc) // Query MntMgr for points, just informative RtlInitUnicodeString(&name, MOUNTMGR_DEVICE_NAME); - NTSTATUS status = IoGetDeviceObjectPointer(&name, FILE_READ_ATTRIBUTES, - &fileObject, &mountmgr); + NTSTATUS status = IoGetDeviceObjectPointer(&name, + FILE_READ_ATTRIBUTES, &fileObject, &mountmgr); char namex[PATH_MAX] = ""; - status = mountmgr_get_drive_letter(mountmgr, &zmo->device_name, namex); + status = mountmgr_get_drive_letter(mountmgr, + &zmo->device_name, namex); #if 0 - error = kernel_ioctl(zmo->deviceObject, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0); + error = kernel_ioctl(zmo->deviceObject, FSCTL_LOCK_VOLUME, + NULL, 0, NULL, 0); dprintf("LOCK_VOLUME said %d\n", error); // If lock fails, it becomes a force dismount - error = kernel_ioctl(zmo->deviceObject, FSCTL_DISMOUNT_VOLUME, NULL, 0, NULL, 0); + error = kernel_ioctl(zmo->deviceObject, FSCTL_DISMOUNT_VOLUME, + NULL, 0, NULL, 0); dprintf("DISMOUNT_VOLUME said %d\n", error); - error = kernel_ioctl(zmo->deviceObject, FSCTL_UNLOCK_VOLUME, NULL, 0, NULL, 0); + error = kernel_ioctl(zmo->deviceObject, FSCTL_UNLOCK_VOLUME, + NULL, 0, NULL, 0); #endif // Flush volume @@ -1451,25 +1565,28 @@ int zfs_windows_unmount(zfs_cmd_t *zc) if (error) goto out_unlock; // Delete mountpoints for our volume manually - // Query the mountmgr for mountpoints and delete them until no mountpoint is left - // Because we are not satisfied with mountmgrs work, it gets offended and - // doesn't automatically create mointpoints for our volume after we deleted them manually - // But as long as we recheck that in mount and create points manually (if necessary), + // Query the mountmgr for mountpoints and delete them + // until no mountpoint is left Because we are not satisfied + // with mountmgrs work, it gets offended and doesn't + // automatically create mointpoints for our volume after we + // deleted them manually But as long as we recheck that in + // mount and create points manually (if necessary), // that should be ok hopefully - - // We used to loop here and keep deleting anything we find, but we - // are only allowed to remove symlinks, anything else and MountMgr - // ignores the device. + // We used to loop here and keep deleting anything we find, + // but we are only allowed to remove symlinks, anything + // else and MountMgr ignores the device. #if 0 while (strlen(namex) > 0) { UNICODE_STRING unicode_mpt; wchar_t wbuf[PATH_MAX]; - mbstowcs(wbuf, namex, sizeof(namex)); + mbstowcs(wbuf, namex, sizeof (namex)); RtlInitUnicodeString(&unicode_mpt, wbuf); - status = SendVolumeDeletePoints(&unicode_mpt, &zmo->device_name); + status = SendVolumeDeletePoints(&unicode_mpt, + &zmo->device_name); namex[0] = 0; - status = mountmgr_get_mountpoint(mountmgr, &zmo->device_name, namex, FALSE, FALSE); + status = mountmgr_get_mountpoint(mountmgr, + &zmo->device_name, namex, FALSE, FALSE); } #endif ObDereferenceObject(fileObject); @@ -1511,5 +1628,5 @@ int zfs_windows_unmount(zfs_cmd_t *zc) // counter to getzfvfs vfs_unbusy(zfsvfs->z_vfs); } - return error; + return (error); } diff --git a/module/os/windows/zfs/zfs_windows_zvol.c b/module/os/windows/zfs/zfs_windows_zvol.c index 74508b9d602..125670b8100 100644 --- a/module/os/windows/zfs/zfs_windows_zvol.c +++ b/module/os/windows/zfs/zfs_windows_zvol.c @@ -24,7 +24,7 @@ #include #include -#include +#include #include #include #include @@ -35,71 +35,97 @@ static pHW_HBA_EXT STOR_HBAExt = NULL; // Verbose -//#undef dprintf -//#define dprintf - -int zvol_start(PDRIVER_OBJECT DriverObject, PUNICODE_STRING pRegistryPath) +int +zvol_start(PDRIVER_OBJECT DriverObject, PUNICODE_STRING pRegistryPath) { pwzvolDriverInfo pwzvolDrvInfo; NTSTATUS status; VIRTUAL_HW_INITIALIZATION_DATA hwInitData; - RtlZeroMemory(&STOR_wzvolDriverInfo, sizeof(STOR_wzvolDriverInfo)); + RtlZeroMemory(&STOR_wzvolDriverInfo, sizeof (STOR_wzvolDriverInfo)); pwzvolDrvInfo = &STOR_wzvolDriverInfo; - RtlZeroMemory(pwzvolDrvInfo, sizeof(wzvolDriverInfo)); // Set pwzvolDrvInfo's storage to a known state. - pwzvolDrvInfo->pDriverObj = DriverObject; // Save pointer to driver object. + RtlZeroMemory(pwzvolDrvInfo, sizeof (wzvolDriverInfo)); + pwzvolDrvInfo->pDriverObj = DriverObject; - KeInitializeSpinLock(&pwzvolDrvInfo->DrvInfoLock); // Initialize spin lock. - KeInitializeSpinLock(&pwzvolDrvInfo->MPIOExtLock); // " - KeInitializeSpinLock(&pwzvolDrvInfo->SrbExtLock); // " + KeInitializeSpinLock(&pwzvolDrvInfo->DrvInfoLock); + KeInitializeSpinLock(&pwzvolDrvInfo->MPIOExtLock); + KeInitializeSpinLock(&pwzvolDrvInfo->SrbExtLock); - InitializeListHead(&pwzvolDrvInfo->ListMPHBAObj); // Initialize list head. + InitializeListHead(&pwzvolDrvInfo->ListMPHBAObj); InitializeListHead(&pwzvolDrvInfo->ListMPIOExt); InitializeListHead(&pwzvolDrvInfo->ListSrbExt); - pwzvolDrvInfo->wzvolRegInfo.BreakOnEntry = DEFAULT_BREAK_ON_ENTRY; // not used. - pwzvolDrvInfo->wzvolRegInfo.DebugLevel = DEFAULT_DEBUG_LEVEL; // not used. - pwzvolDrvInfo->wzvolRegInfo.InitiatorID = DEFAULT_INITIATOR_ID; // not used. - pwzvolDrvInfo->wzvolRegInfo.PhysicalDiskSize = DEFAULT_PHYSICAL_DISK_SIZE; // used. - pwzvolDrvInfo->wzvolRegInfo.VirtualDiskSize = DEFAULT_VIRTUAL_DISK_SIZE; // not used. - pwzvolDrvInfo->wzvolRegInfo.NbrVirtDisks = DEFAULT_NbrVirtDisks; // not used. + pwzvolDrvInfo->wzvolRegInfo.BreakOnEntry = DEFAULT_BREAK_ON_ENTRY; + pwzvolDrvInfo->wzvolRegInfo.DebugLevel = DEFAULT_DEBUG_LEVEL; + pwzvolDrvInfo->wzvolRegInfo.InitiatorID = DEFAULT_INITIATOR_ID; + pwzvolDrvInfo->wzvolRegInfo.PhysicalDiskSize = + DEFAULT_PHYSICAL_DISK_SIZE; + pwzvolDrvInfo->wzvolRegInfo.VirtualDiskSize = DEFAULT_VIRTUAL_DISK_SIZE; + pwzvolDrvInfo->wzvolRegInfo.NbrVirtDisks = DEFAULT_NbrVirtDisks; - pwzvolDrvInfo->wzvolRegInfo.NbrLUNsperHBA = DEFAULT_NbrLUNsperHBA; // used. - pwzvolDrvInfo->wzvolRegInfo.NbrLUNsperTarget = DEFAULT_NbrLUNsperTarget; // used. - pwzvolDrvInfo->wzvolRegInfo.bCombineVirtDisks = DEFAULT_bCombineVirtDisks; // used. If TRUE, MPIO must be installed on the server. + pwzvolDrvInfo->wzvolRegInfo.NbrLUNsperHBA = DEFAULT_NbrLUNsperHBA; + pwzvolDrvInfo->wzvolRegInfo.NbrLUNsperTarget = DEFAULT_NbrLUNsperTarget; + pwzvolDrvInfo->wzvolRegInfo.bCombineVirtDisks = + DEFAULT_bCombineVirtDisks; RtlInitUnicodeString(&pwzvolDrvInfo->wzvolRegInfo.VendorId, VENDOR_ID); - RtlInitUnicodeString(&pwzvolDrvInfo->wzvolRegInfo.ProductId, PRODUCT_ID); - RtlInitUnicodeString(&pwzvolDrvInfo->wzvolRegInfo.ProductRevision, PRODUCT_REV); - - // Calculate the combination of busses, targets and Luns to fit the NbrLUNsperHBA requirement - // We privilege the maximum amount of targets vs. luns so TARGET RESETs don't affect a bunch of LUNs + RtlInitUnicodeString(&pwzvolDrvInfo->wzvolRegInfo.ProductId, + PRODUCT_ID); + RtlInitUnicodeString(&pwzvolDrvInfo->wzvolRegInfo.ProductRevision, + PRODUCT_REV); + + // Calculate the combination of busses, targets and Luns to fit + // the NbrLUNsperHBA requirement. We privilege the maximum amount + // of targets vs. luns so TARGET RESETs don't affect a bunch of LUNs // - if ((pwzvolDrvInfo->wzvolRegInfo.NbrLUNsperHBA / pwzvolDrvInfo->wzvolRegInfo.NbrLUNsperTarget) > SCSI_MAXIMUM_TARGETS_PER_BUS) - pwzvolDrvInfo->MaximumNumberOfTargets = SCSI_MAXIMUM_TARGETS_PER_BUS; + if ((pwzvolDrvInfo->wzvolRegInfo.NbrLUNsperHBA / + pwzvolDrvInfo->wzvolRegInfo.NbrLUNsperTarget) > + SCSI_MAXIMUM_TARGETS_PER_BUS) + pwzvolDrvInfo->MaximumNumberOfTargets = + SCSI_MAXIMUM_TARGETS_PER_BUS; else - pwzvolDrvInfo->MaximumNumberOfTargets = (pwzvolDrvInfo->wzvolRegInfo.NbrLUNsperHBA / pwzvolDrvInfo->wzvolRegInfo.NbrLUNsperTarget) + - (pwzvolDrvInfo->wzvolRegInfo.NbrLUNsperHBA % pwzvolDrvInfo->wzvolRegInfo.NbrLUNsperTarget ? 1 : 0); - - //pwzvolDrvInfo->MaximumNumberOfTargets = (pwzvolDrvInfo->wzvolRegInfo.NbrLUNsperHBA <= SCSI_MAXIMUM_TARGETS_PER_BUS ? pwzvolDrvInfo->wzvolRegInfo.NbrLUNsperHBA : SCSI_MAXIMUM_TARGETS_PER_BUS); - pwzvolDrvInfo->MaximumNumberOfLogicalUnits = (pwzvolDrvInfo->wzvolRegInfo.NbrLUNsperHBA / pwzvolDrvInfo->MaximumNumberOfTargets) + 1; - pwzvolDrvInfo->NumberOfBuses = 1; // supporting more would mean bigger changes in the zv_targets array. now we can go up to 32,640 zvols. - pwzvolDrvInfo->zvContextArray = (wzvolContext*)ExAllocatePoolWithTag(NonPagedPoolNx, ((SIZE_T)pwzvolDrvInfo->MaximumNumberOfTargets * pwzvolDrvInfo->MaximumNumberOfLogicalUnits * sizeof(wzvolContext)), MP_TAG_GENERAL); + pwzvolDrvInfo->MaximumNumberOfTargets = + (pwzvolDrvInfo->wzvolRegInfo.NbrLUNsperHBA / + pwzvolDrvInfo->wzvolRegInfo.NbrLUNsperTarget) + + (pwzvolDrvInfo->wzvolRegInfo.NbrLUNsperHBA % + pwzvolDrvInfo->wzvolRegInfo.NbrLUNsperTarget ? 1 : 0); + + // pwzvolDrvInfo->MaximumNumberOfTargets = + // (pwzvolDrvInfo->wzvolRegInfo.NbrLUNsperHBA <= + // SCSI_MAXIMUM_TARGETS_PER_BUS ? + // pwzvolDrvInfo->wzvolRegInfo.NbrLUNsperHBA : + // SCSI_MAXIMUM_TARGETS_PER_BUS); + pwzvolDrvInfo->MaximumNumberOfLogicalUnits = + (pwzvolDrvInfo->wzvolRegInfo.NbrLUNsperHBA / + pwzvolDrvInfo->MaximumNumberOfTargets) + 1; + // supporting more would mean bigger changes in the zv_targets + // array. now we can go up to 32,640 zvols. + pwzvolDrvInfo->NumberOfBuses = 1; + pwzvolDrvInfo->zvContextArray = + (wzvolContext*)ExAllocatePoolWithTag(NonPagedPoolNx, + ((SIZE_T)pwzvolDrvInfo->MaximumNumberOfTargets * + pwzvolDrvInfo->MaximumNumberOfLogicalUnits * + sizeof (wzvolContext)), MP_TAG_GENERAL); if (pwzvolDrvInfo->zvContextArray == NULL) return (STATUS_NO_MEMORY); - RtlZeroMemory(pwzvolDrvInfo->zvContextArray, ((SIZE_T)pwzvolDrvInfo->MaximumNumberOfTargets * pwzvolDrvInfo->MaximumNumberOfLogicalUnits * (sizeof(wzvolContext)))); - - RtlZeroMemory(&hwInitData, sizeof(VIRTUAL_HW_INITIALIZATION_DATA)); - hwInitData.HwInitializationDataSize = sizeof(VIRTUAL_HW_INITIALIZATION_DATA); + RtlZeroMemory(pwzvolDrvInfo->zvContextArray, + ((SIZE_T)pwzvolDrvInfo->MaximumNumberOfTargets * + pwzvolDrvInfo->MaximumNumberOfLogicalUnits * + (sizeof (wzvolContext)))); + + RtlZeroMemory(&hwInitData, sizeof (VIRTUAL_HW_INITIALIZATION_DATA)); - hwInitData.HwInitialize = wzvol_HwInitialize; // Required. - hwInitData.HwStartIo = wzvol_HwStartIo; // Required. - hwInitData.HwFindAdapter = wzvol_HwFindAdapter; // Required. - hwInitData.HwResetBus = wzvol_HwResetBus; // Required. - hwInitData.HwAdapterControl = wzvol_HwAdapterControl; // Required. + hwInitData.HwInitializationDataSize = + sizeof (VIRTUAL_HW_INITIALIZATION_DATA); + + hwInitData.HwInitialize = wzvol_HwInitialize; + hwInitData.HwStartIo = wzvol_HwStartIo; + hwInitData.HwFindAdapter = wzvol_HwFindAdapter; + hwInitData.HwResetBus = wzvol_HwResetBus; + hwInitData.HwAdapterControl = wzvol_HwAdapterControl; hwInitData.HwFreeAdapterResources = wzvol_HwFreeAdapterResources; hwInitData.HwInitializeTracing = wzvol_TracingInit; hwInitData.HwCleanupTracing = wzvol_TracingCleanup; @@ -108,23 +134,23 @@ int zvol_start(PDRIVER_OBJECT DriverObject, PUNICODE_STRING pRegistryPath) hwInitData.AdapterInterfaceType = Internal; - hwInitData.DeviceExtensionSize = sizeof(HW_HBA_EXT); - hwInitData.SpecificLuExtensionSize = sizeof(HW_LU_EXTENSION); - hwInitData.SrbExtensionSize = sizeof(HW_SRB_EXTENSION) + IoSizeofWorkItem(); // see MP_WorkRtnParms structure. + hwInitData.DeviceExtensionSize = sizeof (HW_HBA_EXT); + hwInitData.SpecificLuExtensionSize = sizeof (HW_LU_EXTENSION); + hwInitData.SrbExtensionSize = + sizeof (HW_SRB_EXTENSION) + IoSizeofWorkItem(); hwInitData.TaggedQueuing = TRUE; hwInitData.AutoRequestSense = TRUE; hwInitData.MultipleRequestPerLu = TRUE; hwInitData.ReceiveEvent = TRUE; - status = StorPortInitialize( // Tell StorPort we're here. - DriverObject, - pRegistryPath, - (PHW_INITIALIZATION_DATA)&hwInitData, // Note: Have to override type! - NULL - ); + status = StorPortInitialize( + DriverObject, + pRegistryPath, + (PHW_INITIALIZATION_DATA)&hwInitData, + NULL); - return status; + return (status); } BOOLEAN @@ -133,19 +159,18 @@ wzvol_HwInitialize(__in pHW_HBA_EXT pHBAExt) UNREFERENCED_PARAMETER(pHBAExt); dprintf("%s: entry\n", __func__); - return TRUE; + return (TRUE); } ULONG wzvol_HwFindAdapter( - __in pHW_HBA_EXT pHBAExt, // Adapter device-object extension from StorPort. - __in PVOID pHwContext, // Pointer to context. - __in PVOID pBusInformation, // Miniport's FDO. - __in PVOID pLowerDO, // Device object beneath FDO. - __in PCHAR pArgumentString, + __in pHW_HBA_EXT pHBAExt, + __in PVOID pHwContext, + __in PVOID pBusInformation, + __in PVOID pLowerDO, + __in PCHAR pArgumentString, __in __out PPORT_CONFIGURATION_INFORMATION pConfigInfo, - __in PBOOLEAN pBAgain -) + __in PBOOLEAN pBAgain) { ULONG i, len, status = SP_RETURN_FOUND; PCHAR pChar; @@ -158,7 +183,7 @@ wzvol_HwFindAdapter( #else - KIRQL SaveIrql; + KIRQL SaveIrql; #endif @@ -167,49 +192,58 @@ wzvol_HwFindAdapter( UNREFERENCED_PARAMETER(pLowerDO); UNREFERENCED_PARAMETER(pArgumentString); - dprintf("%s: pHBAExt = 0x%p, pConfigInfo = 0x%p\n", __func__, - pHBAExt, pConfigInfo); + dprintf("%s: pHBAExt = 0x%p, pConfigInfo = 0x%p\n", __func__, + pHBAExt, pConfigInfo); - pHBAExt->pwzvolDrvObj = &STOR_wzvolDriverInfo; // Copy master object from static variable. + // Copy master object from static variable. + pHBAExt->pwzvolDrvObj = &STOR_wzvolDriverInfo; if (STOR_HBAExt == NULL) { // We save the first adapter only to announce. STOR_HBAExt = pHBAExt; // So we can announce pHBAExt->bDontReport = FALSE; + } else { + // If MPIO support is not requested we won't present + // the LUNs through other found adapters. + pHBAExt->bDontReport = + !STOR_wzvolDriverInfo.wzvolRegInfo.bCombineVirtDisks; } - else { - // If MPIO support is not requested we won;t present the LUNs through other found adapters. - pHBAExt->bDontReport = !STOR_wzvolDriverInfo.wzvolRegInfo.bCombineVirtDisks; - } - - InitializeListHead(&pHBAExt->MPIOLunList); // Initialize list head. + + InitializeListHead(&pHBAExt->MPIOLunList); InitializeListHead(&pHBAExt->LUList); - KeInitializeSpinLock(&pHBAExt->WkItemsLock); // Initialize locks. + KeInitializeSpinLock(&pHBAExt->WkItemsLock); KeInitializeSpinLock(&pHBAExt->WkRoutinesLock); KeInitializeSpinLock(&pHBAExt->MPHBAObjLock); KeInitializeSpinLock(&pHBAExt->LUListLock); - pHBAExt->HostTargetId = (UCHAR)pHBAExt->pwzvolDrvObj->wzvolRegInfo.InitiatorID; + pHBAExt->HostTargetId = + (UCHAR)pHBAExt->pwzvolDrvObj->wzvolRegInfo.InitiatorID; pHBAExt->pDrvObj = pHBAExt->pwzvolDrvObj->pDriverObj; - pHBAExt->NbrLUNsperHBA = pHBAExt->pwzvolDrvObj->wzvolRegInfo.NbrLUNsperHBA; - - pConfigInfo->VirtualDevice = TRUE; // Inidicate no real hardware. - pConfigInfo->WmiDataProvider = TRUE; // Indicate WMI provider. - pConfigInfo->MaximumTransferLength = SP_UNINITIALIZED_VALUE; // Indicate unlimited. - pConfigInfo->AlignmentMask = 0x3; // Indicate DWORD alignment. - pConfigInfo->CachesData = FALSE; // Indicate miniport wants flush and shutdown notification. - pConfigInfo->ScatterGather = TRUE; // Indicate scatter-gather (explicit setting needed for Win2003 at least). - pConfigInfo->MapBuffers = STOR_MAP_ALL_BUFFERS_INCLUDING_READ_WRITE; // we have no DMA operation to justify not letting StorPort map for us. - pConfigInfo->SynchronizationModel = StorSynchronizeFullDuplex; // Indicate full-duplex. - pConfigInfo->MaximumNumberOfLogicalUnits = pHBAExt->pwzvolDrvObj->MaximumNumberOfLogicalUnits; - pConfigInfo->MaximumNumberOfTargets = pHBAExt->pwzvolDrvObj->MaximumNumberOfTargets; + pHBAExt->NbrLUNsperHBA = + pHBAExt->pwzvolDrvObj->wzvolRegInfo.NbrLUNsperHBA; + + pConfigInfo->VirtualDevice = TRUE; + pConfigInfo->WmiDataProvider = TRUE; + pConfigInfo->MaximumTransferLength = SP_UNINITIALIZED_VALUE; + pConfigInfo->AlignmentMask = 0x3; + pConfigInfo->CachesData = FALSE; + pConfigInfo->ScatterGather = TRUE; + pConfigInfo->MapBuffers = STOR_MAP_ALL_BUFFERS_INCLUDING_READ_WRITE; + pConfigInfo->SynchronizationModel = StorSynchronizeFullDuplex; + pConfigInfo->MaximumNumberOfLogicalUnits = + pHBAExt->pwzvolDrvObj->MaximumNumberOfLogicalUnits; + pConfigInfo->MaximumNumberOfTargets = + pHBAExt->pwzvolDrvObj->MaximumNumberOfTargets; pConfigInfo->NumberOfBuses = pHBAExt->pwzvolDrvObj->NumberOfBuses; - dprintf("%s: pHBAExt = 0x%p, NbBuses/MaxTargets/MaxLuns=%d/%d/%d.\n", __func__, - pHBAExt, pConfigInfo->NumberOfBuses, pConfigInfo->MaximumNumberOfTargets, pConfigInfo->MaximumNumberOfLogicalUnits); + dprintf("%s: pHBAExt = 0x%p, NbBuses/MaxTargets/MaxLuns=%d/%d/%d.\n", + __func__, + pHBAExt, pConfigInfo->NumberOfBuses, + pConfigInfo->MaximumNumberOfTargets, + pConfigInfo->MaximumNumberOfLogicalUnits); // Save Vendor Id, Product Id, Revision in device extension. @@ -219,19 +253,23 @@ wzvol_HwFindAdapter( pHBAExt->VendorId[i] = *pChar; pChar = (PCHAR)pHBAExt->pwzvolDrvObj->wzvolRegInfo.ProductId.Buffer; - len = min(16, (pHBAExt->pwzvolDrvObj->wzvolRegInfo.ProductId.Length / 2)); + len = min(16, + (pHBAExt->pwzvolDrvObj->wzvolRegInfo.ProductId.Length / 2)); for (i = 0; i < len; i++, pChar += 2) pHBAExt->ProductId[i] = *pChar; - pChar = (PCHAR)pHBAExt->pwzvolDrvObj->wzvolRegInfo.ProductRevision.Buffer; - len = min(4, (pHBAExt->pwzvolDrvObj->wzvolRegInfo.ProductRevision.Length / 2)); + pChar = (PCHAR)pHBAExt->pwzvolDrvObj-> + wzvolRegInfo.ProductRevision.Buffer; + len = min(4, + (pHBAExt->pwzvolDrvObj->wzvolRegInfo.ProductRevision.Length / 2)); for (i = 0; i < len; i++, pChar += 2) pHBAExt->ProductRevision[i] = *pChar; // Add HBA extension to master driver object's linked list. #if defined(_AMD64_) - KeAcquireInStackQueuedSpinLock(&pHBAExt->pwzvolDrvObj->DrvInfoLock, &LockHandle); + KeAcquireInStackQueuedSpinLock(&pHBAExt->pwzvolDrvObj->DrvInfoLock, + &LockHandle); #else KeAcquireSpinLock(&pHBAExt->pwzvolDrvObj->DrvInfoLock, &SaveIrql); #endif @@ -245,77 +283,83 @@ wzvol_HwFindAdapter( InitializeWmiContext(pHBAExt); - //*pBAgain = FALSE; // should not touch this. + // *pBAgain = FALSE; // should not touch this. - return status; + return (status); } -#define StorPortMaxWMIEventSize 0x80 // Maximum WMIEvent size StorPort will support. -#define InstName L"ZVOL" +// Maximum WMIEvent size StorPort will support. +#define StorPortMaxWMIEventSize 0x80 +#define InstName L"ZVOL" -/**************************************************************************************************/ -/* */ -/**************************************************************************************************/ void - wzvol_HwReportAdapter(__in pHW_HBA_EXT pHBAExt) +wzvol_HwReportAdapter(__in pHW_HBA_EXT pHBAExt) { dprintf("%s: entry\n", __func__); #if 1 - NTSTATUS status; + NTSTATUS status; PWNODE_SINGLE_INSTANCE pWnode; - ULONG WnodeSize, - WnodeSizeInstanceName, - WnodeSizeDataBlock, - length, - size; - GUID lclGuid = MSFC_AdapterEvent_GUID; - UNICODE_STRING lclInstanceName; - UCHAR myPortWWN[8] = { 1, 2, 3, 4, 5, 6, 7, 8 }; - PMSFC_AdapterEvent pAdapterArr; - - // With the instance name used here and with the rounding-up to 4-byte alignment of the data portion used here, - // 0x34 (52) bytes are available for the actual data of the WMI event. (The 0x34 bytes result from the fact that - // StorPort at present (August 2008) allows 0x80 bytes for the entire WMIEvent (header, instance name and data); - // the header is 0x40 bytes; the instance name used here results in 0xA bytes, and the rounding up consumes 2 bytes; - // in other words, 0x80 - (0x40 + 0x0A + 0x02)). - - RtlInitUnicodeString(&lclInstanceName, InstName); // Set Unicode descriptor for instance name. - - // A WMIEvent structure consists of header, instance name and data block. - - WnodeSize = sizeof(WNODE_SINGLE_INSTANCE); - - // Because the first field in the data block, EventType, is a ULONG, ensure that the data block begins on a + ULONG WnodeSize, + WnodeSizeInstanceName, + WnodeSizeDataBlock, + length, + size; + GUID lclGuid = MSFC_AdapterEvent_GUID; + UNICODE_STRING lclInstanceName; + UCHAR myPortWWN[8] = { 1, 2, 3, 4, 5, 6, 7, 8 }; + PMSFC_AdapterEvent pAdapterArr; + + // With the instance name used here and with the rounding-up + // to 4-byte alignment of the data portion used here, + // 0x34 (52) bytes are available for the actual data of the + // WMI event. (The 0x34 bytes result from the fact that StorPort + // at present (August 2008) allows 0x80 bytes for the entire + // WMIEvent (header, instance name and data); the header is 0x40 + // bytes; the instance name used here results in 0xA bytes, + // and the rounding up consumes 2 bytes; in other words, + // 0x80 - (0x40 + 0x0A + 0x02)). + + RtlInitUnicodeString(&lclInstanceName, InstName); + + WnodeSize = sizeof (WNODE_SINGLE_INSTANCE); + + // Because the first field in the data block, EventType, is a ULONG, + // ensure that the data block begins on a // 4-byte boundary (as will be calculated in DataBlockOffset). - WnodeSizeInstanceName = sizeof(USHORT) + // Size of USHORT at beginning plus - lclInstanceName.Length; // size of instance name. - WnodeSizeInstanceName = // Round length up to multiple of 4 (if needed). - (ULONG)WDF_ALIGN_SIZE_UP(WnodeSizeInstanceName, sizeof(ULONG)); + // Size of USHORT at beginning plus + WnodeSizeInstanceName = sizeof (USHORT) + + lclInstanceName.Length; // size of instance name. + // Round length up to multiple of 4 (if needed). + WnodeSizeInstanceName = + (ULONG)WDF_ALIGN_SIZE_UP(WnodeSizeInstanceName, sizeof (ULONG)); WnodeSizeDataBlock = MSFC_AdapterEvent_SIZE; // Size of data block. - size = WnodeSize + // Size of WMIEvent. - WnodeSizeInstanceName + - WnodeSizeDataBlock; + size = WnodeSize + // Size of WMIEvent. + WnodeSizeInstanceName + + WnodeSizeDataBlock; pWnode = ExAllocatePoolWithTag(NonPagedPoolNx, size, MP_TAG_GENERAL); - if (NULL != pWnode) { // Good? + if (NULL != pWnode) { RtlZeroMemory(pWnode, size); - // Fill out most of header. StorPort will set the ProviderId and TimeStamp in the header. + // Fill out most of header. StorPort will set the + // ProviderId and TimeStamp in the header. pWnode->WnodeHeader.BufferSize = size; pWnode->WnodeHeader.Version = 1; - RtlCopyMemory(&pWnode->WnodeHeader.Guid, &lclGuid, sizeof(lclGuid)); + RtlCopyMemory(&pWnode->WnodeHeader.Guid, &lclGuid, + sizeof (lclGuid)); pWnode->WnodeHeader.Flags = WNODE_FLAG_EVENT_ITEM | - WNODE_FLAG_SINGLE_INSTANCE; + WNODE_FLAG_SINGLE_INSTANCE; - // Say where to find instance name and the data block and what is the data block's size. + // Say where to find instance name and the data block + // and what is the data block's size. pWnode->OffsetInstanceName = WnodeSize; pWnode->DataBlockOffset = WnodeSize + WnodeSizeInstanceName; @@ -323,95 +367,99 @@ void // Copy the instance name. - size -= WnodeSize; // Length remaining and available. - status = WDF_WMI_BUFFER_APPEND_STRING( // Copy WCHAR string, preceded by its size. - WDF_PTR_ADD_OFFSET(pWnode, pWnode->OffsetInstanceName), - size, // Length available for copying. - &lclInstanceName, // Unicode string whose WCHAR buffer is to be copied. - &length // Variable to receive size needed. - ); + // Length remaining and available. + size -= WnodeSize; + // Copy WCHAR string, preceded by its size. + status = WDF_WMI_BUFFER_APPEND_STRING( + WDF_PTR_ADD_OFFSET(pWnode, pWnode->OffsetInstanceName), + size, + &lclInstanceName, + &length); - if (STATUS_SUCCESS != status) { // A problem? + if (STATUS_SUCCESS != status) { ASSERT(FALSE); } - pAdapterArr = // Point to data block. - WDF_PTR_ADD_OFFSET(pWnode, pWnode->DataBlockOffset); + pAdapterArr = + WDF_PTR_ADD_OFFSET(pWnode, pWnode->DataBlockOffset); // Copy event code and WWN. pAdapterArr->EventType = HBA_EVENT_ADAPTER_ADD; - RtlCopyMemory(pAdapterArr->PortWWN, myPortWWN, sizeof(myPortWWN)); + RtlCopyMemory(pAdapterArr->PortWWN, myPortWWN, + sizeof (myPortWWN)); // Ask StorPort to announce the event. StorPortNotification(WMIEvent, - pHBAExt, - pWnode, - 0xFF); // Notification pertains to an HBA. + pHBAExt, + pWnode, + 0xFF); // Notification pertains to an HBA. ExFreePoolWithTag(pWnode, MP_TAG_GENERAL); - } - else { + } else { } #endif } -/**************************************************************************************************/ -/* */ -/**************************************************************************************************/ void wzvol_HwReportLink(__in pHW_HBA_EXT pHBAExt) { dprintf("%s: entry\n", __func__); #if 1 - NTSTATUS status; + NTSTATUS status; PWNODE_SINGLE_INSTANCE pWnode; - PMSFC_LinkEvent pLinkEvent; - ULONG WnodeSize, - WnodeSizeInstanceName, - WnodeSizeDataBlock, - length, - size; - GUID lclGuid = MSFC_LinkEvent_GUID; - UNICODE_STRING lclInstanceName; - -#define RLIRBufferArraySize 0x10 // Define 16 entries in MSFC_LinkEvent.RLIRBuffer[]. - - UCHAR myAdapterWWN[8] = { 1, 2, 3, 4, 5, 6, 7, 8 }, - myRLIRBuffer[RLIRBufferArraySize] = { 10, 11, 12, 13, 14, 15, 16, 17, 20, 21, 22, 23, 24, 25, 26, 0xFF }; - - RtlInitUnicodeString(&lclInstanceName, InstName); // Set Unicode descriptor for instance name. - - WnodeSize = sizeof(WNODE_SINGLE_INSTANCE); - WnodeSizeInstanceName = sizeof(USHORT) + // Size of USHORT at beginning plus - lclInstanceName.Length; // size of instance name. - WnodeSizeInstanceName = // Round length up to multiple of 4 (if needed). - (ULONG)WDF_ALIGN_SIZE_UP(WnodeSizeInstanceName, sizeof(ULONG)); - WnodeSizeDataBlock = // Size of data. - FIELD_OFFSET(MSFC_LinkEvent, RLIRBuffer) + - sizeof(myRLIRBuffer); - - size = WnodeSize + // Size of WMIEvent. - WnodeSizeInstanceName + - WnodeSizeDataBlock; + PMSFC_LinkEvent pLinkEvent; + ULONG WnodeSize, + WnodeSizeInstanceName, + WnodeSizeDataBlock, + length, + size; + GUID lclGuid = MSFC_LinkEvent_GUID; + UNICODE_STRING lclInstanceName; + + // Define 16 entries in MSFC_LinkEvent.RLIRBuffer[]. +#define RLIRBufferArraySize 0x10 + + UCHAR myAdapterWWN[8] = { 1, 2, 3, 4, 5, 6, 7, 8 }; + UCHAR myRLIRBuffer[RLIRBufferArraySize] = + { 10, 11, 12, 13, 14, 15, 16, 17, 20, 21, 22, 23, + 24, 25, 26, 0xFF }; + + RtlInitUnicodeString(&lclInstanceName, InstName); + + WnodeSize = sizeof (WNODE_SINGLE_INSTANCE); + WnodeSizeInstanceName = sizeof (USHORT) + + lclInstanceName.Length; + WnodeSizeInstanceName = + (ULONG)WDF_ALIGN_SIZE_UP(WnodeSizeInstanceName, sizeof (ULONG)); + WnodeSizeDataBlock = + FIELD_OFFSET(MSFC_LinkEvent, RLIRBuffer) + + sizeof (myRLIRBuffer); + + size = WnodeSize + + WnodeSizeInstanceName + + WnodeSizeDataBlock; pWnode = ExAllocatePoolWithTag(NonPagedPoolNx, size, MP_TAG_GENERAL); - if (NULL != pWnode) { // Good? + if (NULL != pWnode) { RtlZeroMemory(pWnode, size); - // Fill out most of header. StorPort will set the ProviderId and TimeStamp in the header. + // Fill out most of header. StorPort will set the + // ProviderId and TimeStamp in the header. pWnode->WnodeHeader.BufferSize = size; pWnode->WnodeHeader.Version = 1; - RtlCopyMemory(&pWnode->WnodeHeader.Guid, &lclGuid, sizeof(lclGuid)); + RtlCopyMemory(&pWnode->WnodeHeader.Guid, &lclGuid, + sizeof (lclGuid)); pWnode->WnodeHeader.Flags = WNODE_FLAG_EVENT_ITEM | - WNODE_FLAG_SINGLE_INSTANCE; + WNODE_FLAG_SINGLE_INSTANCE; - // Say where to find instance name and the data block and what is the data block's size. + // Say where to find instance name and the data block + // and what is the data block's size. pWnode->OffsetInstanceName = WnodeSize; pWnode->DataBlockOffset = WnodeSize + WnodeSizeInstanceName; @@ -419,90 +467,89 @@ wzvol_HwReportLink(__in pHW_HBA_EXT pHBAExt) // Copy the instance name. - size -= WnodeSize; // Length remaining and available. - status = WDF_WMI_BUFFER_APPEND_STRING( // Copy WCHAR string, preceded by its size. - WDF_PTR_ADD_OFFSET(pWnode, pWnode->OffsetInstanceName), - size, // Length available for copying. - &lclInstanceName, // Unicode string whose WCHAR buffer is to be copied. - &length // Variable to receive size needed. - ); + size -= WnodeSize; + status = WDF_WMI_BUFFER_APPEND_STRING( + WDF_PTR_ADD_OFFSET(pWnode, pWnode->OffsetInstanceName), + size, + &lclInstanceName, + &length); - if (STATUS_SUCCESS != status) { // A problem? + if (STATUS_SUCCESS != status) { ASSERT(FALSE); } - pLinkEvent = // Point to data block. - WDF_PTR_ADD_OFFSET(pWnode, pWnode->DataBlockOffset); + pLinkEvent = + WDF_PTR_ADD_OFFSET(pWnode, pWnode->DataBlockOffset); // Copy event code, WWN, buffer size and buffer contents. pLinkEvent->EventType = HBA_EVENT_LINK_INCIDENT; - RtlCopyMemory(pLinkEvent->AdapterWWN, myAdapterWWN, sizeof(myAdapterWWN)); + RtlCopyMemory(pLinkEvent->AdapterWWN, myAdapterWWN, + sizeof (myAdapterWWN)); - pLinkEvent->RLIRBufferSize = sizeof(myRLIRBuffer); + pLinkEvent->RLIRBufferSize = sizeof (myRLIRBuffer); - RtlCopyMemory(pLinkEvent->RLIRBuffer, myRLIRBuffer, sizeof(myRLIRBuffer)); + RtlCopyMemory(pLinkEvent->RLIRBuffer, myRLIRBuffer, + sizeof (myRLIRBuffer)); StorPortNotification(WMIEvent, - pHBAExt, - pWnode, - 0xFF); // Notification pertains to an HBA. + pHBAExt, + pWnode, + 0xFF); ExFreePoolWithTag(pWnode, MP_TAG_GENERAL); - } - else { + } else { } #endif } -/**************************************************************************************************/ -/* */ -/**************************************************************************************************/ void wzvol_HwReportLog(__in pHW_HBA_EXT pHBAExt) { dprintf("%s: entry\n", __func__); #if 1 - NTSTATUS status; + NTSTATUS status; PWNODE_SINGLE_INSTANCE pWnode; - ULONG WnodeSize, - WnodeSizeInstanceName, - WnodeSizeDataBlock, - length, - size; - UNICODE_STRING lclInstanceName; - PIO_ERROR_LOG_PACKET pLogError; - - RtlInitUnicodeString(&lclInstanceName, InstName); // Set Unicode descriptor for instance name. - - WnodeSize = sizeof(WNODE_SINGLE_INSTANCE); - WnodeSizeInstanceName = sizeof(USHORT) + // Size of USHORT at beginning plus - lclInstanceName.Length; // size of instance name. - WnodeSizeInstanceName = // Round length up to multiple of 4 (if needed). - (ULONG)WDF_ALIGN_SIZE_UP(WnodeSizeInstanceName, sizeof(ULONG)); - WnodeSizeDataBlock = sizeof(IO_ERROR_LOG_PACKET); // Size of data. - - size = WnodeSize + // Size of WMIEvent. - WnodeSizeInstanceName + - WnodeSizeDataBlock; + ULONG WnodeSize, + WnodeSizeInstanceName, + WnodeSizeDataBlock, + length, + size; + UNICODE_STRING lclInstanceName; + PIO_ERROR_LOG_PACKET pLogError; + + RtlInitUnicodeString(&lclInstanceName, InstName); + + WnodeSize = sizeof (WNODE_SINGLE_INSTANCE); + WnodeSizeInstanceName = sizeof (USHORT) + + lclInstanceName.Length; + WnodeSizeInstanceName = + (ULONG)WDF_ALIGN_SIZE_UP(WnodeSizeInstanceName, sizeof (ULONG)); + WnodeSizeDataBlock = sizeof (IO_ERROR_LOG_PACKET); + + size = WnodeSize + + WnodeSizeInstanceName + + WnodeSizeDataBlock; pWnode = ExAllocatePoolWithTag(NonPagedPoolNx, size, MP_TAG_GENERAL); - if (NULL != pWnode) { // Good? + if (NULL != pWnode) { RtlZeroMemory(pWnode, size); - // Fill out most of header. StorPort will set the ProviderId and TimeStamp in the header. + // Fill out most of header. StorPort will set the + // ProviderId and TimeStamp in the header. pWnode->WnodeHeader.BufferSize = size; pWnode->WnodeHeader.Version = 1; pWnode->WnodeHeader.Flags = WNODE_FLAG_EVENT_ITEM | - WNODE_FLAG_LOG_WNODE; + WNODE_FLAG_LOG_WNODE; pWnode->WnodeHeader.HistoricalContext = 9; - // Say where to find instance name and the data block and what is the data block's size. + // Say where to find instance name and the data + // block and what is the data block's size. pWnode->OffsetInstanceName = WnodeSize; pWnode->DataBlockOffset = WnodeSize + WnodeSizeInstanceName; @@ -510,85 +557,75 @@ wzvol_HwReportLog(__in pHW_HBA_EXT pHBAExt) // Copy the instance name. - size -= WnodeSize; // Length remaining and available. - status = WDF_WMI_BUFFER_APPEND_STRING( // Copy WCHAR string, preceded by its size. - WDF_PTR_ADD_OFFSET(pWnode, pWnode->OffsetInstanceName), - size, // Length available for copying. - &lclInstanceName, // Unicode string whose WCHAR buffer is to be copied. - &length // Variable to receive size needed. - ); + size -= WnodeSize; + status = WDF_WMI_BUFFER_APPEND_STRING( + WDF_PTR_ADD_OFFSET(pWnode, pWnode->OffsetInstanceName), + size, + &lclInstanceName, + &length); - if (STATUS_SUCCESS != status) { // A problem? + if (STATUS_SUCCESS != status) { ASSERT(FALSE); } - pLogError = // Point to data block. - WDF_PTR_ADD_OFFSET(pWnode, pWnode->DataBlockOffset); + pLogError = + WDF_PTR_ADD_OFFSET(pWnode, pWnode->DataBlockOffset); pLogError->UniqueErrorValue = 0x40; pLogError->FinalStatus = 0x41; pLogError->ErrorCode = 0x42; StorPortNotification(WMIEvent, - pHBAExt, - pWnode, - 0xFF); // Notification pertains to an HBA. + pHBAExt, + pWnode, + 0xFF); ExFreePoolWithTag(pWnode, MP_TAG_GENERAL); - } - else { + } else { } #endif -} // End MpHwReportLog(). +} -/**************************************************************************************************/ -/* */ -/**************************************************************************************************/ BOOLEAN wzvol_HwResetBus( - __in pHW_HBA_EXT pHBAExt, // Adapter device-object extension from StorPort. - __in ULONG BusId - ) + __in pHW_HBA_EXT pHBAExt, + __in ULONG BusId) { UNREFERENCED_PARAMETER(pHBAExt); UNREFERENCED_PARAMETER(BusId); - // To do: At some future point, it may be worthwhile to ensure that any SRBs being handled be completed at once. - // Practically speaking, however, it seems that the only SRBs that would not be completed very quickly - // would be those handled by the worker thread. In the future, therefore, there might be a global flag - // set here to instruct the thread to complete outstanding I/Os as they appear; but a period for that - // happening would have to be devised (such completion shouldn't be unbounded). + // To do: At some future point, it may be worthwhile to ensure + // that any SRBs being handled be completed at once. Practically + // speaking, however, it seems that the only SRBs that would not + // be completed very quickly would be those handled by the worker + // thread. In the future, therefore, there might be a global flag + // set here to instruct the thread to complete outstanding I/Os + // as they appear; but a period for that happening would have to + // be devised (such completion shouldn't be unbounded). - return TRUE; -} // End MpHwResetBus(). + return (TRUE); +} -/**************************************************************************************************/ -/* */ -/**************************************************************************************************/ NTSTATUS wzvol_HandleRemoveDevice( - __in pHW_HBA_EXT pHBAExt,// Adapter device-object extension from StorPort. - __in PSCSI_PNP_REQUEST_BLOCK pSrb - ) + __in pHW_HBA_EXT pHBAExt, + __in PSCSI_PNP_REQUEST_BLOCK pSrb) { UNREFERENCED_PARAMETER(pHBAExt); pSrb->SrbStatus = SRB_STATUS_BAD_FUNCTION; - return STATUS_UNSUCCESSFUL; -} // End MpHandleRemoveDevice(). + return (STATUS_UNSUCCESSFUL); +} -/**************************************************************************************************/ -/* */ -/**************************************************************************************************/ NTSTATUS wzvol_HandleQueryCapabilities( - __in pHW_HBA_EXT pHBAExt,// Adapter device-object extension from StorPort. - __in PSCSI_PNP_REQUEST_BLOCK pSrb - ) + __in pHW_HBA_EXT pHBAExt, + __in PSCSI_PNP_REQUEST_BLOCK pSrb) { - NTSTATUS status = STATUS_SUCCESS; - PSTOR_DEVICE_CAPABILITIES pStorageCapabilities = (PSTOR_DEVICE_CAPABILITIES)pSrb->DataBuffer; + NTSTATUS status = STATUS_SUCCESS; + PSTOR_DEVICE_CAPABILITIES pStorageCapabilities = + (PSTOR_DEVICE_CAPABILITIES)pSrb->DataBuffer; UNREFERENCED_PARAMETER(pHBAExt); @@ -601,17 +638,13 @@ wzvol_HandleQueryCapabilities( pSrb->SrbStatus = SRB_STATUS_SUCCESS; - return status; -} // End MpHandleQueryCapabilities(). + return (status); +} -/**************************************************************************************************/ -/* */ -/**************************************************************************************************/ NTSTATUS wzvol_HwHandlePnP( - __in pHW_HBA_EXT pHBAExt, // Adapter device-object extension from StorPort. - __in PSCSI_PNP_REQUEST_BLOCK pSrb - ) + __in pHW_HBA_EXT pHBAExt, + __in PSCSI_PNP_REQUEST_BLOCK pSrb) { NTSTATUS status = STATUS_SUCCESS; dprintf("%s: entry\n", __func__); @@ -621,48 +654,42 @@ wzvol_HwHandlePnP( case StorRemoveDevice: status = wzvol_HandleRemoveDevice(pHBAExt, pSrb); - break; case StorQueryCapabilities: status = wzvol_HandleQueryCapabilities(pHBAExt, pSrb); - break; default: - pSrb->SrbStatus = SRB_STATUS_SUCCESS; // Do nothing. + pSrb->SrbStatus = SRB_STATUS_SUCCESS; } if (STATUS_SUCCESS != status) { } #endif - return status; + return (status); } -/**************************************************************************************************/ -/* */ -/**************************************************************************************************/ BOOLEAN wzvol_HwStartIo( - __in pHW_HBA_EXT pHBAExt, // Adapter device-object extension from StorPort. - __in __out PSCSI_REQUEST_BLOCK pSrb - ) + __in pHW_HBA_EXT pHBAExt, + __in __out PSCSI_REQUEST_BLOCK pSrb) { dprintf("%s: entry\n", __func__); #if 1 - UCHAR srbStatus = SRB_STATUS_INVALID_REQUEST; - BOOLEAN bFlag; - NTSTATUS status; - UCHAR Result = ResultDone; + UCHAR srbStatus = SRB_STATUS_INVALID_REQUEST; + BOOLEAN bFlag; + NTSTATUS status; + UCHAR Result = ResultDone; - dprintf( - "MpHwStartIo: SCSI Request Block = %!SRB!\n", - pSrb); + dprintf("MpHwStartIo: SCSI Request Block = %!SRB!\n", + pSrb); - _InterlockedExchangeAdd((volatile LONG *)&pHBAExt->SRBsSeen, 1); // Bump count of SRBs encountered. + _InterlockedExchangeAdd((volatile LONG *)&pHBAExt->SRBsSeen, 1); - // Next, if true, will cause StorPort to remove the associated LUNs if, for example, devmgmt.msc is asked "scan for hardware changes." + // Next, if true, will cause StorPort to remove the associated LUNs + // if, for example, devmgmt.msc is asked "scan for hardware changes." switch (pSrb->Function) { @@ -672,9 +699,11 @@ wzvol_HwStartIo( break; case SRB_FUNCTION_WMI: - _InterlockedExchangeAdd((volatile LONG *)&pHBAExt->WMISRBsSeen, 1); + _InterlockedExchangeAdd((volatile LONG *)&pHBAExt->WMISRBsSeen, + 1); bFlag = HandleWmiSrb(pHBAExt, (PSCSI_WMI_REQUEST_BLOCK)pSrb); - srbStatus = TRUE == bFlag ? SRB_STATUS_SUCCESS : SRB_STATUS_INVALID_REQUEST; + srbStatus = TRUE == bFlag ? SRB_STATUS_SUCCESS : + SRB_STATUS_INVALID_REQUEST; break; case SRB_FUNCTION_RESET_BUS: @@ -686,20 +715,26 @@ wzvol_HwStartIo( PLIST_ENTRY pNextEntry; PHW_SRB_EXTENSION pSrbExt; KeAcquireSpinLock(&pHBAExt->pwzvolDrvObj->SrbExtLock, &oldIrql); - for (pNextEntry = pHBAExt->pwzvolDrvObj->ListSrbExt.Flink;pNextEntry != &pHBAExt->pwzvolDrvObj->ListSrbExt; pNextEntry = pNextEntry->Flink) - { - pSrbExt = CONTAINING_RECORD(pNextEntry, HW_SRB_EXTENSION, QueuedForProcessing); + for (pNextEntry = pHBAExt->pwzvolDrvObj->ListSrbExt.Flink; + pNextEntry != &pHBAExt->pwzvolDrvObj->ListSrbExt; + pNextEntry = pNextEntry->Flink) { + pSrbExt = CONTAINING_RECORD(pNextEntry, + HW_SRB_EXTENSION, QueuedForProcessing); if ((pSrbExt->pSrbBackPtr->PathId == pSrb->PathId) && - (pSrb->Function == SRB_FUNCTION_RESET_BUS ? TRUE : pSrbExt->pSrbBackPtr->TargetId == pSrb->TargetId) && - (pSrb->Function == SRB_FUNCTION_RESET_BUS || pSrb->Function == SRB_FUNCTION_RESET_DEVICE ? TRUE : pSrbExt->pSrbBackPtr->Lun == pSrb->Lun)) - pSrbExt->Cancelled = 1; + (pSrb->Function == SRB_FUNCTION_RESET_BUS ? TRUE : + pSrbExt->pSrbBackPtr->TargetId == pSrb->TargetId) && + (pSrb->Function == SRB_FUNCTION_RESET_BUS || + pSrb->Function == SRB_FUNCTION_RESET_DEVICE ? TRUE : + pSrbExt->pSrbBackPtr->Lun == pSrb->Lun)) + pSrbExt->Cancelled = 1; } KeReleaseSpinLock(&pHBAExt->pwzvolDrvObj->SrbExtLock, oldIrql); srbStatus = SRB_STATUS_SUCCESS; } break; case SRB_FUNCTION_PNP: - status = wzvol_HwHandlePnP(pHBAExt, (PSCSI_PNP_REQUEST_BLOCK)pSrb); + status = wzvol_HwHandlePnP(pHBAExt, + (PSCSI_PNP_REQUEST_BLOCK)pSrb); srbStatus = pSrb->SrbStatus; break; @@ -717,39 +752,38 @@ wzvol_HwStartIo( break; default: - dprintf("MpHwStartIo: Unknown Srb Function = 0x%x\n", pSrb->Function); + dprintf("MpHwStartIo: Unknown Srb Function = 0x%x\n", + pSrb->Function); srbStatus = SRB_STATUS_INVALID_REQUEST; break; } // switch (pSrb->Function) - if (ResultDone == Result) { // Complete now? + if (ResultDone == Result) { pSrb->SrbStatus = srbStatus; - // Note: A miniport with real hardware would not always be calling RequestComplete from HwStorStartIo. Rather, - // the miniport would typically be doing real I/O and would call RequestComplete only at the end of that - // real I/O, in its HwStorInterrupt or in a DPC routine. + // Note: A miniport with real hardware would not always + // be calling RequestComplete from HwStorStartIo. Rather, + // the miniport would typically be doing real I/O and would + // call RequestComplete only at the end of that + // real I/O, in its HwStorInterrupt or in a DPC routine. StorPortNotification(RequestComplete, pHBAExt, pSrb); } dprintf("MpHwStartIo - OUT\n"); #endif - return TRUE; + return (TRUE); } -/**************************************************************************************************/ -/* */ -/**************************************************************************************************/ SCSI_ADAPTER_CONTROL_STATUS wzvol_HwAdapterControl( - __in pHW_HBA_EXT pHBAExt, // Adapter device-object extension from StorPort. - __in SCSI_ADAPTER_CONTROL_TYPE ControlType, - __in PVOID pParameters - ) + __in pHW_HBA_EXT pHBAExt, + __in SCSI_ADAPTER_CONTROL_TYPE ControlType, + __in PVOID pParameters) { PSCSI_SUPPORTED_CONTROL_TYPE_LIST pCtlTypList; - ULONG i; + ULONG i; dprintf("MpHwAdapterControl: ControlType = %d\n", ControlType); @@ -766,9 +800,9 @@ wzvol_HwAdapterControl( // making sure not to go past the MaxControlType for (i = 0; i < pCtlTypList->MaxControlType; i++) if (i == ScsiQuerySupportedControlTypes || - i == ScsiStopAdapter || i == ScsiRestartAdapter || - i == ScsiSetBootConfig || i == ScsiSetRunningConfig) - { + i == ScsiStopAdapter || i == ScsiRestartAdapter || + i == ScsiSetBootConfig || + i == ScsiSetRunningConfig) { pCtlTypList->SupportedTypeList[i] = TRUE; } break; @@ -806,70 +840,65 @@ wzvol_HwAdapterControl( dprintf("MpHwAdapterControl - OUT\n"); - return ScsiAdapterControlSuccess; + return (ScsiAdapterControlSuccess); } -/**************************************************************************************************/ -/* */ -/**************************************************************************************************/ -VOID -wzvol_StopAdapter(__in pHW_HBA_EXT pHBAExt) // Adapter device-object extension from StorPort. +void +wzvol_StopAdapter(__in pHW_HBA_EXT pHBAExt) { - pHW_LU_EXTENSION pLUExt, - pLUExt2; - PLIST_ENTRY pNextEntry, - pNextEntry2; - pwzvolDriverInfo pwzvolDrvInfo = pHBAExt->pwzvolDrvObj; - pHW_LU_EXTENSION_MPIO pLUMPIOExt = NULL; // Prevent C4701 warning. + pHW_LU_EXTENSION pLUExt, pLUExt2; + PLIST_ENTRY pNextEntry, pNextEntry2; + pwzvolDriverInfo pwzvolDrvInfo = pHBAExt->pwzvolDrvObj; + pHW_LU_EXTENSION_MPIO pLUMPIOExt = NULL; #if defined(_AMD64_) - KLOCK_QUEUE_HANDLE LockHandle; + KLOCK_QUEUE_HANDLE LockHandle; #else - KIRQL SaveIrql; + KIRQL SaveIrql; #endif dprintf("%s: entry\n", __func__); // Clean up the "disk buffers." - for ( // Go through linked list of LUN extensions for this HBA. - pNextEntry = pHBAExt->LUList.Flink; - pNextEntry != &pHBAExt->LUList; - pNextEntry = pNextEntry->Flink - ) { + for (pNextEntry = pHBAExt->LUList.Flink; + pNextEntry != &pHBAExt->LUList; + pNextEntry = pNextEntry->Flink) { pLUExt = CONTAINING_RECORD(pNextEntry, HW_LU_EXTENSION, List); - if (pwzvolDrvInfo->wzvolRegInfo.bCombineVirtDisks) {// MPIO support? + if (pwzvolDrvInfo->wzvolRegInfo.bCombineVirtDisks) { pLUMPIOExt = pLUExt->pLUMPIOExt; - if (!pLUMPIOExt) { // No MPIO extension? + if (!pLUMPIOExt) { break; } #if defined(_AMD64_) - KeAcquireInStackQueuedSpinLock(&pLUMPIOExt->LUExtMPIOLock, &LockHandle); + KeAcquireInStackQueuedSpinLock( + &pLUMPIOExt->LUExtMPIOLock, + &LockHandle); #else - KeAcquireSpinLock(&pLUMPIOExt->LUExtMPIOLock, &SaveIrql); + KeAcquireSpinLock(&pLUMPIOExt->LUExtMPIOLock, + &SaveIrql); #endif - for ( // Go through linked list of LUN extensions for the MPIO collector object (HW_LU_EXTENSION_MPIO). - pNextEntry2 = pLUMPIOExt->LUExtList.Flink; - pNextEntry2 != &pLUMPIOExt->LUExtList; - pNextEntry2 = pNextEntry2->Flink - ) { - pLUExt2 = CONTAINING_RECORD(pNextEntry2, HW_LU_EXTENSION, MPIOList); + for (pNextEntry2 = pLUMPIOExt->LUExtList.Flink; + pNextEntry2 != &pLUMPIOExt->LUExtList; + pNextEntry2 = pNextEntry2->Flink) { + pLUExt2 = CONTAINING_RECORD(pNextEntry2, + HW_LU_EXTENSION, MPIOList); - if (pLUExt2 == pLUExt) { // Pointing to same LUN extension? + if (pLUExt2 == pLUExt) { break; } } - if (pNextEntry2 != &pLUMPIOExt->LUExtList) {// Found it? - RemoveEntryList(pNextEntry2); // Remove LU extension from MPIO collector object. + if (pNextEntry2 != &pLUMPIOExt->LUExtList) { + RemoveEntryList(pNextEntry2); pLUMPIOExt->NbrRealLUNs--; - if (0 == pLUMPIOExt->NbrRealLUNs) { // Was this the last LUN extension in the MPIO collector object? + if (0 == pLUMPIOExt->NbrRealLUNs) { ExFreePool(pLUExt->pDiskBuf); } } @@ -879,38 +908,35 @@ wzvol_StopAdapter(__in pHW_HBA_EXT pHBAExt) // Adapter device-obje #else KeReleaseSpinLock(&pLUMPIOExt->LUExtMPIOLock, SaveIrql); #endif - } - else { + } else { ExFreePool(pLUExt->pDiskBuf); } } // Clean up the linked list of MPIO collector objects, if needed. - if (pwzvolDrvInfo->wzvolRegInfo.bCombineVirtDisks) { // MPIO support? + if (pwzvolDrvInfo->wzvolRegInfo.bCombineVirtDisks) { #if defined(_AMD64_) - KeAcquireInStackQueuedSpinLock( // Serialize the linked list of MPIO collector objects. - &pwzvolDrvInfo->MPIOExtLock, &LockHandle); + KeAcquireInStackQueuedSpinLock( + &pwzvolDrvInfo->MPIOExtLock, &LockHandle); #else KeAcquireSpinLock(&pwzvolDrvInfo->MPIOExtLock, &SaveIrql); #endif - for ( // Go through linked list of MPIO collector objects for this miniport driver. - pNextEntry = pwzvolDrvInfo->ListMPIOExt.Flink; - pNextEntry != &pwzvolDrvInfo->ListMPIOExt; - pNextEntry = pNextEntry2 - ) { - pLUMPIOExt = CONTAINING_RECORD(pNextEntry, HW_LU_EXTENSION_MPIO, List); + for (pNextEntry = pwzvolDrvInfo->ListMPIOExt.Flink; + pNextEntry != &pwzvolDrvInfo->ListMPIOExt; + pNextEntry = pNextEntry2) { + pLUMPIOExt = CONTAINING_RECORD(pNextEntry, + HW_LU_EXTENSION_MPIO, List); - if (!pLUMPIOExt) { // No MPIO extension? + if (!pLUMPIOExt) { break; } - pNextEntry2 = pNextEntry->Flink; // Save forward pointer in case MPIO collector object containing forward pointer is freed. - - if (0 == pLUMPIOExt->NbrRealLUNs) { // No real LUNs (HW_LU_EXTENSION) left? - RemoveEntryList(pNextEntry); // Remove MPIO collector object from miniport driver object. + pNextEntry2 = pNextEntry->Flink; + if (0 == pLUMPIOExt->NbrRealLUNs) { + RemoveEntryList(pNextEntry); ExFreePoolWithTag(pLUMPIOExt, MP_TAG_GENERAL); } } @@ -921,77 +947,53 @@ wzvol_StopAdapter(__in pHW_HBA_EXT pHBAExt) // Adapter device-obje KeReleaseSpinLock(&pwzvolDrvInfo->MPIOExtLock, SaveIrql); #endif } - - - //done: - return; } -/**************************************************************************************************/ -/* */ -/* MPTracingInit. */ -/* */ -/**************************************************************************************************/ -VOID +void wzvol_TracingInit( - __in PVOID pArg1, - __in PVOID pArg2 - ) + __in PVOID pArg1, + __in PVOID pArg2) { // WPP_INIT_TRACING(pArg1, pArg2); -} // End MPTracingInit(). - -/**************************************************************************************************/ -/* */ -/* MPTracingCleanUp. */ -/* */ -/* This is called when the driver is being unloaded. */ -/* */ -/**************************************************************************************************/ +} -VOID +void wzvol_TracingCleanup(__in PVOID pArg1) { #if 1 dprintf("MPTracingCleanUp entered\n"); - //WPP_CLEANUP(pArg1); + // WPP_CLEANUP(pArg1); #endif } -/**************************************************************************************************/ -/* */ -/* MpHwFreeAdapterResources. */ -/* */ -/**************************************************************************************************/ -VOID +void wzvol_HwFreeAdapterResources(__in pHW_HBA_EXT pHBAExt) { #if 1 - PLIST_ENTRY pNextEntry; - pHW_HBA_EXT pLclHBAExt; + PLIST_ENTRY pNextEntry; + pHW_HBA_EXT pLclHBAExt; #if defined(_AMD64_) - KLOCK_QUEUE_HANDLE LockHandle; + KLOCK_QUEUE_HANDLE LockHandle; #else - KIRQL SaveIrql; + KIRQL SaveIrql; #endif dprintf("MpHwFreeAdapterResources entered, pHBAExt = 0x%p\n", pHBAExt); #if defined(_AMD64_) - KeAcquireInStackQueuedSpinLock(&pHBAExt->pwzvolDrvObj->DrvInfoLock, &LockHandle); + KeAcquireInStackQueuedSpinLock(&pHBAExt->pwzvolDrvObj->DrvInfoLock, + &LockHandle); #else KeAcquireSpinLock(&pHBAExt->pwzvolDrvObj->DrvInfoLock, &SaveIrql); #endif - for ( // Go through linked list of HBA extensions. - pNextEntry = pHBAExt->pwzvolDrvObj->ListMPHBAObj.Flink; - pNextEntry != &pHBAExt->pwzvolDrvObj->ListMPHBAObj; - pNextEntry = pNextEntry->Flink - ) { + for (pNextEntry = pHBAExt->pwzvolDrvObj->ListMPHBAObj.Flink; + pNextEntry != &pHBAExt->pwzvolDrvObj->ListMPHBAObj; + pNextEntry = pNextEntry->Flink) { pLclHBAExt = CONTAINING_RECORD(pNextEntry, HW_HBA_EXT, List); - if (pLclHBAExt == pHBAExt) { // Is this entry the same as pHBAExt? + if (pLclHBAExt == pHBAExt) { RemoveEntryList(pNextEntry); pHBAExt->pwzvolDrvObj->DrvInfoNbrMPHBAObj--; break; @@ -1010,22 +1012,17 @@ wzvol_HwFreeAdapterResources(__in pHW_HBA_EXT pHBAExt) STOR_HBAExt = NULL; } -/**************************************************************************************************/ -/* */ -/* MpCompleteIrp. */ -/* */ -/**************************************************************************************************/ -VOID +void wzvol_CompleteIrp( - __in pHW_HBA_EXT pHBAExt, // Adapter device-object extension from StorPort. - __in PIRP pIrp - ) + __in pHW_HBA_EXT pHBAExt, + __in PIRP pIrp) { dprintf("MpCompleteIrp entered\n"); if (NULL != pIrp) { NTSTATUS Status; - PIO_STACK_LOCATION pIrpStack = IoGetCurrentIrpStackLocation(pIrp); + PIO_STACK_LOCATION pIrpStack = + IoGetCurrentIrpStackLocation(pIrp); switch (pIrpStack->Parameters.DeviceIoControl.IoControlCode) { case IOCTL_MINIPORT_PROCESS_SERVICE_IRP: @@ -1038,27 +1035,20 @@ wzvol_CompleteIrp( pIrp->IoStatus.Status = Status; if (NT_SUCCESS(Status)) - pIrp->IoStatus.Information = pIrpStack->Parameters.DeviceIoControl.OutputBufferLength; + pIrp->IoStatus.Information = + pIrpStack-> + Parameters.DeviceIoControl.OutputBufferLength; else pIrp->IoStatus.Information = 0; StorPortCompleteServiceIrp(pHBAExt, pIrp); } -} - -/**************************************************************************************************/ -/* */ -/* MpQueueServiceIrp. */ -/* */ -/* If there is already an IRP queued, it will be dequeued (and then completed) to make way for */ -/* the IRP supplied here. */ -/* */ -/**************************************************************************************************/ -VOID +} + +void wzvol_QueueServiceIrp( - __in pHW_HBA_EXT pHBAExt, // Adapter device-object extension from StorPort. - __in PIRP pIrp // IRP pointer to be queued. - ) + __in pHW_HBA_EXT pHBAExt, + __in PIRP pIrp) { #if 1 @@ -1067,22 +1057,16 @@ wzvol_QueueServiceIrp( dprintf("MpQueueServiceIrp entered\n"); pOldIrp = InterlockedExchangePointer(&pHBAExt->pReverseCallIrp, pIrp); - if (NULL != pOldIrp) { // Found an IRP already queued? - wzvol_CompleteIrp(pHBAExt, pOldIrp); // Complete it. + if (NULL != pOldIrp) { + wzvol_CompleteIrp(pHBAExt, pOldIrp); } #endif -} // End MpQueueServiceIrp(). - -/**************************************************************************************************/ -/* */ -/* MpProcServReq. */ -/* */ -/**************************************************************************************************/ -VOID +} + +void wzvol_ProcServReq( - __in pHW_HBA_EXT pHBAExt, // Adapter device-object extension from StorPort. - __in PIRP pIrp // IRP pointer received. - ) + __in pHW_HBA_EXT pHBAExt, + __in PIRP pIrp) { #if 1 @@ -1090,15 +1074,10 @@ wzvol_ProcServReq( wzvol_QueueServiceIrp(pHBAExt, pIrp); #endif -} // End MpProcServReq(). - -/**************************************************************************************************/ -/* */ -/* MpCompServReq. */ -/* */ -/**************************************************************************************************/ -VOID -wzvol_CompServReq(__in pHW_HBA_EXT pHBAExt) // Adapter device-object extension from StorPort. +} + +void +wzvol_CompServReq(__in pHW_HBA_EXT pHBAExt) { #if 1 @@ -1106,12 +1085,12 @@ wzvol_CompServReq(__in pHW_HBA_EXT pHBAExt) // Adapter device-obje wzvol_QueueServiceIrp(pHBAExt, NULL); #endif -} // End MpCompServReq(). +} -void wzvol_announce_buschange(void) +void +wzvol_announce_buschange(void) { dprintf("%s: \n", __func__); if (STOR_HBAExt != NULL) StorPortNotification(BusChangeDetected, STOR_HBAExt, 0); } - diff --git a/module/os/windows/zfs/zfs_windows_zvol_scsi.c b/module/os/windows/zfs/zfs_windows_zvol_scsi.c index 03b84c493ee..a6d10ad84d5 100644 --- a/module/os/windows/zfs/zfs_windows_zvol_scsi.c +++ b/module/os/windows/zfs/zfs_windows_zvol_scsi.c @@ -1,60 +1,53 @@ -/****************************** Module Header ******************************\ -* Module Name: scsi.c -* Project: CppWDKStorPortVirtualMiniport -* -* Copyright (c) Microsoft Corporation. -* -* a. ScsiExecuteMain() -* Handles SCSI SRBs with opcodes needed to support file system operations by -* calling subroutines. Fails SRBs with other opcodes. -* Note: In a real-world virtual miniport, it may be necessary to handle other opcodes. -* -* b. ScsiOpInquiry() -* Handles Inquiry, including creating a new LUN as needed. -* -* c. ScsiOpVPD() -* Handles Vital Product Data. -* -* d. ScsiOpRead() -* Beginning of a SCSI Read operation. -* -* e. ScsiOpWrite() -* Beginning of a SCSI Write operation. -* -* f. ScsiReadWriteSetup() -* Sets up a work element for SCSI Read or Write and enqueues the element. -* -* g. ScsiOpReportLuns() -* Handles Report LUNs. -* -* -* This source is subject to the Microsoft Public License. -* See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL. -* All other rights reserved. -* -* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, -* EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. -\***************************************************************************/ +/* + * Module Name: scsi.c + * Project: CppWDKStorPortVirtualMiniport + * + * Copyright (c) Microsoft Corporation. + * + * a. ScsiExecuteMain() + * Handles SCSI SRBs with opcodes needed to support file system operations by + * calling subroutines. Fails SRBs with other opcodes. + * Note: In a real-world virtual miniport, it may be necessary to handle + * other opcodes. + * + * b. ScsiOpInquiry() + * Handles Inquiry, including creating a new LUN as needed. + * + * c. ScsiOpVPD() + * Handles Vital Product Data. + * + * d. ScsiOpRead() + * Beginning of a SCSI Read operation. + * + * e. ScsiOpWrite() + * Beginning of a SCSI Write operation. + * + * f. ScsiReadWriteSetup() + * Sets up a work element for SCSI Read or Write and enqueues the element. + * + * g. ScsiOpReportLuns() + * Handles Report LUNs. + * + * + * This source is subject to the Microsoft Public License. + * See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL. + * All other rights reserved. + * + * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, + * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. + */ #include #include #include -//#include -//#include -//#include -//#include -//#include #include -//#include #pragma warning(push) -#pragma warning(disable : 4204) /* Prevent C4204 messages from stortrce.h. */ +#pragma warning(disable : 4204) #include #pragma warning(pop) -//#include "trace.h" -//#include "scsi.tmh" #include #include #include @@ -63,371 +56,418 @@ #include #include -// Verbose SCSI output -//#undef dprintf -//#define dprintf - /* - * We have a list of ZVOLs, and we receive incoming (Target, Lun) requests that needs to be mapped - * to the correct "zv" ptr. + * We have a list of ZVOLs, and we receive incoming (Target, Lun) + * requests that needs to be mapped to the correct "zv" ptr. * - * ssv-18807: fixed the race condition in the zvol destroy processing by adding remove lock logic - * to ensure no new I/O can be processed from the front end (StorPort) and all outstanding host I/Os - * have left the pipeline. + * ssv-18807: fixed the race condition in the zvol destroy processing + * by adding remove lock logic to ensure no new I/O can be processed + * from the front end (StorPort) and all outstanding host I/Os have + * left the pipeline. * - * The zv control block starts to get protected in wzvol_assign_targetid() and this until wzvol_clear_targetid() - * is called. - * - * Once wzvol_find_target(t,l) returns a valid pointer to the zv, that zv is protected via an extra - * reference on its remove lock so it can't be freed unless all references on it are cleared. - * It is the caller's responsibility to clear the extra reference it got by calling wzvol_unlock_target(zv). + * The zv control block starts to get protected in wzvol_assign_targetid() + * and this until wzvol_clear_targetid() is called. * - * wzvol_find_target(t,l) will take an extra reference each time its called so each of those will need their - * wzvol_unlock_target(zv) counterpart call. + * Once wzvol_find_target(t,l) returns a valid pointer to the zv, + * that zv is protected via an extra reference on its remove lock so + * it can't be freed unless all references on it are cleared. + * It is the caller's responsibility to clear the extra reference it got + * by calling wzvol_unlock_target(zv). * - * The wzvol_lock_target(zv) call is commented out because not used yet but its purpose is for when nested - * extra references need to be taken on the zv after wzvol_find_target(t,l) was called. That can be useful - * for when asynchronous processing (queueing) involving the zv control block need to make sure that zv - * stays allocated. + * wzvol_find_target(t,l) will take an extra reference each time its + * called so each of those will need their wzvol_unlock_target(zv) + * counterpart call. * - * When the zvol is destroyed the wzvol_clear_targetid(t,l,zv) will actively wait for all references to - * be released and no new one can be taken. + * The wzvol_lock_target(zv) call is commented out because not used yet + * but its purpose is for when nested extra references need to be taken + * on the zv after wzvol_find_target(t,l) was called. That can be useful + * for when asynchronous processing (queueing) involving the zv control + * block need to make sure that zv stays allocated. * - * programming notes: the remove lock must be dynamically allocated because it cannot be reinitialized. An - * interlocked refcnt variable is also necessary to protect the remove lock control block's allocation. - * when the refcnt reaches 0 it is safe to free the remove lock cb. + * When the zvol is destroyed the wzvol_clear_targetid(t,l,zv) will + * actively wait for all references to be released and no new one can + * be taken. + * + * programming notes: the remove lock must be dynamically allocated + * because it cannot be reinitialized. An interlocked refcnt variable + * is also necessary to protect the remove lock control block's allocation. + * when the refcnt reaches 0 it is safe to free the remove lock cb. */ extern wzvolDriverInfo STOR_wzvolDriverInfo; -inline int resolveArrayIndex(int t, int l, int nbL) { return (t * nbL) + l; } -static inline void wzvol_decref_target(wzvolContext* zvc) +inline int +resolveArrayIndex(int t, int l, int nbL) +{ + return ((t * nbL) + l); +} + +static inline void +wzvol_decref_target(wzvolContext* zvc) { if (atomic_dec_64_nv(&zvc->refCnt) == 0) { PIO_REMOVE_LOCK pIoRemLock = zvc->pIoRemLock; ASSERT(pIoRemLock != NULL); - // when refCnt is 0 we can free the remove lock block. All IoReleaseRemoveLock have been called. + // when refCnt is 0 we can free the remove lock block. + // All IoReleaseRemoveLock have been called. atomic_cas_ptr(&zvc->pIoRemLock, pIoRemLock, NULL); - kmem_free(pIoRemLock, sizeof(*pIoRemLock)); + kmem_free(pIoRemLock, sizeof (*pIoRemLock)); } } -/* not used now but left for completeness in case we need to have an extra reference after calling find_targetid */ -static inline BOOLEAN wzvol_lock_target(zvol_state_t* zv) +/* + * not used now but left for completeness in case we need to have + * an extra reference after calling find_targetid + */ +static inline BOOLEAN +wzvol_lock_target(zvol_state_t *zv) { - wzvolContext* zvc = (pwzvolContext)zv->zv_zso->zso_target_context; + wzvolContext *zvc = (pwzvolContext)zv->zv_zso->zso_target_context; if (zvc) { if (atomic_inc_64_nv(&zvc->refCnt) > 1) { - // safe to access the remove lock. Make sure we are on the same zv. + // safe to access the remove lock. + // Make sure we are on the same zv. if (zvc->zv == zv) { - if (STATUS_SUCCESS == IoAcquireRemoveLock(zvc->pIoRemLock, zv)) - return TRUE; + if (STATUS_SUCCESS == + IoAcquireRemoveLock(zvc->pIoRemLock, zv)) + return (TRUE); else - wzvol_decref_target(zvc); // we are in the process of clearing the t-l - } - else - wzvol_decref_target(zvc); // another zv is using this entry. - } - else - atomic_dec_64_nv(&zvc->refCnt); // we are in the process of clearing the t-l + wzvol_decref_target(zvc); + } else + wzvol_decref_target(zvc); + } else + atomic_dec_64_nv(&zvc->refCnt); } - - return FALSE; + return (FALSE); } -static inline void wzvol_unlock_target(zvol_state_t *zv) -{ + +static inline void +wzvol_unlock_target(zvol_state_t *zv) +{ wzvolContext* zvc = (pwzvolContext)zv->zv_zso->zso_target_context; - IoReleaseRemoveLock(zvc->pIoRemLock, zv); + IoReleaseRemoveLock(zvc->pIoRemLock, zv); wzvol_decref_target(zvc); } -int wzvol_assign_targetid(zvol_state_t *zv) +int +wzvol_assign_targetid(zvol_state_t *zv) { wzvolContext* zv_targets = STOR_wzvolDriverInfo.zvContextArray; ASSERT(zv->zv_zso->zso_target_context == NULL); - PIO_REMOVE_LOCK pIoRemLock = kmem_zalloc(sizeof(*pIoRemLock), KM_SLEEP); + PIO_REMOVE_LOCK pIoRemLock = kmem_zalloc(sizeof (*pIoRemLock), + KM_SLEEP); if (!pIoRemLock) { dprintf("ZFS: Unable to assign targetid - out of memory.\n"); ASSERT("Unable to assign targetid - out of memory."); - return 0; + return (0); } + IoInitializeRemoveLock(pIoRemLock, 'KLRZ', 0, 0); + if (STATUS_SUCCESS != IoAcquireRemoveLock(pIoRemLock, zv)) { - dprintf("ZFS: Unable to assign targetid - can't acquire the remlock.\n"); - ASSERT("Unable to assign targetid - can't acquire the remlock."); - } - else { - for (uint8_t l = 0; l < STOR_wzvolDriverInfo.MaximumNumberOfLogicalUnits; l++) { - for (uint8_t t = 0; t < STOR_wzvolDriverInfo.MaximumNumberOfTargets; t++) { - int zvidx = resolveArrayIndex(t, l, STOR_wzvolDriverInfo.MaximumNumberOfLogicalUnits); - if (zv_targets[zvidx].zv == NULL && zv_targets[zvidx].pIoRemLock == NULL) { - if (atomic_inc_64_nv(&zv_targets[zvidx].refCnt) == 1) { - // brand new entry - got it. - ASSERT(zv_targets[zvidx].pIoRemLock == NULL); + dprintf("ZFS: Unable to assign targetid - can't acquire " + "the remlock.\n"); + ASSERT("Unable to assign targetid - can't acquire remlock."); + } else { + for (uint8_t l = 0; + l < STOR_wzvolDriverInfo.MaximumNumberOfLogicalUnits; + l++) { + for (uint8_t t = 0; + t < STOR_wzvolDriverInfo.MaximumNumberOfTargets; + t++) { + int zvidx = resolveArrayIndex(t, l, + STOR_wzvolDriverInfo. + MaximumNumberOfLogicalUnits); + + if (zv_targets[zvidx].zv == NULL && + zv_targets[zvidx].pIoRemLock == NULL) { + if (atomic_inc_64_nv( + &zv_targets[zvidx].refCnt) == 1) { + // brand new entry - got it. + ASSERT( + zv_targets[zvidx].pIoRemLock + == NULL); zv->zv_zso->zso_target_id = t; zv->zv_zso->zso_lun_id = l; - zv->zv_zso->zso_target_context = &zv_targets[zvidx]; - zv_targets[zvidx].pIoRemLock = pIoRemLock; - atomic_cas_ptr(&zv_targets[zvidx].zv, NULL, zv); // zv is now searchable - return 1; + zv->zv_zso->zso_target_context = + &zv_targets[zvidx]; + zv_targets[zvidx].pIoRemLock = + pIoRemLock; + atomic_cas_ptr( + &zv_targets[zvidx].zv, + NULL, zv); + // zv is now searchable + return (1); + } else { + // assign_targetid collision + // (very rare) + wzvol_decref_target( + &zv_targets[zvidx]); } - else { // assign_targetid collision (very rare) - wzvol_decref_target(&zv_targets[zvidx]); - } } } } - IoReleaseRemoveLock(pIoRemLock, zv); // housekeeping. it will be freed next. + IoReleaseRemoveLock(pIoRemLock, zv); } - kmem_free(pIoRemLock, sizeof(*pIoRemLock)); + kmem_free(pIoRemLock, sizeof (*pIoRemLock)); dprintf("ZFS: Unable to assign targetid - out of room.\n"); ASSERT("Unable to assign targetid - out of room."); - return 0; + return (0); } -/* note: find_target will lock the zv's remove lock. caller is responsible to unlock_target - if a non-NULL zv pointer is returned -*/ -static inline zvol_state_t *wzvol_find_target(uint8_t targetid, uint8_t lun) +/* + * note: find_target will lock the zv's remove lock. caller + * is responsible to unlock_target if a non-NULL zv pointer is returned + */ +static inline zvol_state_t * +wzvol_find_target(uint8_t targetid, uint8_t lun) { - wzvolContext* zv_targets = STOR_wzvolDriverInfo.zvContextArray; + wzvolContext *zv_targets = STOR_wzvolDriverInfo.zvContextArray; ASSERT(targetid < STOR_wzvolDriverInfo.MaximumNumberOfTargets); ASSERT(lun < STOR_wzvolDriverInfo.MaximumNumberOfLogicalUnits); - if (targetid < STOR_wzvolDriverInfo.MaximumNumberOfTargets && lun < STOR_wzvolDriverInfo.MaximumNumberOfLogicalUnits) { - int zvidx = resolveArrayIndex(targetid, lun, STOR_wzvolDriverInfo.MaximumNumberOfLogicalUnits); + if (targetid < STOR_wzvolDriverInfo.MaximumNumberOfTargets && + lun < STOR_wzvolDriverInfo.MaximumNumberOfLogicalUnits) { + int zvidx = resolveArrayIndex(targetid, lun, + STOR_wzvolDriverInfo.MaximumNumberOfLogicalUnits); zvol_state_t *zv = zv_targets[zvidx].zv; if (zv) { - if (atomic_inc_64_nv(&zv_targets[zvidx].refCnt) > 1) { + if (atomic_inc_64_nv(&zv_targets[zvidx].refCnt) > 1) { // safe to access the remove lock - if (STATUS_SUCCESS == IoAcquireRemoveLock(zv_targets[zvidx].pIoRemLock, zv)) - return (zvol_state_t*)zv_targets[zvidx].zv; + if (STATUS_SUCCESS == + IoAcquireRemoveLock( + zv_targets[zvidx].pIoRemLock, + zv)) + return ((zvol_state_t *) + zv_targets[zvidx].zv); else - wzvol_decref_target(&zv_targets[zvidx]); // we are in the process of clearing the t-l - } - else - atomic_dec_64_nv(&zv_targets[zvidx].refCnt); // we are in the process of clearing the t-l + wzvol_decref_target(&zv_targets[zvidx]); + } else + atomic_dec_64_nv(&zv_targets[zvidx].refCnt); } // nothing in that t-l - } - return NULL; + } + return (NULL); } -void wzvol_clear_targetid(uint8_t targetid, uint8_t lun, zvol_state_t* zv) +void +wzvol_clear_targetid(uint8_t targetid, uint8_t lun, zvol_state_t *zv) { - wzvolContext* zvc = (pwzvolContext)zv->zv_zso->zso_target_context; + wzvolContext *zvc = (pwzvolContext)zv->zv_zso->zso_target_context; ASSERT(KeGetCurrentIrql() < DISPATCH_LEVEL); ASSERT(targetid < STOR_wzvolDriverInfo.MaximumNumberOfTargets); ASSERT(lun < STOR_wzvolDriverInfo.MaximumNumberOfLogicalUnits); - if (targetid < STOR_wzvolDriverInfo.MaximumNumberOfTargets && lun < STOR_wzvolDriverInfo.MaximumNumberOfLogicalUnits) { - /* make sure no new I/O can enter the front-end + all outstanding I/Os are completed (ssv-18807). */ - if (atomic_cas_ptr(&STOR_wzvolDriverInfo.zvContextArray[resolveArrayIndex(targetid, lun, STOR_wzvolDriverInfo.MaximumNumberOfLogicalUnits)].zv, zv, NULL) == zv) { - IoReleaseRemoveLockAndWait(zvc->pIoRemLock, zv); // new calls to acquire remove lock will fail from now on + if (targetid < STOR_wzvolDriverInfo.MaximumNumberOfTargets && + lun < STOR_wzvolDriverInfo.MaximumNumberOfLogicalUnits) { + /* + * make sure no new I/O can enter the front-end + all + * outstanding I/Os are completed (ssv-18807). + */ + if (atomic_cas_ptr( + &STOR_wzvolDriverInfo.zvContextArray[resolveArrayIndex( + targetid, lun, + STOR_wzvolDriverInfo.MaximumNumberOfLogicalUnits)].zv, + zv, NULL) == zv) { + IoReleaseRemoveLockAndWait(zvc->pIoRemLock, zv); wzvol_decref_target(zvc); } } } -/**************************************************************************************************/ -/* */ -/**************************************************************************************************/ UCHAR ScsiExecuteMain( - __in pHW_HBA_EXT pHBAExt, // Adapter device-object extension from StorPort. - __in PSCSI_REQUEST_BLOCK pSrb, - __in PUCHAR pResult - ) + __in pHW_HBA_EXT pHBAExt, + __in PSCSI_REQUEST_BLOCK pSrb, + __in PUCHAR pResult) { - UCHAR status = SRB_STATUS_INVALID_REQUEST; + UCHAR status = SRB_STATUS_INVALID_REQUEST; - dprintf("ScsiExecute: pSrb = 0x%p, CDB = 0x%x Path: %x TID: %x Lun: %x\n", - pSrb, pSrb->Cdb[0], pSrb->PathId, pSrb->TargetId, pSrb->Lun); + dprintf("ScsiExecute: pSrb = 0x%p, CDB = 0x%x Path: %x " + "TID: %x Lun: %x\n", + pSrb, pSrb->Cdb[0], pSrb->PathId, pSrb->TargetId, pSrb->Lun); - *pResult = ResultDone; + *pResult = ResultDone; // Verify that the B/T/L is not out of bound. if (pSrb->PathId > 0) { status = SRB_STATUS_INVALID_PATH_ID; goto Done; - } else if (pSrb->TargetId >= STOR_wzvolDriverInfo.MaximumNumberOfTargets) { + } else if (pSrb->TargetId >= + STOR_wzvolDriverInfo.MaximumNumberOfTargets) { status = SRB_STATUS_INVALID_TARGET_ID; goto Done; - } else if (pSrb->Lun >= STOR_wzvolDriverInfo.MaximumNumberOfLogicalUnits) { + } else if (pSrb->Lun >= + STOR_wzvolDriverInfo.MaximumNumberOfLogicalUnits) { status = SRB_STATUS_INVALID_LUN; goto Done; } - // Handle sufficient opcodes to support a LUN suitable for a file system. Other opcodes are failed. - switch (pSrb->Cdb[0]) { + // Handle sufficient opcodes to support a LUN suitable + // for a file system. Other opcodes are failed. + switch (pSrb->Cdb[0]) { - case SCSIOP_TEST_UNIT_READY: - case SCSIOP_SYNCHRONIZE_CACHE: - case SCSIOP_START_STOP_UNIT: - case SCSIOP_VERIFY: - status = SRB_STATUS_SUCCESS; - break; + case SCSIOP_TEST_UNIT_READY: + case SCSIOP_SYNCHRONIZE_CACHE: + case SCSIOP_START_STOP_UNIT: + case SCSIOP_VERIFY: + status = SRB_STATUS_SUCCESS; + break; - case SCSIOP_INQUIRY: - status = ScsiOpInquiry(pHBAExt, pSrb); - break; + case SCSIOP_INQUIRY: + status = ScsiOpInquiry(pHBAExt, pSrb); + break; - case SCSIOP_READ_CAPACITY: - status = ScsiOpReadCapacity(pHBAExt, pSrb); - break; + case SCSIOP_READ_CAPACITY: + status = ScsiOpReadCapacity(pHBAExt, pSrb); + break; - case SCSIOP_READ_CAPACITY16: - status = ScsiOpReadCapacity16(pHBAExt, pSrb); - break; + case SCSIOP_READ_CAPACITY16: + status = ScsiOpReadCapacity16(pHBAExt, pSrb); + break; - case SCSIOP_READ: - case SCSIOP_READ16: - status = ScsiOpRead(pHBAExt, pSrb, pResult); - break; + case SCSIOP_READ: + case SCSIOP_READ16: + status = ScsiOpRead(pHBAExt, pSrb, pResult); + break; - case SCSIOP_WRITE: - case SCSIOP_WRITE16: - status = ScsiOpWrite(pHBAExt, pSrb, pResult); - break; + case SCSIOP_WRITE: + case SCSIOP_WRITE16: + status = ScsiOpWrite(pHBAExt, pSrb, pResult); + break; - case SCSIOP_MODE_SENSE: - status = ScsiOpModeSense(pHBAExt, pSrb); - break; + case SCSIOP_MODE_SENSE: + status = ScsiOpModeSense(pHBAExt, pSrb); + break; - case SCSIOP_REPORT_LUNS: - status = ScsiOpReportLuns(pHBAExt, pSrb); - break; + case SCSIOP_REPORT_LUNS: + status = ScsiOpReportLuns(pHBAExt, pSrb); + break; - default: - status = SRB_STATUS_INVALID_REQUEST; - break; + default: + status = SRB_STATUS_INVALID_REQUEST; + break; - } // switch (pSrb->Cdb[0]) + } // switch (pSrb->Cdb[0]) Done: - return status; -} // End ScsiExecuteMain. - -/**************************************************************************************************/ -/* */ -/* Find an MPIO-collecting LUN object for the supplied (new) LUN, or allocate one. */ -/* */ -/**************************************************************************************************/ + return (status); +} + pHW_LU_EXTENSION_MPIO ScsiGetMPIOExt( - __in pHW_HBA_EXT pHBAExt, // Adapter device-object extension from StorPort. - __in pHW_LU_EXTENSION pLUExt, // LUN device-object extension from StorPort. - __in PSCSI_REQUEST_BLOCK pSrb - ) + __in pHW_HBA_EXT pHBAExt, + __in pHW_LU_EXTENSION pLUExt, + __in PSCSI_REQUEST_BLOCK pSrb) { - pHW_LU_EXTENSION_MPIO pLUMPIOExt = NULL; // Prevent C4701. + pHW_LU_EXTENSION_MPIO pLUMPIOExt = NULL; #if defined(_AMD64_) - KLOCK_QUEUE_HANDLE LockHandle, - LockHandle2; + KLOCK_QUEUE_HANDLE LockHandle, + LockHandle2; #else - KIRQL SaveIrql, - SaveIrql2; + KIRQL SaveIrql, + SaveIrql2; #endif - PLIST_ENTRY pNextEntry; + PLIST_ENTRY pNextEntry; #if defined(_AMD64_) - KeAcquireInStackQueuedSpinLock(&pHBAExt->pwzvolDrvObj->MPIOExtLock, &LockHandle); + KeAcquireInStackQueuedSpinLock(&pHBAExt->pwzvolDrvObj->MPIOExtLock, + &LockHandle); #else - KeAcquireSpinLock(&pHBAExt->pwzvolDrvObj->MPIOExtLock, &SaveIrql); + KeAcquireSpinLock(&pHBAExt->pwzvolDrvObj->MPIOExtLock, &SaveIrql); #endif - for ( // Go through linked list of MPIO-collecting LUN objects. - pNextEntry = pHBAExt->pwzvolDrvObj->ListMPIOExt.Flink; - pNextEntry != &pHBAExt->pwzvolDrvObj->ListMPIOExt; - pNextEntry = pNextEntry->Flink - ) { - pLUMPIOExt = CONTAINING_RECORD(pNextEntry, HW_LU_EXTENSION_MPIO, List); - - if (pSrb->PathId==pLUMPIOExt->ScsiAddr.PathId // Same SCSI address? - && - pSrb->TargetId==pLUMPIOExt->ScsiAddr.TargetId - && - pSrb->Lun==pLUMPIOExt->ScsiAddr.Lun - ) { - break; - } - } - - if (pNextEntry==&pHBAExt->pwzvolDrvObj->ListMPIOExt) { // No match? That is, is this to be a new MPIO LUN extension? - pLUMPIOExt = ExAllocatePoolWithTag(NonPagedPoolNx, sizeof(HW_LU_EXTENSION_MPIO), MP_TAG_GENERAL); - - if (!pLUMPIOExt) { - dprintf("Failed to allocate HW_LU_EXTENSION_MPIO\n"); + for (pNextEntry = pHBAExt->pwzvolDrvObj->ListMPIOExt.Flink; + pNextEntry != &pHBAExt->pwzvolDrvObj->ListMPIOExt; + pNextEntry = pNextEntry->Flink) { + pLUMPIOExt = CONTAINING_RECORD(pNextEntry, + HW_LU_EXTENSION_MPIO, List); - goto Done; - } + if (pSrb->PathId == pLUMPIOExt->ScsiAddr.PathId && + pSrb->TargetId == pLUMPIOExt->ScsiAddr.TargetId && + pSrb->Lun == pLUMPIOExt->ScsiAddr.Lun) { + break; + } + } - RtlZeroMemory(pLUMPIOExt, sizeof(HW_LU_EXTENSION_MPIO)); + if (pNextEntry == &pHBAExt->pwzvolDrvObj->ListMPIOExt) { + pLUMPIOExt = ExAllocatePoolWithTag(NonPagedPoolNx, + sizeof (HW_LU_EXTENSION_MPIO), MP_TAG_GENERAL); - pLUMPIOExt->ScsiAddr.PathId = pSrb->PathId; - pLUMPIOExt->ScsiAddr.TargetId = pSrb->TargetId; - pLUMPIOExt->ScsiAddr.Lun = pSrb->Lun; + if (!pLUMPIOExt) { + dprintf("Failed to allocate HW_LU_EXTENSION_MPIO\n"); + goto Done; + } + + RtlZeroMemory(pLUMPIOExt, sizeof (HW_LU_EXTENSION_MPIO)); + + pLUMPIOExt->ScsiAddr.PathId = pSrb->PathId; + pLUMPIOExt->ScsiAddr.TargetId = pSrb->TargetId; + pLUMPIOExt->ScsiAddr.Lun = pSrb->Lun; - KeInitializeSpinLock(&pLUMPIOExt->LUExtMPIOLock); + KeInitializeSpinLock(&pLUMPIOExt->LUExtMPIOLock); - InitializeListHead(&pLUMPIOExt->LUExtList); + InitializeListHead(&pLUMPIOExt->LUExtList); - //ScsiAllocDiskBuf(pHBAExt, &pLUMPIOExt->pDiskBuf, &pLUExt->MaxBlocks); + // ScsiAllocDiskBuf(pHBAExt, + // &pLUMPIOExt->pDiskBuf, &pLUExt->MaxBlocks); - if (!pLUMPIOExt->pDiskBuf) { + if (!pLUMPIOExt->pDiskBuf) { dprintf("Failed to allocate DiskBuf\n"); - ExFreePoolWithTag(pLUMPIOExt, MP_TAG_GENERAL); - pLUMPIOExt = NULL; + ExFreePoolWithTag(pLUMPIOExt, MP_TAG_GENERAL); + pLUMPIOExt = NULL; - goto Done; - } + goto Done; + } - InsertTailList(&pHBAExt->pwzvolDrvObj->ListMPIOExt, &pLUMPIOExt->List); + InsertTailList(&pHBAExt->pwzvolDrvObj->ListMPIOExt, + &pLUMPIOExt->List); - pHBAExt->pwzvolDrvObj->DrvInfoNbrMPIOExtObj++; - } - else { - pLUExt->MaxBlocks = (USHORT)(pHBAExt->pwzvolDrvObj->wzvolRegInfo.PhysicalDiskSize / MP_BLOCK_SIZE); - } + pHBAExt->pwzvolDrvObj->DrvInfoNbrMPIOExtObj++; + } else { + pLUExt->MaxBlocks = + (USHORT)(pHBAExt->pwzvolDrvObj-> + wzvolRegInfo.PhysicalDiskSize / MP_BLOCK_SIZE); + } Done: - if (pLUMPIOExt) { // Have an MPIO-collecting LUN object? - // Add the real LUN to the MPIO-collecting LUN object. + if (pLUMPIOExt) { #if defined(_AMD64_) - KeAcquireInStackQueuedSpinLock(&pLUMPIOExt->LUExtMPIOLock, &LockHandle2); + KeAcquireInStackQueuedSpinLock(&pLUMPIOExt->LUExtMPIOLock, + &LockHandle2); #else - KeAcquireSpinLock(&pLUMPIOExt->LUExtMPIOLock, &SaveIrql2); + KeAcquireSpinLock(&pLUMPIOExt->LUExtMPIOLock, &SaveIrql2); #endif - pLUExt->pLUMPIOExt = pLUMPIOExt; - pLUExt->pDiskBuf = pLUMPIOExt->pDiskBuf; + pLUExt->pLUMPIOExt = pLUMPIOExt; + pLUExt->pDiskBuf = pLUMPIOExt->pDiskBuf; - InsertTailList(&pLUMPIOExt->LUExtList, &pLUExt->MPIOList); - pLUMPIOExt->NbrRealLUNs++; + InsertTailList(&pLUMPIOExt->LUExtList, &pLUExt->MPIOList); + pLUMPIOExt->NbrRealLUNs++; #if defined(_AMD64_) - KeReleaseInStackQueuedSpinLock(&LockHandle2); // Release serialization on MPIO-collecting LUN object. + KeReleaseInStackQueuedSpinLock(&LockHandle2); #else - KeReleaseSpinLock(&pLUMPIOExt->LUExtMPIOLock, SaveIrql2); + KeReleaseSpinLock(&pLUMPIOExt->LUExtMPIOLock, SaveIrql2); #endif - } + } #if defined(_AMD64_) - KeReleaseInStackQueuedSpinLock(&LockHandle); // Release the linked list of MPIO collector objects. + KeReleaseInStackQueuedSpinLock(&LockHandle); #else - KeReleaseSpinLock(&pHBAExt->pwzvolDrvObj->MPIOExtLock, SaveIrql); + KeReleaseSpinLock(&pHBAExt->pwzvolDrvObj->MPIOExtLock, SaveIrql); #endif - return pLUMPIOExt; -} // End ScsiGetMPIOExt. + return (pLUMPIOExt); +} UCHAR ScsiOpInquiry( - __in pHW_HBA_EXT pHBAExt, // Adapter device-object extension from StorPort. - __in PSCSI_REQUEST_BLOCK pSrb) + __in pHW_HBA_EXT pHBAExt, + __in PSCSI_REQUEST_BLOCK pSrb) { UCHAR status = SRB_STATUS_SUCCESS; - zvol_state_t* zv = NULL; + zvol_state_t *zv = NULL; if (pHBAExt->bDontReport) { status = SRB_STATUS_NO_DEVICE; @@ -437,7 +477,7 @@ ScsiOpInquiry( zv = wzvol_find_target(pSrb->TargetId, pSrb->Lun); if (NULL == zv) { dprintf("Unable to get zv context for device %d:%d:%d\n", - pSrb->PathId, pSrb->TargetId, pSrb->Lun); + pSrb->PathId, pSrb->TargetId, pSrb->Lun); status = SRB_STATUS_NO_DEVICE; goto out; } @@ -447,12 +487,12 @@ ScsiOpInquiry( status = SRB_STATUS_DATA_OVERRUN; goto out; } + RtlZeroMemory((PUCHAR)pSrb->DataBuffer, pSrb->DataTransferLength); if (1 == ((PCDB)pSrb->Cdb)->CDB6INQUIRY3.EnableVitalProductData) { status = ScsiOpVPD(pHBAExt, pSrb, zv); - } - else { + } else { PINQUIRYDATA pInqData = pSrb->DataBuffer; // Claim SCSI-3 commands support pInqData->DeviceType = DISK_DEVICE; @@ -464,39 +504,40 @@ ScsiOpInquiry( RtlMoveMemory(pInqData->VendorId, pHBAExt->VendorId, 8); RtlMoveMemory(pInqData->ProductId, pHBAExt->ProductId, 16); - RtlMoveMemory(pInqData->ProductRevisionLevel, pHBAExt->ProductRevision, 4); - memset((PCHAR)pInqData->VendorSpecific, ' ', sizeof(pInqData->VendorSpecific)); - sprintf(pInqData->VendorSpecific, "%.04d-%.04d-%.04d", pSrb->PathId, pSrb->TargetId, pSrb->Lun); - pInqData->VendorSpecific[strlen(pInqData->VendorSpecific)] = ' '; - - pInqData->AdditionalLength = sizeof(*pInqData) - 4; + RtlMoveMemory(pInqData->ProductRevisionLevel, + pHBAExt->ProductRevision, 4); + memset((PCHAR)pInqData->VendorSpecific, ' ', + sizeof (pInqData->VendorSpecific)); + sprintf(pInqData->VendorSpecific, "%.04d-%.04d-%.04d", + pSrb->PathId, pSrb->TargetId, pSrb->Lun); + pInqData->VendorSpecific[strlen(pInqData->VendorSpecific)] = + ' '; + + pInqData->AdditionalLength = sizeof (*pInqData) - 4; } out: if (zv) wzvol_unlock_target(zv); - return status; -} // End ScsiOpInquiry. - + return (status); +} -/**************************************************************************************************/ -/* */ -/**************************************************************************************************/ UCHAR ScsiOpVPD( - __in pHW_HBA_EXT pHBAExt, // Adapter device-object extension from StorPort. - __in PSCSI_REQUEST_BLOCK pSrb, - __in PVOID zvContext) + __in pHW_HBA_EXT pHBAExt, + __in PSCSI_REQUEST_BLOCK pSrb, + __in PVOID zvContext) { - UCHAR status = SRB_STATUS_SUCCESS; - ULONG len = 0; - zvol_state_t* zv = (zvol_state_t*)zvContext; + UCHAR status = SRB_STATUS_SUCCESS; + ULONG len = 0; + zvol_state_t *zv = (zvol_state_t *)zvContext; - switch (((struct _CDB6INQUIRY3*)&pSrb->Cdb)->PageCode) { + switch (((struct _CDB6INQUIRY3 *)&pSrb->Cdb)->PageCode) { case VPD_SUPPORTED_PAGES: { PVPD_SUPPORTED_PAGES_PAGE pPage = pSrb->DataBuffer; - len = sizeof(VPD_SUPPORTED_PAGES_PAGE) + 3; // 0x00 + 0x80 + 0x83 + // 0x00 + 0x80 + 0x83 + len = sizeof (VPD_SUPPORTED_PAGES_PAGE) + 3; if (pSrb->DataTransferLength < len) { status = SRB_STATUS_DATA_OVERRUN; goto ScsiOpVPD_done; @@ -514,7 +555,7 @@ ScsiOpVPD( case VPD_SERIAL_NUMBER: { PVPD_SERIAL_NUMBER_PAGE pPage = pSrb->DataBuffer; - len = sizeof(VPD_SERIAL_NUMBER_PAGE) + strlen(zv->zv_name); + len = sizeof (VPD_SERIAL_NUMBER_PAGE) + strlen(zv->zv_name); if (pSrb->DataTransferLength < len) { status = SRB_STATUS_DATA_OVERRUN; goto ScsiOpVPD_done; @@ -524,32 +565,43 @@ ScsiOpVPD( pPage->DeviceTypeQualifier = DEVICE_CONNECTED; pPage->PageCode = VPD_SERIAL_NUMBER; pPage->PageLength = strlen(zv->zv_name); - memcpy(&pPage->SerialNumber[0], zv->zv_name, strlen(zv->zv_name)); + memcpy(&pPage->SerialNumber[0], zv->zv_name, + strlen(zv->zv_name)); - dprintf("ScsiOpVPD: VPD Page: %d Serial No.: %s", pPage->PageCode, (const char*)pPage->SerialNumber); + dprintf("ScsiOpVPD: VPD Page: %d Serial No.: %s", + pPage->PageCode, (const char *)pPage->SerialNumber); } break; case VPD_DEVICE_IDENTIFIERS: { PVPD_IDENTIFICATION_PAGE pPage = pSrb->DataBuffer; - PVPD_IDENTIFICATION_DESCRIPTOR pDesc = (PVPD_IDENTIFICATION_DESCRIPTOR)&pPage->Descriptors[0]; + PVPD_IDENTIFICATION_DESCRIPTOR pDesc = + (PVPD_IDENTIFICATION_DESCRIPTOR)&pPage->Descriptors[0]; - len = sizeof(VPD_IDENTIFICATION_PAGE) + sizeof(VPD_IDENTIFICATION_DESCRIPTOR) + strlen(VENDOR_ID_ascii) + strlen(zv->zv_name); + len = sizeof (VPD_IDENTIFICATION_PAGE) + + sizeof (VPD_IDENTIFICATION_DESCRIPTOR) + + strlen(VENDOR_ID_ascii) + strlen(zv->zv_name); if (pSrb->DataTransferLength < len) { status = SRB_STATUS_DATA_OVERRUN; goto ScsiOpVPD_done; } pPage->PageCode = VPD_DEVICE_IDENTIFIERS; - // Only descriptor is the vendor T10 for now: VendorId:Poolname/Zvolname + // Only descriptor is the vendor T10 for now: + // VendorId:Poolname/Zvolname // NAA can't be done as OpenZFS is not IEEE registered for NAA. pDesc->CodeSet = VpdCodeSetAscii; pDesc->IdentifierType = VpdIdentifierTypeVendorId; pDesc->Association = VpdAssocDevice; - pDesc->IdentifierLength = strlen(VENDOR_ID_ascii) + strlen(zv->zv_name); - memcpy(&pDesc->Identifier[0], VENDOR_ID_ascii, strlen(VENDOR_ID_ascii)); - memcpy(&pDesc->Identifier[strlen(VENDOR_ID_ascii)], zv->zv_name, strlen(zv->zv_name)); - pPage->PageLength = FIELD_OFFSET(VPD_IDENTIFICATION_DESCRIPTOR, Identifier) + pDesc->IdentifierLength; + pDesc->IdentifierLength = strlen(VENDOR_ID_ascii) + + strlen(zv->zv_name); + memcpy(&pDesc->Identifier[0], VENDOR_ID_ascii, + strlen(VENDOR_ID_ascii)); + memcpy(&pDesc->Identifier[strlen(VENDOR_ID_ascii)], + zv->zv_name, strlen(zv->zv_name)); + pPage->PageLength = + FIELD_OFFSET(VPD_IDENTIFICATION_DESCRIPTOR, + Identifier) + pDesc->IdentifierLength; } break; default: @@ -560,36 +612,35 @@ ScsiOpVPD( ScsiOpVPD_done: pSrb->DataTransferLength = len; - return status; -} // End ScsiOpVPD(). + return (status); +} -/**************************************************************************************************/ -/* */ -/**************************************************************************************************/ UCHAR ScsiOpReadCapacity( - __in pHW_HBA_EXT pHBAExt, // Adapter device-object extension from StorPort. - __in PSCSI_REQUEST_BLOCK pSrb - ) + __in pHW_HBA_EXT pHBAExt, + __in PSCSI_REQUEST_BLOCK pSrb) { - UNREFERENCED_PARAMETER(pHBAExt); - PREAD_CAPACITY_DATA readCapacity = pSrb->DataBuffer; - ULONG maxBlocks, - blockSize; - zvol_state_t* zv = wzvol_find_target(pSrb->TargetId, pSrb->Lun); + UNREFERENCED_PARAMETER(pHBAExt); + PREAD_CAPACITY_DATA readCapacity = pSrb->DataBuffer; + ULONG maxBlocks, + blockSize; + zvol_state_t *zv = wzvol_find_target(pSrb->TargetId, pSrb->Lun); if (NULL == zv) { dprintf("Unable to get zv context for device %d:%d:%d\n", - pSrb->PathId, pSrb->TargetId, pSrb->Lun); + pSrb->PathId, pSrb->TargetId, pSrb->Lun); pSrb->DataTransferLength = 0; - return SRB_STATUS_NO_DEVICE; + return (SRB_STATUS_NO_DEVICE); } - RtlZeroMemory((PUCHAR)pSrb->DataBuffer, pSrb->DataTransferLength ); + RtlZeroMemory((PUCHAR)pSrb->DataBuffer, pSrb->DataTransferLength); - /* fake maxBlocks to ULONG_MAX so that Windows calls with SCSIOP_READ_CAPACITY16. - * This would help specify non-zero LogicalPerPhysicalExponent that makes logical - * and physical sector size of a zvol different, kind of 512e disk! - */ + /* + * fake maxBlocks to ULONG_MAX so that Windows calls with + * SCSIOP_READ_CAPACITY16. + * This would help specify non-zero LogicalPerPhysicalExponent + * that makes logical and physical sector size of a zvol different, + * kind of 512e disk! + */ maxBlocks = ULONG_MAX; blockSize = MP_BLOCK_SIZE; @@ -598,17 +649,13 @@ ScsiOpReadCapacity( REVERSE_BYTES(&readCapacity->LogicalBlockAddress, &maxBlocks); wzvol_unlock_target(zv); - return SRB_STATUS_SUCCESS; -} // End ScsiOpReadCapacity. + return (SRB_STATUS_SUCCESS); +} -/**************************************************************************************************/ -/* */ -/**************************************************************************************************/ UCHAR ScsiOpReadCapacity16( - __in pHW_HBA_EXT pHBAExt, - __in PSCSI_REQUEST_BLOCK pSrb - ) + __in pHW_HBA_EXT pHBAExt, + __in PSCSI_REQUEST_BLOCK pSrb) { PREAD_CAPACITY16_DATA readCapacity = pSrb->DataBuffer; ULONGLONG maxBlocks = 0; @@ -617,186 +664,174 @@ ScsiOpReadCapacity16( ULONG lppFactor; UNREFERENCED_PARAMETER(pHBAExt); - zvol_state_t * zv = wzvol_find_target(pSrb->TargetId, pSrb->Lun); + zvol_state_t *zv = wzvol_find_target(pSrb->TargetId, pSrb->Lun); if (NULL == zv) { dprintf("Unable to get zv context for device %d:%d:%d\n", - pSrb->PathId, pSrb->TargetId, pSrb->Lun); - pSrb->DataTransferLength = 0; - return SRB_STATUS_NO_DEVICE; + pSrb->PathId, pSrb->TargetId, pSrb->Lun); + pSrb->DataTransferLength = 0; + return (SRB_STATUS_NO_DEVICE); } RtlZeroMemory((PUCHAR)pSrb->DataBuffer, pSrb->DataTransferLength); blockSize = MP_BLOCK_SIZE; maxBlocks = (zv->zv_volsize / blockSize) - 1; - dprintf("Block Size: 0x%x Total Blocks: 0x%llx\n", blockSize, maxBlocks); + dprintf("Block Size: 0x%x Total Blocks: 0x%llx\n", blockSize, + maxBlocks); REVERSE_BYTES(&readCapacity->BytesPerBlock, &blockSize); - REVERSE_BYTES_QUAD(&readCapacity->LogicalBlockAddress.QuadPart, &maxBlocks); + REVERSE_BYTES_QUAD(&readCapacity->LogicalBlockAddress.QuadPart, + &maxBlocks); lppFactor = zv->zv_volblocksize / MP_BLOCK_SIZE; - ASSERT((lppFactor & (lppFactor - 1)) == 0); // make sure the factor is power of 2 + ASSERT((lppFactor & (lppFactor - 1)) == 0); while (lppFactor >>= 1) lppExponent++; readCapacity->LogicalPerPhysicalExponent = lppExponent; wzvol_unlock_target(zv); - return SRB_STATUS_SUCCESS; + return (SRB_STATUS_SUCCESS); } -/**************************************************************************************************/ -/* */ -/**************************************************************************************************/ UCHAR ScsiOpRead( - __in pHW_HBA_EXT pHBAExt, // Adapter device-object extension from StorPort. - __in PSCSI_REQUEST_BLOCK pSrb, - __in PUCHAR pResult - ) + __in pHW_HBA_EXT pHBAExt, + __in PSCSI_REQUEST_BLOCK pSrb, + __in PUCHAR pResult) { - UCHAR status; + UCHAR status; - status = ScsiReadWriteSetup(pHBAExt, pSrb, ActionRead, pResult); + status = ScsiReadWriteSetup(pHBAExt, pSrb, ActionRead, pResult); - return status; -} // End ScsiOpRead. + return (status); +} -/**************************************************************************************************/ -/* */ -/**************************************************************************************************/ UCHAR ScsiOpWrite( - __in pHW_HBA_EXT pHBAExt, // Adapter device-object extension from StorPort. - __in PSCSI_REQUEST_BLOCK pSrb, - __in PUCHAR pResult - ) + __in pHW_HBA_EXT pHBAExt, + __in PSCSI_REQUEST_BLOCK pSrb, + __in PUCHAR pResult) { - UCHAR status; + UCHAR status; - status = ScsiReadWriteSetup(pHBAExt, pSrb, ActionWrite, pResult); + status = ScsiReadWriteSetup(pHBAExt, pSrb, ActionWrite, pResult); - return status; -} // End ScsiOpWrite. + return (status); +} -/**************************************************************************************************/ -/* */ -/* This routine does the setup for reading or writing. The reading/writing could be effected */ -/* here rather than in MpGeneralWkRtn, but in the general case MpGeneralWkRtn is going to be the */ -/* place to do the work since it gets control at PASSIVE_LEVEL and so could do real I/O, could */ -/* wait, etc, etc. */ -/* */ -/**************************************************************************************************/ UCHAR ScsiReadWriteSetup( - __in pHW_HBA_EXT pHBAExt, // Adapter device-object extension from StorPort. - __in PSCSI_REQUEST_BLOCK pSrb, - __in MpWkRtnAction WkRtnAction, - __in PUCHAR pResult -) + __in pHW_HBA_EXT pHBAExt, + __in PSCSI_REQUEST_BLOCK pSrb, + __in MpWkRtnAction WkRtnAction, + __in PUCHAR pResult) { - PCDB pCdb = (PCDB)pSrb->Cdb; - PHW_SRB_EXTENSION pSrbExt = pSrb->SrbExtension; - ULONG startingSector, - sectorOffset; - USHORT numBlocks; - pMP_WorkRtnParms pWkRtnParms = &pSrbExt->WkRtnParms; + PCDB pCdb = (PCDB)pSrb->Cdb; + PHW_SRB_EXTENSION pSrbExt = pSrb->SrbExtension; + ULONG startingSector, + sectorOffset; + USHORT numBlocks; + pMP_WorkRtnParms pWkRtnParms = &pSrbExt->WkRtnParms; ASSERT(pSrb->DataBuffer != NULL); - *pResult = ResultDone; // Assume no queuing. + *pResult = ResultDone; - RtlZeroMemory(pWkRtnParms, sizeof(MP_WorkRtnParms)); + RtlZeroMemory(pWkRtnParms, sizeof (MP_WorkRtnParms)); pWkRtnParms->pHBAExt = pHBAExt; pWkRtnParms->pSrb = pSrb; - pWkRtnParms->Action = ActionRead == WkRtnAction ? ActionRead : ActionWrite; + pWkRtnParms->Action = ActionRead == + WkRtnAction ? ActionRead : ActionWrite; - IoInitializeWorkItem((PDEVICE_OBJECT)pHBAExt->pDrvObj, (PIO_WORKITEM)pWkRtnParms->pQueueWorkItem); + IoInitializeWorkItem((PDEVICE_OBJECT)pHBAExt->pDrvObj, + (PIO_WORKITEM)pWkRtnParms->pQueueWorkItem); - // Save the SRB in a list allowing cancellation via SRB_FUNCTION_RESET_xxx + // Save the SRB in a list allowing cancellation via + // SRB_FUNCTION_RESET_xxx pSrbExt->pSrbBackPtr = pSrb; pSrbExt->Cancelled = 0; KIRQL oldIrql; KeAcquireSpinLock(&pHBAExt->pwzvolDrvObj->SrbExtLock, &oldIrql); - InsertTailList(&pHBAExt->pwzvolDrvObj->ListSrbExt,&pSrbExt->QueuedForProcessing); + InsertTailList(&pHBAExt->pwzvolDrvObj->ListSrbExt, + &pSrbExt->QueuedForProcessing); KeReleaseSpinLock(&pHBAExt->pwzvolDrvObj->SrbExtLock, oldIrql); // Queue work item, which will run in the System process. - IoQueueWorkItem((PIO_WORKITEM)pWkRtnParms->pQueueWorkItem, wzvol_GeneralWkRtn, DelayedWorkQueue, pWkRtnParms); + IoQueueWorkItem((PIO_WORKITEM)pWkRtnParms->pQueueWorkItem, + wzvol_GeneralWkRtn, DelayedWorkQueue, pWkRtnParms); - *pResult = ResultQueued; // Indicate queuing. - - return SRB_STATUS_SUCCESS; -} // End ScsiReadWriteSetup. + *pResult = ResultQueued; + return (SRB_STATUS_SUCCESS); +} -/**************************************************************************************************/ -/* */ -/**************************************************************************************************/ UCHAR ScsiOpModeSense( - __in pHW_HBA_EXT pHBAExt, // Adapter device-object extension from StorPort. - __in PSCSI_REQUEST_BLOCK pSrb - ) + __in pHW_HBA_EXT pHBAExt, + __in PSCSI_REQUEST_BLOCK pSrb) { - UNREFERENCED_PARAMETER(pHBAExt); + UNREFERENCED_PARAMETER(pHBAExt); - RtlZeroMemory((PUCHAR)pSrb->DataBuffer, pSrb->DataTransferLength); + RtlZeroMemory((PUCHAR)pSrb->DataBuffer, pSrb->DataTransferLength); - return SRB_STATUS_SUCCESS; + return (SRB_STATUS_SUCCESS); } -/**************************************************************************************************/ -/* */ -/**************************************************************************************************/ UCHAR -ScsiOpReportLuns( - __in __out pHW_HBA_EXT pHBAExt, // Adapter device-object extension from StorPort. - __in PSCSI_REQUEST_BLOCK pSrb - ) +ScsiOpReportLuns( + __in __out pHW_HBA_EXT pHBAExt, + __in PSCSI_REQUEST_BLOCK pSrb) { - UCHAR status = SRB_STATUS_SUCCESS; - PLUN_LIST pLunList = (PLUN_LIST)pSrb->DataBuffer; // Point to LUN list. - uint8_t GoodLunIdx = 0; - uint8_t totalLun = 0; - zvol_state_t* zv; - - if (FALSE==pHBAExt->bReportAdapterDone) { // This opcode will be one of the earliest I/O requests for a new HBA (and may be received later, too). - wzvol_HwReportAdapter(pHBAExt); // WMIEvent test. - wzvol_HwReportLink(pHBAExt); // WMIEvent test. - wzvol_HwReportLog(pHBAExt); // WMIEvent test. - pHBAExt->bReportAdapterDone = TRUE; - } - + UCHAR status = SRB_STATUS_SUCCESS; + PLUN_LIST pLunList = (PLUN_LIST)pSrb->DataBuffer; // Point to LUN list. + uint8_t GoodLunIdx = 0; + uint8_t totalLun = 0; + zvol_state_t *zv; + + if (FALSE == pHBAExt->bReportAdapterDone) { + wzvol_HwReportAdapter(pHBAExt); + wzvol_HwReportLink(pHBAExt); + wzvol_HwReportLog(pHBAExt); + pHBAExt->bReportAdapterDone = TRUE; + } + RtlZeroMemory((PUCHAR)pSrb->DataBuffer, pSrb->DataTransferLength); if (!pHBAExt->bDontReport) { - // Set the LUN numbers if there is enough room, and set only those LUNs to be reported. - for (uint8_t i = 0; i < STOR_wzvolDriverInfo.MaximumNumberOfLogicalUnits; i ++) { + for (uint8_t i = 0; + i < STOR_wzvolDriverInfo.MaximumNumberOfLogicalUnits; + i++) { // make sure we have the space for 1 more LUN each time. - if ((zv = wzvol_find_target(pSrb->TargetId, i))!=NULL) { + if ((zv = wzvol_find_target(pSrb->TargetId, i)) != + NULL) { totalLun++; - if (pSrb->DataTransferLength >= FIELD_OFFSET(LUN_LIST, Lun) + (GoodLunIdx * sizeof(pLunList->Lun[0])) + sizeof(pLunList->Lun[0])) { + if (pSrb->DataTransferLength >= + FIELD_OFFSET(LUN_LIST, Lun) + + (GoodLunIdx * sizeof (pLunList->Lun[0])) + + sizeof (pLunList->Lun[0])) { pLunList->Lun[GoodLunIdx][1] = (UCHAR)i; GoodLunIdx++; } wzvol_unlock_target(zv); } - } - } // else: we chose to not report any LUN through that HBA (see FindAdapter routine). + } + } - *((ULONG*)&pLunList->LunListLength) = RtlUlongByteSwap(totalLun * sizeof(pLunList->Lun[0])); - pSrb->DataTransferLength = FIELD_OFFSET(LUN_LIST, Lun) + (GoodLunIdx * sizeof(pLunList->Lun[0])); + *((ULONG*)&pLunList->LunListLength) = + RtlUlongByteSwap(totalLun * sizeof (pLunList->Lun[0])); + pSrb->DataTransferLength = FIELD_OFFSET(LUN_LIST, Lun) + + (GoodLunIdx * sizeof (pLunList->Lun[0])); - return status; -} // End ScsiOpReportLuns. + return (status); +} -VOID -wzvol_WkRtn(__in PVOID pWkParms) // Parm list pointer. +void +wzvol_WkRtn(__in PVOID pWkParms) { - pMP_WorkRtnParms pWkRtnParms = (pMP_WorkRtnParms)pWkParms; - pHW_HBA_EXT pHBAExt = pWkRtnParms->pHBAExt; - PSCSI_REQUEST_BLOCK pSrb = pWkRtnParms->pSrb; - PCDB pCdb = (PCDB)pSrb->Cdb; - PHW_SRB_EXTENSION pSrbExt = (PHW_SRB_EXTENSION)pSrb->SrbExtension; - ULONGLONG startingSector=0ULL, sectorOffset=0ULL; - ULONG lclStatus; - UCHAR status; + pMP_WorkRtnParms pWkRtnParms = (pMP_WorkRtnParms)pWkParms; + pHW_HBA_EXT pHBAExt = pWkRtnParms->pHBAExt; + PSCSI_REQUEST_BLOCK pSrb = pWkRtnParms->pSrb; + PCDB pCdb = (PCDB)pSrb->Cdb; + PHW_SRB_EXTENSION pSrbExt = (PHW_SRB_EXTENSION)pSrb->SrbExtension; + ULONGLONG startingSector = 0ULL, sectorOffset = 0ULL; + ULONG lclStatus; + UCHAR status; int flags = 0; zvol_state_t *zv = NULL; @@ -819,29 +854,31 @@ wzvol_WkRtn(__in PVOID pWkParms) // Parm list pointer. if (pSrb->CdbLength == 10) { startingSector = (ULONG)pCdb->CDB10.LogicalBlockByte3 | - pCdb->CDB10.LogicalBlockByte2 << 8 | - pCdb->CDB10.LogicalBlockByte1 << 16 | - pCdb->CDB10.LogicalBlockByte0 << 24; + pCdb->CDB10.LogicalBlockByte2 << 8 | + pCdb->CDB10.LogicalBlockByte1 << 16 | + pCdb->CDB10.LogicalBlockByte0 << 24; if (pCdb->CDB10.ForceUnitAccess) flags |= ZVOL_WRITE_SYNC; - } - else if (pSrb->CdbLength == 16) { + } else if (pSrb->CdbLength == 16) { REVERSE_BYTES_QUAD(&startingSector, pCdb->CDB16.LogicalBlock); if (pCdb->CDB16.ForceUnitAccess) flags |= ZVOL_WRITE_SYNC; - } - else { + } else { status = SRB_STATUS_ERROR; goto Done; } sectorOffset = startingSector * MP_BLOCK_SIZE; - dprintf("MpWkRtn Action: %X, starting sector: 0x%llX, sector offset: 0x%llX\n", pWkRtnParms->Action, startingSector, sectorOffset); - dprintf("MpWkRtn pSrb: 0x%p, pSrb->DataBuffer: 0x%p\n", pSrb, pSrb->DataBuffer); + dprintf("MpWkRtn Action: %X, starting sector: 0x%llX, " + "sector offset: 0x%llX\n", pWkRtnParms->Action, + startingSector, sectorOffset); + dprintf("MpWkRtn pSrb: 0x%p, pSrb->DataBuffer: 0x%p\n", + pSrb, pSrb->DataBuffer); - if (sectorOffset >= zv->zv_volsize) { // Starting sector beyond the bounds? - dprintf("%s: invalid starting sector: %d\n", __func__, startingSector); + if (sectorOffset >= zv->zv_volsize) { + dprintf("%s: invalid starting sector: %d\n", __func__, + startingSector); status = SRB_STATUS_INVALID_REQUEST; goto Done; } @@ -850,23 +887,23 @@ wzvol_WkRtn(__in PVOID pWkParms) // Parm list pointer. // the uio in some Extension to this IO, we could // save the allocation here. uio_t *uio = uio_create(1, 0, UIO_SYSSPACE, - ActionRead == pWkRtnParms->Action ? UIO_READ : UIO_WRITE); + ActionRead == pWkRtnParms->Action ? UIO_READ : UIO_WRITE); if (uio == NULL) { dprintf("%s: out of memory.\n", __func__); status = SRB_STATUS_INVALID_REQUEST; goto Done; } VERIFY0(uio_addiov(uio, (user_addr_t)pSrb->DataBuffer, - pSrb->DataTransferLength)); + pSrb->DataTransferLength)); uio_setoffset(uio, sectorOffset); /* Call ZFS to read/write data */ - if (ActionRead == pWkRtnParms->Action) { + if (ActionRead == pWkRtnParms->Action) { status = zvol_os_read_zv(zv, uio, flags); - } else { + } else { status = zvol_os_write_zv(zv, uio, flags); } - + if (status == 0) status = SRB_STATUS_SUCCESS; @@ -879,18 +916,15 @@ wzvol_WkRtn(__in PVOID pWkParms) // Parm list pointer. pSrb->SrbStatus = status; // Tell StorPort this action has been completed. - StorPortNotification(RequestComplete, pHBAExt, pSrb); -} // End MpWkRtn(). - +} -VOID +void wzvol_GeneralWkRtn( - __in PVOID pDummy, // Not used. - __in PVOID pWkParms // Parm list pointer. -) + __in PVOID pDummy, + __in PVOID pWkParms) { - pMP_WorkRtnParms pWkRtnParms = (pMP_WorkRtnParms)pWkParms; + pMP_WorkRtnParms pWkRtnParms = (pMP_WorkRtnParms)pWkParms; UNREFERENCED_PARAMETER(pDummy); IoUninitializeWorkItem((PIO_WORKITEM)pWkRtnParms->pQueueWorkItem); @@ -900,11 +934,12 @@ wzvol_GeneralWkRtn( while (pWkRtnParms->SecondsToDelay) { LARGE_INTEGER delay; - delay.QuadPart = -10 * 1000 * 1000 * pWkRtnParms->SecondsToDelay; + delay.QuadPart = + -10 * 1000 * 1000 * pWkRtnParms->SecondsToDelay; KeDelayExecutionThread(KernelMode, TRUE, &delay); } - wzvol_WkRtn(pWkParms); // Do the actual work. -} // End MpGeneralWkRtn(). + wzvol_WkRtn(pWkParms); +} diff --git a/module/os/windows/zfs/zfs_windows_zvol_wmi.c b/module/os/windows/zfs/zfs_windows_zvol_wmi.c index ee3d1f525cc..3d46541d4af 100644 --- a/module/os/windows/zfs/zfs_windows_zvol_wmi.c +++ b/module/os/windows/zfs/zfs_windows_zvol_wmi.c @@ -1,26 +1,26 @@ -/****************************** Module Header ******************************\ -* Module Name: wmi.c -* Project: CppWDKStorPortVirtualMiniport -* -* Copyright (c) Microsoft Corporation. -* -* a. HandleWmiSrb() -* Handles WMI SRBs, possibly by calling a subroutine. -* -* b. QueryWmiDataBlock() -* Supports WMI Query Data Block. -* -* c. ExecuteWmiMethod() -* Supports WMI Execute Method. -* -* This source is subject to the Microsoft Public License. -* See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL. -* All other rights reserved. -* -* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, -* EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. -\***************************************************************************/ +/* + * Module Name: wmi.c + * Project: CppWDKStorPortVirtualMiniport + * + * Copyright (c) Microsoft Corporation. + * + * a. HandleWmiSrb() + * Handles WMI SRBs, possibly by calling a subroutine. + * + * b. QueryWmiDataBlock() + * Supports WMI Query Data Block. + * + * c. ExecuteWmiMethod() + * Supports WMI Execute Method. + * + * This source is subject to the Microsoft Public License. + * See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL. + * All other rights reserved. + * + * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, + * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. + */ #include #include @@ -32,1094 +32,1118 @@ #include #include -//#include "trace.h" -//#include "wmi.tmh" +// #include "trace.h" +// #include "wmi.tmh" // Paper about FC WMI classes, including C++ and VBS examples: // -// http://download.microsoft.com/download/9/c/5/9c5b2167-8017-4bae-9fde-d599bac8184a/FCTopology.doc +// http:/ /download.microsoft.com/download/9/c/5/ +// 9c5b2167-8017-4bae-9fde-d599bac8184a/FCTopology.doc // -/**************************************************************************************************/ -/* */ -/* Globals, forward definitions, etc. */ -/* */ -/**************************************************************************************************/ -#define IdxGmDemoDriver_GUID 0 // Index value of GmDemoDriver_GUID in GuidList[]. -#define IdxGmDemoDriver2_GUID 1 // Index value of GmDemoDriver2_GUID in GuidList[]. -#define IdxGmDemoDriverSrbActivity_GUID 2 // Index value of GmDemoDriverSrbActivity_GUID in GuidList[]. -#define IdxGmDrvDrvMethodGuid 3 // Index value of Mpf2DrvMethod_GUID in GuidList[]. -#define IdxMSFC_AdapterEvent_GUID 4 // This index value isn't used for anything: Just being neat. -#define IdxMSFC_LinkEvent_GUID 5 // This index value isn't used for anything: Just being neat. -#define IdxMSFC_FibrePortHBAStatistics_GUID 6 -#define IdxMSFC_FibrePortHBAAttributes_GUID 7 -#define IdxMSFC_FCAdapterHBAAttributes_GUID 8 -#define IdxMSFC_HBAFCPInfo_GUID 9 -#define IdxMSFC_FibrePortHBAMethods_GUID 10 -#define IdxMSFC_HBAAdapterMethods_GUID 11 -#define IdxMSFC_HBAPortStatistics_GUID 12 - -#define NUMBEROFPORTS 1 - -SCSIWMIGUIDREGINFO WmiGuidList[] = // GUIDs supported. - { - {&GmDemoDriver_GUID, 1, WMIREG_FLAG_INSTANCE_PDO}, - {&GmDemoDriver2_GUID, 1, WMIREG_FLAG_INSTANCE_PDO}, - {&GmDemoDriverSrbActivity_GUID, 1, WMIREG_FLAG_INSTANCE_PDO}, - {&GmDrvDrvMethod_GUID, 1, 0x0}, - {&MSFC_AdapterEvent_GUID, NUMBEROFPORTS, 0x0}, - {&MSFC_LinkEvent_GUID, NUMBEROFPORTS, 0x0}, - {&MSFC_FibrePortHBAStatistics_GUID, NUMBEROFPORTS, 0x0}, - {&MSFC_FibrePortHBAAttributes_GUID, NUMBEROFPORTS, 0x0}, - {&MSFC_FCAdapterHBAAttributes_GUID, NUMBEROFPORTS, 0x0}, - {&MSFC_HBAFCPInfo_GUID, NUMBEROFPORTS, 0x0}, - {&MSFC_FibrePortHBAMethods_GUID, NUMBEROFPORTS, 0x0}, - {&MSFC_HBAAdapterMethods_GUID, NUMBEROFPORTS, 0x0}, - {&MSFC_HBAPortStatistics_GUID, NUMBEROFPORTS, 0x0}, - }; - -#define WmiGuidCount (sizeof(WmiGuidList) / sizeof(SCSIWMIGUIDREGINFO)) +#define IdxGmDemoDriver_GUID 0 +#define IdxGmDemoDriver2_GUID 1 +#define IdxGmDemoDriverSrbActivity_GUID 2 +#define IdxGmDrvDrvMethodGuid 3 +#define IdxMSFC_AdapterEvent_GUID 4 +#define IdxMSFC_LinkEvent_GUID 5 +#define IdxMSFC_FibrePortHBAStatistics_GUID 6 +#define IdxMSFC_FibrePortHBAAttributes_GUID 7 +#define IdxMSFC_FCAdapterHBAAttributes_GUID 8 +#define IdxMSFC_HBAFCPInfo_GUID 9 +#define IdxMSFC_FibrePortHBAMethods_GUID 10 +#define IdxMSFC_HBAAdapterMethods_GUID 11 +#define IdxMSFC_HBAPortStatistics_GUID 12 + +#define NUMBEROFPORTS 1 + +SCSIWMIGUIDREGINFO WmiGuidList[] = // GUIDs supported. +{ + {&GmDemoDriver_GUID, 1, WMIREG_FLAG_INSTANCE_PDO}, + {&GmDemoDriver2_GUID, 1, WMIREG_FLAG_INSTANCE_PDO}, + {&GmDemoDriverSrbActivity_GUID, 1, WMIREG_FLAG_INSTANCE_PDO}, + {&GmDrvDrvMethod_GUID, 1, 0x0}, + {&MSFC_AdapterEvent_GUID, NUMBEROFPORTS, 0x0}, + {&MSFC_LinkEvent_GUID, NUMBEROFPORTS, 0x0}, + {&MSFC_FibrePortHBAStatistics_GUID, NUMBEROFPORTS, 0x0}, + {&MSFC_FibrePortHBAAttributes_GUID, NUMBEROFPORTS, 0x0}, + {&MSFC_FCAdapterHBAAttributes_GUID, NUMBEROFPORTS, 0x0}, + {&MSFC_HBAFCPInfo_GUID, NUMBEROFPORTS, 0x0}, + {&MSFC_FibrePortHBAMethods_GUID, NUMBEROFPORTS, 0x0}, + {&MSFC_HBAAdapterMethods_GUID, NUMBEROFPORTS, 0x0}, + {&MSFC_HBAPortStatistics_GUID, NUMBEROFPORTS, 0x0}, +}; + +#define WmiGuidCount (sizeof (WmiGuidList) / sizeof (SCSIWMIGUIDREGINFO)) UCHAR -QueryWmiRegInfo( - IN PVOID pContext, - IN PSCSIWMI_REQUEST_CONTEXT pRequestContext, - OUT PWCHAR * pMofResourceName - ); +QueryWmiRegInfo(IN PVOID pContext, + IN PSCSIWMI_REQUEST_CONTEXT pRequestContext, + OUT PWCHAR *pMofResourceName); BOOLEAN QueryWmiDataBlock( - IN PVOID pContext, - IN PSCSIWMI_REQUEST_CONTEXT pDispatchContext, - IN ULONG GuidIndex, - IN ULONG InstanceIndex, - IN ULONG InstanceCount, - IN OUT PULONG pInstanceLengthArray, - IN ULONG BufferAvail, - OUT PUCHAR pBuffer - ); + IN PVOID pContext, + IN PSCSIWMI_REQUEST_CONTEXT pDispatchContext, + IN ULONG GuidIndex, + IN ULONG InstanceIndex, + IN ULONG InstanceCount, + IN OUT PULONG pInstanceLengthArray, + IN ULONG BufferAvail, + OUT PUCHAR); UCHAR SetWmiDataBlock( - IN PVOID pContext, - IN PSCSIWMI_REQUEST_CONTEXT pDispatchContext, - IN ULONG GuidIndex, - IN ULONG InstanceIndex, - IN ULONG BufferSize, - IN PUCHAR pBuffer - ); + IN PVOID pContext, + IN PSCSIWMI_REQUEST_CONTEXT pDispatchContext, + IN ULONG GuidIndex, + IN ULONG InstanceIndex, + IN ULONG BufferSize, + IN PUCHAR pBuffer); UCHAR ExecuteWmiMethod( - IN PVOID pContext, - IN PSCSIWMI_REQUEST_CONTEXT pDispatchContext, - IN ULONG GuidIndex, - IN ULONG InstanceIndex, - IN ULONG MethodId, - IN ULONG InBufferSize, - IN ULONG OutBufferSize, - IN OUT PUCHAR pBuffer - ); - -VOID + IN PVOID pContext, + IN PSCSIWMI_REQUEST_CONTEXT pDispatchContext, + IN ULONG GuidIndex, + IN ULONG InstanceIndex, + IN ULONG MethodId, + IN ULONG InBufferSize, + IN ULONG OutBufferSize, + IN OUT PUCHAR pBuffer); + +void SpUpdateWmiRequest( - pHW_HBA_EXT pHbaExtension, - PSCSI_WMI_REQUEST_BLOCK pSrb, - PSCSIWMI_REQUEST_CONTEXT pDispatchContext, - UCHAR Status, - ULONG SizeNeeded - ); - -/**************************************************************************************************/ -/* */ -/* InitializeWmiContext. */ -/* */ -/* Build WMILIB block, with pointers to supported callbacks, GUIDs, etc. */ -/* */ -/**************************************************************************************************/ + pHW_HBA_EXT pHbaExtension, + PSCSI_WMI_REQUEST_BLOCK pSrb, + PSCSIWMI_REQUEST_CONTEXT pDispatchContext, + UCHAR Status, + ULONG SizeNeeded); + void InitializeWmiContext(__in pHW_HBA_EXT pHbaExtension) { - PSCSI_WMILIB_CONTEXT pWmiLibContext = // Point to WMI context block. - &(pHbaExtension->WmiLibContext); - - RtlZeroMemory(pWmiLibContext, // Clear WMI context block. - sizeof(SCSI_WMILIB_CONTEXT)); - - pWmiLibContext->GuidCount = WmiGuidCount; - pWmiLibContext->GuidList = WmiGuidList; - - // - // Point to WMI callback routines. - // - pWmiLibContext->QueryWmiRegInfo = QueryWmiRegInfo; - pWmiLibContext->QueryWmiDataBlock = QueryWmiDataBlock; - pWmiLibContext->SetWmiDataBlock = SetWmiDataBlock; - pWmiLibContext->ExecuteWmiMethod = ExecuteWmiMethod; - pWmiLibContext->WmiFunctionControl = NULL; -} // End InitializeWmiContext(). - -/**************************************************************************************************/ -/* */ -/* HandleWmiSrb. */ -/* */ -/* General handler (dispatch point) for WMI SRBs. */ -/* */ -/**************************************************************************************************/ + PSCSI_WMILIB_CONTEXT pWmiLibContext = + &(pHbaExtension->WmiLibContext); + + RtlZeroMemory(pWmiLibContext, + sizeof (SCSI_WMILIB_CONTEXT)); + + pWmiLibContext->GuidCount = WmiGuidCount; + pWmiLibContext->GuidList = WmiGuidList; + + // + // Point to WMI callback routines. + // + pWmiLibContext->QueryWmiRegInfo = QueryWmiRegInfo; + pWmiLibContext->QueryWmiDataBlock = QueryWmiDataBlock; + pWmiLibContext->SetWmiDataBlock = SetWmiDataBlock; + pWmiLibContext->ExecuteWmiMethod = ExecuteWmiMethod; + pWmiLibContext->WmiFunctionControl = NULL; +} + BOOLEAN HandleWmiSrb( - __in pHW_HBA_EXT pHbaExtension, - __in __out PSCSI_WMI_REQUEST_BLOCK pSrb - ) + __in pHW_HBA_EXT pHbaExtension, + __in __out PSCSI_WMI_REQUEST_BLOCK pSrb) { - PSCSIWMI_REQUEST_CONTEXT pRequestContext; - PHW_SRB_EXTENSION pSrbExtension; - BOOLEAN bPending = FALSE; - - // - // Validate our assumptions. - // - ASSERT(pSrb->Function == SRB_FUNCTION_WMI); - ASSERT(pSrb->Length == sizeof(SCSI_WMI_REQUEST_BLOCK)); - - if (!(pSrb->WMIFlags & SRB_WMI_FLAGS_ADAPTER_REQUEST)) { - - // - // This is targetted to one of the disks, since there is no per-disk - // WMI information we return an error. Note that if there was per- - // disk information, then you'd likely have a different WmiLibContext - // and a different set of GUIDs. - // - pSrb->DataTransferLength = 0; - pSrb->SrbStatus = SRB_STATUS_NO_DEVICE; - - } else { - if (IRP_MN_ENABLE_EVENTS==pSrb->WMISubFunction) { - } - - pSrbExtension = (PHW_SRB_EXTENSION)pSrb->SrbExtension; - pRequestContext = &(pSrbExtension->WmiRequestContext); - - // - // Save the pointer to the SRB in UserContext of SCSIWMI_REQUEST_CONTEXT - // - pRequestContext->UserContext = pSrb; - - // - // Process the incoming WMI request. - // - - bPending = ScsiPortWmiDispatchFunction( - &pHbaExtension->WmiLibContext, - pSrb->WMISubFunction, - pHbaExtension, - pRequestContext, - pSrb->DataPath, - pSrb->DataTransferLength, - pSrb->DataBuffer - ); - - // If the request is complete, status and transfer length aren't ever going to be set. - - if (FALSE==bPending) { // Completed? - pSrb->DataTransferLength = ScsiPortWmiGetReturnSize(pRequestContext);; - pSrb->SrbStatus = ScsiPortWmiGetReturnStatus(pRequestContext); - } - } - - return TRUE; -} // End HandleWmiSrb(). - -/**************************************************************************************************/ -/* */ -/* QueryWmiRegInfo. */ -/* */ -/* Answers query for WMI registration information. */ -/* */ -/**************************************************************************************************/ + PSCSIWMI_REQUEST_CONTEXT pRequestContext; + PHW_SRB_EXTENSION pSrbExtension; + BOOLEAN bPending = FALSE; + + // + // Validate our assumptions. + // + ASSERT(pSrb->Function == SRB_FUNCTION_WMI); + ASSERT(pSrb->Length == sizeof (SCSI_WMI_REQUEST_BLOCK)); + + if (!(pSrb->WMIFlags & SRB_WMI_FLAGS_ADAPTER_REQUEST)) { + + // + // This is targetted to one of the disks, since there is + // no per-disk WMI information we return an error. + // Note that if there was per-disk information, then you'd + // likely have a different WmiLibContext and a different + // set of GUIDs. + // + pSrb->DataTransferLength = 0; + pSrb->SrbStatus = SRB_STATUS_NO_DEVICE; + + } else { + if (IRP_MN_ENABLE_EVENTS == pSrb->WMISubFunction) { + } + + pSrbExtension = (PHW_SRB_EXTENSION)pSrb->SrbExtension; + pRequestContext = &(pSrbExtension->WmiRequestContext); + + // + // Save the pointer to the SRB in UserContext of + // SCSIWMI_REQUEST_CONTEXT + // + pRequestContext->UserContext = pSrb; + + // + // Process the incoming WMI request. + // + + bPending = ScsiPortWmiDispatchFunction( + &pHbaExtension->WmiLibContext, + pSrb->WMISubFunction, + pHbaExtension, + pRequestContext, + pSrb->DataPath, + pSrb->DataTransferLength, + pSrb->DataBuffer); + + // If the request is complete, status and transfer + // length aren't ever going to be set. + + if (FALSE == bPending) { + pSrb->DataTransferLength = + ScsiPortWmiGetReturnSize(pRequestContext); + pSrb->SrbStatus = + ScsiPortWmiGetReturnStatus(pRequestContext); + } + } + + return (TRUE); +} + UCHAR QueryWmiRegInfo( - __in PVOID pContext, - __in PSCSIWMI_REQUEST_CONTEXT pRequestContext, - __out PWCHAR * pMofResourceName - ) + __in PVOID pContext, + __in PSCSIWMI_REQUEST_CONTEXT pRequestContext, + __out PWCHAR *pMofResourceName) { - KIRQL saveIRQL; - UNREFERENCED_PARAMETER(pContext); - UNREFERENCED_PARAMETER(pRequestContext); - - saveIRQL = KeGetCurrentIrql(); - - *pMofResourceName = L"MofResource"; - - return SRB_STATUS_SUCCESS; -} // End QueryWmiRegInfo(). - -/**************************************************************************************************/ -/* */ -/* QueryWmiDataBlock. */ -/* */ -/* Answers query for WMI data block. */ -/* */ -/* Note: The support for MSFC GUIDs is only illustrative, showing how to produce plausible */ -/* results. */ -/* */ -/**************************************************************************************************/ + KIRQL saveIRQL; + UNREFERENCED_PARAMETER(pContext); + UNREFERENCED_PARAMETER(pRequestContext); + + saveIRQL = KeGetCurrentIrql(); + + *pMofResourceName = L"MofResource"; + + return (SRB_STATUS_SUCCESS); +} + BOOLEAN QueryWmiDataBlock( - __in PVOID pContext, - __in PSCSIWMI_REQUEST_CONTEXT pDispatchContext, - __in ULONG GuidIndex, - __in ULONG InstanceIndex, - __in ULONG InstanceCount, - __in __out PULONG pInstanceLenArr, - __in ULONG BufferAvail, - __out PUCHAR pBuffer - ) + __in PVOID pContext, + __in PSCSIWMI_REQUEST_CONTEXT pDispatchContext, + __in ULONG GuidIndex, + __in ULONG InstanceIndex, + __in ULONG InstanceCount, + __in __out PULONG pInstanceLenArr, + __in ULONG BufferAvail, + __out PUCHAR pBuffer) { - pHW_HBA_EXT pHbaExtension = (pHW_HBA_EXT)pContext; - PSCSI_WMI_REQUEST_BLOCK pSrb = (PSCSI_WMI_REQUEST_BLOCK)pDispatchContext->UserContext; - ULONG sizeNeeded = 0, - i, - IdxLim = InstanceIndex + InstanceCount, - ulBfrUsed = 0, - LastIndex, - InstanceSize; - UCHAR status = SRB_STATUS_SUCCESS; - PWCHAR pBfrX; + pHW_HBA_EXT pHbaExtension = (pHW_HBA_EXT)pContext; + PSCSI_WMI_REQUEST_BLOCK pSrb = + (PSCSI_WMI_REQUEST_BLOCK)pDispatchContext->UserContext; + ULONG sizeNeeded = 0, + i, + IdxLim = InstanceIndex + InstanceCount, + ulBfrUsed = 0, + LastIndex, + InstanceSize; + UCHAR status = SRB_STATUS_SUCCESS; + PWCHAR pBfrX; + + switch (GuidIndex) { + case IdxGmDemoDriver_GUID: + + // Demo index. + + sizeNeeded = GmDemoDriver_SIZE; + + if (BufferAvail < sizeNeeded) { + status = SRB_STATUS_DATA_OVERRUN; + break; + } + + for (i = InstanceIndex; i < IdxLim; i++) { + PGmDemoDriver pOut = + (PGmDemoDriver) + ((PUCHAR)pBuffer + ulBfrUsed); + + pOut->TheAnswer = 22; + pOut->TheNextAnswer = 23; + pOut->SRBsSeen = pHbaExtension->SRBsSeen; + pOut->WMISRBsSeen = pHbaExtension->WMISRBsSeen; + + pInstanceLenArr[i] = sizeNeeded; + ulBfrUsed += pInstanceLenArr[i]; + } + + break; + + case IdxGmDemoDriver2_GUID: + sizeNeeded = sizeof (ULONG); + + if (BufferAvail < sizeNeeded) { + status = SRB_STATUS_DATA_OVERRUN; + break; + } + + status = SRB_STATUS_INVALID_REQUEST; + break; + + case IdxGmDemoDriverSrbActivity_GUID: + sizeNeeded = 0; + break; + + case IdxGmDrvDrvMethodGuid: + sizeNeeded = sizeof (ULONG); + + if (BufferAvail < sizeNeeded) { + status = SRB_STATUS_DATA_OVERRUN; + break; + } + break; + + case IdxMSFC_FibrePortHBAStatistics_GUID: { + PMSFC_FibrePortHBAStatistics pPortStats; + PMSFC_HBAPortStatistics pHBAPortStats; + + // Verify there is enough room in the output buffer + // to return all data requested. + // Calculate size, rounding up to a multiple of + // 8 if needed. + InstanceSize = + (sizeof (MSFC_FibrePortHBAStatistics)+7) & ~7; + sizeNeeded = InstanceCount * InstanceSize; + + if (BufferAvail >= sizeNeeded) { + LastIndex = InstanceIndex + InstanceCount; + + for (i = InstanceIndex, + pPortStats = + (PMSFC_FibrePortHBAStatistics)pBuffer; + i < LastIndex; + i++, pPortStats++) { + // Set a unique value for the port. + + pPortStats->UniquePortId = + (ULONGLONG)pHbaExtension + i; + + pPortStats->HBAStatus = HBA_STATUS_OK; + + pHBAPortStats = + &pPortStats->Statistics; + + pHBAPortStats->SecondsSinceLastReset = + 10; + pHBAPortStats->TxFrames = 11; + pHBAPortStats->TxWords = 12; + pHBAPortStats->RxFrames = 13; + pHBAPortStats->RxWords = 14; + pHBAPortStats->LIPCount = 15; + pHBAPortStats->NOSCount = 16; + pHBAPortStats->ErrorFrames = 17; + pHBAPortStats->DumpedFrames = 18; + pHBAPortStats->LinkFailureCount = 19; + pHBAPortStats->LossOfSyncCount = 20; + pHBAPortStats->LossOfSignalCount = 21; + pHBAPortStats-> + PrimitiveSeqProtocolErrCount = 22; + pHBAPortStats->InvalidTxWordCount = 23; + pHBAPortStats->InvalidCRCCount = 24; + + *pInstanceLenArr++ = + sizeof (MSFC_FibrePortHBAStatistics); + } + } else { + status = SRB_STATUS_DATA_OVERRUN; + } + + break; + } + + case IdxMSFC_HBAPortStatistics_GUID: { + PMSFC_HBAPortStatistics pHBAPortStats; + PUCHAR pBuffer2 = pBuffer; + + InstanceSize = (sizeof (MSFC_HBAPortStatistics)+7) & ~7; + sizeNeeded = InstanceCount * InstanceSize; + + if (BufferAvail >= sizeNeeded) { + LastIndex = InstanceIndex + InstanceCount; + + for (i = InstanceIndex; i < LastIndex; i++) { + pHBAPortStats = + (PMSFC_HBAPortStatistics)pBuffer2; + + memset(pBuffer2, 0, InstanceSize); + + pHBAPortStats->SecondsSinceLastReset = + 0; + pHBAPortStats->TxFrames = 1; + pHBAPortStats->TxWords = 2; + pHBAPortStats->RxFrames = 3; + pHBAPortStats->RxWords = 4; + pHBAPortStats->LIPCount = 5; + pHBAPortStats->NOSCount = 6; + pHBAPortStats->ErrorFrames = 7; + pHBAPortStats->DumpedFrames = 8; + pHBAPortStats->LinkFailureCount = 9; + pHBAPortStats->LossOfSyncCount = 10; + pHBAPortStats->LossOfSignalCount = 11; + pHBAPortStats-> + PrimitiveSeqProtocolErrCount = 12; + pHBAPortStats->InvalidTxWordCount = 13; + pHBAPortStats->InvalidCRCCount = 14; + + pBuffer2 += InstanceSize; + *pInstanceLenArr++ = + sizeof (MSFC_HBAPortStatistics); + } + } else { + status = SRB_STATUS_DATA_OVERRUN; + } + + break; + } + + case IdxMSFC_FibrePortHBAAttributes_GUID: { + PUCHAR pBuffer2 = pBuffer; + +#define FibrePortHBAAttributesNODEWWN "VM123456" +/* Will appear as 56:4D:32:33:34:35:36:37 */ +#define FibrePortHBAAttributesPortWWN "VM234567" +#define FibrePortHBAAttributesPortType 0x99 +#define FibrePortHBAAttributesPortSupportedFc4Types "VM345678" +#define FibrePortHBAAttributesPortActiveFc4Types "VM456789" +#define FibrePortHBAAttributesFabricName "VM56789A" + + InstanceSize = + (sizeof (MSFC_FibrePortHBAAttributes)+7)&~7; + sizeNeeded = InstanceCount * InstanceSize; + + if (BufferAvail >= sizeNeeded) { + LastIndex = InstanceIndex + InstanceCount; + + for (i = InstanceIndex; i < LastIndex; i++) { + PMSFC_FibrePortHBAAttributes + pFibrePortHBAAttributes = + (PMSFC_FibrePortHBAAttributes) + pBuffer2; + + memset(pBuffer2, 0, InstanceSize); + + pFibrePortHBAAttributes->UniquePortId = + ((ULONGLONG)pHbaExtension) + i; + pFibrePortHBAAttributes->HBAStatus = + HBA_STATUS_OK; + + memcpy(pFibrePortHBAAttributes->Attributes.NodeWWN, + FibrePortHBAAttributesNODEWWN, + sizeof (pFibrePortHBAAttributes->Attributes.NodeWWN)); + + memcpy(pFibrePortHBAAttributes->Attributes.PortWWN, + FibrePortHBAAttributesPortWWN, + sizeof (pFibrePortHBAAttributes->Attributes.PortWWN)); + + pFibrePortHBAAttributes->Attributes. + PortFcId = i + 0x100; + pFibrePortHBAAttributes->Attributes. + PortType = + FibrePortHBAAttributesPortType + i; + pFibrePortHBAAttributes->Attributes. + PortState = i; + pFibrePortHBAAttributes->Attributes. + PortSupportedClassofService = i; + + memcpy(pFibrePortHBAAttributes->Attributes.PortSupportedFc4Types, + FibrePortHBAAttributesPortSupportedFc4Types, + sizeof (pFibrePortHBAAttributes->Attributes.PortSupportedFc4Types)); + + memcpy(pFibrePortHBAAttributes->Attributes.PortActiveFc4Types, + FibrePortHBAAttributesPortActiveFc4Types, + sizeof (pFibrePortHBAAttributes->Attributes.PortActiveFc4Types)); + + pFibrePortHBAAttributes->Attributes. + PortSupportedSpeed = i * 2; + pFibrePortHBAAttributes->Attributes. + PortSpeed = i; + pFibrePortHBAAttributes->Attributes. + PortMaxFrameSize = i * 4; + + memcpy(pFibrePortHBAAttributes->Attributes.FabricName, + FibrePortHBAAttributesFabricName, + sizeof (pFibrePortHBAAttributes->Attributes.FabricName)); + + pFibrePortHBAAttributes->Attributes. + NumberofDiscoveredPorts = 1; + + pBuffer2 += InstanceSize; + *pInstanceLenArr++ = + sizeof (MSFC_FibrePortHBAAttributes); + } + } else { + status = SRB_STATUS_DATA_OVERRUN; + } + break; + } + +#define CopyWMIString(_pDest, _pSrc, _maxlength) \ + { \ + PUSHORT _pDestTemp = _pDest; \ + USHORT _length = _maxlength - sizeof (USHORT); \ + *_pDestTemp++ = _length;\ + _length = (USHORT)min(wcslen(_pSrc)*sizeof (WCHAR), _length); \ + memcpy(_pDestTemp, _pSrc, _length);\ + } + + case IdxMSFC_FCAdapterHBAAttributes_GUID: + { + PMSFC_FCAdapterHBAAttributes pFCAdapterHBAAttributes; + + // + // First thing to do is verify if there is enough + // room in the output buffer to return all data + // requested + // + sizeNeeded = (sizeof (MSFC_FCAdapterHBAAttributes)); + + if (BufferAvail >= sizeNeeded) { +#define FCAdapterHBAAttributesNODEWWN "12345678" +#define VENDORID 0x1234 +#define PRODUCTID 0x5678 +#define MANUFACTURER L"OpenZFS" +#define SERIALNUMBER L"ZVOL SerialNumber" +#define MODEL L"ZVOL Model" +#define MODELDESCRIPTION L"ZVOL ModelDescription" +#define NODESYMBOLICNAME L"ZVOL NodeSymbolicName" +#define HARDWAREVERSION L"ZVOL HardwareVersion" +#define DRIVERVERSION L"ZVOL DriverVersion" +#define OPTIONROMVERSION L"ZVOL OptionROMVersion" +#define DRIVERNAME L"ZVOL DriverName" +#define FIRMWAREVERSION L"ZVOL FirmwareVersion" +#define MFRDOMAIN L"ZVOL MfrDomain" + + // + // We know there is always only 1 instance + // for this guid + // + pFCAdapterHBAAttributes = + (PMSFC_FCAdapterHBAAttributes)pBuffer; + memset(pBuffer, 0, sizeNeeded); + pFCAdapterHBAAttributes->UniqueAdapterId = + (ULONGLONG)pHbaExtension; + + pFCAdapterHBAAttributes->HBAStatus = + HBA_STATUS_OK; + + memcpy(pFCAdapterHBAAttributes->NodeWWN, + FCAdapterHBAAttributesNODEWWN, + sizeof (pFCAdapterHBAAttributes->NodeWWN)); + + pFCAdapterHBAAttributes->VendorSpecificID = + VENDORID | (PRODUCTID<<16); + + pFCAdapterHBAAttributes->NumberOfPorts = + NUMBEROFPORTS; + + pBfrX = pFCAdapterHBAAttributes->Manufacturer; + + CopyWMIString(pFCAdapterHBAAttributes->Manufacturer, + MANUFACTURER, + sizeof (pFCAdapterHBAAttributes->Manufacturer)); + + CopyWMIString(pFCAdapterHBAAttributes->SerialNumber, + SERIALNUMBER, + sizeof (pFCAdapterHBAAttributes->SerialNumber)); + + CopyWMIString(pFCAdapterHBAAttributes->Model, + MODEL, + sizeof (pFCAdapterHBAAttributes->Model)); + + CopyWMIString(pFCAdapterHBAAttributes->ModelDescription, + MODELDESCRIPTION, + sizeof (pFCAdapterHBAAttributes->ModelDescription)); + + CopyWMIString(pFCAdapterHBAAttributes->NodeSymbolicName, + NODESYMBOLICNAME, + sizeof (pFCAdapterHBAAttributes->NodeSymbolicName)); + + CopyWMIString(pFCAdapterHBAAttributes->HardwareVersion, + HARDWAREVERSION, + sizeof (pFCAdapterHBAAttributes->HardwareVersion)); + + CopyWMIString(pFCAdapterHBAAttributes->DriverVersion, + DRIVERVERSION, + sizeof (pFCAdapterHBAAttributes->DriverVersion)); + + CopyWMIString(pFCAdapterHBAAttributes->OptionROMVersion, + OPTIONROMVERSION, + sizeof (pFCAdapterHBAAttributes->OptionROMVersion)); + + CopyWMIString(pFCAdapterHBAAttributes->FirmwareVersion, + FIRMWAREVERSION, + sizeof (pFCAdapterHBAAttributes->FirmwareVersion)); + + CopyWMIString(pFCAdapterHBAAttributes->DriverName, + DRIVERNAME, + sizeof (pFCAdapterHBAAttributes->DriverName)); + + CopyWMIString(pFCAdapterHBAAttributes->MfgDomain, + MFRDOMAIN, + sizeof (pFCAdapterHBAAttributes->MfgDomain)); + + pInstanceLenArr[0] = + sizeof (MSFC_FCAdapterHBAAttributes); + + } else { + status = SRB_STATUS_DATA_OVERRUN; + } + break; + } + + case IdxMSFC_HBAFCPInfo_GUID: + case IdxMSFC_FibrePortHBAMethods_GUID: + case IdxMSFC_HBAAdapterMethods_GUID: + { + // + // Methods don't return data per se, but must respond to + // queries with an empty data block. We know that all of + // these method guids only have one instance + // + sizeNeeded = sizeof (ULONG); + + if (BufferAvail >= sizeNeeded) { + pInstanceLenArr[0] = sizeNeeded; + } else { + status = SRB_STATUS_DATA_OVERRUN; + } + break; + } + + default: + status = SRB_STATUS_ERROR; + break; + } + + SpUpdateWmiRequest(pHbaExtension, pSrb, pDispatchContext, + status, sizeNeeded); + + return (SRB_STATUS_PENDING); +} - switch(GuidIndex) { - case IdxGmDemoDriver_GUID: - - // Demo index. - - sizeNeeded = GmDemoDriver_SIZE; - - if (BufferAvailTheAnswer = 22; - pOut->TheNextAnswer = 23; - pOut->SRBsSeen = pHbaExtension->SRBsSeen; - pOut->WMISRBsSeen = pHbaExtension->WMISRBsSeen; - - pInstanceLenArr[i] = sizeNeeded; // Set size of data items in instance. - ulBfrUsed += pInstanceLenArr[i]; // Update running count of bytes used. - } - - break; - - case IdxGmDemoDriver2_GUID: - - // Demo index. - - sizeNeeded = sizeof(ULONG); - - if (BufferAvail= sizeNeeded) { - LastIndex = InstanceIndex + InstanceCount; - - for ( - i = InstanceIndex, pPortStats = (PMSFC_FibrePortHBAStatistics)pBuffer; - i < LastIndex; - i++, pPortStats++ - ) { - // Set a unique value for the port. - - pPortStats->UniquePortId = (ULONGLONG)pHbaExtension + i; - - pPortStats->HBAStatus = HBA_STATUS_OK; - - pHBAPortStats = // Point to the Statistics area. - &pPortStats->Statistics; - - pHBAPortStats->SecondsSinceLastReset = 10; - pHBAPortStats->TxFrames = 11; - pHBAPortStats->TxWords = 12; - pHBAPortStats->RxFrames = 13; - pHBAPortStats->RxWords = 14; - pHBAPortStats->LIPCount = 15; - pHBAPortStats->NOSCount = 16; - pHBAPortStats->ErrorFrames = 17; - pHBAPortStats->DumpedFrames = 18; - pHBAPortStats->LinkFailureCount = 19; - pHBAPortStats->LossOfSyncCount = 20; - pHBAPortStats->LossOfSignalCount = 21; - pHBAPortStats->PrimitiveSeqProtocolErrCount = 22; - pHBAPortStats->InvalidTxWordCount = 23; - pHBAPortStats->InvalidCRCCount = 24; - - *pInstanceLenArr++ = sizeof(MSFC_FibrePortHBAStatistics); - } - } else { - status = SRB_STATUS_DATA_OVERRUN; - } - - break; - } - - case IdxMSFC_HBAPortStatistics_GUID: { - PMSFC_HBAPortStatistics pHBAPortStats; - PUCHAR pBuffer2 = pBuffer; - - InstanceSize = (sizeof(MSFC_HBAPortStatistics)+7) & ~7; - sizeNeeded = InstanceCount * InstanceSize; - - if (BufferAvail >= sizeNeeded) { - LastIndex = InstanceIndex + InstanceCount; - - for (i = InstanceIndex; i < LastIndex; i++) { - pHBAPortStats = (PMSFC_HBAPortStatistics)pBuffer2; - - memset(pBuffer2, 0, InstanceSize); - - pHBAPortStats->SecondsSinceLastReset = 0; - pHBAPortStats->TxFrames = 1; - pHBAPortStats->TxWords = 2; - pHBAPortStats->RxFrames = 3; - pHBAPortStats->RxWords = 4; - pHBAPortStats->LIPCount = 5; - pHBAPortStats->NOSCount = 6; - pHBAPortStats->ErrorFrames = 7; - pHBAPortStats->DumpedFrames = 8; - pHBAPortStats->LinkFailureCount = 9; - pHBAPortStats->LossOfSyncCount = 10; - pHBAPortStats->LossOfSignalCount = 11; - pHBAPortStats->PrimitiveSeqProtocolErrCount = 12; - pHBAPortStats->InvalidTxWordCount = 13; - pHBAPortStats->InvalidCRCCount = 14; - - pBuffer2 += InstanceSize; - *pInstanceLenArr++ = sizeof(MSFC_HBAPortStatistics); - } - } else { - status = SRB_STATUS_DATA_OVERRUN; - } - - break; - } - - case IdxMSFC_FibrePortHBAAttributes_GUID: { - PUCHAR pBuffer2 = pBuffer; - - #define FibrePortHBAAttributesNODEWWN "VM123456" - #define FibrePortHBAAttributesPortWWN "VM234567" /* Will appear as 56:4D:32:33:34:35:36:37 */ - #define FibrePortHBAAttributesPortType 0x99 - #define FibrePortHBAAttributesPortSupportedFc4Types "VM345678" - #define FibrePortHBAAttributesPortActiveFc4Types "VM456789" - #define FibrePortHBAAttributesFabricName "VM56789A" - - InstanceSize = (sizeof(MSFC_FibrePortHBAAttributes)+7)&~7; - sizeNeeded = InstanceCount * InstanceSize; - - if (BufferAvail >= sizeNeeded) { - LastIndex = InstanceIndex + InstanceCount; - - for (i = InstanceIndex; i < LastIndex; i++) { - PMSFC_FibrePortHBAAttributes pFibrePortHBAAttributes = (PMSFC_FibrePortHBAAttributes)pBuffer2; - - memset(pBuffer2, 0, InstanceSize); - - pFibrePortHBAAttributes->UniquePortId = ((ULONGLONG)pHbaExtension) + i; - pFibrePortHBAAttributes->HBAStatus = HBA_STATUS_OK; - - memcpy(pFibrePortHBAAttributes->Attributes.NodeWWN, FibrePortHBAAttributesNODEWWN, - sizeof(pFibrePortHBAAttributes->Attributes.NodeWWN)); - - memcpy(pFibrePortHBAAttributes->Attributes.PortWWN, FibrePortHBAAttributesPortWWN, - sizeof(pFibrePortHBAAttributes->Attributes.PortWWN)); - - pFibrePortHBAAttributes->Attributes.PortFcId = i + 0x100; - pFibrePortHBAAttributes->Attributes.PortType = FibrePortHBAAttributesPortType + i; - pFibrePortHBAAttributes->Attributes.PortState = i; - pFibrePortHBAAttributes->Attributes.PortSupportedClassofService = i; - - memcpy(pFibrePortHBAAttributes->Attributes.PortSupportedFc4Types, FibrePortHBAAttributesPortSupportedFc4Types, - sizeof(pFibrePortHBAAttributes->Attributes.PortSupportedFc4Types)); - - memcpy(pFibrePortHBAAttributes->Attributes.PortActiveFc4Types, FibrePortHBAAttributesPortActiveFc4Types, - sizeof(pFibrePortHBAAttributes->Attributes.PortActiveFc4Types)); - - pFibrePortHBAAttributes->Attributes.PortSupportedSpeed = i*2; - pFibrePortHBAAttributes->Attributes.PortSpeed = i; - pFibrePortHBAAttributes->Attributes.PortMaxFrameSize = i*4; - - memcpy(pFibrePortHBAAttributes->Attributes.FabricName, FibrePortHBAAttributesFabricName, - sizeof(pFibrePortHBAAttributes->Attributes.FabricName)); - - pFibrePortHBAAttributes->Attributes.NumberofDiscoveredPorts = 1; - - pBuffer2 += InstanceSize; - *pInstanceLenArr++ = sizeof(MSFC_FibrePortHBAAttributes); - } - } else { - status = SRB_STATUS_DATA_OVERRUN; - } - break; - } - - #define CopyWMIString(_pDest, _pSrc, _maxlength) /* Destination addr, source addr, max length. */ \ - { \ - PUSHORT _pDestTemp = _pDest; /* Point to output area. */ \ - USHORT _length = _maxlength - sizeof(USHORT); /* Determine length of area for string itself. */ \ - \ - *_pDestTemp++ = _length; /* Insert area length as USHORT, bump pointer. */ \ - \ - _length = (USHORT)min(wcslen(_pSrc)*sizeof(WCHAR), _length); /* Determine actual length of string, up to max. */ \ - memcpy(_pDestTemp, _pSrc, _length); /* Copy actual string. */ \ - } - - case IdxMSFC_FCAdapterHBAAttributes_GUID: - { - PMSFC_FCAdapterHBAAttributes pFCAdapterHBAAttributes; - - // - // First thing to do is verify if there is enough room in - // the output buffer to return all data requested - // - sizeNeeded = (sizeof(MSFC_FCAdapterHBAAttributes)); - - if (BufferAvail >= sizeNeeded) { - #define FCAdapterHBAAttributesNODEWWN "12345678" - #define VENDORID 0x1234 - #define PRODUCTID 0x5678 - #define MANUFACTURER L"OpenZFS" - #define SERIALNUMBER L"ZVOL SerialNumber" - #define MODEL L"ZVOL Model" - #define MODELDESCRIPTION L"ZVOL ModelDescription" - #define NODESYMBOLICNAME L"ZVOL NodeSymbolicName" - #define HARDWAREVERSION L"ZVOL HardwareVersion" - #define DRIVERVERSION L"ZVOL DriverVersion" - #define OPTIONROMVERSION L"ZVOL OptionROMVersion" - #define DRIVERNAME L"ZVOL DriverName" - #define FIRMWAREVERSION L"ZVOL FirmwareVersion" - #define MFRDOMAIN L"ZVOL MfrDomain" - - // - // We know there is always only 1 instance for this - // guid - // - pFCAdapterHBAAttributes = (PMSFC_FCAdapterHBAAttributes)pBuffer; - - memset(pBuffer, 0, sizeNeeded); - - pFCAdapterHBAAttributes->UniqueAdapterId = (ULONGLONG)pHbaExtension; - - pFCAdapterHBAAttributes->HBAStatus = HBA_STATUS_OK; - - memcpy(pFCAdapterHBAAttributes->NodeWWN, FCAdapterHBAAttributesNODEWWN, sizeof(pFCAdapterHBAAttributes->NodeWWN)); - - pFCAdapterHBAAttributes->VendorSpecificID = VENDORID | (PRODUCTID<<16); - - pFCAdapterHBAAttributes->NumberOfPorts = NUMBEROFPORTS; - - pBfrX = pFCAdapterHBAAttributes->Manufacturer; - - CopyWMIString(pFCAdapterHBAAttributes->Manufacturer, MANUFACTURER, sizeof(pFCAdapterHBAAttributes->Manufacturer)); - - CopyWMIString(pFCAdapterHBAAttributes->SerialNumber, SERIALNUMBER, sizeof(pFCAdapterHBAAttributes->SerialNumber)); - - CopyWMIString(pFCAdapterHBAAttributes->Model, MODEL, sizeof(pFCAdapterHBAAttributes->Model)); - - CopyWMIString(pFCAdapterHBAAttributes->ModelDescription, MODELDESCRIPTION, sizeof(pFCAdapterHBAAttributes->ModelDescription)); - - CopyWMIString(pFCAdapterHBAAttributes->NodeSymbolicName, NODESYMBOLICNAME, sizeof(pFCAdapterHBAAttributes->NodeSymbolicName)); - - CopyWMIString(pFCAdapterHBAAttributes->HardwareVersion, HARDWAREVERSION, sizeof(pFCAdapterHBAAttributes->HardwareVersion)); - - CopyWMIString(pFCAdapterHBAAttributes->DriverVersion, DRIVERVERSION, sizeof(pFCAdapterHBAAttributes->DriverVersion)); - - CopyWMIString(pFCAdapterHBAAttributes->OptionROMVersion, OPTIONROMVERSION, sizeof(pFCAdapterHBAAttributes->OptionROMVersion)); - - CopyWMIString(pFCAdapterHBAAttributes->FirmwareVersion, FIRMWAREVERSION, sizeof(pFCAdapterHBAAttributes->FirmwareVersion)); - - CopyWMIString(pFCAdapterHBAAttributes->DriverName, DRIVERNAME, sizeof(pFCAdapterHBAAttributes->DriverName)); - - CopyWMIString(pFCAdapterHBAAttributes->MfgDomain, MFRDOMAIN, sizeof(pFCAdapterHBAAttributes->MfgDomain)); - - pInstanceLenArr[0] = sizeof(MSFC_FCAdapterHBAAttributes); // Only 1 instance. - - } else { - status = SRB_STATUS_DATA_OVERRUN; - } - break; - } - - case IdxMSFC_HBAFCPInfo_GUID: - case IdxMSFC_FibrePortHBAMethods_GUID: - case IdxMSFC_HBAAdapterMethods_GUID: - { - // - // Methods don't return data per se, but must respond to - // queries with an empty data block. We know that all of - // these method guids only have one instance - // - sizeNeeded = sizeof(ULONG); - - if (BufferAvail >= sizeNeeded) { - pInstanceLenArr[0] = sizeNeeded; - } else { - status = SRB_STATUS_DATA_OVERRUN; - } - break; - } - - default: // Unsupported GUID. - - status = SRB_STATUS_ERROR; // Follow practice in iSCSI client. - break; - } // End switch(GuidIndex). - - SpUpdateWmiRequest(pHbaExtension, pSrb, pDispatchContext, status, sizeNeeded); - - return SRB_STATUS_PENDING; -} // End QueryWmiDataBlock(); - -/**************************************************************************************************/ -/* */ -/* SetWmiDataBlock. */ -/* */ -/* Sets WMI data block. */ -/* */ -/**************************************************************************************************/ UCHAR SetWmiDataBlock( - __in PVOID pContext, - __in PSCSIWMI_REQUEST_CONTEXT pDispatchContext, - __in ULONG GuidIndex, - __in ULONG InstanceIndex, - __in ULONG BufferSize, - __in PUCHAR pBuffer - ) + __in PVOID pContext, + __in PSCSIWMI_REQUEST_CONTEXT pDispatchContext, + __in ULONG GuidIndex, + __in ULONG InstanceIndex, + __in ULONG BufferSize, + __in PUCHAR pBuffer) { - pHW_HBA_EXT pHbaExtension = (pHW_HBA_EXT)pContext; - PSCSI_WMI_REQUEST_BLOCK pSrb = (PSCSI_WMI_REQUEST_BLOCK)pDispatchContext->UserContext; - UCHAR status = SRB_STATUS_SUCCESS; - ULONG sizeNeeded = 0; - - UNREFERENCED_PARAMETER(InstanceIndex); - UNREFERENCED_PARAMETER(BufferSize); - UNREFERENCED_PARAMETER(pBuffer); - - switch(GuidIndex) { - - default: - - status = SRB_STATUS_INVALID_REQUEST; - break; - } // End switch(GuidIndex). - - SpUpdateWmiRequest(pHbaExtension, pSrb, pDispatchContext, status, sizeNeeded); - - return SRB_STATUS_PENDING; -} // End SetWmiDataBlock(). - -/**************************************************************************************************/ -/* */ -/* ExecuteWmiMethod. */ -/* */ -/* Executes a WMI method. */ -/* */ -/* Note: The support for MSFC GUIDs is only illustrative, showing how to produce plausible */ -/* results. */ -/* */ -/**************************************************************************************************/ -UCHAR -ExecuteWmiMethod( - __in PVOID pContext, - __in PSCSIWMI_REQUEST_CONTEXT pDispatchContext, - __in ULONG GuidIndex, - __in ULONG InstanceIndex, - __in ULONG MethodId, - __in ULONG InBufferSize, - __in ULONG OutBufferSize, - __in __out PUCHAR pBuffer - ) -{ - pHW_HBA_EXT pHbaExtension = (pHW_HBA_EXT)pContext; - PSCSI_WMI_REQUEST_BLOCK pSrb = (PSCSI_WMI_REQUEST_BLOCK)pDispatchContext->UserContext; - ULONG sizeNeeded = 0, - i; - UCHAR status = SRB_STATUS_SUCCESS; - - UNREFERENCED_PARAMETER(InstanceIndex); - - switch(GuidIndex) { - - case IdxMSFC_HBAFCPInfo_GUID: - - switch(MethodId) { - - // The next is the source of LUN that FCInfo gets (via HBAAPI!HbapGetFcpTargets). - - case GetFcpTargetMapping: { - #define PORTNAME L"VirtMini FibrePortName" - #define OSDEVICENAME L"VirtMini OsDeviceName" - #define LuidNAME "VirtMini Dummy LUID" - - #define FcpIdNODEWWN "23456789" - #define FcpIdPORTWWN "3456789A" - - sizeNeeded = FIELD_OFFSET(GetFcpTargetMapping_OUT, Entry) + // Fixed portion. - (pHbaExtension->NbrLUNsperHBA * sizeof(HBAFCPScsiEntry)); // Variable portion. - - if (OutBufferSize >= sizeNeeded) { - PGetFcpTargetMapping_IN pIn = (PGetFcpTargetMapping_IN)pBuffer; - PGetFcpTargetMapping_OUT pOut = (PGetFcpTargetMapping_OUT)pBuffer; - - pIn; // Prevent C4189. - - // It would be a good thing to proceed only if pIn->HbaPortWWN = 'VM234567', ie, FibrePortHBAAttributesPortWWN. - // Probably (evaluate!) then pOut->TotalEntryCount = 0 and pOut->OutEntryCount = 0 - // and pOut->HBAStatus = HBA_STATUS_ERROR_ILLEGAL_WWN. And update sizeNeeded to reflect data actually returned. + pHW_HBA_EXT pHbaExtension = (pHW_HBA_EXT)pContext; + PSCSI_WMI_REQUEST_BLOCK pSrb = + (PSCSI_WMI_REQUEST_BLOCK)pDispatchContext->UserContext; + UCHAR status = SRB_STATUS_SUCCESS; + ULONG sizeNeeded = 0; - RtlZeroMemory(pOut, OutBufferSize); + UNREFERENCED_PARAMETER(InstanceIndex); + UNREFERENCED_PARAMETER(BufferSize); + UNREFERENCED_PARAMETER(pBuffer); - pOut->HBAStatus = HBA_STATUS_OK; + switch (GuidIndex) { - pOut->TotalEntryCount = pHbaExtension->NbrLUNsperHBA; + default: - pOut->OutEntryCount = pHbaExtension->NbrLUNsperHBA; + status = SRB_STATUS_INVALID_REQUEST; + break; + } - for (i=0; iNbrLUNsperHBA; i++) { // Construct each HBAFCPScsiEntry. - // Construct the present HBAFCPID. - - pOut->Entry[i].FCPId.Fcid = i; - - memcpy(pOut->Entry[i].FCPId.NodeWWN, FcpIdNODEWWN, - sizeof(pOut->Entry[i].FCPId.NodeWWN)); + SpUpdateWmiRequest(pHbaExtension, pSrb, pDispatchContext, + status, sizeNeeded); - memcpy(pOut->Entry[i].FCPId.PortWWN, FcpIdPORTWWN, - sizeof(pOut->Entry[i].FCPId.PortWWN)); + return (SRB_STATUS_PENDING); +} - pOut->Entry[i].FCPId.FcpLun = i; - - // Construct Luid. - - memcpy(pOut->Entry[i].Luid, LuidNAME, min(sizeof(pOut->Entry[i].Luid), sizeof(LuidNAME)-1)); - - // Construct the present HBAScsiID. - - pOut->Entry[i].ScsiId.ScsiBusNumber = 0; - pOut->Entry[i].ScsiId.ScsiTargetNumber = 0; - pOut->Entry[i].ScsiId.ScsiOSLun = i; - } - } else { - status = SRB_STATUS_DATA_OVERRUN; - } - - break; - } - - default: // Unsupported method. - - __try { // In case there's no kernel debugger. - DbgBreakPoint(); - } - __except(EXCEPTION_EXECUTE_HANDLER) { - } - - status = SRB_STATUS_INVALID_REQUEST; - break; - } // End switch(MethodId). - - break; - - case IdxMSFC_HBAAdapterMethods_GUID: - - switch(MethodId) { - - case RefreshInformation: { - - // Do nothing. - - break; - } - - case ScsiInquiry: { - PScsiInquiry_OUT pOut = (PScsiInquiry_OUT)pBuffer; - PScsiInquiry_IN pIn = (PScsiInquiry_IN)pBuffer; - PINQUIRYDATA pInqData = (PINQUIRYDATA)pOut->ResponseBuffer; - struct _CDB6INQUIRY3 * pCdbInq = (struct _CDB6INQUIRY3 *)pBuffer; - - sizeNeeded = FIELD_OFFSET(ScsiInquiry_OUT, ResponseBuffer) + sizeof(INQUIRYDATA); - - if (OutBufferSizeHBAStatus = HBA_STATUS_OK; - pOut->ResponseBufferSize = sizeof(INQUIRYDATA); - pOut->SenseBufferSize = 0; - pOut->ScsiStatus = 0; - - pInqData->DeviceType = DISK_DEVICE; - pInqData->RemovableMedia = FALSE; - pInqData->CommandQueue = TRUE; - - RtlMoveMemory(pInqData->VendorId, VENDOR_ID_ascii, sizeof(pInqData->VendorId)); - RtlMoveMemory(pInqData->ProductId, PRODUCT_ID_ascii, sizeof(pInqData->ProductId)); - RtlMoveMemory(pInqData->ProductRevisionLevel, PRODUCT_REV_ascii, sizeof(pInqData->ProductRevisionLevel)); - - break; - } - - case SendCTPassThru: { - - #define minSizeNeeded 0x1000 - - // - // Derived from \\tkcsssrcidx01\windows2008r2-windows7\rtm\drivers\storage\hbaapi\dll\ctpass.h - // - - // Response codes, see 4.3.1.6 FC-GS3. Note they are reversed since they are little endian in the packet. - - #define CTREJECT 0x0180 - #define CTACCESPT 0x0280 - - // CT Passthru definitions. See section 4.3 in FC-GS3 - - typedef struct _CTPREAMBLE { - UCHAR Revision; // protocol revision - UCHAR IN_ID[3]; // set to 0 by requestor - UCHAR GS_Type; // General services type - UCHAR GS_SubType; // General services sub type - UCHAR Options; // See FC-GS3 4.3.1.5 - UCHAR Reserved1; - USHORT CommandResponse; // Command or respose code - union { - USHORT MaxResidualSize; // For request: max size. For accept: size left - USHORT MaxSize; // max accept (not counting preamble) - } _xx; - UCHAR Reserved2; - UCHAR Reason; // reject reason code - UCHAR ReasonExplaination;// reject reason code explaination - UCHAR VendorSpecific; - } CTPREAMBLE, *PCTPREAMBLE; - - typedef struct _CTPASSTHRU_GSPN_ID_ACCEPT { - CTPREAMBLE Preamble; - UCHAR SymbolicNameLen; // number of bytes in symbolic name that follow - UCHAR SymbolicName[1]; // symbolic name - } CTPASSTHRU_GSPN_ID_ACCEPT, *PCTPASSTHRU_GSPN_ID_ACCEPT; - - PSendCTPassThru_IN pIn; - PSendCTPassThru_OUT pOut; - ULONG RequestCount, - ResponseCount; - - if (InBufferSize >= sizeof(ULONG)) { - pIn = (PSendCTPassThru_IN)pBuffer; - - RequestCount = pIn->RequestBufferCount; - sizeNeeded = FIELD_OFFSET(SendCTPassThru_IN, RequestBuffer) + RequestCount; - - if (InBufferSize >= sizeNeeded) { - #define RESPONSE_BUFFER_SIZE 0x1000 - - ResponseCount = RESPONSE_BUFFER_SIZE; - sizeNeeded = FIELD_OFFSET(SendCTPassThru_OUT, ResponseBuffer) + ResponseCount; - - if (OutBufferSize >= sizeNeeded) { - PCTPASSTHRU_GSPN_ID_ACCEPT pRespBfr; - #define SYMBOLICNAME "VMSymName" - - pOut = (PSendCTPassThru_OUT)pBuffer; - pOut->HBAStatus = HBA_STATUS_OK; - pOut->TotalResponseBufferCount = ResponseCount; - pOut->ActualResponseBufferCount = ResponseCount; - - pRespBfr = (PCTPASSTHRU_GSPN_ID_ACCEPT)pOut->ResponseBuffer; - - memset(pRespBfr, 0, ResponseCount); - - pRespBfr->Preamble.CommandResponse = CTACCESPT; - pRespBfr->SymbolicNameLen = sizeof(SYMBOLICNAME)-1; - memcpy(pRespBfr->SymbolicName, SYMBOLICNAME, pRespBfr->SymbolicNameLen); - } else { - status = SRB_STATUS_DATA_OVERRUN; - } - } else { - status = SRB_STATUS_ERROR; - } - } else { - sizeNeeded = minSizeNeeded; - status = SRB_STATUS_ERROR; - } - - break; - } - - case ScsiReadCapacity: { - PScsiReadCapacity_IN pIn; - PScsiReadCapacity_OUT pOut; - PREAD_CAPACITY_DATA pReadCapData; - - if (InBufferSize >= sizeof(ULONG)) { - pIn = (PScsiReadCapacity_IN)pBuffer; - - sizeNeeded = sizeof(ScsiReadCapacity_IN); - - if (InBufferSize >= sizeNeeded) { - sizeNeeded = FIELD_OFFSET(ScsiReadCapacity_OUT, ResponseBuffer) + - ScsiReadCapacity_OUT_ResponseBuffer_SIZE_HINT; - - if (OutBufferSize >= sizeNeeded) { - pOut = (PScsiReadCapacity_OUT)pBuffer; - pOut->HBAStatus = HBA_STATUS_OK; - pOut->ResponseBufferSize = sizeNeeded; - pOut->SenseBufferSize = 0; - - pReadCapData = (PREAD_CAPACITY_DATA)pOut->ResponseBuffer; - pReadCapData->LogicalBlockAddress = 0; - pReadCapData->BytesPerBlock = MP_BLOCK_SIZE; - } else { - status = SRB_STATUS_DATA_OVERRUN; - } - } else { - status = SRB_STATUS_ERROR; - } - } - else { - sizeNeeded = minSizeNeeded; - status = SRB_STATUS_ERROR; - } - - break; - } - - case SendRNID: { - PSendRNID_IN pIn; - PSendRNID_OUT pOut; - - if (InBufferSize >= sizeof(ULONG)) { - pIn = (PSendRNID_IN)pBuffer; - - sizeNeeded = sizeof(SendRNID_IN); - - if (InBufferSize >= sizeNeeded) { - sizeNeeded = FIELD_OFFSET(SendRNID_OUT, ResponseBuffer) + - SendRNID_OUT_ResponseBuffer_SIZE_HINT; - - if (OutBufferSize >= sizeNeeded) { - pOut = (PSendRNID_OUT)pBuffer; +UCHAR +ExecuteWmiMethod( + __in PVOID pContext, + __in PSCSIWMI_REQUEST_CONTEXT pDispatchContext, + __in ULONG GuidIndex, + __in ULONG InstanceIndex, + __in ULONG MethodId, + __in ULONG InBufferSize, + __in ULONG OutBufferSize, + __in __out PUCHAR pBuffer) +{ + pHW_HBA_EXT pHbaExtension = (pHW_HBA_EXT)pContext; + PSCSI_WMI_REQUEST_BLOCK pSrb = + (PSCSI_WMI_REQUEST_BLOCK)pDispatchContext->UserContext; + ULONG sizeNeeded = 0, + i; + UCHAR status = SRB_STATUS_SUCCESS; - pOut->HBAStatus = HBA_STATUS_OK; - pOut->ResponseBufferCount = SendRNID_OUT_ResponseBuffer_SIZE_HINT; + UNREFERENCED_PARAMETER(InstanceIndex); - memset(pOut->ResponseBuffer, 0xFF, pOut->ResponseBufferCount); - } else { - status = SRB_STATUS_DATA_OVERRUN; - } - } else { - status = SRB_STATUS_ERROR; - } - } - else { - sizeNeeded = minSizeNeeded; - status = SRB_STATUS_ERROR; - } + switch (GuidIndex) { - break; - } + case IdxMSFC_HBAFCPInfo_GUID: - default: // Unsupported method. + switch (MethodId) { - __try { // In case there's no kernel debugger. - DbgBreakPoint(); - } - __except(EXCEPTION_EXECUTE_HANDLER) { - } + // The next is the source of LUN that FCInfo + // gets (via HBAAPI!HbapGetFcpTargets). - status = SRB_STATUS_INVALID_REQUEST; + case GetFcpTargetMapping: { +#define PORTNAME L"VirtMini FibrePortName" +#define OSDEVICENAME L"VirtMini OsDeviceName" +#define LuidNAME "VirtMini Dummy LUID" - break; - } // End switch(MethodId). +#define FcpIdNODEWWN "23456789" +#define FcpIdPORTWWN "3456789A" - break; + sizeNeeded = FIELD_OFFSET( + GetFcpTargetMapping_OUT, + Entry) + + (pHbaExtension->NbrLUNsperHBA * + sizeof (HBAFCPScsiEntry)); - case IdxGmDrvDrvMethodGuid: + if (OutBufferSize >= sizeNeeded) { + PGetFcpTargetMapping_IN pIn = + (PGetFcpTargetMapping_IN) + pBuffer; + PGetFcpTargetMapping_OUT pOut = + (PGetFcpTargetMapping_OUT) + pBuffer; - switch(MethodId) { + pIn; - case GmDrvDemoMethod1: { + RtlZeroMemory(pOut, OutBufferSize); - // Demo method. + pOut->HBAStatus = HBA_STATUS_OK; - PGmDrvDemoMethod1_IN pInBfr = (PGmDrvDemoMethod1_IN)pBuffer; - PGmDrvDemoMethod1_OUT pOutBfr = (PGmDrvDemoMethod1_OUT)pBuffer; + pOut->TotalEntryCount = + pHbaExtension->NbrLUNsperHBA; - sizeNeeded = GmDrvDemoMethod1_OUT_SIZE; + pOut->OutEntryCount = + pHbaExtension->NbrLUNsperHBA; - if (OutBufferSizeNbrLUNsperHBA; + i++) { + // Construct the present HBAFCPID. - if (InBufferSizeEntry[i].FCPId.Fcid = i; - pOutBfr->outDatum = pInBfr->inDatum + 1; + memcpy(pOut->Entry[i].FCPId.NodeWWN, + FcpIdNODEWWN, + sizeof (pOut->Entry[i].FCPId.NodeWWN)); - break; + memcpy(pOut->Entry[i].FCPId.PortWWN, + FcpIdPORTWWN, + sizeof (pOut->Entry[i].FCPId.PortWWN)); - } + pOut->Entry[i].FCPId.FcpLun = i; - case GmDrvDemoMethod2: { + // Construct Luid. - // Demo method. + memcpy(pOut->Entry[i].Luid, LuidNAME, + min(sizeof (pOut->Entry[i].Luid), + sizeof (LuidNAME)-1)); - PGmDrvDemoMethod2_IN pInBfr = (PGmDrvDemoMethod2_IN)pBuffer; - PGmDrvDemoMethod2_OUT pOutBfr = (PGmDrvDemoMethod2_OUT)pBuffer; + // Construct the present HBAScsiID. - sizeNeeded = GmDrvDemoMethod2_OUT_SIZE; + pOut->Entry[i].ScsiId.ScsiBusNumber = 0; + pOut->Entry[i].ScsiId.ScsiTargetNumber = + 0; + pOut->Entry[i].ScsiId.ScsiOSLun = i; + } + } else { + status = SRB_STATUS_DATA_OVERRUN; + } - if (OutBufferSizeoutDatum1 = pInBfr->inDatum1 + pInBfr->inDatum2 + 1; + __try { + DbgBreakPoint(); + } + __except(EXCEPTION_EXECUTE_HANDLER) { + } - break; + status = SRB_STATUS_INVALID_REQUEST; + break; + } - } + break; - case GmDrvDemoMethod3: { + case IdxMSFC_HBAAdapterMethods_GUID: - // Demo method. + switch (MethodId) { - ULONG x1, x2; + case RefreshInformation: { + break; + } - PGmDrvDemoMethod3_IN pInBfr = (PGmDrvDemoMethod3_IN)pBuffer; - PGmDrvDemoMethod3_OUT pOutBfr = (PGmDrvDemoMethod3_OUT)pBuffer; + case ScsiInquiry: { + PScsiInquiry_OUT pOut = + (PScsiInquiry_OUT)pBuffer; + PScsiInquiry_IN pIn = + (PScsiInquiry_IN)pBuffer; + PINQUIRYDATA pInqData = + (PINQUIRYDATA)pOut->ResponseBuffer; + struct _CDB6INQUIRY3 *pCdbInq = + (struct _CDB6INQUIRY3 *)pBuffer; - sizeNeeded = GmDrvDemoMethod3_OUT_SIZE; + sizeNeeded = + FIELD_OFFSET(ScsiInquiry_OUT, + ResponseBuffer) + + sizeof (INQUIRYDATA); - if (OutBufferSizeinDatum1 + 1; - x2 = pInBfr->inDatum2 + 1; + memset(pOut, 0, OutBufferSize); - pOutBfr->outDatum1 = x1; - pOutBfr->outDatum2 = x2; + pOut->HBAStatus = HBA_STATUS_OK; + pOut->ResponseBufferSize = + sizeof (INQUIRYDATA); + pOut->SenseBufferSize = 0; + pOut->ScsiStatus = 0; - break; + pInqData->DeviceType = DISK_DEVICE; + pInqData->RemovableMedia = FALSE; + pInqData->CommandQueue = TRUE; - } + RtlMoveMemory(pInqData->VendorId, + VENDOR_ID_ascii, + sizeof (pInqData->VendorId)); + RtlMoveMemory(pInqData->ProductId, + PRODUCT_ID_ascii, + sizeof (pInqData->ProductId)); + RtlMoveMemory(pInqData->ProductRevisionLevel, + PRODUCT_REV_ascii, + sizeof (pInqData->ProductRevisionLevel)); + + break; + } - default: // Unsupported method. + case SendCTPassThru: { - status = SRB_STATUS_INVALID_REQUEST; - break; - } // End switch(MethodId). +#define minSizeNeeded 0x1000 - break; +// +// Derived from \\tkcsssrcidx01\windows2008r2-windows7\rtm\drivers\ +// storage\hbaapi\dll\ctpass.h +// - default: // Unsupported GUID. +// Response codes, see 4.3.1.6 FC-GS3. Note they are reversed since +// they are little endian in the packet. + +#define CTREJECT 0x0180 +#define CTACCESPT 0x0280 + +// CT Passthru definitions. See section 4.3 in FC-GS3 + + typedef struct _CTPREAMBLE { + UCHAR Revision; + UCHAR IN_ID[3]; + UCHAR GS_Type; + UCHAR GS_SubType; + UCHAR Options; + UCHAR Reserved1; + USHORT CommandResponse; + union { + USHORT MaxResidualSize; + USHORT MaxSize; + } _xx; + UCHAR Reserved2; + UCHAR Reason; + UCHAR ReasonExplaination; + UCHAR VendorSpecific; + } CTPREAMBLE, *PCTPREAMBLE; + + typedef struct _CTPASSTHRU_GSPN_ID_ACCEPT { + CTPREAMBLE Preamble; + UCHAR SymbolicNameLen; + UCHAR SymbolicName[1]; // symbolic name + } CTPASSTHRU_GSPN_ID_ACCEPT, *PCTPASSTHRU_GSPN_ID_ACCEPT; + + PSendCTPassThru_IN pIn; + PSendCTPassThru_OUT pOut; + ULONG RequestCount, + ResponseCount; + + if (InBufferSize >= sizeof (ULONG)) { + pIn = (PSendCTPassThru_IN)pBuffer; + + RequestCount = pIn->RequestBufferCount; + sizeNeeded = FIELD_OFFSET(SendCTPassThru_IN, + RequestBuffer) + RequestCount; + + if (InBufferSize >= sizeNeeded) { +#define RESPONSE_BUFFER_SIZE 0x1000 + + ResponseCount = RESPONSE_BUFFER_SIZE; + sizeNeeded = FIELD_OFFSET(SendCTPassThru_OUT, + ResponseBuffer) + ResponseCount; + + if (OutBufferSize >= sizeNeeded) { + PCTPASSTHRU_GSPN_ID_ACCEPT pRespBfr; +#define SYMBOLICNAME "VMSymName" + + pOut = (PSendCTPassThru_OUT)pBuffer; + pOut->HBAStatus = HBA_STATUS_OK; + pOut->TotalResponseBufferCount = + ResponseCount; + pOut->ActualResponseBufferCount = + ResponseCount; + + pRespBfr = + (PCTPASSTHRU_GSPN_ID_ACCEPT) + pOut->ResponseBuffer; + + memset(pRespBfr, 0, ResponseCount); + + pRespBfr->Preamble.CommandResponse = + CTACCESPT; + pRespBfr->SymbolicNameLen = + sizeof (SYMBOLICNAME)-1; + memcpy(pRespBfr->SymbolicName, + SYMBOLICNAME, + pRespBfr->SymbolicNameLen); + } else { + status = SRB_STATUS_DATA_OVERRUN; + } + } else { + status = SRB_STATUS_ERROR; + } + } else { + sizeNeeded = minSizeNeeded; + status = SRB_STATUS_ERROR; + } + + break; + } + + case ScsiReadCapacity: { + PScsiReadCapacity_IN pIn; + PScsiReadCapacity_OUT pOut; + PREAD_CAPACITY_DATA pReadCapData; + + if (InBufferSize >= sizeof (ULONG)) { + pIn = (PScsiReadCapacity_IN)pBuffer; + sizeNeeded = sizeof (ScsiReadCapacity_IN); + if (InBufferSize >= sizeNeeded) { + sizeNeeded = FIELD_OFFSET(ScsiReadCapacity_OUT, + ResponseBuffer) + + ScsiReadCapacity_OUT_ResponseBuffer_SIZE_HINT; + + if (OutBufferSize >= sizeNeeded) { + pOut = (PScsiReadCapacity_OUT) + pBuffer; + pOut->HBAStatus = HBA_STATUS_OK; + pOut->ResponseBufferSize = + sizeNeeded; + pOut->SenseBufferSize = 0; + + pReadCapData = + (PREAD_CAPACITY_DATA) + pOut->ResponseBuffer; + pReadCapData-> + LogicalBlockAddress = 0; + pReadCapData->BytesPerBlock = + MP_BLOCK_SIZE; + } else { + status = + SRB_STATUS_DATA_OVERRUN; + } + } else { + status = SRB_STATUS_ERROR; + } + } else { + sizeNeeded = minSizeNeeded; + status = SRB_STATUS_ERROR; + } + break; + } + case SendRNID: { + PSendRNID_IN pIn; + PSendRNID_OUT pOut; + + if (InBufferSize >= sizeof (ULONG)) { + pIn = (PSendRNID_IN)pBuffer; + + sizeNeeded = sizeof (SendRNID_IN); + + if (InBufferSize >= sizeNeeded) { + sizeNeeded = FIELD_OFFSET( + SendRNID_OUT, ResponseBuffer) + + SendRNID_OUT_ResponseBuffer_SIZE_HINT; + + if (OutBufferSize >= sizeNeeded) { + pOut = (PSendRNID_OUT)pBuffer; + + pOut->HBAStatus = HBA_STATUS_OK; + pOut->ResponseBufferCount = + SendRNID_OUT_ResponseBuffer_SIZE_HINT; + + memset(pOut->ResponseBuffer, + 0xFF, + pOut->ResponseBufferCount); + } else { + status = + SRB_STATUS_DATA_OVERRUN; + } + } else { + status = SRB_STATUS_ERROR; + } + } else { + sizeNeeded = minSizeNeeded; + status = SRB_STATUS_ERROR; + } + break; + } + + default: + __try { + DbgBreakPoint(); + } + __except(EXCEPTION_EXECUTE_HANDLER) { + } + + status = SRB_STATUS_INVALID_REQUEST; + break; + } + break; + + case IdxGmDrvDrvMethodGuid: + + switch (MethodId) { + + case GmDrvDemoMethod1: { + PGmDrvDemoMethod1_IN pInBfr = + (PGmDrvDemoMethod1_IN)pBuffer; + PGmDrvDemoMethod1_OUT pOutBfr = + (PGmDrvDemoMethod1_OUT)pBuffer; + + sizeNeeded = GmDrvDemoMethod1_OUT_SIZE; + + if (OutBufferSize < sizeNeeded) { + status = + SRB_STATUS_DATA_OVERRUN; + break; + } + + if (InBufferSize < GmDrvDemoMethod1_IN_SIZE) { + status = SRB_STATUS_BAD_FUNCTION; + break; + } + + pOutBfr->outDatum = pInBfr->inDatum + 1; + break; + + } + + case GmDrvDemoMethod2: { + PGmDrvDemoMethod2_IN pInBfr = + (PGmDrvDemoMethod2_IN)pBuffer; + PGmDrvDemoMethod2_OUT pOutBfr = + (PGmDrvDemoMethod2_OUT)pBuffer; + + sizeNeeded = GmDrvDemoMethod2_OUT_SIZE; + + if (OutBufferSize < sizeNeeded) { + status = SRB_STATUS_DATA_OVERRUN; + break; + } + + if (InBufferSize < GmDrvDemoMethod2_IN_SIZE) { + status = SRB_STATUS_BAD_FUNCTION; + break; + } + + pOutBfr->outDatum1 = pInBfr->inDatum1 + + pInBfr->inDatum2 + 1; + break; + + } + + case GmDrvDemoMethod3: { + ULONG x1, x2; + PGmDrvDemoMethod3_IN pInBfr = + (PGmDrvDemoMethod3_IN)pBuffer; + PGmDrvDemoMethod3_OUT pOutBfr = + (PGmDrvDemoMethod3_OUT)pBuffer; + + sizeNeeded = GmDrvDemoMethod3_OUT_SIZE; + + if (OutBufferSize < sizeNeeded) { + status = SRB_STATUS_DATA_OVERRUN; + break; + } + + if (InBufferSize < GmDrvDemoMethod3_IN_SIZE) { + status = SRB_STATUS_BAD_FUNCTION; + break; + } + + x1 = pInBfr->inDatum1 + 1; + x2 = pInBfr->inDatum2 + 1; + + pOutBfr->outDatum1 = x1; + pOutBfr->outDatum2 = x2; + + break; + } + + default: + status = SRB_STATUS_INVALID_REQUEST; + break; + } + break; - status = SRB_STATUS_INVALID_REQUEST; - break; - } // End switch(GuidIndex). + default: + status = SRB_STATUS_INVALID_REQUEST; + break; + } - SpUpdateWmiRequest(pHbaExtension, pSrb, pDispatchContext, status, sizeNeeded); + SpUpdateWmiRequest(pHbaExtension, pSrb, pDispatchContext, + status, sizeNeeded); - return SRB_STATUS_PENDING; -} // End ExecuteWmiMethod(). + return (SRB_STATUS_PENDING); +} -/**************************************************************************************************/ -/* */ -/**************************************************************************************************/ -VOID +void SpUpdateWmiRequest( - __in pHW_HBA_EXT pHbaExtension, - __in PSCSI_WMI_REQUEST_BLOCK pSrb, - __in PSCSIWMI_REQUEST_CONTEXT pDispatchContext, - __in UCHAR Status, - __in ULONG SizeNeeded - ) + __in pHW_HBA_EXT pHbaExtension, + __in PSCSI_WMI_REQUEST_BLOCK pSrb, + __in PSCSIWMI_REQUEST_CONTEXT pDispatchContext, + __in UCHAR Status, + __in ULONG SizeNeeded) { - UNREFERENCED_PARAMETER(pHbaExtension); + UNREFERENCED_PARAMETER(pHbaExtension); + + // Update the request if the status is NOT pending or NOT + // already completed within the callback. - // Update the request if the status is NOT pending or NOT already completed within the callback. - - if (SRB_STATUS_PENDING!=Status) { + if (SRB_STATUS_PENDING != Status) { - // - // Request completed successfully or there was an error. - // + // + // Request completed successfully or there was an error. + // - ScsiPortWmiPostProcess(pDispatchContext, Status,SizeNeeded); + ScsiPortWmiPostProcess(pDispatchContext, Status, SizeNeeded); - pSrb->SrbStatus = ScsiPortWmiGetReturnStatus(pDispatchContext); - pSrb->DataTransferLength = ScsiPortWmiGetReturnSize(pDispatchContext); - } -} // End SpUpdateWmiRequest(). + pSrb->SrbStatus = ScsiPortWmiGetReturnStatus(pDispatchContext); + pSrb->DataTransferLength = + ScsiPortWmiGetReturnSize(pDispatchContext); + } +} diff --git a/module/os/windows/zfs/zvol_os.c b/module/os/windows/zfs/zvol_os.c index 9fc32c66070..d788a0f423a 100644 --- a/module/os/windows/zfs/zvol_os.c +++ b/module/os/windows/zfs/zvol_os.c @@ -49,7 +49,7 @@ unsigned int zvol_threads = 8; taskq_t *zvol_taskq; typedef struct zv_request { - zvol_state_t *zv; + zvol_state_t *zv; void (*zv_func)(void *); void *zv_arg; @@ -198,7 +198,7 @@ zvol_os_read_zv(zvol_state_t *zv, uio_t *uio, int flags) if (error == ECKSUM) error = EIO; break; - } + } } zfs_rangelock_exit(lr); @@ -253,18 +253,18 @@ zvol_os_write_zv(zvol_state_t *zv, uio_t *uio, int flags) sync = (zv->zv_objset->os_sync == ZFS_SYNC_ALWAYS); /* Lock the entire range */ - lr = zfs_rangelock_enter(&zv->zv_rangelock, uio_offset(uio), uio_resid(uio), - RL_WRITER); + lr = zfs_rangelock_enter(&zv->zv_rangelock, uio_offset(uio), + uio_resid(uio), RL_WRITER); /* Iterate over (DMU_MAX_ACCESS/2) segments */ - while (uio_resid(uio) > 0 && uio_offset(uio) < volsize) { - uint64_t bytes = MIN(uio_resid(uio), DMU_MAX_ACCESS >> 1); - uint64_t off = uio_offset(uio); + while (uio_resid(uio) > 0 && uio_offset(uio) < volsize) { + uint64_t bytes = MIN(uio_resid(uio), DMU_MAX_ACCESS >> 1); + uint64_t off = uio_offset(uio); dmu_tx_t *tx = dmu_tx_create(zv->zv_objset); /* don't write past the end */ - if (bytes > volsize - off) - bytes = volsize - off; + if (bytes > volsize - off) + bytes = volsize - off; dmu_tx_hold_write_by_dnode(tx, zv->zv_dn, off, bytes); error = dmu_tx_assign(tx, TXG_WAIT); @@ -397,11 +397,10 @@ zvol_os_update_volsize(zvol_state_t *zv, uint64_t volsize) static void zvol_os_clear_private(zvol_state_t *zv) { - // Close the Storport half open if (zv->zv_open_count == 0) { - - wzvol_clear_targetid(zv->zv_zso->zso_target_id, zv->zv_zso->zso_lun_id, zv); + wzvol_clear_targetid(zv->zv_zso->zso_target_id, + zv->zv_zso->zso_lun_id, zv); wzvol_announce_buschange(); } } @@ -436,7 +435,7 @@ zvol_os_find_by_dev(dev_t dev) zvol_state_t * zvol_os_targetlun_lookup(uint8_t target, uint8_t lun) { - zvol_state_t *zv; + zvol_state_t *zv; dprintf("%s\n", __func__); @@ -444,7 +443,8 @@ zvol_os_targetlun_lookup(uint8_t target, uint8_t lun) for (zv = list_head(&zvol_state_list); zv != NULL; zv = list_next(&zvol_state_list, zv)) { mutex_enter(&zv->zv_state_lock); - if (zv->zv_zso->zso_target_id == target && zv->zv_zso->zso_lun_id == lun) { + if (zv->zv_zso->zso_target_id == target && + zv->zv_zso->zso_lun_id == lun) { rw_exit(&zvol_state_lock); return (zv); } @@ -605,32 +605,34 @@ zvol_os_create_minor(const char *name) zil_replay(os, zv, zvol_replay_vector); } - // Assign new TargetId and Lun - wzvol_assign_targetid(zv); - + // Assign new TargetId and Lun + wzvol_assign_targetid(zv); rw_enter(&zvol_state_lock, RW_WRITER); zvol_insert(zv); rw_exit(&zvol_state_lock); /* - * Here is where we differ to upstream. They will call open and close, as userland - * opens the /dev/disk node. Once opened, it has the open_count, and long_holds held, - * which is used in read/write. Once closed, everything is released. - * So when it comes to export/unmount/destroy of the ZVOL, it checks for opencount==0 - * and longholds==0. They should allow for == 1 for Windows. - * However, in Windows there is no open/close devnode, but rather, we assign the zvol - * to the storport API, to expose the device. Really, the zvol needs to be "open" the - * entire time that storport has it. If we leave zvol "open" it will fail the checks - * for "==0". So we steal an opencount, and remember it privately. We could also + * Here is where we differ to upstream. They will call open and + * close, as userland opens the /dev/disk node. Once opened, it + * has the open_count, and long_holds held, which is used in + * read/write. Once closed, everything is released. So when it + * comes to export/unmount/destroy of the ZVOL, it checks for + * opencount==0 and longholds==0. They should allow for == 1 + * for Windows. + * However, in Windows there is no open/close devnode, but rather, + * we assign the zvol to the storport API, to expose the device. + * Really, the zvol needs to be "open" the entire time that storport + * has it. If we leave zvol "open" it will fail the checks for "==0". + * So we steal an opencount, and remember it privately. We could also * change zvol.c to special-case it for Windows. - */ - //error = zvol_os_open_zv(zv, FWRITE, 0, NULL); + */ #if 0 if (error == 0) { error = dnode_hold(os, ZVOL_OBJ, FTAG, &zv->zv_zso->zso_dn); if (error == 0) { - zfs_rangelock_init(&zv->zv_zso->zso_rangelock, NULL, NULL); + zfs_rangelock_init(&zv->zv_zso->zso_rangelock, NULL, + NULL); wzvol_announce_buschange(); } // zvol_os_close_zv(zv, FWRITE, 0, NULL); @@ -652,9 +654,10 @@ zvol_os_create_minor(const char *name) if (error == 0) { error = zvol_os_open_zv(zv, FWRITE, 0, NULL); - + if (error == 0) { - // Steal this open_count; or we can't export/destroy (EBUSY) + // Steal this open_count; or we can't + // export/destroy (EBUSY) zv->zv_zso->zso_open_count++; zv->zv_open_count--; @@ -869,7 +872,7 @@ zvol_os_ioctl(dev_t dev, unsigned long cmd, caddr_t data, int isblk, return (ENXIO); } - // + // mutex_exit(&zv->zv_state_lock);