diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..cbe4cf5 --- /dev/null +++ b/.clang-format @@ -0,0 +1,2 @@ +IncludeBlocks: Preserve +SortIncludes: Never diff --git a/common/gcc-millicode/adddi3.c b/common/gcc-millicode/adddi3.c index af3b51e..6313ac4 100644 --- a/common/gcc-millicode/adddi3.c +++ b/common/gcc-millicode/adddi3.c @@ -43,14 +43,12 @@ * is less than either x or y (the choice to compare with x or y is * arbitrary). */ -long long -__adddi3(long long a, long long b) -{ - union uu aa, bb, sum; +long long __adddi3(long long a, long long b) { + union uu aa, bb, sum; - aa.ll = a; - bb.ll = b; - sum.ui[L] = aa.ui[L] + bb.ui[L]; - sum.ui[H] = aa.ui[H] + bb.ui[H] + (sum.ui[L] < bb.ui[L]); - return (sum.ll); + aa.ll = a; + bb.ll = b; + sum.ui[L] = aa.ui[L] + bb.ui[L]; + sum.ui[H] = aa.ui[H] + bb.ui[H] + (sum.ui[L] < bb.ui[L]); + return (sum.ll); } diff --git a/common/gcc-millicode/anddi3.c b/common/gcc-millicode/anddi3.c index 007e0c5..c4eca66 100644 --- a/common/gcc-millicode/anddi3.c +++ b/common/gcc-millicode/anddi3.c @@ -40,14 +40,12 @@ /* * Return a & b, in long long. */ -long long -__anddi3(long long a, long long b) -{ - union uu aa, bb; +long long __anddi3(long long a, long long b) { + union uu aa, bb; - aa.ll = a; - bb.ll = b; - aa.ui[0] &= bb.ui[0]; - aa.ui[1] &= bb.ui[1]; - return (aa.ll); + aa.ll = a; + bb.ll = b; + aa.ui[0] &= bb.ui[0]; + aa.ui[1] &= bb.ui[1]; + return (aa.ll); } diff --git a/common/gcc-millicode/ashldi3.c b/common/gcc-millicode/ashldi3.c index 4aa876e..d5b15fb 100644 --- a/common/gcc-millicode/ashldi3.c +++ b/common/gcc-millicode/ashldi3.c @@ -41,21 +41,18 @@ * Shift a (signed) long long value left (arithmetic shift left). * This is the same as logical shift left! */ -long long -__ashldi3(long long a, unsigned int shift) -{ - union uu aa; +long long __ashldi3(long long a, unsigned int shift) { + union uu aa; - if (shift == 0) - return(a); - aa.ll = a; - if (shift >= INT_BITS) { - aa.ui[H] = aa.ui[L] << (shift - INT_BITS); - aa.ui[L] = 0; - } else { - aa.ui[H] = (aa.ui[H] << shift) | - (aa.ui[L] >> (INT_BITS - shift)); - aa.ui[L] <<= shift; - } - return (aa.ll); + if (shift == 0) + return (a); + aa.ll = a; + if (shift >= INT_BITS) { + aa.ui[H] = aa.ui[L] << (shift - INT_BITS); + aa.ui[L] = 0; + } else { + aa.ui[H] = (aa.ui[H] << shift) | (aa.ui[L] >> (INT_BITS - shift)); + aa.ui[L] <<= shift; + } + return (aa.ll); } diff --git a/common/gcc-millicode/ashrdi3.c b/common/gcc-millicode/ashrdi3.c index b143d6f..4dcfc01 100644 --- a/common/gcc-millicode/ashrdi3.c +++ b/common/gcc-millicode/ashrdi3.c @@ -40,34 +40,31 @@ /* * Shift a (signed) long long value right (arithmetic shift right). */ -long long -__ashrdi3(long long a, unsigned int shift) -{ - union uu aa; +long long __ashrdi3(long long a, unsigned int shift) { + union uu aa; - if (shift == 0) - return(a); - aa.ll = a; - if (shift >= INT_BITS) { - int s; + if (shift == 0) + return (a); + aa.ll = a; + if (shift >= INT_BITS) { + int s; - /* - * Smear bits rightward using the machine's right-shift - * method, whether that is sign extension or zero fill, - * to get the `sign word' s. Note that shifting by - * INT_BITS is undefined, so we shift (INT_BITS-1), - * then 1 more, to get our answer. - */ - /* LINTED inherits machine dependency */ - s = (aa.si[H] >> (INT_BITS - 1)) >> 1; - /* LINTED inherits machine dependency*/ - aa.ui[L] = aa.si[H] >> (shift - INT_BITS); - aa.ui[H] = s; - } else { - aa.ui[L] = (aa.ui[L] >> shift) | - (aa.ui[H] << (INT_BITS - shift)); - /* LINTED inherits machine dependency */ - aa.si[H] >>= shift; - } - return (aa.ll); + /* + * Smear bits rightward using the machine's right-shift + * method, whether that is sign extension or zero fill, + * to get the `sign word' s. Note that shifting by + * INT_BITS is undefined, so we shift (INT_BITS-1), + * then 1 more, to get our answer. + */ + /* LINTED inherits machine dependency */ + s = (aa.si[H] >> (INT_BITS - 1)) >> 1; + /* LINTED inherits machine dependency*/ + aa.ui[L] = aa.si[H] >> (shift - INT_BITS); + aa.ui[H] = s; + } else { + aa.ui[L] = (aa.ui[L] >> shift) | (aa.ui[H] << (INT_BITS - shift)); + /* LINTED inherits machine dependency */ + aa.si[H] >>= shift; + } + return (aa.ll); } diff --git a/common/gcc-millicode/cmpdi2.c b/common/gcc-millicode/cmpdi2.c index 15e893e..043f8c9 100644 --- a/common/gcc-millicode/cmpdi2.c +++ b/common/gcc-millicode/cmpdi2.c @@ -42,13 +42,14 @@ * Both a and b are considered signed---which means only the high word is * signed. */ -int -__cmpdi2(long long a, long long b) -{ - union uu aa, bb; +int __cmpdi2(long long a, long long b) { + union uu aa, bb; - aa.ll = a; - bb.ll = b; - return (aa.si[H] < bb.si[H] ? 0 : aa.si[H] > bb.si[H] ? 2 : - aa.ui[L] < bb.ui[L] ? 0 : aa.ui[L] > bb.ui[L] ? 2 : 1); + aa.ll = a; + bb.ll = b; + return (aa.si[H] < bb.si[H] ? 0 + : aa.si[H] > bb.si[H] ? 2 + : aa.ui[L] < bb.ui[L] ? 0 + : aa.ui[L] > bb.ui[L] ? 2 + : 1); } diff --git a/common/gcc-millicode/divdi3.c b/common/gcc-millicode/divdi3.c index d1671dd..8c5bbfa 100644 --- a/common/gcc-millicode/divdi3.c +++ b/common/gcc-millicode/divdi3.c @@ -41,22 +41,20 @@ * Divide two signed long longs. * ??? if -1/2 should produce -1 on this machine, this code is wrong */ -long long -__divdi3(long long a, long long b) -{ - unsigned long long ua, ub, uq; - int neg = 0; +long long __divdi3(long long a, long long b) { + unsigned long long ua, ub, uq; + int neg = 0; - ua = a; - ub = b; + ua = a; + ub = b; - if (a < 0) - ua = -ua, neg ^= 1; - if (b < 0) - ub = -ub, neg ^= 1; + if (a < 0) + ua = -ua, neg ^= 1; + if (b < 0) + ub = -ub, neg ^= 1; - uq = __qdivrem(ua, ub, NULL); - if (neg) - uq = - uq; - return uq; + uq = __qdivrem(ua, ub, NULL); + if (neg) + uq = -uq; + return uq; } diff --git a/common/gcc-millicode/iordi3.c b/common/gcc-millicode/iordi3.c index 00ee2f2..0fe6424 100644 --- a/common/gcc-millicode/iordi3.c +++ b/common/gcc-millicode/iordi3.c @@ -40,14 +40,12 @@ /* * Return a | b, in long long. */ -long long -__iordi3(long long a, long long b) -{ - union uu aa, bb; +long long __iordi3(long long a, long long b) { + union uu aa, bb; - aa.ll = a; - bb.ll = b; - aa.ui[0] |= bb.ui[0]; - aa.ui[1] |= bb.ui[1]; - return (aa.ll); + aa.ll = a; + bb.ll = b; + aa.ui[0] |= bb.ui[0]; + aa.ui[1] |= bb.ui[1]; + return (aa.ll); } diff --git a/common/gcc-millicode/longlong.h b/common/gcc-millicode/longlong.h index ad33566..b80a882 100644 --- a/common/gcc-millicode/longlong.h +++ b/common/gcc-millicode/longlong.h @@ -68,10 +68,10 @@ * one or more of the following formats. */ union uu { - long long ll; /* as a (signed) long long */ - unsigned long long ull; /* as an unsigned long long */ - int si[2]; /* as two (signed) ints */ - unsigned int ui[2]; /* as two unsigned ints */ + long long ll; /* as a (signed) long long */ + unsigned long long ull; /* as an unsigned long long */ + int si[2]; /* as two (signed) ints */ + unsigned int ui[2]; /* as two unsigned ints */ }; /* @@ -87,15 +87,14 @@ union uu { #define L 1 #endif - /* * Total number of bits in a long long and in the pieces that make it up. * These are used for shifting, and also below for halfword extraction * and assembly. */ -#define LONGLONG_BITS (sizeof(long long) * CHAR_BIT) -#define INT_BITS (sizeof(int) * CHAR_BIT) -#define HALF_BITS (sizeof(int) * CHAR_BIT / 2) +#define LONGLONG_BITS (sizeof(long long) * CHAR_BIT) +#define INT_BITS (sizeof(int) * CHAR_BIT) +#define HALF_BITS (sizeof(int) * CHAR_BIT / 2) /* * Extract high and low shortwords from longword, and move low shortword of @@ -107,38 +106,38 @@ union uu { * and lower halves, and to reassemble a product as a long long, shifted * left (sizeof(int)*CHAR_BIT/2). */ -#define HHALF(x) ((unsigned int)(x) >> HALF_BITS) -#define LHALF(x) ((unsigned int)(x) & (((int)1 << HALF_BITS) - 1)) -#define LHUP(x) ((unsigned int)(x) << HALF_BITS) +#define HHALF(x) ((unsigned int)(x) >> HALF_BITS) +#define LHALF(x) ((unsigned int)(x) & (((int)1 << HALF_BITS) - 1)) +#define LHUP(x) ((unsigned int)(x) << HALF_BITS) -long long __adddi3 ( long long, long long); -long long __anddi3 ( long long, long long); -long long __ashldi3 ( long long, unsigned int); -long long __ashrdi3 ( long long, unsigned int); -int __cmpdi2 ( long long, long long); -long long __divdi3 ( long long, long long); -long long __iordi3 ( long long, long long); -long long __lshldi3 ( long long, unsigned int); -long long __lshrdi3 ( long long, unsigned int); -long long __moddi3 ( long long, long long); -long long __muldi3 ( long long, long long); -long long __negdi2 ( long long); -long long __one_cmpldi2 ( long long); -long long __subdi3 ( long long, long long); -int __ucmpdi2 (unsigned long long, unsigned long long); -unsigned long long __udivdi3 (unsigned long long, unsigned long long); -unsigned long long __umoddi3 (unsigned long long, unsigned long long); -long long __xordi3 ( long long, long long); +long long __adddi3(long long, long long); +long long __anddi3(long long, long long); +long long __ashldi3(long long, unsigned int); +long long __ashrdi3(long long, unsigned int); +int __cmpdi2(long long, long long); +long long __divdi3(long long, long long); +long long __iordi3(long long, long long); +long long __lshldi3(long long, unsigned int); +long long __lshrdi3(long long, unsigned int); +long long __moddi3(long long, long long); +long long __muldi3(long long, long long); +long long __negdi2(long long); +long long __one_cmpldi2(long long); +long long __subdi3(long long, long long); +int __ucmpdi2(unsigned long long, unsigned long long); +unsigned long long __udivdi3(unsigned long long, unsigned long long); +unsigned long long __umoddi3(unsigned long long, unsigned long long); +long long __xordi3(long long, long long); #ifndef _KERNEL -long long __fixdfdi (double); -long long __fixsfdi (float); -unsigned long long __fixunsdfdi (double); -unsigned long long __fixunssfdi (float); -double __floatdidf (long long); -float __floatdisf (long long); -double __floatunsdidf(unsigned long long); +long long __fixdfdi(double); +long long __fixsfdi(float); +unsigned long long __fixunsdfdi(double); +unsigned long long __fixunssfdi(float); +double __floatdidf(long long); +float __floatdisf(long long); +double __floatunsdidf(unsigned long long); #endif -unsigned long long __qdivrem (unsigned long long, unsigned long long, - unsigned long long *); +unsigned long long __qdivrem(unsigned long long, unsigned long long, + unsigned long long *); diff --git a/common/gcc-millicode/lshldi3.c b/common/gcc-millicode/lshldi3.c index dd96581..f25a7de 100644 --- a/common/gcc-millicode/lshldi3.c +++ b/common/gcc-millicode/lshldi3.c @@ -41,21 +41,18 @@ * Shift an (unsigned) long long value left (logical shift left). * This is the same as arithmetic shift left! */ -long long -__lshldi3(long long a, unsigned int shift) -{ - union uu aa; +long long __lshldi3(long long a, unsigned int shift) { + union uu aa; - if (shift == 0) - return(a); - aa.ll = a; - if (shift >= INT_BITS) { - aa.ui[H] = aa.ui[L] << (shift - INT_BITS); - aa.ui[L] = 0; - } else { - aa.ui[H] = (aa.ui[H] << shift) | - (aa.ui[L] >> (INT_BITS - shift)); - aa.ui[L] <<= shift; - } - return (aa.ll); + if (shift == 0) + return (a); + aa.ll = a; + if (shift >= INT_BITS) { + aa.ui[H] = aa.ui[L] << (shift - INT_BITS); + aa.ui[L] = 0; + } else { + aa.ui[H] = (aa.ui[H] << shift) | (aa.ui[L] >> (INT_BITS - shift)); + aa.ui[L] <<= shift; + } + return (aa.ll); } diff --git a/common/gcc-millicode/lshrdi3.c b/common/gcc-millicode/lshrdi3.c index c555fea..58399da 100644 --- a/common/gcc-millicode/lshrdi3.c +++ b/common/gcc-millicode/lshrdi3.c @@ -40,21 +40,18 @@ /* * Shift an (unsigned) long long value right (logical shift right). */ -long long -__lshrdi3(long long a, unsigned int shift) -{ - union uu aa; +long long __lshrdi3(long long a, unsigned int shift) { + union uu aa; - if (shift == 0) - return(a); - aa.ll = a; - if (shift >= INT_BITS) { - aa.ui[L] = aa.ui[H] >> (shift - INT_BITS); - aa.ui[H] = 0; - } else { - aa.ui[L] = (aa.ui[L] >> shift) | - (aa.ui[H] << (INT_BITS - shift)); - aa.ui[H] >>= shift; - } - return (aa.ll); + if (shift == 0) + return (a); + aa.ll = a; + if (shift >= INT_BITS) { + aa.ui[L] = aa.ui[H] >> (shift - INT_BITS); + aa.ui[H] = 0; + } else { + aa.ui[L] = (aa.ui[L] >> shift) | (aa.ui[H] << (INT_BITS - shift)); + aa.ui[H] >>= shift; + } + return (aa.ll); } diff --git a/common/gcc-millicode/moddi3.c b/common/gcc-millicode/moddi3.c index ac53705..e0150f6 100644 --- a/common/gcc-millicode/moddi3.c +++ b/common/gcc-millicode/moddi3.c @@ -42,21 +42,19 @@ * * XXX we assume a % b < 0 iff a < 0, but this is actually machine-dependent. */ -long long -__moddi3(long long a, long long b) -{ - unsigned long long ua, ub, ur; - int neg = 0; +long long __moddi3(long long a, long long b) { + unsigned long long ua, ub, ur; + int neg = 0; - ua = a; - ub = b; + ua = a; + ub = b; - if (a < 0) - ua = -ua, neg ^= 1; - if (b < 0) - ub = -ub; - (void)__qdivrem(ua, ub, &ur); - if (neg) - ur = -ur; - return (ur); + if (a < 0) + ua = -ua, neg ^= 1; + if (b < 0) + ub = -ub; + (void)__qdivrem(ua, ub, &ur); + if (neg) + ur = -ur; + return (ur); } diff --git a/common/gcc-millicode/muldi3.c b/common/gcc-millicode/muldi3.c index 1cef86c..6eb499d 100644 --- a/common/gcc-millicode/muldi3.c +++ b/common/gcc-millicode/muldi3.c @@ -96,67 +96,64 @@ */ static long long __lmulq(unsigned int, unsigned int); -long long -__muldi3(long long a, long long b) -{ - union uu u, v, low, prod; - unsigned int high, mid, udiff, vdiff; - int negall, negmid; -#define u1 u.ui[H] -#define u0 u.ui[L] -#define v1 v.ui[H] -#define v0 v.ui[L] +long long __muldi3(long long a, long long b) { + union uu u, v, low, prod; + unsigned int high, mid, udiff, vdiff; + int negall, negmid; +#define u1 u.ui[H] +#define u0 u.ui[L] +#define v1 v.ui[H] +#define v0 v.ui[L] - /* - * Get u and v such that u, v >= 0. When this is finished, - * u1, u0, v1, and v0 will be directly accessible through the - * int fields. - */ - if (a >= 0) - u.ll = a, negall = 0; - else - u.ll = -a, negall = 1; - if (b >= 0) - v.ll = b; - else - v.ll = -b, negall ^= 1; + /* + * Get u and v such that u, v >= 0. When this is finished, + * u1, u0, v1, and v0 will be directly accessible through the + * int fields. + */ + if (a >= 0) + u.ll = a, negall = 0; + else + u.ll = -a, negall = 1; + if (b >= 0) + v.ll = b; + else + v.ll = -b, negall ^= 1; - if (u1 == 0 && v1 == 0) { - /* - * An (I hope) important optimization occurs when u1 and v1 - * are both 0. This should be common since most numbers - * are small. Here the product is just u0*v0. - */ - prod.ll = __lmulq(u0, v0); - } else { - /* - * Compute the three intermediate products, remembering - * whether the middle term is negative. We can discard - * any upper bits in high and mid, so we can use native - * unsigned int * unsigned int => unsigned int arithmetic. - */ - low.ll = __lmulq(u0, v0); + if (u1 == 0 && v1 == 0) { + /* + * An (I hope) important optimization occurs when u1 and v1 + * are both 0. This should be common since most numbers + * are small. Here the product is just u0*v0. + */ + prod.ll = __lmulq(u0, v0); + } else { + /* + * Compute the three intermediate products, remembering + * whether the middle term is negative. We can discard + * any upper bits in high and mid, so we can use native + * unsigned int * unsigned int => unsigned int arithmetic. + */ + low.ll = __lmulq(u0, v0); - if (u1 >= u0) - negmid = 0, udiff = u1 - u0; - else - negmid = 1, udiff = u0 - u1; - if (v0 >= v1) - vdiff = v0 - v1; - else - vdiff = v1 - v0, negmid ^= 1; - mid = udiff * vdiff; + if (u1 >= u0) + negmid = 0, udiff = u1 - u0; + else + negmid = 1, udiff = u0 - u1; + if (v0 >= v1) + vdiff = v0 - v1; + else + vdiff = v1 - v0, negmid ^= 1; + mid = udiff * vdiff; - high = u1 * v1; + high = u1 * v1; - /* - * Assemble the final product. - */ - prod.ui[H] = high + (negmid ? -mid : mid) + low.ui[L] + - low.ui[H]; - prod.ui[L] = low.ui[L]; - } - return (negall ? -prod.ll : prod.ll); + /* + * Assemble the final product. + */ + prod.ui[H] = high + (negmid ? -mid : mid) + low.ui[L] + low.ui[H]; + prod.ui[L] = low.ui[L]; + } + return (negall ? -prod.ll : prod.ll); #undef u1 #undef u0 #undef v1 @@ -180,62 +177,60 @@ __muldi3(long long a, long long b) * * splits into high and low ints as HHALF(l) and LHUP(l) respectively. */ -static long long -__lmulq(unsigned int u, unsigned int v) -{ - unsigned int u1, u0, v1, v0, udiff, vdiff, high, mid, low; - unsigned int prodh, prodl, was; - union uu prod; - int neg; +static long long __lmulq(unsigned int u, unsigned int v) { + unsigned int u1, u0, v1, v0, udiff, vdiff, high, mid, low; + unsigned int prodh, prodl, was; + union uu prod; + int neg; - u1 = HHALF(u); - u0 = LHALF(u); - v1 = HHALF(v); - v0 = LHALF(v); + u1 = HHALF(u); + u0 = LHALF(u); + v1 = HHALF(v); + v0 = LHALF(v); - low = u0 * v0; + low = u0 * v0; - /* This is the same small-number optimization as before. */ - if (u1 == 0 && v1 == 0) - return (low); + /* This is the same small-number optimization as before. */ + if (u1 == 0 && v1 == 0) + return (low); - if (u1 >= u0) - udiff = u1 - u0, neg = 0; - else - udiff = u0 - u1, neg = 1; - if (v0 >= v1) - vdiff = v0 - v1; - else - vdiff = v1 - v0, neg ^= 1; - mid = udiff * vdiff; + if (u1 >= u0) + udiff = u1 - u0, neg = 0; + else + udiff = u0 - u1, neg = 1; + if (v0 >= v1) + vdiff = v0 - v1; + else + vdiff = v1 - v0, neg ^= 1; + mid = udiff * vdiff; - high = u1 * v1; + high = u1 * v1; - /* prod = (high << 2N) + (high << N); */ - prodh = high + HHALF(high); - prodl = LHUP(high); + /* prod = (high << 2N) + (high << N); */ + prodh = high + HHALF(high); + prodl = LHUP(high); - /* if (neg) prod -= mid << N; else prod += mid << N; */ - if (neg) { - was = prodl; - prodl -= LHUP(mid); - prodh -= HHALF(mid) + (prodl > was); - } else { - was = prodl; - prodl += LHUP(mid); - prodh += HHALF(mid) + (prodl < was); - } + /* if (neg) prod -= mid << N; else prod += mid << N; */ + if (neg) { + was = prodl; + prodl -= LHUP(mid); + prodh -= HHALF(mid) + (prodl > was); + } else { + was = prodl; + prodl += LHUP(mid); + prodh += HHALF(mid) + (prodl < was); + } - /* prod += low << N */ - was = prodl; - prodl += LHUP(low); - prodh += HHALF(low) + (prodl < was); - /* ... + low; */ - if ((prodl += low) < low) - prodh++; + /* prod += low << N */ + was = prodl; + prodl += LHUP(low); + prodh += HHALF(low) + (prodl < was); + /* ... + low; */ + if ((prodl += low) < low) + prodh++; - /* return 4N-bit product */ - prod.ui[H] = prodh; - prod.ui[L] = prodl; - return (prod.ll); + /* return 4N-bit product */ + prod.ui[H] = prodh; + prod.ui[L] = prodl; + return (prod.ll); } diff --git a/common/gcc-millicode/negdi2.c b/common/gcc-millicode/negdi2.c index abb7973..3effe82 100644 --- a/common/gcc-millicode/negdi2.c +++ b/common/gcc-millicode/negdi2.c @@ -40,13 +40,11 @@ /* * Return -a (or, equivalently, 0 - a), in long long. See subdi3.c. */ -long long -__negdi2(long long a) -{ - union uu aa, res; +long long __negdi2(long long a) { + union uu aa, res; - aa.ll = a; - res.ui[L] = -aa.ui[L]; - res.ui[H] = -aa.ui[H] - (res.ui[L] > 0); - return (res.ll); + aa.ll = a; + res.ui[L] = -aa.ui[L]; + res.ui[H] = -aa.ui[H] - (res.ui[L] > 0); + return (res.ll); } diff --git a/common/gcc-millicode/notdi2.c b/common/gcc-millicode/notdi2.c index 614cd32..6a096ac 100644 --- a/common/gcc-millicode/notdi2.c +++ b/common/gcc-millicode/notdi2.c @@ -41,13 +41,11 @@ * Return ~a. For some reason gcc calls this `one's complement' rather * than `not'. */ -long long -__one_cmpldi2(long long a) -{ - union uu aa; +long long __one_cmpldi2(long long a) { + union uu aa; - aa.ll = a; - aa.ui[0] = ~aa.ui[0]; - aa.ui[1] = ~aa.ui[1]; - return (aa.ll); + aa.ll = a; + aa.ui[0] = ~aa.ui[0]; + aa.ui[1] = ~aa.ui[1]; + return (aa.ll); } diff --git a/common/gcc-millicode/qdivrem.c b/common/gcc-millicode/qdivrem.c index 5c43da5..8169781 100644 --- a/common/gcc-millicode/qdivrem.c +++ b/common/gcc-millicode/qdivrem.c @@ -42,10 +42,10 @@ #include "longlong.h" -#define B ((int)1 << HALF_BITS) /* digit base */ +#define B ((int)1 << HALF_BITS) /* digit base */ /* Combine two `digits' to make a single two-digit number. */ -#define COMBINE(a, b) (((unsigned int)(a) << HALF_BITS) | (b)) +#define COMBINE(a, b) (((unsigned int)(a) << HALF_BITS) | (b)) /* select a type for digits in base B: use unsigned short if they fit */ #if UINT_MAX == 0xffffffffU && USHRT_MAX >= 0xffff @@ -64,202 +64,199 @@ static void shl(digit *p, int len, int sh); * length dividend and divisor are 4 `digits' in this base (they are * shorter if they have leading zeros). */ -unsigned long long -__qdivrem(unsigned long long ull, unsigned long long vll, - unsigned long long *arq) -{ - union uu tmp; - digit *u, *v, *q; - digit v1, v2; - unsigned int qhat, rhat, t; - int m, n, d, j, i; - digit uspace[5], vspace[5], qspace[5]; +unsigned long long __qdivrem(unsigned long long ull, unsigned long long vll, + unsigned long long *arq) { + union uu tmp; + digit *u, *v, *q; + digit v1, v2; + unsigned int qhat, rhat, t; + int m, n, d, j, i; + digit uspace[5], vspace[5], qspace[5]; - /* - * Take care of special cases: divide by zero, and u < v. - */ - if (vll == 0) { - /* divide by zero. */ - static volatile const unsigned int zero = 0; + /* + * Take care of special cases: divide by zero, and u < v. + */ + if (vll == 0) { + /* divide by zero. */ + static volatile const unsigned int zero = 0; - tmp.ui[H] = tmp.ui[L] = 1 / zero; - if (arq) - *arq = ull; - return (tmp.ll); - } - if (ull < vll) { - if (arq) - *arq = ull; - return (0); - } - u = &uspace[0]; - v = &vspace[0]; - q = &qspace[0]; + tmp.ui[H] = tmp.ui[L] = 1 / zero; + if (arq) + *arq = ull; + return (tmp.ll); + } + if (ull < vll) { + if (arq) + *arq = ull; + return (0); + } + u = &uspace[0]; + v = &vspace[0]; + q = &qspace[0]; - /* - * Break dividend and divisor into digits in base B, then - * count leading zeros to determine m and n. When done, we - * will have: - * u = (u[1]u[2]...u[m+n]) sub B - * v = (v[1]v[2]...v[n]) sub B - * v[1] != 0 - * 1 < n <= 4 (if n = 1, we use a different division algorithm) - * m >= 0 (otherwise u < v, which we already checked) - * m + n = 4 - * and thus - * m = 4 - n <= 2 - */ - tmp.ull = ull; - u[0] = 0; - u[1] = (digit)HHALF(tmp.ui[H]); - u[2] = (digit)LHALF(tmp.ui[H]); - u[3] = (digit)HHALF(tmp.ui[L]); - u[4] = (digit)LHALF(tmp.ui[L]); - tmp.ull = vll; - v[1] = (digit)HHALF(tmp.ui[H]); - v[2] = (digit)LHALF(tmp.ui[H]); - v[3] = (digit)HHALF(tmp.ui[L]); - v[4] = (digit)LHALF(tmp.ui[L]); - for (n = 4; v[1] == 0; v++) { - if (--n == 1) { - unsigned int rbj; /* r*B+u[j] (not root boy jim) */ - digit q1, q2, q3, q4; + /* + * Break dividend and divisor into digits in base B, then + * count leading zeros to determine m and n. When done, we + * will have: + * u = (u[1]u[2]...u[m+n]) sub B + * v = (v[1]v[2]...v[n]) sub B + * v[1] != 0 + * 1 < n <= 4 (if n = 1, we use a different division algorithm) + * m >= 0 (otherwise u < v, which we already checked) + * m + n = 4 + * and thus + * m = 4 - n <= 2 + */ + tmp.ull = ull; + u[0] = 0; + u[1] = (digit)HHALF(tmp.ui[H]); + u[2] = (digit)LHALF(tmp.ui[H]); + u[3] = (digit)HHALF(tmp.ui[L]); + u[4] = (digit)LHALF(tmp.ui[L]); + tmp.ull = vll; + v[1] = (digit)HHALF(tmp.ui[H]); + v[2] = (digit)LHALF(tmp.ui[H]); + v[3] = (digit)HHALF(tmp.ui[L]); + v[4] = (digit)LHALF(tmp.ui[L]); + for (n = 4; v[1] == 0; v++) { + if (--n == 1) { + unsigned int rbj; /* r*B+u[j] (not root boy jim) */ + digit q1, q2, q3, q4; - /* - * Change of plan, per exercise 16. - * r = 0; - * for j = 1..4: - * q[j] = floor((r*B + u[j]) / v), - * r = (r*B + u[j]) % v; - * We unroll this completely here. - */ - t = v[2]; /* nonzero, by definition */ - q1 = (digit)(u[1] / t); - rbj = COMBINE(u[1] % t, u[2]); - q2 = (digit)(rbj / t); - rbj = COMBINE(rbj % t, u[3]); - q3 = (digit)(rbj / t); - rbj = COMBINE(rbj % t, u[4]); - q4 = (digit)(rbj / t); - if (arq) - *arq = rbj % t; - tmp.ui[H] = COMBINE(q1, q2); - tmp.ui[L] = COMBINE(q3, q4); - return (tmp.ll); - } - } + /* + * Change of plan, per exercise 16. + * r = 0; + * for j = 1..4: + * q[j] = floor((r*B + u[j]) / v), + * r = (r*B + u[j]) % v; + * We unroll this completely here. + */ + t = v[2]; /* nonzero, by definition */ + q1 = (digit)(u[1] / t); + rbj = COMBINE(u[1] % t, u[2]); + q2 = (digit)(rbj / t); + rbj = COMBINE(rbj % t, u[3]); + q3 = (digit)(rbj / t); + rbj = COMBINE(rbj % t, u[4]); + q4 = (digit)(rbj / t); + if (arq) + *arq = rbj % t; + tmp.ui[H] = COMBINE(q1, q2); + tmp.ui[L] = COMBINE(q3, q4); + return (tmp.ll); + } + } - /* - * By adjusting q once we determine m, we can guarantee that - * there is a complete four-digit quotient at &qspace[1] when - * we finally stop. - */ - for (m = 4 - n; u[1] == 0; u++) - m--; - for (i = 4 - m; --i >= 0;) - q[i] = 0; - q += 4 - m; + /* + * By adjusting q once we determine m, we can guarantee that + * there is a complete four-digit quotient at &qspace[1] when + * we finally stop. + */ + for (m = 4 - n; u[1] == 0; u++) + m--; + for (i = 4 - m; --i >= 0;) + q[i] = 0; + q += 4 - m; - /* - * Here we run Program D, translated from MIX to C and acquiring - * a few minor changes. - * - * D1: choose multiplier 1 << d to ensure v[1] >= B/2. - */ - d = 0; - for (t = v[1]; t < B / 2; t <<= 1) - d++; - if (d > 0) { - shl(&u[0], m + n, d); /* u <<= d */ - shl(&v[1], n - 1, d); /* v <<= d */ - } - /* - * D2: j = 0. - */ - j = 0; - v1 = v[1]; /* for D3 -- note that v[1..n] are constant */ - v2 = v[2]; /* for D3 */ - do { - digit uj0, uj1, uj2; + /* + * Here we run Program D, translated from MIX to C and acquiring + * a few minor changes. + * + * D1: choose multiplier 1 << d to ensure v[1] >= B/2. + */ + d = 0; + for (t = v[1]; t < B / 2; t <<= 1) + d++; + if (d > 0) { + shl(&u[0], m + n, d); /* u <<= d */ + shl(&v[1], n - 1, d); /* v <<= d */ + } + /* + * D2: j = 0. + */ + j = 0; + v1 = v[1]; /* for D3 -- note that v[1..n] are constant */ + v2 = v[2]; /* for D3 */ + do { + digit uj0, uj1, uj2; - /* - * D3: Calculate qhat (\^q, in TeX notation). - * Let qhat = min((u[j]*B + u[j+1])/v[1], B-1), and - * let rhat = (u[j]*B + u[j+1]) mod v[1]. - * While rhat < B and v[2]*qhat > rhat*B+u[j+2], - * decrement qhat and increase rhat correspondingly. - * Note that if rhat >= B, v[2]*qhat < rhat*B. - */ - uj0 = u[j + 0]; /* for D3 only -- note that u[j+...] change */ - uj1 = u[j + 1]; /* for D3 only */ - uj2 = u[j + 2]; /* for D3 only */ - if (uj0 == v1) { - qhat = B; - rhat = uj1; - goto qhat_too_big; - } else { - unsigned int nn = COMBINE(uj0, uj1); - qhat = nn / v1; - rhat = nn % v1; - } - while (v2 * qhat > COMBINE(rhat, uj2)) { - qhat_too_big: - qhat--; - if ((rhat += v1) >= B) - break; - } - /* - * D4: Multiply and subtract. - * The variable `t' holds any borrows across the loop. - * We split this up so that we do not require v[0] = 0, - * and to eliminate a final special case. - */ - for (t = 0, i = n; i > 0; i--) { - t = u[i + j] - v[i] * qhat - t; - u[i + j] = (digit)LHALF(t); - t = (B - HHALF(t)) & (B - 1); - } - t = u[j] - t; - u[j] = (digit)LHALF(t); - /* - * D5: test remainder. - * There is a borrow if and only if HHALF(t) is nonzero; - * in that (rare) case, qhat was too large (by exactly 1). - * Fix it by adding v[1..n] to u[j..j+n]. - */ - if (HHALF(t)) { - qhat--; - for (t = 0, i = n; i > 0; i--) { /* D6: add back. */ - t += u[i + j] + v[i]; - u[i + j] = (digit)LHALF(t); - t = HHALF(t); - } - u[j] = (digit)LHALF(u[j] + t); - } - q[j] = (digit)qhat; - } while (++j <= m); /* D7: loop on j. */ + /* + * D3: Calculate qhat (\^q, in TeX notation). + * Let qhat = min((u[j]*B + u[j+1])/v[1], B-1), and + * let rhat = (u[j]*B + u[j+1]) mod v[1]. + * While rhat < B and v[2]*qhat > rhat*B+u[j+2], + * decrement qhat and increase rhat correspondingly. + * Note that if rhat >= B, v[2]*qhat < rhat*B. + */ + uj0 = u[j + 0]; /* for D3 only -- note that u[j+...] change */ + uj1 = u[j + 1]; /* for D3 only */ + uj2 = u[j + 2]; /* for D3 only */ + if (uj0 == v1) { + qhat = B; + rhat = uj1; + goto qhat_too_big; + } else { + unsigned int nn = COMBINE(uj0, uj1); + qhat = nn / v1; + rhat = nn % v1; + } + while (v2 * qhat > COMBINE(rhat, uj2)) { + qhat_too_big: + qhat--; + if ((rhat += v1) >= B) + break; + } + /* + * D4: Multiply and subtract. + * The variable `t' holds any borrows across the loop. + * We split this up so that we do not require v[0] = 0, + * and to eliminate a final special case. + */ + for (t = 0, i = n; i > 0; i--) { + t = u[i + j] - v[i] * qhat - t; + u[i + j] = (digit)LHALF(t); + t = (B - HHALF(t)) & (B - 1); + } + t = u[j] - t; + u[j] = (digit)LHALF(t); + /* + * D5: test remainder. + * There is a borrow if and only if HHALF(t) is nonzero; + * in that (rare) case, qhat was too large (by exactly 1). + * Fix it by adding v[1..n] to u[j..j+n]. + */ + if (HHALF(t)) { + qhat--; + for (t = 0, i = n; i > 0; i--) { /* D6: add back. */ + t += u[i + j] + v[i]; + u[i + j] = (digit)LHALF(t); + t = HHALF(t); + } + u[j] = (digit)LHALF(u[j] + t); + } + q[j] = (digit)qhat; + } while (++j <= m); /* D7: loop on j. */ - /* - * If caller wants the remainder, we have to calculate it as - * u[m..m+n] >> d (this is at most n digits and thus fits in - * u[m+1..m+n], but we may need more source digits). - */ - if (arq) { - if (d) { - for (i = m + n; i > m; --i) - u[i] = (digit)(((unsigned int)u[i] >> d) | - LHALF((unsigned int)u[i - 1] << - (HALF_BITS - d))); - u[i] = 0; - } - tmp.ui[H] = COMBINE(uspace[1], uspace[2]); - tmp.ui[L] = COMBINE(uspace[3], uspace[4]); - *arq = tmp.ll; - } + /* + * If caller wants the remainder, we have to calculate it as + * u[m..m+n] >> d (this is at most n digits and thus fits in + * u[m+1..m+n], but we may need more source digits). + */ + if (arq) { + if (d) { + for (i = m + n; i > m; --i) + u[i] = (digit)(((unsigned int)u[i] >> d) | + LHALF((unsigned int)u[i - 1] << (HALF_BITS - d))); + u[i] = 0; + } + tmp.ui[H] = COMBINE(uspace[1], uspace[2]); + tmp.ui[L] = COMBINE(uspace[3], uspace[4]); + *arq = tmp.ll; + } - tmp.ui[H] = COMBINE(qspace[1], qspace[2]); - tmp.ui[L] = COMBINE(qspace[3], qspace[4]); - return (tmp.ll); + tmp.ui[H] = COMBINE(qspace[1], qspace[2]); + tmp.ui[L] = COMBINE(qspace[3], qspace[4]); + return (tmp.ll); } /* @@ -267,13 +264,11 @@ __qdivrem(unsigned long long ull, unsigned long long vll, * `fall out' the left (there never will be any such anyway). * We may assume len >= 0. NOTE THAT THIS WRITES len+1 DIGITS. */ -static void -shl(digit *p, int len, int sh) -{ - int i; +static void shl(digit *p, int len, int sh) { + int i; - for (i = 0; i < len; i++) - p[i] = (digit)(LHALF((unsigned int)p[i] << sh) | - ((unsigned int)p[i + 1] >> (HALF_BITS - sh))); - p[i] = (digit)(LHALF((unsigned int)p[i] << sh)); + for (i = 0; i < len; i++) + p[i] = (digit)(LHALF((unsigned int)p[i] << sh) | + ((unsigned int)p[i + 1] >> (HALF_BITS - sh))); + p[i] = (digit)(LHALF((unsigned int)p[i] << sh)); } diff --git a/common/gcc-millicode/subdi3.c b/common/gcc-millicode/subdi3.c index 1e95350..0950228 100644 --- a/common/gcc-millicode/subdi3.c +++ b/common/gcc-millicode/subdi3.c @@ -42,14 +42,12 @@ * carry from a single unsigned int difference x-y occurs if and only * if (x-y) > x. */ -long long -__subdi3(long long a, long long b) -{ - union uu aa, bb, diff; +long long __subdi3(long long a, long long b) { + union uu aa, bb, diff; - aa.ll = a; - bb.ll = b; - diff.ui[L] = aa.ui[L] - bb.ui[L]; - diff.ui[H] = aa.ui[H] - bb.ui[H] - (diff.ui[L] > aa.ui[L]); - return (diff.ll); + aa.ll = a; + bb.ll = b; + diff.ui[L] = aa.ui[L] - bb.ui[L]; + diff.ui[H] = aa.ui[H] - bb.ui[H] - (diff.ui[L] > aa.ui[L]); + return (diff.ll); } diff --git a/common/gcc-millicode/ucmpdi2.c b/common/gcc-millicode/ucmpdi2.c index b7e1a47..f55b616 100644 --- a/common/gcc-millicode/ucmpdi2.c +++ b/common/gcc-millicode/ucmpdi2.c @@ -41,13 +41,14 @@ * Return 0, 1, or 2 as a <, =, > b respectively. * Neither a nor b are considered signed. */ -int -__ucmpdi2(unsigned long long a, unsigned long long b) -{ - union uu aa, bb; +int __ucmpdi2(unsigned long long a, unsigned long long b) { + union uu aa, bb; - aa.ull = a; - bb.ull = b; - return (aa.ui[H] < bb.ui[H] ? 0 : aa.ui[H] > bb.ui[H] ? 2 : - aa.ui[L] < bb.ui[L] ? 0 : aa.ui[L] > bb.ui[L] ? 2 : 1); + aa.ull = a; + bb.ull = b; + return (aa.ui[H] < bb.ui[H] ? 0 + : aa.ui[H] > bb.ui[H] ? 2 + : aa.ui[L] < bb.ui[L] ? 0 + : aa.ui[L] > bb.ui[L] ? 2 + : 1); } diff --git a/common/gcc-millicode/udivdi3.c b/common/gcc-millicode/udivdi3.c index 89cdf00..04bcd39 100644 --- a/common/gcc-millicode/udivdi3.c +++ b/common/gcc-millicode/udivdi3.c @@ -40,9 +40,7 @@ /* * Divide two unsigned long longs. */ -unsigned long long -__udivdi3(unsigned long long a, unsigned long long b) -{ +unsigned long long __udivdi3(unsigned long long a, unsigned long long b) { - return __qdivrem(a, b, NULL); + return __qdivrem(a, b, NULL); } diff --git a/common/gcc-millicode/umoddi3.c b/common/gcc-millicode/umoddi3.c index 0e403d1..1a9e304 100644 --- a/common/gcc-millicode/umoddi3.c +++ b/common/gcc-millicode/umoddi3.c @@ -40,11 +40,9 @@ /* * Return remainder after dividing two unsigned long longs. */ -unsigned long long -__umoddi3(unsigned long long a, unsigned long long b) -{ - unsigned long long r; +unsigned long long __umoddi3(unsigned long long a, unsigned long long b) { + unsigned long long r; - (void)__qdivrem(a, b, &r); - return (r); + (void)__qdivrem(a, b, &r); + return (r); } diff --git a/common/gcc-millicode/xordi3.c b/common/gcc-millicode/xordi3.c index 010603b..7882826 100644 --- a/common/gcc-millicode/xordi3.c +++ b/common/gcc-millicode/xordi3.c @@ -40,14 +40,12 @@ /* * Return a ^ b, in long long. */ -long long -__xordi3(long long a, long long b) -{ - union uu aa, bb; +long long __xordi3(long long a, long long b) { + union uu aa, bb; - aa.ll = a; - bb.ll = b; - aa.ui[0] ^= bb.ui[0]; - aa.ui[1] ^= bb.ui[1]; - return (aa.ll); + aa.ll = a; + bb.ll = b; + aa.ui[0] ^= bb.ui[0]; + aa.ui[1] ^= bb.ui[1]; + return (aa.ll); } diff --git a/common/libc/printf/__printf.c b/common/libc/printf/__printf.c index b2476b4..323d551 100644 --- a/common/libc/printf/__printf.c +++ b/common/libc/printf/__printf.c @@ -52,7 +52,6 @@ #include - /* * Do we want to support "long long" types with %lld? * @@ -67,12 +66,11 @@ * Define a type that holds the longest signed integer we intend to support. */ #ifdef USE_LONGLONG -#define INTTYPE long long +#define INTTYPE long long #else -#define INTTYPE long +#define INTTYPE long #endif - /* * Space for a long long in base 8, plus a NUL, plus one * character extra for slop. @@ -87,52 +85,52 @@ * Structure holding the state for printf. */ typedef struct { - /* Callback for sending printed string data */ - void (*sendfunc)(void *clientdata, const char *str, size_t len); - void *clientdata; + /* Callback for sending printed string data */ + void (*sendfunc)(void *clientdata, const char *str, size_t len); + void *clientdata; - /* The varargs argument pointer */ - va_list ap; + /* The varargs argument pointer */ + va_list ap; - /* Total count of characters printed */ - int charcount; + /* Total count of characters printed */ + int charcount; - /* Flag that's true if we are currently looking in a %-format */ - int in_pct; + /* Flag that's true if we are currently looking in a %-format */ + int in_pct; - /* Size of the integer argument to retrieve */ - enum { - INTSZ, - LONGSZ, + /* Size of the integer argument to retrieve */ + enum { + INTSZ, + LONGSZ, #ifdef USE_LONGLONG - LLONGSZ, + LLONGSZ, #endif - SIZETSZ, - } size; + SIZETSZ, + } size; - /* The value of the integer argument retrieved */ - unsigned INTTYPE num; + /* The value of the integer argument retrieved */ + unsigned INTTYPE num; - /* Sign of the integer argument (0 = positive; -1 = negative) */ - int sign; + /* Sign of the integer argument (0 = positive; -1 = negative) */ + int sign; - /* Field width (number of spaces) */ - int spacing; + /* Field width (number of spaces) */ + int spacing; - /* Flag: align to left in field instead of right */ - int rightspc; + /* Flag: align to left in field instead of right */ + int rightspc; - /* Character to pad to field size with (space or 0) */ - int fillchar; + /* Character to pad to field size with (space or 0) */ + int fillchar; - /* Number base to print the integer argument in (8, 10, 16) */ - int base; + /* Number base to print the integer argument in (8, 10, 16) */ + int base; - /* Flag: if set, print 0x before hex and 0 before octal numbers */ - int baseprefix; + /* Flag: if set, print 0x before hex and 0 before octal numbers */ + int baseprefix; - /* Flag: alternative output format selected with %#... */ - int altformat; + /* Flag: alternative output format selected with %#... */ + int altformat; } PF; /* @@ -141,31 +139,25 @@ typedef struct { * We count the total length we send out so we can return it from __vprintf, * since that's what most printf-like functions want to return. */ -static -void -__pf_print(PF *pf, const char *txt, size_t len) -{ - pf->sendfunc(pf->clientdata, txt, len); - pf->charcount += len; +static void __pf_print(PF *pf, const char *txt, size_t len) { + pf->sendfunc(pf->clientdata, txt, len); + pf->charcount += len; } /* * Reset the state for the next %-field. */ -static -void -__pf_endfield(PF *pf) -{ - pf->in_pct = 0; - pf->size = INTSZ; - pf->num = 0; - pf->sign = 0; - pf->spacing = 0; - pf->rightspc = 0; - pf->fillchar = ' '; - pf->base = 0; - pf->baseprefix = 0; - pf->altformat = 0; +static void __pf_endfield(PF *pf) { + pf->in_pct = 0; + pf->size = INTSZ; + pf->num = 0; + pf->sign = 0; + pf->spacing = 0; + pf->rightspc = 0; + pf->fillchar = ' '; + pf->base = 0; + pf->baseprefix = 0; + pf->altformat = 0; } /* @@ -177,59 +169,54 @@ __pf_endfield(PF *pf) * 0-9 field width * leading 0 pad with zeros instead of spaces */ -static -void -__pf_modifier(PF *pf, int ch) -{ - switch (ch) { - case '#': - pf->altformat = 1; - break; - case '-': - pf->rightspc = 1; - break; - case 'l': - if (pf->size==LONGSZ) { +static void __pf_modifier(PF *pf, int ch) { + switch (ch) { + case '#': + pf->altformat = 1; + break; + case '-': + pf->rightspc = 1; + break; + case 'l': + if (pf->size == LONGSZ) { #ifdef USE_LONGLONG - pf->size = LLONGSZ; + pf->size = LLONGSZ; #endif - } - else { - pf->size = LONGSZ; - } - break; - case 'z': - pf->size = SIZETSZ; - break; - case '0': - if (pf->spacing>0) { - /* - * Already seen some digits; this is part of the - * field size. - */ - pf->spacing = pf->spacing*10; - } - else { - /* - * Leading zero; set the padding character to 0. - */ - pf->fillchar = '0'; - } - break; - default: - /* - * Invalid characters should be filtered out by a - * higher-level function, so if this assert goes off - * it's our fault. - */ - assert(ch>'0' && ch<='9'); + } else { + pf->size = LONGSZ; + } + break; + case 'z': + pf->size = SIZETSZ; + break; + case '0': + if (pf->spacing > 0) { + /* + * Already seen some digits; this is part of the + * field size. + */ + pf->spacing = pf->spacing * 10; + } else { + /* + * Leading zero; set the padding character to 0. + */ + pf->fillchar = '0'; + } + break; + default: + /* + * Invalid characters should be filtered out by a + * higher-level function, so if this assert goes off + * it's our fault. + */ + assert(ch > '0' && ch <= '9'); - /* - * Got a digit; accumulate the field size. - */ - pf->spacing = pf->spacing*10 + (ch-'0'); - break; - } + /* + * Got a digit; accumulate the field size. + */ + pf->spacing = pf->spacing * 10 + (ch - '0'); + break; + } } /* @@ -237,77 +224,71 @@ __pf_modifier(PF *pf, int ch) * in pf->num, according to the size recorded in pf->size and using * the numeric type specified by ch. */ -static -void -__pf_getnum(PF *pf, int ch) -{ - if (ch=='p') { - /* - * Pointer. - * - * uintptr_t is a C99 standard type that's an unsigned - * integer the same size as a pointer. - */ - pf->num = (uintptr_t) va_arg(pf->ap, void *); - } - else if (ch=='d') { - /* signed integer */ - INTTYPE signednum=0; - switch (pf->size) { - case INTSZ: - /* %d */ - signednum = va_arg(pf->ap, int); - break; - case LONGSZ: - /* %ld */ - signednum = va_arg(pf->ap, long); - break; +static void __pf_getnum(PF *pf, int ch) { + if (ch == 'p') { + /* + * Pointer. + * + * uintptr_t is a C99 standard type that's an unsigned + * integer the same size as a pointer. + */ + pf->num = (uintptr_t)va_arg(pf->ap, void *); + } else if (ch == 'd') { + /* signed integer */ + INTTYPE signednum = 0; + switch (pf->size) { + case INTSZ: + /* %d */ + signednum = va_arg(pf->ap, int); + break; + case LONGSZ: + /* %ld */ + signednum = va_arg(pf->ap, long); + break; #ifdef USE_LONGLONG - case LLONGSZ: - /* %lld */ - signednum = va_arg(pf->ap, long long); - break; + case LLONGSZ: + /* %lld */ + signednum = va_arg(pf->ap, long long); + break; #endif - case SIZETSZ: - /* %zd */ - signednum = va_arg(pf->ap, ssize_t); - break; - } + case SIZETSZ: + /* %zd */ + signednum = va_arg(pf->ap, ssize_t); + break; + } - /* - * Check for negative numbers. - */ - if (signednum < 0) { - pf->sign = -1; - pf->num = -signednum; - } - else { - pf->num = signednum; - } - } - else { - /* unsigned integer */ - switch (pf->size) { - case INTSZ: - /* %u (or %o, %x) */ - pf->num = va_arg(pf->ap, unsigned int); - break; - case LONGSZ: - /* %lu (or %lo, %lx) */ - pf->num = va_arg(pf->ap, unsigned long); - break; + /* + * Check for negative numbers. + */ + if (signednum < 0) { + pf->sign = -1; + pf->num = -signednum; + } else { + pf->num = signednum; + } + } else { + /* unsigned integer */ + switch (pf->size) { + case INTSZ: + /* %u (or %o, %x) */ + pf->num = va_arg(pf->ap, unsigned int); + break; + case LONGSZ: + /* %lu (or %lo, %lx) */ + pf->num = va_arg(pf->ap, unsigned long); + break; #ifdef USE_LONGLONG - case LLONGSZ: - /* %llu, %llo, %llx */ - pf->num = va_arg(pf->ap, unsigned long long); - break; + case LLONGSZ: + /* %llu, %llo, %llx */ + pf->num = va_arg(pf->ap, unsigned long long); + break; #endif - case SIZETSZ: - /* %zu, %zo, %zx */ - pf->num = va_arg(pf->ap, size_t); - break; - } - } + case SIZETSZ: + /* %zu, %zo, %zx */ + pf->num = va_arg(pf->ap, size_t); + break; + } + } } /* @@ -320,40 +301,34 @@ __pf_getnum(PF *pf, int ch) * If the "alternate format" was requested, or always for pointers, * note to print the C prefix for the type. */ -static -void -__pf_setbase(PF *pf, int ch) -{ - switch (ch) { - case 'd': - case 'u': - pf->base = 10; - break; - case 'x': - case 'p': - pf->base = 16; - break; - case 'o': - pf->base = 8; - break; - } - if (pf->altformat || ch=='p') { - pf->baseprefix = 1; - } +static void __pf_setbase(PF *pf, int ch) { + switch (ch) { + case 'd': + case 'u': + pf->base = 10; + break; + case 'x': + case 'p': + pf->base = 16; + break; + case 'o': + pf->base = 8; + break; + } + if (pf->altformat || ch == 'p') { + pf->baseprefix = 1; + } } /* * Function to print "spc" instances of the fill character. */ -static -void -__pf_fill(PF *pf, int spc) -{ - char f = pf->fillchar; - int i; - for (i=0; ifillchar; + int i; + for (i = 0; i < spc; i++) { + __pf_print(pf, &f, 1); + } } /* @@ -362,45 +337,40 @@ __pf_fill(PF *pf, int spc) * and the other is the sign) get printed *after* space padding but * *before* zero padding, if padding is on the left. */ -static -void -__pf_printstuff(PF *pf, - const char *prefix, const char *prefix2, - const char *stuff) -{ - /* Total length to print. */ - int len = strlen(prefix)+strlen(prefix2)+strlen(stuff); +static void __pf_printstuff(PF *pf, const char *prefix, const char *prefix2, + const char *stuff) { + /* Total length to print. */ + int len = strlen(prefix) + strlen(prefix2) + strlen(stuff); - /* Get field width and compute amount of padding in "spc". */ - int spc = pf->spacing; - if (spc > len) { - spc -= len; - } - else { - spc = 0; - } + /* Get field width and compute amount of padding in "spc". */ + int spc = pf->spacing; + if (spc > len) { + spc -= len; + } else { + spc = 0; + } - /* If padding on left and the fill char is not 0, pad first. */ - if (spc > 0 && pf->rightspc==0 && pf->fillchar!='0') { - __pf_fill(pf, spc); - } + /* If padding on left and the fill char is not 0, pad first. */ + if (spc > 0 && pf->rightspc == 0 && pf->fillchar != '0') { + __pf_fill(pf, spc); + } - /* Print the prefixes. */ - __pf_print(pf, prefix, strlen(prefix)); - __pf_print(pf, prefix2, strlen(prefix2)); + /* Print the prefixes. */ + __pf_print(pf, prefix, strlen(prefix)); + __pf_print(pf, prefix2, strlen(prefix2)); - /* If padding on left and the fill char *is* 0, pad here. */ - if (spc > 0 && pf->rightspc==0 && pf->fillchar=='0') { - __pf_fill(pf, spc); - } + /* If padding on left and the fill char *is* 0, pad here. */ + if (spc > 0 && pf->rightspc == 0 && pf->fillchar == '0') { + __pf_fill(pf, spc); + } - /* Print the actual string. */ - __pf_print(pf, stuff, strlen(stuff)); + /* Print the actual string. */ + __pf_print(pf, stuff, strlen(stuff)); - /* If padding on the right, pad afterwards. */ - if (spc > 0 && pf->rightspc!=0) { - __pf_fill(pf, spc); - } + /* If padding on the right, pad afterwards. */ + if (spc > 0 && pf->rightspc != 0) { + __pf_fill(pf, spc); + } } /* @@ -410,156 +380,142 @@ __pf_printstuff(PF *pf, * NUMBER_BUF_SIZE is set so that the longest number string we can * generate (a long long printed in octal) will fit. See above. */ -static -void -__pf_printnum(PF *pf) -{ - /* Digits to print with. */ - const char *const digits = "0123456789abcdef"; +static void __pf_printnum(PF *pf) { + /* Digits to print with. */ + const char *const digits = "0123456789abcdef"; - char buf[NUMBER_BUF_SIZE]; /* Accumulation buffer for string. */ - char *x; /* Current pointer into buf. */ - unsigned INTTYPE xnum; /* Current value to print. */ - const char *bprefix; /* Base prefix (0, 0x, or nothing) */ - const char *sprefix; /* Sign prefix (- or nothing) */ + char buf[NUMBER_BUF_SIZE]; /* Accumulation buffer for string. */ + char *x; /* Current pointer into buf. */ + unsigned INTTYPE xnum; /* Current value to print. */ + const char *bprefix; /* Base prefix (0, 0x, or nothing) */ + const char *sprefix; /* Sign prefix (- or nothing) */ - /* Start in the last slot of the buffer. */ - x = buf+sizeof(buf)-1; + /* Start in the last slot of the buffer. */ + x = buf + sizeof(buf) - 1; - /* Insert null terminator. */ - *x-- = 0; + /* Insert null terminator. */ + *x-- = 0; - /* Initialize value. */ - xnum = pf->num; + /* Initialize value. */ + xnum = pf->num; - /* - * Convert a single digit. - * Do this loop at least once - that way 0 prints as 0 and not "". - */ - do { - /* - * Get the digit character for the least significant - * part of xnum. - */ - *x = digits[xnum % pf->base]; + /* + * Convert a single digit. + * Do this loop at least once - that way 0 prints as 0 and not "". + */ + do { + /* + * Get the digit character for the least significant + * part of xnum. + */ + *x = digits[xnum % pf->base]; - /* - * Back up the pointer to point to the next space to the left. - */ - x--; + /* + * Back up the pointer to point to the next space to the left. + */ + x--; - /* - * Drop the value of the digit we just printed from xnum. - */ - xnum = xnum / pf->base; + /* + * Drop the value of the digit we just printed from xnum. + */ + xnum = xnum / pf->base; - /* - * If xnum hits 0 there's no more number left. - */ - } while (xnum > 0); + /* + * If xnum hits 0 there's no more number left. + */ + } while (xnum > 0); - /* - * x points to the *next* slot in the buffer to use. - * However, we're done printing the number. So it's pointing - * one slot *before* the start of the actual number text. - * So advance it by one so it actually points at the number. - */ - x++; + /* + * x points to the *next* slot in the buffer to use. + * However, we're done printing the number. So it's pointing + * one slot *before* the start of the actual number text. + * So advance it by one so it actually points at the number. + */ + x++; - /* - * If a base prefix was requested, select it. - */ - if (pf->baseprefix && pf->base==16) { - bprefix = "0x"; - } - else if (pf->baseprefix && pf->base==8) { - bprefix = "0"; - } - else { - bprefix = ""; - } + /* + * If a base prefix was requested, select it. + */ + if (pf->baseprefix && pf->base == 16) { + bprefix = "0x"; + } else if (pf->baseprefix && pf->base == 8) { + bprefix = "0"; + } else { + bprefix = ""; + } - /* - * Choose the sign prefix. - */ - sprefix = pf->sign ? "-" : ""; + /* + * Choose the sign prefix. + */ + sprefix = pf->sign ? "-" : ""; - /* - * Now actually print the string we just generated. - */ - __pf_printstuff(pf, sprefix, bprefix, x); + /* + * Now actually print the string we just generated. + */ + __pf_printstuff(pf, sprefix, bprefix, x); } /* * Process a single character out of the format string. */ -static -void -__pf_send(PF *pf, int ch) -{ - /* Cannot get NULs here. */ - assert(ch!=0); +static void __pf_send(PF *pf, int ch) { + /* Cannot get NULs here. */ + assert(ch != 0); - if (pf->in_pct==0 && ch!='%') { - /* - * Not currently in a format, and not a %. Just send - * the character on through. - */ - char c = ch; - __pf_print(pf, &c, 1); - } - else if (pf->in_pct==0) { - /* - * Not in a format, but got a %. Start a format. - */ - pf->in_pct = 1; - } - else if (strchr("#-lz0123456789", ch)) { - /* - * These are the modifier characters we recognize. - * (These are the characters between the % and the type.) - */ - __pf_modifier(pf, ch); - } - else if (strchr("doupx", ch)) { - /* - * Integer types. - * Fetch the number, set the base, print it, then - * reset for the next format. - */ - __pf_getnum(pf, ch); - __pf_setbase(pf, ch); - __pf_printnum(pf); - __pf_endfield(pf); - } - else if (ch=='s') { - /* - * Print a string. - */ - const char *str = va_arg(pf->ap, const char *); - if (str==NULL) { - str = "(null)"; - } - __pf_printstuff(pf, "", "", str); - __pf_endfield(pf); - } - else { - /* - * %%, %c, or illegal character. - * Illegal characters are printed like %%. - * for example, %5k prints " k". - */ - char x[2]; - if (ch=='c') { - x[0] = va_arg(pf->ap, int); - } - else { - x[0] = ch; - } - x[1] = 0; - __pf_printstuff(pf, "", "", x); - __pf_endfield(pf); - } + if (pf->in_pct == 0 && ch != '%') { + /* + * Not currently in a format, and not a %. Just send + * the character on through. + */ + char c = ch; + __pf_print(pf, &c, 1); + } else if (pf->in_pct == 0) { + /* + * Not in a format, but got a %. Start a format. + */ + pf->in_pct = 1; + } else if (strchr("#-lz0123456789", ch)) { + /* + * These are the modifier characters we recognize. + * (These are the characters between the % and the type.) + */ + __pf_modifier(pf, ch); + } else if (strchr("doupx", ch)) { + /* + * Integer types. + * Fetch the number, set the base, print it, then + * reset for the next format. + */ + __pf_getnum(pf, ch); + __pf_setbase(pf, ch); + __pf_printnum(pf); + __pf_endfield(pf); + } else if (ch == 's') { + /* + * Print a string. + */ + const char *str = va_arg(pf->ap, const char *); + if (str == NULL) { + str = "(null)"; + } + __pf_printstuff(pf, "", "", str); + __pf_endfield(pf); + } else { + /* + * %%, %c, or illegal character. + * Illegal characters are printed like %%. + * for example, %5k prints " k". + */ + char x[2]; + if (ch == 'c') { + x[0] = va_arg(pf->ap, int); + } else { + x[0] = ch; + } + x[1] = 0; + __pf_printstuff(pf, "", "", x); + __pf_endfield(pf); + } } /* @@ -567,26 +523,24 @@ __pf_send(PF *pf, int ch) * Create and initialize a printf state object, * then send it each character from the format string. */ -int -__vprintf(void (*func)(void *clientdata, const char *str, size_t len), - void *clientdata, const char *format, va_list ap) -{ - PF pf; - int i; +int __vprintf(void (*func)(void *clientdata, const char *str, size_t len), + void *clientdata, const char *format, va_list ap) { + PF pf; + int i; - pf.sendfunc = func; - pf.clientdata = clientdata; + pf.sendfunc = func; + pf.clientdata = clientdata; #ifdef va_copy - va_copy(pf.ap, ap); + va_copy(pf.ap, ap); #else - pf.ap = ap; + pf.ap = ap; #endif - pf.charcount = 0; - __pf_endfield(&pf); + pf.charcount = 0; + __pf_endfield(&pf); - for (i=0; format[i]; i++) { - __pf_send(&pf, format[i]); - } + for (i = 0; format[i]; i++) { + __pf_send(&pf, format[i]); + } - return pf.charcount; + return pf.charcount; } diff --git a/common/libc/printf/snprintf.c b/common/libc/printf/snprintf.c index a64b530..9fa2f9e 100644 --- a/common/libc/printf/snprintf.c +++ b/common/libc/printf/snprintf.c @@ -47,7 +47,6 @@ * Standard C string/IO function: printf into a character buffer. */ - /* * Context structure for snprintf: buffer to print into, maximum * length, and index of the next character to write. @@ -58,9 +57,9 @@ */ typedef struct { - char *buf; - size_t buflen; - size_t bufpos; + char *buf; + size_t buflen; + size_t bufpos; } SNP; /* @@ -70,88 +69,79 @@ typedef struct { * null-terminated. */ -static -void -__snprintf_send(void *mydata, const char *data, size_t len) -{ - SNP *snp = mydata; - unsigned i; +static void __snprintf_send(void *mydata, const char *data, size_t len) { + SNP *snp = mydata; + unsigned i; - /* For each character we're sent... */ - for (i=0; ibufpos < snp->buflen) { + /* If we aren't past the length, */ + if (snp->bufpos < snp->buflen) { - /* store the character */ - snp->buf[snp->bufpos] = data[i]; + /* store the character */ + snp->buf[snp->bufpos] = data[i]; - /* and increment the position. */ - snp->bufpos++; - } - } + /* and increment the position. */ + snp->bufpos++; + } + } } /* * The va_list version of snprintf. */ -int -vsnprintf(char *buf, size_t len, const char *fmt, va_list ap) -{ - int chars; - SNP snp; +int vsnprintf(char *buf, size_t len, const char *fmt, va_list ap) { + int chars; + SNP snp; - /* - * Fill in the context structure. - * We set snp.buflen to the number of characters that can be - * written (excluding the null terminator) so as not to have - * to special-case the possibility that we got passed a length - * of zero elsewhere. - */ - snp.buf = buf; - if (len==0) { - snp.buflen = 0; - } - else { - snp.buflen = len-1; - } - snp.bufpos = 0; + /* + * Fill in the context structure. + * We set snp.buflen to the number of characters that can be + * written (excluding the null terminator) so as not to have + * to special-case the possibility that we got passed a length + * of zero elsewhere. + */ + snp.buf = buf; + if (len == 0) { + snp.buflen = 0; + } else { + snp.buflen = len - 1; + } + snp.bufpos = 0; - /* Call __vprintf to do the actual work. */ - chars = __vprintf(__snprintf_send, &snp, fmt, ap); + /* Call __vprintf to do the actual work. */ + chars = __vprintf(__snprintf_send, &snp, fmt, ap); - /* - * Add a null terminator. If the length *we were passed* is greater - * than zero, we reserved a space in the buffer for the terminator, - * so this won't overflow. If the length we were passed is zero, - * nothing will have been or should be written anyway, and buf - * might even be NULL. (C99 explicitly endorses this possibility.) - */ - if (len > 0) { - buf[snp.bufpos] = 0; - } + /* + * Add a null terminator. If the length *we were passed* is greater + * than zero, we reserved a space in the buffer for the terminator, + * so this won't overflow. If the length we were passed is zero, + * nothing will have been or should be written anyway, and buf + * might even be NULL. (C99 explicitly endorses this possibility.) + */ + if (len > 0) { + buf[snp.bufpos] = 0; + } - /* - * Return the number of characters __vprintf processed. - * According to C99, snprintf should return this number, not - * the number of characters actually stored, and should not - * return -1 on overflow but only on other errors. (All none - * of them since we don't do multibyte characters...) - */ - return chars; + /* + * Return the number of characters __vprintf processed. + * According to C99, snprintf should return this number, not + * the number of characters actually stored, and should not + * return -1 on overflow but only on other errors. (All none + * of them since we don't do multibyte characters...) + */ + return chars; } /* * snprintf - hand off to vsnprintf. */ -int -snprintf(char *buf, size_t len, const char *fmt, ...) -{ - int chars; - va_list ap; - va_start(ap, fmt); - chars = vsnprintf(buf, len, fmt, ap); - va_end(ap); - return chars; +int snprintf(char *buf, size_t len, const char *fmt, ...) { + int chars; + va_list ap; + va_start(ap, fmt); + chars = vsnprintf(buf, len, fmt, ap); + va_end(ap); + return chars; } - diff --git a/common/libc/stdlib/atoi.c b/common/libc/stdlib/atoi.c index 1bbeace..c9b82a1 100644 --- a/common/libc/stdlib/atoi.c +++ b/common/libc/stdlib/atoi.c @@ -46,56 +46,53 @@ * really report syntax errors or overflow in any useful way. */ -int -atoi(const char *s) -{ - static const char digits[] = "0123456789"; /* legal digits in order */ - unsigned val=0; /* value we're accumulating */ - int neg=0; /* set to true if we see a minus sign */ +int atoi(const char *s) { + static const char digits[] = "0123456789"; /* legal digits in order */ + unsigned val = 0; /* value we're accumulating */ + int neg = 0; /* set to true if we see a minus sign */ - /* skip whitespace */ - while (*s==' ' || *s=='\t') { - s++; - } + /* skip whitespace */ + while (*s == ' ' || *s == '\t') { + s++; + } - /* check for sign */ - if (*s=='-') { - neg=1; - s++; - } - else if (*s=='+') { - s++; - } + /* check for sign */ + if (*s == '-') { + neg = 1; + s++; + } else if (*s == '+') { + s++; + } - /* process each digit */ - while (*s) { - const char *where; - unsigned digit; + /* process each digit */ + while (*s) { + const char *where; + unsigned digit; - /* look for the digit in the list of digits */ - where = strchr(digits, *s); - if (where==NULL) { - /* not found; not a digit, so stop */ - break; - } + /* look for the digit in the list of digits */ + where = strchr(digits, *s); + if (where == NULL) { + /* not found; not a digit, so stop */ + break; + } - /* get the index into the digit list, which is the value */ - digit = (where - digits); + /* get the index into the digit list, which is the value */ + digit = (where - digits); - /* could (should?) check for overflow here */ + /* could (should?) check for overflow here */ - /* shift the number over and add in the new digit */ - val = val*10 + digit; + /* shift the number over and add in the new digit */ + val = val * 10 + digit; - /* look at the next character */ - s++; - } + /* look at the next character */ + s++; + } - /* handle negative numbers */ - if (neg) { - return -val; - } + /* handle negative numbers */ + if (neg) { + return -val; + } - /* done */ - return val; + /* done */ + return val; } diff --git a/common/libc/string/bzero.c b/common/libc/string/bzero.c index efd1552..c1c6b73 100644 --- a/common/libc/string/bzero.c +++ b/common/libc/string/bzero.c @@ -45,32 +45,28 @@ * memory. */ -void -bzero(void *vblock, size_t len) -{ - char *block = vblock; - size_t i; +void bzero(void *vblock, size_t len) { + char *block = vblock; + size_t i; - /* - * For performance, optimize the common case where the pointer - * and the length are word-aligned, and write word-at-a-time - * instead of byte-at-a-time. Otherwise, write bytes. - * - * The alignment logic here should be portable. We rely on the - * compiler to be reasonably intelligent about optimizing the - * divides and moduli out. Fortunately, it is. - */ + /* + * For performance, optimize the common case where the pointer + * and the length are word-aligned, and write word-at-a-time + * instead of byte-at-a-time. Otherwise, write bytes. + * + * The alignment logic here should be portable. We rely on the + * compiler to be reasonably intelligent about optimizing the + * divides and moduli out. Fortunately, it is. + */ - if ((uintptr_t)block % sizeof(long) == 0 && - len % sizeof(long) == 0) { - long *lb = (long *)block; - for (i=0; i0 is that - * i is unsigned -- so testing i>=0 doesn't work. - */ + /* + * The reason we copy index i-1 and test i>0 is that + * i is unsigned -- so testing i>=0 doesn't work. + */ - for (i=len/sizeof(long); i>0; i--) { - d[i-1] = s[i-1]; - } - } - else { - char *d = dst; - const char *s = src; + for (i = len / sizeof(long); i > 0; i--) { + d[i - 1] = s[i - 1]; + } + } else { + char *d = dst; + const char *s = src; - for (i=len; i>0; i--) { - d[i-1] = s[i-1]; - } - } + for (i = len; i > 0; i--) { + d[i - 1] = s[i - 1]; + } + } - return dst; + return dst; } diff --git a/common/libc/string/memset.c b/common/libc/string/memset.c index 8301ebd..0b7e5f8 100644 --- a/common/libc/string/memset.c +++ b/common/libc/string/memset.c @@ -38,15 +38,13 @@ * C standard function - initialize a block of memory */ -void * -memset(void *ptr, int ch, size_t len) -{ - char *p = ptr; - size_t i; +void *memset(void *ptr, int ch, size_t len) { + char *p = ptr; + size_t i; - for (i=0; i (unsigned char)b[i]) { - return 1; - } - else if (a[i] == b[i]) { - return 0; - } - return -1; + /* + * If A is greater than B, return 1. If A is less than B, + * return -1. If they're the same, return 0. Since we have + * stopped at the first character of difference (or the end of + * both strings) checking the character under I accomplishes + * this. + * + * Note that strcmp does not handle accented characters, + * internationalization, or locale sort order; strcoll() does + * that. + * + * The rules say we compare order in terms of *unsigned* char. + */ + if ((unsigned char)a[i] > (unsigned char)b[i]) { + return 1; + } else if (a[i] == b[i]) { + return 0; + } + return -1; } diff --git a/common/libc/string/strcpy.c b/common/libc/string/strcpy.c index 88627ed..b124395 100644 --- a/common/libc/string/strcpy.c +++ b/common/libc/string/strcpy.c @@ -42,22 +42,20 @@ /* * Standard C string function: copy one string to another. */ -char * -strcpy(char *dest, const char *src) -{ - size_t i; +char *strcpy(char *dest, const char *src) { + size_t i; - /* - * Copy characters until we hit the null terminator. - */ - for (i=0; src[i]; i++) { - dest[i] = src[i]; - } + /* + * Copy characters until we hit the null terminator. + */ + for (i = 0; src[i]; i++) { + dest[i] = src[i]; + } - /* - * Add null terminator to result. - */ - dest[i] = 0; + /* + * Add null terminator to result. + */ + dest[i] = 0; - return dest; + return dest; } diff --git a/common/libc/string/strlen.c b/common/libc/string/strlen.c index 0c5a248..69b159d 100644 --- a/common/libc/string/strlen.c +++ b/common/libc/string/strlen.c @@ -43,13 +43,11 @@ * C standard string function: get length of a string */ -size_t -strlen(const char *str) -{ - size_t ret = 0; +size_t strlen(const char *str) { + size_t ret = 0; - while (str[ret]) { - ret++; - } - return ret; + while (str[ret]) { + ret++; + } + return ret; } diff --git a/common/libc/string/strrchr.c b/common/libc/string/strrchr.c index 40cf255..fd4ceb4 100644 --- a/common/libc/string/strrchr.c +++ b/common/libc/string/strrchr.c @@ -43,27 +43,25 @@ * C standard string function: find rightmost instance of a character * in a string. */ -char * -strrchr(const char *s, int ch_arg) -{ - /* avoid sign-extension problems */ - const char ch = ch_arg; +char *strrchr(const char *s, int ch_arg) { + /* avoid sign-extension problems */ + const char ch = ch_arg; - /* start one past the last character INCLUDING NULL TERMINATOR */ - size_t i = strlen(s)+1; + /* start one past the last character INCLUDING NULL TERMINATOR */ + size_t i = strlen(s) + 1; - /* go from right to left; stop at 0 */ - while (i > 0) { + /* go from right to left; stop at 0 */ + while (i > 0) { - /* decrement first */ - i--; + /* decrement first */ + i--; - /* now check the character we're over */ - if (s[i] == ch) { - return (char *)(s+i); - } - } + /* now check the character we're over */ + if (s[i] == ch) { + return (char *)(s + i); + } + } - /* didn't find it */ - return NULL; + /* didn't find it */ + return NULL; } diff --git a/common/libc/string/strtok_r.c b/common/libc/string/strtok_r.c index 033fc85..394b789 100644 --- a/common/libc/string/strtok_r.c +++ b/common/libc/string/strtok_r.c @@ -46,51 +46,48 @@ * The "context" argument should point to a "char *" that is preserved * between calls to strtok_r that wish to operate on same string. */ -char * -strtok_r(char *string, const char *seps, char **context) -{ - char *head; /* start of word */ - char *tail; /* end of word */ +char *strtok_r(char *string, const char *seps, char **context) { + char *head; /* start of word */ + char *tail; /* end of word */ - /* If we're starting up, initialize context */ - if (string) { - *context = string; - } + /* If we're starting up, initialize context */ + if (string) { + *context = string; + } - /* Get potential start of this next word */ - head = *context; - if (head == NULL) { - return NULL; - } + /* Get potential start of this next word */ + head = *context; + if (head == NULL) { + return NULL; + } - /* Skip any leading separators */ - while (*head && strchr(seps, *head)) { - head++; - } + /* Skip any leading separators */ + while (*head && strchr(seps, *head)) { + head++; + } - /* Did we hit the end? */ - if (*head == 0) { - /* Nothing left */ - *context = NULL; - return NULL; - } + /* Did we hit the end? */ + if (*head == 0) { + /* Nothing left */ + *context = NULL; + return NULL; + } - /* skip over word */ - tail = head; - while (*tail && !strchr(seps, *tail)) { - tail++; - } + /* skip over word */ + tail = head; + while (*tail && !strchr(seps, *tail)) { + tail++; + } - /* Save head for next time in context */ - if (*tail == 0) { - *context = NULL; - } - else { - *tail = 0; - tail++; - *context = tail; - } + /* Save head for next time in context */ + if (*tail == 0) { + *context = NULL; + } else { + *tail = 0; + tail++; + *context = tail; + } - /* Return current word */ - return head; + /* Return current word */ + return head; } diff --git a/kern/arch/mips/include/current.h b/kern/arch/mips/include/current.h index 12f257c..1324257 100644 --- a/kern/arch/mips/include/current.h +++ b/kern/arch/mips/include/current.h @@ -30,7 +30,6 @@ #ifndef _MIPS_CURRENT_H_ #define _MIPS_CURRENT_H_ - /* * Macro for current thread, or current cpu. * @@ -60,7 +59,7 @@ */ #ifdef __GNUC__ -register struct thread *curthread __asm("$23"); /* s7 register */ +register struct thread *curthread __asm("$23"); /* s7 register */ #else #error "Don't know how to declare curthread in this compiler" #endif diff --git a/kern/arch/mips/include/elf.h b/kern/arch/mips/include/elf.h index c97aff7..32660a7 100644 --- a/kern/arch/mips/include/elf.h +++ b/kern/arch/mips/include/elf.h @@ -34,25 +34,23 @@ * MIPS machine-dependent definitions for the ELF binary format. */ - /* The ELF executable type. */ -#define EM_MACHINE EM_MIPS +#define EM_MACHINE EM_MIPS /* Linker relocation codes. SIZE DESCRIPTION */ -#define R_MIPS_NONE 0 /* --- nop */ -#define R_MIPS_16 1 /* u16 value */ -#define R_MIPS_32 2 /* u32 value */ -#define R_MIPS_REL32 3 /* u32 value relative to patched address */ -#define R_MIPS_26 4 /* u26 j/jal instruction address field */ -#define R_MIPS_HI16 5 /* u16 %hi(sym) as below */ -#define R_MIPS_LO16 6 /* s16 %lo(sym) as below */ -#define R_MIPS_GPREL16 7 /* s16 offset from GP register */ -#define R_MIPS_LITERAL 8 /* s16 GPREL16 for file-local symbols (?) */ -#define R_MIPS_GOT16 9 /* u16 offset into global offset table */ -#define R_MIPS_PC16 10 /* s16 PC-relative reference */ -#define R_MIPS_CALL16 11 /* u16 call through global offset table */ -#define R_MIPS_GPREL32 12 /* s32 offset from GP register */ +#define R_MIPS_NONE 0 /* --- nop */ +#define R_MIPS_16 1 /* u16 value */ +#define R_MIPS_32 2 /* u32 value */ +#define R_MIPS_REL32 3 /* u32 value relative to patched address */ +#define R_MIPS_26 4 /* u26 j/jal instruction address field */ +#define R_MIPS_HI16 5 /* u16 %hi(sym) as below */ +#define R_MIPS_LO16 6 /* s16 %lo(sym) as below */ +#define R_MIPS_GPREL16 7 /* s16 offset from GP register */ +#define R_MIPS_LITERAL 8 /* s16 GPREL16 for file-local symbols (?) */ +#define R_MIPS_GOT16 9 /* u16 offset into global offset table */ +#define R_MIPS_PC16 10 /* s16 PC-relative reference */ +#define R_MIPS_CALL16 11 /* u16 call through global offset table */ +#define R_MIPS_GPREL32 12 /* s32 offset from GP register */ /* %hi/%lo are defined so %hi(sym) << 16 + %lo(sym) = sym */ - #endif /* _MIPS_ELF_H_ */ diff --git a/kern/arch/mips/include/kern/regdefs.h b/kern/arch/mips/include/kern/regdefs.h index 5fd6a6e..59acaf6 100644 --- a/kern/arch/mips/include/kern/regdefs.h +++ b/kern/arch/mips/include/kern/regdefs.h @@ -36,39 +36,37 @@ #ifndef _KERN_MIPS_REGDEFS_H_ #define _KERN_MIPS_REGDEFS_H_ - -#define z0 $0 /* always zero register */ -#define AT $1 /* assembler temp register */ -#define v0 $2 /* value 0 */ -#define v1 $3 /* value 1 */ -#define a0 $4 /* argument 0 */ -#define a1 $5 /* argument 1 */ -#define a2 $6 /* argument 2 */ -#define a3 $7 /* argument 3 */ -#define t0 $8 /* temporary (caller-save) 0 */ -#define t1 $9 /* temporary (caller-save) 1 */ -#define t2 $10 /* temporary (caller-save) 2 */ -#define t3 $11 /* temporary (caller-save) 3 */ -#define t4 $12 /* temporary (caller-save) 4 */ -#define t5 $13 /* temporary (caller-save) 5 */ -#define t6 $14 /* temporary (caller-save) 6 */ -#define t7 $15 /* temporary (caller-save) 7 */ -#define s0 $16 /* saved (callee-save) 0 */ -#define s1 $17 /* saved (callee-save) 1 */ -#define s2 $18 /* saved (callee-save) 2 */ -#define s3 $19 /* saved (callee-save) 3 */ -#define s4 $20 /* saved (callee-save) 4 */ -#define s5 $21 /* saved (callee-save) 5 */ -#define s6 $22 /* saved (callee-save) 6 */ -#define s7 $23 /* saved (callee-save) 7 */ -#define t8 $24 /* temporary (caller-save) 8 */ -#define t9 $25 /* temporary (caller-save) 9 */ -#define k0 $26 /* kernel temporary 0 */ -#define k1 $27 /* kernel temporary 1 */ -#define gp $28 /* global pointer */ -#define sp $29 /* stack pointer */ -#define s8 $30 /* saved (callee-save) 8 = frame pointer */ -#define ra $31 /* return address */ - +#define z0 $0 /* always zero register */ +#define AT $1 /* assembler temp register */ +#define v0 $2 /* value 0 */ +#define v1 $3 /* value 1 */ +#define a0 $4 /* argument 0 */ +#define a1 $5 /* argument 1 */ +#define a2 $6 /* argument 2 */ +#define a3 $7 /* argument 3 */ +#define t0 $8 /* temporary (caller-save) 0 */ +#define t1 $9 /* temporary (caller-save) 1 */ +#define t2 $10 /* temporary (caller-save) 2 */ +#define t3 $11 /* temporary (caller-save) 3 */ +#define t4 $12 /* temporary (caller-save) 4 */ +#define t5 $13 /* temporary (caller-save) 5 */ +#define t6 $14 /* temporary (caller-save) 6 */ +#define t7 $15 /* temporary (caller-save) 7 */ +#define s0 $16 /* saved (callee-save) 0 */ +#define s1 $17 /* saved (callee-save) 1 */ +#define s2 $18 /* saved (callee-save) 2 */ +#define s3 $19 /* saved (callee-save) 3 */ +#define s4 $20 /* saved (callee-save) 4 */ +#define s5 $21 /* saved (callee-save) 5 */ +#define s6 $22 /* saved (callee-save) 6 */ +#define s7 $23 /* saved (callee-save) 7 */ +#define t8 $24 /* temporary (caller-save) 8 */ +#define t9 $25 /* temporary (caller-save) 9 */ +#define k0 $26 /* kernel temporary 0 */ +#define k1 $27 /* kernel temporary 1 */ +#define gp $28 /* global pointer */ +#define sp $29 /* stack pointer */ +#define s8 $30 /* saved (callee-save) 8 = frame pointer */ +#define ra $31 /* return address */ #endif /* _KERN_MIPS_REGDEFS_H_ */ diff --git a/kern/arch/mips/include/kern/setjmp.h b/kern/arch/mips/include/kern/setjmp.h index 13596a1..8a25ec6 100644 --- a/kern/arch/mips/include/kern/setjmp.h +++ b/kern/arch/mips/include/kern/setjmp.h @@ -38,10 +38,9 @@ * Must save: s0-s8, sp, ra (11 registers) * Don't change __JB_REGS without adjusting mips_setjmp.S accordingly. */ -#define __JB_REGS 11 +#define __JB_REGS 11 /* A jmp_buf is an array of __JB_REGS registers */ typedef uint32_t jmp_buf[__JB_REGS]; - #endif /* _MIPS_SETJMP_H_ */ diff --git a/kern/arch/mips/include/kern/signal.h b/kern/arch/mips/include/kern/signal.h index fbc713d..1eb97b9 100644 --- a/kern/arch/mips/include/kern/signal.h +++ b/kern/arch/mips/include/kern/signal.h @@ -27,7 +27,6 @@ * SUCH DAMAGE. */ - #ifndef _KERN_MIPS_SIGNAL_H_ #define _KERN_MIPS_SIGNAL_H_ @@ -39,7 +38,7 @@ * probably won't.) */ struct sigcontext { - /* Dummy. */ + /* Dummy. */ }; #endif /* _KERN_MIPS_SIGNAL_H_ */ diff --git a/kern/arch/mips/include/kern/types.h b/kern/arch/mips/include/kern/types.h index fd93ba4..4f520a7 100644 --- a/kern/arch/mips/include/kern/types.h +++ b/kern/arch/mips/include/kern/types.h @@ -38,21 +38,20 @@ * See kern/types.h for an explanation of the underscores. */ - /* Sized integer types, with convenient short names */ -typedef char __i8; /* 8-bit signed integer */ -typedef short __i16; /* 16-bit signed integer */ -typedef int __i32; /* 32-bit signed integer */ -typedef long long __i64; /* 64-bit signed integer */ +typedef char __i8; /* 8-bit signed integer */ +typedef short __i16; /* 16-bit signed integer */ +typedef int __i32; /* 32-bit signed integer */ +typedef long long __i64; /* 64-bit signed integer */ -typedef unsigned char __u8; /* 8-bit unsigned integer */ -typedef unsigned short __u16; /* 16-bit unsigned integer */ -typedef unsigned int __u32; /* 32-bit unsigned integer */ -typedef unsigned long long __u64; /* 64-bit unsigned integer */ +typedef unsigned char __u8; /* 8-bit unsigned integer */ +typedef unsigned short __u16; /* 16-bit unsigned integer */ +typedef unsigned int __u32; /* 32-bit unsigned integer */ +typedef unsigned long long __u64; /* 64-bit unsigned integer */ /* Further standard C types */ -typedef long __intptr_t; /* Signed pointer-sized integer */ -typedef unsigned long __uintptr_t; /* Unsigned pointer-sized integer */ +typedef long __intptr_t; /* Signed pointer-sized integer */ +typedef unsigned long __uintptr_t; /* Unsigned pointer-sized integer */ /* * Since we're a 32-bit platform, size_t, ssize_t, and ptrdiff_t can @@ -62,17 +61,16 @@ typedef unsigned long __uintptr_t; /* Unsigned pointer-sized integer */ * errors involving size_t, try changing this. */ #if 1 -typedef unsigned __size_t; /* Size of a memory region */ -typedef int __ssize_t; /* Signed type of same size */ -typedef int __ptrdiff_t; /* Difference of two pointers */ +typedef unsigned __size_t; /* Size of a memory region */ +typedef int __ssize_t; /* Signed type of same size */ +typedef int __ptrdiff_t; /* Difference of two pointers */ #else -typedef unsigned long __size_t; /* Size of a memory region */ -typedef long __ssize_t; /* Signed type of same size */ -typedef long __ptrdiff_t; /* Difference of two pointers */ +typedef unsigned long __size_t; /* Size of a memory region */ +typedef long __ssize_t; /* Signed type of same size */ +typedef long __ptrdiff_t; /* Difference of two pointers */ #endif /* Number of bits per byte. */ -#define __CHAR_BIT 8 - +#define __CHAR_BIT 8 #endif /* _KERN_MIPS_TYPES_H_ */ diff --git a/kern/arch/mips/include/membar.h b/kern/arch/mips/include/membar.h index 95b05fe..a54e60f 100644 --- a/kern/arch/mips/include/membar.h +++ b/kern/arch/mips/include/membar.h @@ -41,17 +41,14 @@ */ MEMBAR_INLINE -void -membar_any_any(void) -{ - __asm volatile( - ".set push;" /* save assembler mode */ - ".set mips32;" /* allow MIPS32 instructions */ - "sync;" /* do it */ - ".set pop" /* restore assembler mode */ - : /* no outputs */ - : /* no inputs */ - : "memory"); /* "changes" memory */ +void membar_any_any(void) { + __asm volatile(".set push;" /* save assembler mode */ + ".set mips32;" /* allow MIPS32 instructions */ + "sync;" /* do it */ + ".set pop" /* restore assembler mode */ + : /* no outputs */ + : /* no inputs */ + : "memory"); /* "changes" memory */ } MEMBAR_INLINE void membar_load_load(void) { membar_any_any(); } @@ -59,5 +56,4 @@ MEMBAR_INLINE void membar_store_store(void) { membar_any_any(); } MEMBAR_INLINE void membar_store_any(void) { membar_any_any(); } MEMBAR_INLINE void membar_any_store(void) { membar_any_any(); } - #endif /* _MIPS_MEMBAR_H_ */ diff --git a/kern/arch/mips/include/specialreg.h b/kern/arch/mips/include/specialreg.h index 84b6e88..fedb97e 100644 --- a/kern/arch/mips/include/specialreg.h +++ b/kern/arch/mips/include/specialreg.h @@ -30,62 +30,61 @@ #ifndef _MIPS_SPECIALREG_H_ #define _MIPS_SPECIALREG_H_ - /* * Coprocessor 0 (system processor) register numbers */ -#define c0_index $0 /* TLB entry index register */ -#define c0_random $1 /* TLB random slot register */ -#define c0_entrylo $2 /* TLB entry contents (low-order half) */ -/* c0_entrylo0 $2 */ /* MIPS-II and up only */ -/* c0_entrylo1 $3 */ /* MIPS-II and up only */ -#define c0_context $4 /* some precomputed pagetable stuff */ -/* c0_pagemask $5 */ /* MIPS-II and up only */ -/* c0_wired $6 */ /* MIPS-II and up only */ -#define c0_vaddr $8 /* virtual addr of failing memory access */ -#define c0_count $9 /* cycle counter (MIPS-II and up) */ -#define c0_entryhi $10 /* TLB entry contents (high-order half) */ -#define c0_compare $11 /* on-chip timer control (MIPS-II and up) */ -#define c0_status $12 /* processor status register */ -#define c0_cause $13 /* exception cause register */ -#define c0_epc $14 /* exception PC register */ -#define c0_prid $15 /* processor ID register */ -/* c0_config $16 */ /* MIPS-II and up only */ -/* c0_lladdr $17 */ /* MIPS-II and up only */ -/* c0_watchlo $18 */ /* MIPS-II and up only */ -/* c0_watchhi $19 */ /* MIPS-II and up only */ +#define c0_index $0 /* TLB entry index register */ +#define c0_random $1 /* TLB random slot register */ +#define c0_entrylo $2 /* TLB entry contents (low-order half) */ +/* c0_entrylo0 $2 */ /* MIPS-II and up only */ +/* c0_entrylo1 $3 */ /* MIPS-II and up only */ +#define c0_context $4 /* some precomputed pagetable stuff */ +/* c0_pagemask $5 */ /* MIPS-II and up only */ +/* c0_wired $6 */ /* MIPS-II and up only */ +#define c0_vaddr $8 /* virtual addr of failing memory access */ +#define c0_count $9 /* cycle counter (MIPS-II and up) */ +#define c0_entryhi $10 /* TLB entry contents (high-order half) */ +#define c0_compare $11 /* on-chip timer control (MIPS-II and up) */ +#define c0_status $12 /* processor status register */ +#define c0_cause $13 /* exception cause register */ +#define c0_epc $14 /* exception PC register */ +#define c0_prid $15 /* processor ID register */ +/* c0_config $16 */ /* MIPS-II and up only */ +/* c0_lladdr $17 */ /* MIPS-II and up only */ +/* c0_watchlo $18 */ /* MIPS-II and up only */ +/* c0_watchhi $19 */ /* MIPS-II and up only */ /* * Mode bits in c0_status */ -#define CST_IEc 0x00000001 /* current: interrupt enable */ -#define CST_KUc 0x00000002 /* current: user mode */ -#define CST_IEp 0x00000004 /* previous: interrupt enable */ -#define CST_KUp 0x00000008 /* previous: user mode */ -#define CST_IEo 0x00000010 /* old: interrupt enable */ -#define CST_KUo 0x00000020 /* old: user mode */ +#define CST_IEc 0x00000001 /* current: interrupt enable */ +#define CST_KUc 0x00000002 /* current: user mode */ +#define CST_IEp 0x00000004 /* previous: interrupt enable */ +#define CST_KUp 0x00000008 /* previous: user mode */ +#define CST_IEo 0x00000010 /* old: interrupt enable */ +#define CST_KUo 0x00000020 /* old: user mode */ #define CST_MODEMASK 0x0000003f /* mask for the above */ -#define CST_IRQMASK 0x0000ff00 /* mask for the individual irq enable bits */ -#define CST_BEV 0x00400000 /* bootstrap exception vectors flag */ +#define CST_IRQMASK 0x0000ff00 /* mask for the individual irq enable bits */ +#define CST_BEV 0x00400000 /* bootstrap exception vectors flag */ /* * Fields of the c0_cause register */ -#define CCA_UTLB 0x00000001 /* true if UTLB exception (set by our asm) */ -#define CCA_CODE 0x0000003c /* EX_foo in trapframe.h */ -#define CCA_IRQS 0x0000ff00 /* Currently pending interrupts */ -#define CCA_COPN 0x30000000 /* Coprocessor number for EX_CPU */ -#define CCA_JD 0x80000000 /* True if exception happened in jump delay */ +#define CCA_UTLB 0x00000001 /* true if UTLB exception (set by our asm) */ +#define CCA_CODE 0x0000003c /* EX_foo in trapframe.h */ +#define CCA_IRQS 0x0000ff00 /* Currently pending interrupts */ +#define CCA_COPN 0x30000000 /* Coprocessor number for EX_CPU */ +#define CCA_JD 0x80000000 /* True if exception happened in jump delay */ -#define CCA_CODESHIFT 2 /* shift for CCA_CODE field */ +#define CCA_CODESHIFT 2 /* shift for CCA_CODE field */ /* * Fields of the c0_index register */ -#define CIN_P 0x80000000 /* nonzero -> TLB probe found nothing */ -#define CIN_INDEX 0x00003f00 /* 6-bit index into TLB */ +#define CIN_P 0x80000000 /* nonzero -> TLB probe found nothing */ +#define CIN_INDEX 0x00003f00 /* 6-bit index into TLB */ -#define CIN_INDEXSHIFT 8 /* shift for CIN_INDEX field */ +#define CIN_INDEXSHIFT 8 /* shift for CIN_INDEX field */ /* * Fields of the c0_context register @@ -102,16 +101,15 @@ * there's no other good place in the chip to put it. See discussions * elsewhere. */ -#define CTX_VSHIFT 0x001ffffc /* shifted/masked copy of c0_vaddr */ -#define CTX_PTBASE 0xffe00000 /* page table base address */ +#define CTX_VSHIFT 0x001ffffc /* shifted/masked copy of c0_vaddr */ +#define CTX_PTBASE 0xffe00000 /* page table base address */ -#define CTX_PTBASESHIFT 21 /* shift for CTX_PBASE field */ +#define CTX_PTBASESHIFT 21 /* shift for CTX_PBASE field */ /* * Hardwired exception handler addresses. */ -#define EXADDR_UTLB 0x80000000 -#define EXADDR_GENERAL 0x80000080 - +#define EXADDR_UTLB 0x80000000 +#define EXADDR_GENERAL 0x80000080 #endif /* _MIPS_SPECIALREG_H_ */ diff --git a/kern/arch/mips/include/spinlock.h b/kern/arch/mips/include/spinlock.h index 7c3ea1a..78e8ff8 100644 --- a/kern/arch/mips/include/spinlock.h +++ b/kern/arch/mips/include/spinlock.h @@ -32,12 +32,11 @@ #include - /* Type of value needed to actually spin on */ typedef unsigned spinlock_data_t; /* Initializer for use by SPINLOCK_INITIALIZER */ -#define SPINLOCK_DATA_INITIALIZER 0 +#define SPINLOCK_DATA_INITIALIZER 0 /* Atomic operations on spinlock_data_t */ SPINLOCK_INLINE @@ -55,10 +54,8 @@ spinlock_data_t spinlock_data_testandset(volatile spinlock_data_t *sd); * memory. */ SPINLOCK_INLINE -void -spinlock_data_set(volatile spinlock_data_t *sd, unsigned val) -{ - *sd = val; +void spinlock_data_set(volatile spinlock_data_t *sd, unsigned val) { + *sd = val; } /* @@ -66,11 +63,7 @@ spinlock_data_set(volatile spinlock_data_t *sd, unsigned val) * instruction, and instructions are atomic with respect to memory. */ SPINLOCK_INLINE -spinlock_data_t -spinlock_data_get(volatile spinlock_data_t *sd) -{ - return *sd; -} +spinlock_data_t spinlock_data_get(volatile spinlock_data_t *sd) { return *sd; } /* * Test-and-set a spinlock_data_t. Use the LL/SC instructions to @@ -86,37 +79,34 @@ spinlock_data_get(volatile spinlock_data_t *sd) * to atomically update one machine word. */ SPINLOCK_INLINE -spinlock_data_t -spinlock_data_testandset(volatile spinlock_data_t *sd) -{ - spinlock_data_t x; - spinlock_data_t y; +spinlock_data_t spinlock_data_testandset(volatile spinlock_data_t *sd) { + spinlock_data_t x; + spinlock_data_t y; - /* - * Test-and-set using LL/SC. - * - * Load the existing value into X, and use Y to store 1. - * After the SC, Y contains 1 if the store succeeded, - * 0 if it failed. - * - * On failure, return 1 to pretend that the spinlock - * was already held. - */ + /* + * Test-and-set using LL/SC. + * + * Load the existing value into X, and use Y to store 1. + * After the SC, Y contains 1 if the store succeeded, + * 0 if it failed. + * + * On failure, return 1 to pretend that the spinlock + * was already held. + */ - y = 1; - __asm volatile( - ".set push;" /* save assembler mode */ - ".set mips32;" /* allow MIPS32 instructions */ - ".set volatile;" /* avoid unwanted optimization */ - "ll %0, 0(%2);" /* x = *sd */ - "sc %1, 0(%2);" /* *sd = y; y = success? */ - ".set pop" /* restore assembler mode */ - : "=&r" (x), "+r" (y) : "r" (sd)); - if (y == 0) { - return 1; - } - return x; + y = 1; + __asm volatile(".set push;" /* save assembler mode */ + ".set mips32;" /* allow MIPS32 instructions */ + ".set volatile;" /* avoid unwanted optimization */ + "ll %0, 0(%2);" /* x = *sd */ + "sc %1, 0(%2);" /* *sd = y; y = success? */ + ".set pop" /* restore assembler mode */ + : "=&r"(x), "+r"(y) + : "r"(sd)); + if (y == 0) { + return 1; + } + return x; } - #endif /* _MIPS_SPINLOCK_H_ */ diff --git a/kern/arch/mips/include/thread.h b/kern/arch/mips/include/thread.h index 822781e..afdd3ea 100644 --- a/kern/arch/mips/include/thread.h +++ b/kern/arch/mips/include/thread.h @@ -30,7 +30,6 @@ #ifndef _MIPS_THREAD_H_ #define _MIPS_THREAD_H_ - /* * Machine-dependent thread bits. */ @@ -40,9 +39,8 @@ typedef void (*badfaultfunc_t)(void); struct thread_machdep { - badfaultfunc_t tm_badfaultfunc; /* fault hook used by copyin/out */ - jmp_buf tm_copyjmp; /* longjmp area used by copyin/out */ + badfaultfunc_t tm_badfaultfunc; /* fault hook used by copyin/out */ + jmp_buf tm_copyjmp; /* longjmp area used by copyin/out */ }; - #endif /* _MIPS_THREAD_H_ */ diff --git a/kern/arch/mips/include/tlb.h b/kern/arch/mips/include/tlb.h index 31d1890..c707d03 100644 --- a/kern/arch/mips/include/tlb.h +++ b/kern/arch/mips/include/tlb.h @@ -77,14 +77,14 @@ int tlb_probe(uint32_t entryhi, uint32_t entrylo); */ /* Fields in the high-order word */ -#define TLBHI_VPAGE 0xfffff000 +#define TLBHI_VPAGE 0xfffff000 /* TLBHI_PID 0x00000fc0 */ /* Fields in the low-order word */ -#define TLBLO_PPAGE 0xfffff000 +#define TLBLO_PPAGE 0xfffff000 #define TLBLO_NOCACHE 0x00000800 -#define TLBLO_DIRTY 0x00000400 -#define TLBLO_VALID 0x00000200 +#define TLBLO_DIRTY 0x00000400 +#define TLBLO_VALID 0x00000200 /* TLBLO_GLOBAL 0x00000100 */ /* @@ -92,14 +92,13 @@ int tlb_probe(uint32_t entryhi, uint32_t entrylo); * be passed to TLBHI_INVALID; this prevents loading the same invalid * entry into multiple TLB slots. */ -#define TLBHI_INVALID(entryno) ((0x80000+(entryno))<<12) -#define TLBLO_INVALID() (0) +#define TLBHI_INVALID(entryno) ((0x80000 + (entryno)) << 12) +#define TLBLO_INVALID() (0) /* * Number of TLB entries in the processor. */ -#define NUM_TLB 64 - +#define NUM_TLB 64 #endif /* _MIPS_TLB_H_ */ diff --git a/kern/arch/mips/include/trapframe.h b/kern/arch/mips/include/trapframe.h index 931ed89..cc28d52 100644 --- a/kern/arch/mips/include/trapframe.h +++ b/kern/arch/mips/include/trapframe.h @@ -38,59 +38,59 @@ */ struct trapframe { - uint32_t tf_vaddr; /* coprocessor 0 vaddr register */ - uint32_t tf_status; /* coprocessor 0 status register */ - uint32_t tf_cause; /* coprocessor 0 cause register */ - uint32_t tf_lo; - uint32_t tf_hi; - uint32_t tf_ra; /* Saved register 31 */ - uint32_t tf_at; /* Saved register 1 (AT) */ - uint32_t tf_v0; /* Saved register 2 (v0) */ - uint32_t tf_v1; /* etc. */ - uint32_t tf_a0; - uint32_t tf_a1; - uint32_t tf_a2; - uint32_t tf_a3; - uint32_t tf_t0; - uint32_t tf_t1; - uint32_t tf_t2; - uint32_t tf_t3; - uint32_t tf_t4; - uint32_t tf_t5; - uint32_t tf_t6; - uint32_t tf_t7; - uint32_t tf_s0; - uint32_t tf_s1; - uint32_t tf_s2; - uint32_t tf_s3; - uint32_t tf_s4; - uint32_t tf_s5; - uint32_t tf_s6; - uint32_t tf_s7; - uint32_t tf_t8; - uint32_t tf_t9; - uint32_t tf_gp; - uint32_t tf_sp; - uint32_t tf_s8; - uint32_t tf_epc; /* coprocessor 0 epc register */ + uint32_t tf_vaddr; /* coprocessor 0 vaddr register */ + uint32_t tf_status; /* coprocessor 0 status register */ + uint32_t tf_cause; /* coprocessor 0 cause register */ + uint32_t tf_lo; + uint32_t tf_hi; + uint32_t tf_ra; /* Saved register 31 */ + uint32_t tf_at; /* Saved register 1 (AT) */ + uint32_t tf_v0; /* Saved register 2 (v0) */ + uint32_t tf_v1; /* etc. */ + uint32_t tf_a0; + uint32_t tf_a1; + uint32_t tf_a2; + uint32_t tf_a3; + uint32_t tf_t0; + uint32_t tf_t1; + uint32_t tf_t2; + uint32_t tf_t3; + uint32_t tf_t4; + uint32_t tf_t5; + uint32_t tf_t6; + uint32_t tf_t7; + uint32_t tf_s0; + uint32_t tf_s1; + uint32_t tf_s2; + uint32_t tf_s3; + uint32_t tf_s4; + uint32_t tf_s5; + uint32_t tf_s6; + uint32_t tf_s7; + uint32_t tf_t8; + uint32_t tf_t9; + uint32_t tf_gp; + uint32_t tf_sp; + uint32_t tf_s8; + uint32_t tf_epc; /* coprocessor 0 epc register */ }; /* * MIPS exception codes. */ -#define EX_IRQ 0 /* Interrupt */ -#define EX_MOD 1 /* TLB Modify (write to read-only page) */ -#define EX_TLBL 2 /* TLB miss on load */ -#define EX_TLBS 3 /* TLB miss on store */ -#define EX_ADEL 4 /* Address error on load */ -#define EX_ADES 5 /* Address error on store */ -#define EX_IBE 6 /* Bus error on instruction fetch */ -#define EX_DBE 7 /* Bus error on data load *or* store */ -#define EX_SYS 8 /* Syscall */ -#define EX_BP 9 /* Breakpoint */ -#define EX_RI 10 /* Reserved (illegal) instruction */ -#define EX_CPU 11 /* Coprocessor unusable */ -#define EX_OVF 12 /* Arithmetic overflow */ +#define EX_IRQ 0 /* Interrupt */ +#define EX_MOD 1 /* TLB Modify (write to read-only page) */ +#define EX_TLBL 2 /* TLB miss on load */ +#define EX_TLBS 3 /* TLB miss on store */ +#define EX_ADEL 4 /* Address error on load */ +#define EX_ADES 5 /* Address error on store */ +#define EX_IBE 6 /* Bus error on instruction fetch */ +#define EX_DBE 7 /* Bus error on data load *or* store */ +#define EX_SYS 8 /* Syscall */ +#define EX_BP 9 /* Breakpoint */ +#define EX_RI 10 /* Reserved (illegal) instruction */ +#define EX_CPU 11 /* Coprocessor unusable */ +#define EX_OVF 12 /* Arithmetic overflow */ /* * Function to enter user mode. Does not return. The trapframe must @@ -104,5 +104,4 @@ __DEAD void mips_usermode(struct trapframe *tf); extern vaddr_t cpustacks[]; extern vaddr_t cputhreads[]; - #endif /* _MIPS_TRAPFRAME_H_ */ diff --git a/kern/arch/mips/include/vm.h b/kern/arch/mips/include/vm.h index 92fb454..127adbd 100644 --- a/kern/arch/mips/include/vm.h +++ b/kern/arch/mips/include/vm.h @@ -30,13 +30,12 @@ #ifndef _MIPS_VM_H_ #define _MIPS_VM_H_ - /* * Machine-dependent VM system definitions. */ -#define PAGE_SIZE 4096 /* size of VM page */ -#define PAGE_FRAME 0xfffff000 /* mask for getting page number from addr */ +#define PAGE_SIZE 4096 /* size of VM page */ +#define PAGE_FRAME 0xfffff000 /* mask for getting page number from addr */ /* * MIPS-I hardwired memory layout: @@ -48,10 +47,10 @@ * (mips32 is a little different) */ -#define MIPS_KUSEG 0x00000000 -#define MIPS_KSEG0 0x80000000 -#define MIPS_KSEG1 0xa0000000 -#define MIPS_KSEG2 0xc0000000 +#define MIPS_KUSEG 0x00000000 +#define MIPS_KSEG0 0x80000000 +#define MIPS_KSEG1 0xa0000000 +#define MIPS_KSEG2 0xc0000000 /* * The first 512 megs of physical space can be addressed in both kseg0 and @@ -65,13 +64,13 @@ * exception handler code) when converted to a vaddr it's *not* NULL, *is* * a valid address, and will make a *huge* mess if you scribble on it. */ -#define PADDR_TO_KVADDR(paddr) ((paddr)+MIPS_KSEG0) +#define PADDR_TO_KVADDR(paddr) ((paddr) + MIPS_KSEG0) /* * The top of user space. (Actually, the address immediately above the * last valid user address.) */ -#define USERSPACETOP MIPS_KSEG0 +#define USERSPACETOP MIPS_KSEG0 /* * The starting value for the stack pointer at user level. Because @@ -81,7 +80,7 @@ * We put the stack at the very top of user virtual memory because it * grows downwards. */ -#define USERSTACK USERSPACETOP +#define USERSTACK USERSPACETOP /* * Interface to the low-level module that looks after the amount of @@ -117,13 +116,12 @@ paddr_t ram_getfirstfree(void); */ struct tlbshootdown { - /* - * Change this to what you need for your VM design. - */ - int ts_placeholder; + /* + * Change this to what you need for your VM design. + */ + int ts_placeholder; }; #define TLBSHOOTDOWN_MAX 16 - #endif /* _MIPS_VM_H_ */ diff --git a/kern/arch/mips/locore/trap.c b/kern/arch/mips/locore/trap.c index 69ae12c..7af258e 100644 --- a/kern/arch/mips/locore/trap.c +++ b/kern/arch/mips/locore/trap.c @@ -40,81 +40,68 @@ #include #include - /* in exception-*.S */ extern __DEAD void asm_usermode(struct trapframe *tf); /* called only from assembler, so not declared in a header */ void mips_trap(struct trapframe *tf); - /* Names for trap codes */ #define NTRAPCODES 13 static const char *const trapcodenames[NTRAPCODES] = { - "Interrupt", - "TLB modify trap", - "TLB miss on load", - "TLB miss on store", - "Address error on load", - "Address error on store", - "Bus error on code", - "Bus error on data", - "System call", - "Break instruction", - "Illegal instruction", - "Coprocessor unusable", - "Arithmetic overflow", + "Interrupt", "TLB modify trap", "TLB miss on load", + "TLB miss on store", "Address error on load", "Address error on store", + "Bus error on code", "Bus error on data", "System call", + "Break instruction", "Illegal instruction", "Coprocessor unusable", + "Arithmetic overflow", }; /* * Function called when user-level code hits a fatal fault. */ -static -void -kill_curthread(vaddr_t epc, unsigned code, vaddr_t vaddr) -{ - int sig = 0; +static void kill_curthread(vaddr_t epc, unsigned code, vaddr_t vaddr) { + int sig = 0; - KASSERT(code < NTRAPCODES); - switch (code) { - case EX_IRQ: - case EX_IBE: - case EX_DBE: - case EX_SYS: - /* should not be seen */ - KASSERT(0); - sig = SIGABRT; - break; - case EX_MOD: - case EX_TLBL: - case EX_TLBS: - sig = SIGSEGV; - break; - case EX_ADEL: - case EX_ADES: - sig = SIGBUS; - break; - case EX_BP: - sig = SIGTRAP; - break; - case EX_RI: - sig = SIGILL; - break; - case EX_CPU: - sig = SIGSEGV; - break; - case EX_OVF: - sig = SIGFPE; - break; - } + KASSERT(code < NTRAPCODES); + switch (code) { + case EX_IRQ: + case EX_IBE: + case EX_DBE: + case EX_SYS: + /* should not be seen */ + KASSERT(0); + sig = SIGABRT; + break; + case EX_MOD: + case EX_TLBL: + case EX_TLBS: + sig = SIGSEGV; + break; + case EX_ADEL: + case EX_ADES: + sig = SIGBUS; + break; + case EX_BP: + sig = SIGTRAP; + break; + case EX_RI: + sig = SIGILL; + break; + case EX_CPU: + sig = SIGSEGV; + break; + case EX_OVF: + sig = SIGFPE; + break; + } - /* - * You will probably want to change this. - */ + /* + * You will probably want to change this. + */ - kprintf("Fatal user mode trap %u sig %d (%s, epc 0x%x, vaddr 0x%x)\n", - code, sig, trapcodenames[code], epc, vaddr); - panic("I don't know how to handle this\n"); + kprintf("Fatal user mode trap %u sig %d (%s, epc 0x%x, vaddr 0x%x)\n", code, + sig, trapcodenames[code], epc, vaddr); + panic("I don't know how to handle this\n"); } /* @@ -122,229 +109,223 @@ kill_curthread(vaddr_t epc, unsigned code, vaddr_t vaddr) * This is called by the assembly-language exception handler once * the trapframe has been set up. */ -void -mips_trap(struct trapframe *tf) -{ - uint32_t code; - /*bool isutlb; -- not used */ - bool iskern; - int spl; +void mips_trap(struct trapframe *tf) { + uint32_t code; + /*bool isutlb; -- not used */ + bool iskern; + int spl; - /* The trap frame is supposed to be 35 registers long. */ - KASSERT(sizeof(struct trapframe)==(35*4)); + /* The trap frame is supposed to be 35 registers long. */ + KASSERT(sizeof(struct trapframe) == (35 * 4)); - /* - * Extract the exception code info from the register fields. - */ - code = (tf->tf_cause & CCA_CODE) >> CCA_CODESHIFT; - /*isutlb = (tf->tf_cause & CCA_UTLB) != 0;*/ - iskern = (tf->tf_status & CST_KUp) == 0; + /* + * Extract the exception code info from the register fields. + */ + code = (tf->tf_cause & CCA_CODE) >> CCA_CODESHIFT; + /*isutlb = (tf->tf_cause & CCA_UTLB) != 0;*/ + iskern = (tf->tf_status & CST_KUp) == 0; - KASSERT(code < NTRAPCODES); + KASSERT(code < NTRAPCODES); - /* Make sure we haven't run off our stack */ - if (curthread != NULL && curthread->t_stack != NULL) { - KASSERT((vaddr_t)tf > (vaddr_t)curthread->t_stack); - KASSERT((vaddr_t)tf < (vaddr_t)(curthread->t_stack - + STACK_SIZE)); - } + /* Make sure we haven't run off our stack */ + if (curthread != NULL && curthread->t_stack != NULL) { + KASSERT((vaddr_t)tf > (vaddr_t)curthread->t_stack); + KASSERT((vaddr_t)tf < (vaddr_t)(curthread->t_stack + STACK_SIZE)); + } - /* Interrupt? Call the interrupt handler and return. */ - if (code == EX_IRQ) { - int old_in; - bool doadjust; + /* Interrupt? Call the interrupt handler and return. */ + if (code == EX_IRQ) { + int old_in; + bool doadjust; - old_in = curthread->t_in_interrupt; - curthread->t_in_interrupt = 1; + old_in = curthread->t_in_interrupt; + curthread->t_in_interrupt = 1; - /* - * The processor has turned interrupts off; if the - * currently recorded interrupt state is interrupts on - * (spl of 0), adjust the recorded state to match, and - * restore after processing the interrupt. - * - * How can we get an interrupt if the recorded state - * is interrupts off? Well, as things currently stand - * when the CPU finishes idling it flips interrupts on - * and off to allow things to happen, but leaves - * curspl high while doing so. - * - * While we're here, assert that the interrupt - * handling code hasn't leaked a spinlock or an - * splhigh(). - */ + /* + * The processor has turned interrupts off; if the + * currently recorded interrupt state is interrupts on + * (spl of 0), adjust the recorded state to match, and + * restore after processing the interrupt. + * + * How can we get an interrupt if the recorded state + * is interrupts off? Well, as things currently stand + * when the CPU finishes idling it flips interrupts on + * and off to allow things to happen, but leaves + * curspl high while doing so. + * + * While we're here, assert that the interrupt + * handling code hasn't leaked a spinlock or an + * splhigh(). + */ - if (curthread->t_curspl == 0) { - KASSERT(curthread->t_curspl == 0); - KASSERT(curthread->t_iplhigh_count == 0); - curthread->t_curspl = IPL_HIGH; - curthread->t_iplhigh_count++; - doadjust = true; - } - else { - doadjust = false; - } + if (curthread->t_curspl == 0) { + KASSERT(curthread->t_curspl == 0); + KASSERT(curthread->t_iplhigh_count == 0); + curthread->t_curspl = IPL_HIGH; + curthread->t_iplhigh_count++; + doadjust = true; + } else { + doadjust = false; + } - mainbus_interrupt(tf); + mainbus_interrupt(tf); - if (doadjust) { - KASSERT(curthread->t_curspl == IPL_HIGH); - KASSERT(curthread->t_iplhigh_count == 1); - curthread->t_iplhigh_count--; - curthread->t_curspl = 0; - } + if (doadjust) { + KASSERT(curthread->t_curspl == IPL_HIGH); + KASSERT(curthread->t_iplhigh_count == 1); + curthread->t_iplhigh_count--; + curthread->t_curspl = 0; + } - curthread->t_in_interrupt = old_in; - goto done2; - } + curthread->t_in_interrupt = old_in; + goto done2; + } - /* - * The processor turned interrupts off when it took the trap. - * - * While we're in the kernel, and not actually handling an - * interrupt, restore the interrupt state to where it was in - * the previous context, which may be low (interrupts on). - * - * Do this by forcing splhigh(), which may do a redundant - * cpu_irqoff() but forces the stored MI interrupt state into - * sync, then restoring the previous state. - */ - spl = splhigh(); - splx(spl); + /* + * The processor turned interrupts off when it took the trap. + * + * While we're in the kernel, and not actually handling an + * interrupt, restore the interrupt state to where it was in + * the previous context, which may be low (interrupts on). + * + * Do this by forcing splhigh(), which may do a redundant + * cpu_irqoff() but forces the stored MI interrupt state into + * sync, then restoring the previous state. + */ + spl = splhigh(); + splx(spl); - /* Syscall? Call the syscall handler and return. */ - if (code == EX_SYS) { - /* Interrupts should have been on while in user mode. */ - KASSERT(curthread->t_curspl == 0); - KASSERT(curthread->t_iplhigh_count == 0); + /* Syscall? Call the syscall handler and return. */ + if (code == EX_SYS) { + /* Interrupts should have been on while in user mode. */ + KASSERT(curthread->t_curspl == 0); + KASSERT(curthread->t_iplhigh_count == 0); - DEBUG(DB_SYSCALL, "syscall: #%d, args %x %x %x %x\n", - tf->tf_v0, tf->tf_a0, tf->tf_a1, tf->tf_a2, tf->tf_a3); + DEBUG(DB_SYSCALL, "syscall: #%d, args %x %x %x %x\n", tf->tf_v0, tf->tf_a0, + tf->tf_a1, tf->tf_a2, tf->tf_a3); - syscall(tf); - goto done; - } + syscall(tf); + goto done; + } - /* - * Ok, it wasn't any of the really easy cases. - * Call vm_fault on the TLB exceptions. - * Panic on the bus error exceptions. - */ - switch (code) { - case EX_MOD: - if (vm_fault(VM_FAULT_READONLY, tf->tf_vaddr)==0) { - goto done; - } - break; - case EX_TLBL: - if (vm_fault(VM_FAULT_READ, tf->tf_vaddr)==0) { - goto done; - } - break; - case EX_TLBS: - if (vm_fault(VM_FAULT_WRITE, tf->tf_vaddr)==0) { - goto done; - } - break; - case EX_IBE: - case EX_DBE: - /* - * This means you loaded invalid TLB entries, or - * touched invalid parts of the direct-mapped - * segments. These are serious kernel errors, so - * panic. - * - * The MIPS won't even tell you what invalid address - * caused the bus error. - */ - panic("Bus error exception, PC=0x%x\n", tf->tf_epc); - break; - } + /* + * Ok, it wasn't any of the really easy cases. + * Call vm_fault on the TLB exceptions. + * Panic on the bus error exceptions. + */ + switch (code) { + case EX_MOD: + if (vm_fault(VM_FAULT_READONLY, tf->tf_vaddr) == 0) { + goto done; + } + break; + case EX_TLBL: + if (vm_fault(VM_FAULT_READ, tf->tf_vaddr) == 0) { + goto done; + } + break; + case EX_TLBS: + if (vm_fault(VM_FAULT_WRITE, tf->tf_vaddr) == 0) { + goto done; + } + break; + case EX_IBE: + case EX_DBE: + /* + * This means you loaded invalid TLB entries, or + * touched invalid parts of the direct-mapped + * segments. These are serious kernel errors, so + * panic. + * + * The MIPS won't even tell you what invalid address + * caused the bus error. + */ + panic("Bus error exception, PC=0x%x\n", tf->tf_epc); + break; + } - /* - * If we get to this point, it's a fatal fault - either it's - * one of the other exceptions, like illegal instruction, or - * it was a page fault we couldn't handle. - */ + /* + * If we get to this point, it's a fatal fault - either it's + * one of the other exceptions, like illegal instruction, or + * it was a page fault we couldn't handle. + */ - if (!iskern) { - /* - * Fatal fault in user mode. - * Kill the current user process. - */ - kill_curthread(tf->tf_epc, code, tf->tf_vaddr); - goto done; - } + if (!iskern) { + /* + * Fatal fault in user mode. + * Kill the current user process. + */ + kill_curthread(tf->tf_epc, code, tf->tf_vaddr); + goto done; + } - /* - * Fatal fault in kernel mode. - * - * If pcb_badfaultfunc is set, we do not panic; badfaultfunc is - * set by copyin/copyout and related functions to signify that - * the addresses they're accessing are userlevel-supplied and - * not trustable. What we actually want to do is resume - * execution at the function pointed to by badfaultfunc. That's - * going to be "copyfail" (see copyinout.c), which longjmps - * back to copyin/copyout or wherever and returns EFAULT. - * - * Note that we do not just *call* this function, because that - * won't necessarily do anything. We want the control flow - * that is currently executing in copyin (or whichever), and - * is stopped while we process the exception, to *teleport* to - * copyfail. - * - * This is accomplished by changing tf->tf_epc and returning - * from the exception handler. - */ + /* + * Fatal fault in kernel mode. + * + * If pcb_badfaultfunc is set, we do not panic; badfaultfunc is + * set by copyin/copyout and related functions to signify that + * the addresses they're accessing are userlevel-supplied and + * not trustable. What we actually want to do is resume + * execution at the function pointed to by badfaultfunc. That's + * going to be "copyfail" (see copyinout.c), which longjmps + * back to copyin/copyout or wherever and returns EFAULT. + * + * Note that we do not just *call* this function, because that + * won't necessarily do anything. We want the control flow + * that is currently executing in copyin (or whichever), and + * is stopped while we process the exception, to *teleport* to + * copyfail. + * + * This is accomplished by changing tf->tf_epc and returning + * from the exception handler. + */ - if (curthread != NULL && - curthread->t_machdep.tm_badfaultfunc != NULL) { - tf->tf_epc = (vaddr_t) curthread->t_machdep.tm_badfaultfunc; - goto done; - } + if (curthread != NULL && curthread->t_machdep.tm_badfaultfunc != NULL) { + tf->tf_epc = (vaddr_t)curthread->t_machdep.tm_badfaultfunc; + goto done; + } - /* - * Really fatal kernel-mode fault. - */ + /* + * Really fatal kernel-mode fault. + */ - kprintf("panic: Fatal exception %u (%s) in kernel mode\n", code, - trapcodenames[code]); - kprintf("panic: EPC 0x%x, exception vaddr 0x%x\n", - tf->tf_epc, tf->tf_vaddr); + kprintf("panic: Fatal exception %u (%s) in kernel mode\n", code, + trapcodenames[code]); + kprintf("panic: EPC 0x%x, exception vaddr 0x%x\n", tf->tf_epc, tf->tf_vaddr); - panic("I can't handle this... I think I'll just die now...\n"); + panic("I can't handle this... I think I'll just die now...\n"); - done: - /* - * Turn interrupts off on the processor, without affecting the - * stored interrupt state. - */ - cpu_irqoff(); - done2: +done: + /* + * Turn interrupts off on the processor, without affecting the + * stored interrupt state. + */ + cpu_irqoff(); +done2: - /* - * The boot thread can get here (e.g. on interrupt return) but - * since it doesn't go to userlevel, it can't be returning to - * userlevel, so there's no need to set cputhreads[] and - * cpustacks[]. Just return. - */ - if (curthread->t_stack == NULL) { - return; - } + /* + * The boot thread can get here (e.g. on interrupt return) but + * since it doesn't go to userlevel, it can't be returning to + * userlevel, so there's no need to set cputhreads[] and + * cpustacks[]. Just return. + */ + if (curthread->t_stack == NULL) { + return; + } - cputhreads[curcpu->c_number] = (vaddr_t)curthread; - cpustacks[curcpu->c_number] = (vaddr_t)curthread->t_stack + STACK_SIZE; + cputhreads[curcpu->c_number] = (vaddr_t)curthread; + cpustacks[curcpu->c_number] = (vaddr_t)curthread->t_stack + STACK_SIZE; - /* - * This assertion will fail if either - * (1) curthread->t_stack is corrupted, or - * (2) the trap frame is somehow on the wrong kernel stack. - * - * If cpustacks[] is corrupted, the next trap back to the - * kernel will (most likely) hang the system, so it's better - * to find out now. - */ - KASSERT(SAME_STACK(cpustacks[curcpu->c_number]-1, (vaddr_t)tf)); + /* + * This assertion will fail if either + * (1) curthread->t_stack is corrupted, or + * (2) the trap frame is somehow on the wrong kernel stack. + * + * If cpustacks[] is corrupted, the next trap back to the + * kernel will (most likely) hang the system, so it's better + * to find out now. + */ + KASSERT(SAME_STACK(cpustacks[curcpu->c_number] - 1, (vaddr_t)tf)); } /* @@ -364,43 +345,41 @@ mips_trap(struct trapframe *tf) * - enter_new_process, for use by exec and equivalent. * - enter_forked_process, in syscall.c, for use by fork. */ -void -mips_usermode(struct trapframe *tf) -{ +void mips_usermode(struct trapframe *tf) { - /* - * Interrupts should be off within the kernel while entering - * user mode. However, while in user mode, interrupts should - * be on. To interact properly with the spl-handling logic - * above, we explicitly call spl0() and then call cpu_irqoff(). - */ - spl0(); - cpu_irqoff(); + /* + * Interrupts should be off within the kernel while entering + * user mode. However, while in user mode, interrupts should + * be on. To interact properly with the spl-handling logic + * above, we explicitly call spl0() and then call cpu_irqoff(). + */ + spl0(); + cpu_irqoff(); - cputhreads[curcpu->c_number] = (vaddr_t)curthread; - cpustacks[curcpu->c_number] = (vaddr_t)curthread->t_stack + STACK_SIZE; + cputhreads[curcpu->c_number] = (vaddr_t)curthread; + cpustacks[curcpu->c_number] = (vaddr_t)curthread->t_stack + STACK_SIZE; - /* - * This assertion will fail if either - * (1) cpustacks[] is corrupted, or - * (2) the trap frame is not on our own kernel stack, or - * (3) the boot thread tries to enter user mode. - * - * If cpustacks[] is corrupted, the next trap back to the - * kernel will (most likely) hang the system, so it's better - * to find out now. - * - * It's necessary for the trap frame used here to be on the - * current thread's own stack. It cannot correctly be on - * either another thread's stack or in the kernel heap. - * (Exercise: why?) - */ - KASSERT(SAME_STACK(cpustacks[curcpu->c_number]-1, (vaddr_t)tf)); + /* + * This assertion will fail if either + * (1) cpustacks[] is corrupted, or + * (2) the trap frame is not on our own kernel stack, or + * (3) the boot thread tries to enter user mode. + * + * If cpustacks[] is corrupted, the next trap back to the + * kernel will (most likely) hang the system, so it's better + * to find out now. + * + * It's necessary for the trap frame used here to be on the + * current thread's own stack. It cannot correctly be on + * either another thread's stack or in the kernel heap. + * (Exercise: why?) + */ + KASSERT(SAME_STACK(cpustacks[curcpu->c_number] - 1, (vaddr_t)tf)); - /* - * This actually does it. See exception-*.S. - */ - asm_usermode(tf); + /* + * This actually does it. See exception-*.S. + */ + asm_usermode(tf); } /* @@ -419,20 +398,18 @@ mips_usermode(struct trapframe *tf) * * Works by creating an ersatz trapframe. */ -void -enter_new_process(int argc, userptr_t argv, userptr_t env, - vaddr_t stack, vaddr_t entry) -{ - struct trapframe tf; +void enter_new_process(int argc, userptr_t argv, userptr_t env, vaddr_t stack, + vaddr_t entry) { + struct trapframe tf; - bzero(&tf, sizeof(tf)); + bzero(&tf, sizeof(tf)); - tf.tf_status = CST_IRQMASK | CST_IEp | CST_KUp; - tf.tf_epc = entry; - tf.tf_a0 = argc; - tf.tf_a1 = (vaddr_t)argv; - tf.tf_a2 = (vaddr_t)env; - tf.tf_sp = stack; + tf.tf_status = CST_IRQMASK | CST_IEp | CST_KUp; + tf.tf_epc = entry; + tf.tf_a0 = argc; + tf.tf_a1 = (vaddr_t)argv; + tf.tf_a2 = (vaddr_t)env; + tf.tf_sp = stack; - mips_usermode(&tf); + mips_usermode(&tf); } diff --git a/kern/arch/mips/syscall/syscall.c b/kern/arch/mips/syscall/syscall.c index d37d239..14ff871 100644 --- a/kern/arch/mips/syscall/syscall.c +++ b/kern/arch/mips/syscall/syscall.c @@ -36,7 +36,6 @@ #include #include - /* * System call dispatcher. * @@ -75,75 +74,70 @@ * stack, starting at sp+16 to skip over the slots for the * registerized values, with copyin(). */ -void -syscall(struct trapframe *tf) -{ - int callno; - int32_t retval; - int err; +void syscall(struct trapframe *tf) { + int callno; + int32_t retval; + int err; - KASSERT(curthread != NULL); - KASSERT(curthread->t_curspl == 0); - KASSERT(curthread->t_iplhigh_count == 0); + KASSERT(curthread != NULL); + KASSERT(curthread->t_curspl == 0); + KASSERT(curthread->t_iplhigh_count == 0); - callno = tf->tf_v0; + callno = tf->tf_v0; - /* - * Initialize retval to 0. Many of the system calls don't - * really return a value, just 0 for success and -1 on - * error. Since retval is the value returned on success, - * initialize it to 0 by default; thus it's not necessary to - * deal with it except for calls that return other values, - * like write. - */ + /* + * Initialize retval to 0. Many of the system calls don't + * really return a value, just 0 for success and -1 on + * error. Since retval is the value returned on success, + * initialize it to 0 by default; thus it's not necessary to + * deal with it except for calls that return other values, + * like write. + */ - retval = 0; + retval = 0; - switch (callno) { - case SYS_reboot: - err = sys_reboot(tf->tf_a0); - break; + switch (callno) { + case SYS_reboot: + err = sys_reboot(tf->tf_a0); + break; - case SYS___time: - err = sys___time((userptr_t)tf->tf_a0, - (userptr_t)tf->tf_a1); - break; + case SYS___time: + err = sys___time((userptr_t)tf->tf_a0, (userptr_t)tf->tf_a1); + break; - /* Add stuff here */ + /* Add stuff here */ - default: - kprintf("Unknown syscall %d\n", callno); - err = ENOSYS; - break; - } + default: + kprintf("Unknown syscall %d\n", callno); + err = ENOSYS; + break; + } + if (err) { + /* + * Return the error code. This gets converted at + * userlevel to a return value of -1 and the error + * code in errno. + */ + tf->tf_v0 = err; + tf->tf_a3 = 1; /* signal an error */ + } else { + /* Success. */ + tf->tf_v0 = retval; + tf->tf_a3 = 0; /* signal no error */ + } - if (err) { - /* - * Return the error code. This gets converted at - * userlevel to a return value of -1 and the error - * code in errno. - */ - tf->tf_v0 = err; - tf->tf_a3 = 1; /* signal an error */ - } - else { - /* Success. */ - tf->tf_v0 = retval; - tf->tf_a3 = 0; /* signal no error */ - } + /* + * Now, advance the program counter, to avoid restarting + * the syscall over and over again. + */ - /* - * Now, advance the program counter, to avoid restarting - * the syscall over and over again. - */ + tf->tf_epc += 4; - tf->tf_epc += 4; - - /* Make sure the syscall code didn't forget to lower spl */ - KASSERT(curthread->t_curspl == 0); - /* ...or leak any spinlocks */ - KASSERT(curthread->t_iplhigh_count == 0); + /* Make sure the syscall code didn't forget to lower spl */ + KASSERT(curthread->t_curspl == 0); + /* ...or leak any spinlocks */ + KASSERT(curthread->t_iplhigh_count == 0); } /* @@ -154,8 +148,4 @@ syscall(struct trapframe *tf) * * Thus, you can trash it and do things another way if you prefer. */ -void -enter_forked_process(struct trapframe *tf) -{ - (void)tf; -} +void enter_forked_process(struct trapframe *tf) { (void)tf; } diff --git a/kern/arch/mips/thread/cpu.c b/kern/arch/mips/thread/cpu.c index d43a4ec..5f188d6 100644 --- a/kern/arch/mips/thread/cpu.c +++ b/kern/arch/mips/thread/cpu.c @@ -72,30 +72,27 @@ vaddr_t cputhreads[MAXCPUS]; * associated with a new cpu. Note that we're not running on the new * cpu when this is called. */ -void -cpu_machdep_init(struct cpu *c) -{ - vaddr_t stackpointer; +void cpu_machdep_init(struct cpu *c) { + vaddr_t stackpointer; - KASSERT(c->c_number < MAXCPUS); + KASSERT(c->c_number < MAXCPUS); - if (c->c_curthread->t_stack == NULL) { - /* boot cpu; don't need to do anything here */ - } - else { - /* - * Stick the stack in cpustacks[], and thread pointer - * in cputhreads[]. - */ + if (c->c_curthread->t_stack == NULL) { + /* boot cpu; don't need to do anything here */ + } else { + /* + * Stick the stack in cpustacks[], and thread pointer + * in cputhreads[]. + */ - /* stack base address */ - stackpointer = (vaddr_t) c->c_curthread->t_stack; - /* since stacks grow down, get the top */ - stackpointer += STACK_SIZE; + /* stack base address */ + stackpointer = (vaddr_t)c->c_curthread->t_stack; + /* since stacks grow down, get the top */ + stackpointer += STACK_SIZE; - cpustacks[c->c_number] = stackpointer; - cputhreads[c->c_number] = (vaddr_t)c->c_curthread; - } + cpustacks[c->c_number] = stackpointer; + cputhreads[c->c_number] = (vaddr_t)c->c_curthread; + } } //////////////////////////////////////////////////////////// @@ -107,73 +104,61 @@ cpu_machdep_init(struct cpu *c) * System/161 processor-ID values. */ -#define SYS161_PRID_ORIG 0x000003ff -#define SYS161_PRID_2X 0x000000a1 +#define SYS161_PRID_ORIG 0x000003ff +#define SYS161_PRID_2X 0x000000a1 -static inline -uint32_t -cpu_getprid(void) -{ - uint32_t prid; +static inline uint32_t cpu_getprid(void) { + uint32_t prid; - __asm volatile("mfc0 %0,$15" : "=r" (prid)); - return prid; + __asm volatile("mfc0 %0,$15" : "=r"(prid)); + return prid; } -static inline -uint32_t -cpu_getfeatures(void) -{ - uint32_t features; +static inline uint32_t cpu_getfeatures(void) { + uint32_t features; - __asm volatile(".set push;" /* save assembler mode */ - ".set mips32;" /* allow mips32 instructions */ - "mfc0 %0,$15,1;" /* get cop0 reg 15 sel 1 */ - ".set pop" /* restore assembler mode */ - : "=r" (features)); - return features; + __asm volatile(".set push;" /* save assembler mode */ + ".set mips32;" /* allow mips32 instructions */ + "mfc0 %0,$15,1;" /* get cop0 reg 15 sel 1 */ + ".set pop" /* restore assembler mode */ + : "=r"(features)); + return features; } -static inline -uint32_t -cpu_getifeatures(void) -{ - uint32_t features; +static inline uint32_t cpu_getifeatures(void) { + uint32_t features; - __asm volatile(".set push;" /* save assembler mode */ - ".set mips32;" /* allow mips32 instructions */ - "mfc0 %0,$15,2;" /* get cop0 reg 15 sel 2 */ - ".set pop" /* restore assembler mode */ - : "=r" (features)); - return features; + __asm volatile(".set push;" /* save assembler mode */ + ".set mips32;" /* allow mips32 instructions */ + "mfc0 %0,$15,2;" /* get cop0 reg 15 sel 2 */ + ".set pop" /* restore assembler mode */ + : "=r"(features)); + return features; } -void -cpu_identify(char *buf, size_t max) -{ - uint32_t prid; - uint32_t features; +void cpu_identify(char *buf, size_t max) { + uint32_t prid; + uint32_t features; - prid = cpu_getprid(); - switch (prid) { - case SYS161_PRID_ORIG: - snprintf(buf, max, "MIPS/161 (System/161 1.x and pre-2.x)"); - break; - case SYS161_PRID_2X: - features = cpu_getfeatures(); - snprintf(buf, max, "MIPS/161 (System/161 2.x) features 0x%x", - features); - features = cpu_getifeatures(); - if (features != 0) { - kprintf("WARNING: unknown CPU incompatible features " - "0x%x\n", features); - } - break; - default: - snprintf(buf, max, "32-bit MIPS (unknown type, CPU ID 0x%x)", - prid); - break; - } + prid = cpu_getprid(); + switch (prid) { + case SYS161_PRID_ORIG: + snprintf(buf, max, "MIPS/161 (System/161 1.x and pre-2.x)"); + break; + case SYS161_PRID_2X: + features = cpu_getfeatures(); + snprintf(buf, max, "MIPS/161 (System/161 2.x) features 0x%x", features); + features = cpu_getifeatures(); + if (features != 0) { + kprintf("WARNING: unknown CPU incompatible features " + "0x%x\n", + features); + } + break; + default: + snprintf(buf, max, "32-bit MIPS (unknown type, CPU ID 0x%x)", prid); + break; + } } //////////////////////////////////////////////////////////// @@ -200,50 +185,43 @@ cpu_identify(char *buf, size_t max) * These considerations do not (currently) apply to System/161, * however. */ -#define GET_STATUS(x) __asm volatile("mfc0 %0,$12" : "=r" (x)) -#define SET_STATUS(x) __asm volatile("mtc0 %0,$12" :: "r" (x)) +#define GET_STATUS(x) __asm volatile("mfc0 %0,$12" : "=r"(x)) +#define SET_STATUS(x) __asm volatile("mtc0 %0,$12" ::"r"(x)) /* * Interrupts on. */ -void -cpu_irqon(void) -{ - uint32_t x; +void cpu_irqon(void) { + uint32_t x; - GET_STATUS(x); - x |= CST_IEc; - SET_STATUS(x); + GET_STATUS(x); + x |= CST_IEc; + SET_STATUS(x); } /* * Interrupts off. */ -void -cpu_irqoff(void) -{ - uint32_t x; +void cpu_irqoff(void) { + uint32_t x; - GET_STATUS(x); - x &= ~(uint32_t)CST_IEc; - SET_STATUS(x); + GET_STATUS(x); + x &= ~(uint32_t)CST_IEc; + SET_STATUS(x); } /* * Used below. */ -static -void -cpu_irqonoff(void) -{ - uint32_t x, xon, xoff; +static void cpu_irqonoff(void) { + uint32_t x, xon, xoff; - GET_STATUS(x); - xon = x | CST_IEc; - xoff = x & ~(uint32_t)CST_IEc; - SET_STATUS(xon); - __asm volatile("nop; nop; nop; nop"); - SET_STATUS(xoff); + GET_STATUS(x); + xon = x | CST_IEc; + xoff = x & ~(uint32_t)CST_IEc; + SET_STATUS(xon); + __asm volatile("nop; nop; nop; nop"); + SET_STATUS(xoff); } //////////////////////////////////////////////////////////// @@ -261,49 +239,40 @@ cpu_irqonoff(void) * appropriate the mips32 WAIT instruction. */ -static -inline -void -wait(void) -{ - /* - * The WAIT instruction goes into powersave mode until an - * interrupt is trying to occur. - * - * Then switch interrupts on and off again, so we actually - * take the interrupt. - * - * Note that the precise behavior of this instruction in the - * System/161 simulator is partly guesswork. This code may not - * work on a real mips. - */ - __asm volatile( - ".set push;" /* save assembler mode */ - ".set mips32;" /* allow MIPS32 instructions */ - ".set volatile;" /* avoid unwanted optimization */ - "wait;" /* suspend until interrupted */ - ".set pop" /* restore assembler mode */ - ); +static inline void wait(void) { + /* + * The WAIT instruction goes into powersave mode until an + * interrupt is trying to occur. + * + * Then switch interrupts on and off again, so we actually + * take the interrupt. + * + * Note that the precise behavior of this instruction in the + * System/161 simulator is partly guesswork. This code may not + * work on a real mips. + */ + __asm volatile(".set push;" /* save assembler mode */ + ".set mips32;" /* allow MIPS32 instructions */ + ".set volatile;" /* avoid unwanted optimization */ + "wait;" /* suspend until interrupted */ + ".set pop" /* restore assembler mode */ + ); } /* * Idle the processor until something happens. */ -void -cpu_idle(void) -{ - wait(); - cpu_irqonoff(); +void cpu_idle(void) { + wait(); + cpu_irqonoff(); } /* * Halt the CPU permanently. */ -void -cpu_halt(void) -{ - cpu_irqoff(); - while (1) { - wait(); - } +void cpu_halt(void) { + cpu_irqoff(); + while (1) { + wait(); + } } diff --git a/kern/arch/mips/thread/switchframe.c b/kern/arch/mips/thread/switchframe.c index 1a7a41b..95444f8 100644 --- a/kern/arch/mips/thread/switchframe.c +++ b/kern/arch/mips/thread/switchframe.c @@ -37,7 +37,6 @@ /* in threadstart.S */ extern void mips_threadstart(/* arguments are in unusual registers */); - /* * Function to initialize the switchframe of a new thread, which is * *not* the one that is currently running. @@ -51,48 +50,46 @@ extern void mips_threadstart(/* arguments are in unusual registers */); * store the arguments in the s* registers, and use a bit of asm * (mips_threadstart) to move them and then jump to thread_startup. */ -void -switchframe_init(struct thread *thread, - void (*entrypoint)(void *data1, unsigned long data2), - void *data1, unsigned long data2) -{ - vaddr_t stacktop; - struct switchframe *sf; +void switchframe_init(struct thread *thread, + void (*entrypoint)(void *data1, unsigned long data2), + void *data1, unsigned long data2) { + vaddr_t stacktop; + struct switchframe *sf; - /* - * MIPS stacks grow down. t_stack is just a hunk of memory, so - * get the other end of it. Then set up a switchframe on the - * top of the stack. - */ - stacktop = ((vaddr_t)thread->t_stack) + STACK_SIZE; - sf = ((struct switchframe *) stacktop) - 1; + /* + * MIPS stacks grow down. t_stack is just a hunk of memory, so + * get the other end of it. Then set up a switchframe on the + * top of the stack. + */ + stacktop = ((vaddr_t)thread->t_stack) + STACK_SIZE; + sf = ((struct switchframe *)stacktop) - 1; - /* Zero out the switchframe. */ - bzero(sf, sizeof(*sf)); + /* Zero out the switchframe. */ + bzero(sf, sizeof(*sf)); - /* - * Now set the important parts: pass through the three arguments, - * and set the return address register to the place we want - * execution to begin. - * - * Thus, when switchframe_switch does its "j ra", it will - * actually jump to mips_threadstart, which will move the - * arguments into the right register and jump to - * thread_startup(). - * - * Note that this means that when we call switchframe_switch() - * in thread_switch(), we may not come back out the same way - * in the next thread. (Though we will come back out the same - * way when we later come back to the same thread again.) - * - * This has implications for code at the bottom of - * thread_switch, described in thread.c. - */ - sf->sf_s0 = (uint32_t)entrypoint; - sf->sf_s1 = (uint32_t)data1; - sf->sf_s2 = (uint32_t)data2; - sf->sf_ra = (uint32_t)mips_threadstart; + /* + * Now set the important parts: pass through the three arguments, + * and set the return address register to the place we want + * execution to begin. + * + * Thus, when switchframe_switch does its "j ra", it will + * actually jump to mips_threadstart, which will move the + * arguments into the right register and jump to + * thread_startup(). + * + * Note that this means that when we call switchframe_switch() + * in thread_switch(), we may not come back out the same way + * in the next thread. (Though we will come back out the same + * way when we later come back to the same thread again.) + * + * This has implications for code at the bottom of + * thread_switch, described in thread.c. + */ + sf->sf_s0 = (uint32_t)entrypoint; + sf->sf_s1 = (uint32_t)data1; + sf->sf_s2 = (uint32_t)data2; + sf->sf_ra = (uint32_t)mips_threadstart; - /* Set ->t_context, and we're done. */ - thread->t_context = sf; + /* Set ->t_context, and we're done. */ + thread->t_context = sf; } diff --git a/kern/arch/mips/thread/switchframe.h b/kern/arch/mips/thread/switchframe.h index 140ebcc..a3895b6 100644 --- a/kern/arch/mips/thread/switchframe.h +++ b/kern/arch/mips/thread/switchframe.h @@ -37,16 +37,16 @@ */ struct switchframe { - uint32_t sf_s0; - uint32_t sf_s1; - uint32_t sf_s2; - uint32_t sf_s3; - uint32_t sf_s4; - uint32_t sf_s5; - uint32_t sf_s6; - uint32_t sf_s8; - uint32_t sf_gp; - uint32_t sf_ra; + uint32_t sf_s0; + uint32_t sf_s1; + uint32_t sf_s2; + uint32_t sf_s3; + uint32_t sf_s4; + uint32_t sf_s5; + uint32_t sf_s6; + uint32_t sf_s8; + uint32_t sf_gp; + uint32_t sf_ra; }; #endif /* _MIPS_SWITCHFRAME_H_ */ diff --git a/kern/arch/mips/thread/thread_machdep.c b/kern/arch/mips/thread/thread_machdep.c index fcd82ba..7524b67 100644 --- a/kern/arch/mips/thread/thread_machdep.c +++ b/kern/arch/mips/thread/thread_machdep.c @@ -36,14 +36,10 @@ #include #include -void -thread_machdep_init(struct thread_machdep *tm) -{ - tm->tm_badfaultfunc = NULL; +void thread_machdep_init(struct thread_machdep *tm) { + tm->tm_badfaultfunc = NULL; } -void -thread_machdep_cleanup(struct thread_machdep *tm) -{ - KASSERT(tm->tm_badfaultfunc == NULL); +void thread_machdep_cleanup(struct thread_machdep *tm) { + KASSERT(tm->tm_badfaultfunc == NULL); } diff --git a/kern/arch/mips/vm/dumbvm.c b/kern/arch/mips/vm/dumbvm.c index cf9d916..7e7b740 100644 --- a/kern/arch/mips/vm/dumbvm.c +++ b/kern/arch/mips/vm/dumbvm.c @@ -57,18 +57,14 @@ /* under dumbvm, always have 72k of user stack */ /* (this must be > 64K so argument blocks of size ARG_MAX will fit) */ -#define DUMBVM_STACKPAGES 18 +#define DUMBVM_STACKPAGES 18 /* * Wrap ram_stealmem in a spinlock. */ static struct spinlock stealmem_lock = SPINLOCK_INITIALIZER; -void -vm_bootstrap(void) -{ - /* Do nothing. */ -} +void vm_bootstrap(void) { /* Do nothing. */ } /* * Check if we're in a context that can sleep. While most of the @@ -77,351 +73,311 @@ vm_bootstrap(void) * avoid the situation where syscall-layer code that works ok with * dumbvm starts blowing up during the VM assignment. */ -static -void -dumbvm_can_sleep(void) -{ - if (CURCPU_EXISTS()) { - /* must not hold spinlocks */ - KASSERT(curcpu->c_spinlocks == 0); +static void dumbvm_can_sleep(void) { + if (CURCPU_EXISTS()) { + /* must not hold spinlocks */ + KASSERT(curcpu->c_spinlocks == 0); - /* must not be in an interrupt handler */ - KASSERT(curthread->t_in_interrupt == 0); - } + /* must not be in an interrupt handler */ + KASSERT(curthread->t_in_interrupt == 0); + } } -static -paddr_t -getppages(unsigned long npages) -{ - paddr_t addr; +static paddr_t getppages(unsigned long npages) { + paddr_t addr; - spinlock_acquire(&stealmem_lock); + spinlock_acquire(&stealmem_lock); - addr = ram_stealmem(npages); + addr = ram_stealmem(npages); - spinlock_release(&stealmem_lock); - return addr; + spinlock_release(&stealmem_lock); + return addr; } /* Allocate/free some kernel-space virtual pages */ -vaddr_t -alloc_kpages(unsigned npages) -{ - paddr_t pa; +vaddr_t alloc_kpages(unsigned npages) { + paddr_t pa; - dumbvm_can_sleep(); - pa = getppages(npages); - if (pa==0) { - return 0; - } - return PADDR_TO_KVADDR(pa); + dumbvm_can_sleep(); + pa = getppages(npages); + if (pa == 0) { + return 0; + } + return PADDR_TO_KVADDR(pa); } -void -free_kpages(vaddr_t addr) -{ - /* nothing - leak the memory. */ +void free_kpages(vaddr_t addr) { + /* nothing - leak the memory. */ - (void)addr; + (void)addr; } -void -vm_tlbshootdown(const struct tlbshootdown *ts) -{ - (void)ts; - panic("dumbvm tried to do tlb shootdown?!\n"); +void vm_tlbshootdown(const struct tlbshootdown *ts) { + (void)ts; + panic("dumbvm tried to do tlb shootdown?!\n"); } -int -vm_fault(int faulttype, vaddr_t faultaddress) -{ - vaddr_t vbase1, vtop1, vbase2, vtop2, stackbase, stacktop; - paddr_t paddr; - int i; - uint32_t ehi, elo; - struct addrspace *as; - int spl; +int vm_fault(int faulttype, vaddr_t faultaddress) { + vaddr_t vbase1, vtop1, vbase2, vtop2, stackbase, stacktop; + paddr_t paddr; + int i; + uint32_t ehi, elo; + struct addrspace *as; + int spl; - faultaddress &= PAGE_FRAME; + faultaddress &= PAGE_FRAME; - DEBUG(DB_VM, "dumbvm: fault: 0x%x\n", faultaddress); + DEBUG(DB_VM, "dumbvm: fault: 0x%x\n", faultaddress); - switch (faulttype) { - case VM_FAULT_READONLY: - /* We always create pages read-write, so we can't get this */ - panic("dumbvm: got VM_FAULT_READONLY\n"); - case VM_FAULT_READ: - case VM_FAULT_WRITE: - break; - default: - return EINVAL; - } + switch (faulttype) { + case VM_FAULT_READONLY: + /* We always create pages read-write, so we can't get this */ + panic("dumbvm: got VM_FAULT_READONLY\n"); + case VM_FAULT_READ: + case VM_FAULT_WRITE: + break; + default: + return EINVAL; + } - if (curproc == NULL) { - /* - * No process. This is probably a kernel fault early - * in boot. Return EFAULT so as to panic instead of - * getting into an infinite faulting loop. - */ - return EFAULT; - } + if (curproc == NULL) { + /* + * No process. This is probably a kernel fault early + * in boot. Return EFAULT so as to panic instead of + * getting into an infinite faulting loop. + */ + return EFAULT; + } - as = proc_getas(); - if (as == NULL) { - /* - * No address space set up. This is probably also a - * kernel fault early in boot. - */ - return EFAULT; - } + as = proc_getas(); + if (as == NULL) { + /* + * No address space set up. This is probably also a + * kernel fault early in boot. + */ + return EFAULT; + } - /* Assert that the address space has been set up properly. */ - KASSERT(as->as_vbase1 != 0); - KASSERT(as->as_pbase1 != 0); - KASSERT(as->as_npages1 != 0); - KASSERT(as->as_vbase2 != 0); - KASSERT(as->as_pbase2 != 0); - KASSERT(as->as_npages2 != 0); - KASSERT(as->as_stackpbase != 0); - KASSERT((as->as_vbase1 & PAGE_FRAME) == as->as_vbase1); - KASSERT((as->as_pbase1 & PAGE_FRAME) == as->as_pbase1); - KASSERT((as->as_vbase2 & PAGE_FRAME) == as->as_vbase2); - KASSERT((as->as_pbase2 & PAGE_FRAME) == as->as_pbase2); - KASSERT((as->as_stackpbase & PAGE_FRAME) == as->as_stackpbase); + /* Assert that the address space has been set up properly. */ + KASSERT(as->as_vbase1 != 0); + KASSERT(as->as_pbase1 != 0); + KASSERT(as->as_npages1 != 0); + KASSERT(as->as_vbase2 != 0); + KASSERT(as->as_pbase2 != 0); + KASSERT(as->as_npages2 != 0); + KASSERT(as->as_stackpbase != 0); + KASSERT((as->as_vbase1 & PAGE_FRAME) == as->as_vbase1); + KASSERT((as->as_pbase1 & PAGE_FRAME) == as->as_pbase1); + KASSERT((as->as_vbase2 & PAGE_FRAME) == as->as_vbase2); + KASSERT((as->as_pbase2 & PAGE_FRAME) == as->as_pbase2); + KASSERT((as->as_stackpbase & PAGE_FRAME) == as->as_stackpbase); - vbase1 = as->as_vbase1; - vtop1 = vbase1 + as->as_npages1 * PAGE_SIZE; - vbase2 = as->as_vbase2; - vtop2 = vbase2 + as->as_npages2 * PAGE_SIZE; - stackbase = USERSTACK - DUMBVM_STACKPAGES * PAGE_SIZE; - stacktop = USERSTACK; + vbase1 = as->as_vbase1; + vtop1 = vbase1 + as->as_npages1 * PAGE_SIZE; + vbase2 = as->as_vbase2; + vtop2 = vbase2 + as->as_npages2 * PAGE_SIZE; + stackbase = USERSTACK - DUMBVM_STACKPAGES * PAGE_SIZE; + stacktop = USERSTACK; - if (faultaddress >= vbase1 && faultaddress < vtop1) { - paddr = (faultaddress - vbase1) + as->as_pbase1; - } - else if (faultaddress >= vbase2 && faultaddress < vtop2) { - paddr = (faultaddress - vbase2) + as->as_pbase2; - } - else if (faultaddress >= stackbase && faultaddress < stacktop) { - paddr = (faultaddress - stackbase) + as->as_stackpbase; - } - else { - return EFAULT; - } + if (faultaddress >= vbase1 && faultaddress < vtop1) { + paddr = (faultaddress - vbase1) + as->as_pbase1; + } else if (faultaddress >= vbase2 && faultaddress < vtop2) { + paddr = (faultaddress - vbase2) + as->as_pbase2; + } else if (faultaddress >= stackbase && faultaddress < stacktop) { + paddr = (faultaddress - stackbase) + as->as_stackpbase; + } else { + return EFAULT; + } - /* make sure it's page-aligned */ - KASSERT((paddr & PAGE_FRAME) == paddr); + /* make sure it's page-aligned */ + KASSERT((paddr & PAGE_FRAME) == paddr); - /* Disable interrupts on this CPU while frobbing the TLB. */ - spl = splhigh(); + /* Disable interrupts on this CPU while frobbing the TLB. */ + spl = splhigh(); - for (i=0; i 0x%x\n", faultaddress, paddr); - tlb_write(ehi, elo, i); - splx(spl); - return 0; - } + for (i = 0; i < NUM_TLB; i++) { + tlb_read(&ehi, &elo, i); + if (elo & TLBLO_VALID) { + continue; + } + ehi = faultaddress; + elo = paddr | TLBLO_DIRTY | TLBLO_VALID; + DEBUG(DB_VM, "dumbvm: 0x%x -> 0x%x\n", faultaddress, paddr); + tlb_write(ehi, elo, i); + splx(spl); + return 0; + } - kprintf("dumbvm: Ran out of TLB entries - cannot handle page fault\n"); - splx(spl); - return EFAULT; + kprintf("dumbvm: Ran out of TLB entries - cannot handle page fault\n"); + splx(spl); + return EFAULT; } -struct addrspace * -as_create(void) -{ - struct addrspace *as = kmalloc(sizeof(struct addrspace)); - if (as==NULL) { - return NULL; - } +struct addrspace *as_create(void) { + struct addrspace *as = kmalloc(sizeof(struct addrspace)); + if (as == NULL) { + return NULL; + } - as->as_vbase1 = 0; - as->as_pbase1 = 0; - as->as_npages1 = 0; - as->as_vbase2 = 0; - as->as_pbase2 = 0; - as->as_npages2 = 0; - as->as_stackpbase = 0; + as->as_vbase1 = 0; + as->as_pbase1 = 0; + as->as_npages1 = 0; + as->as_vbase2 = 0; + as->as_pbase2 = 0; + as->as_npages2 = 0; + as->as_stackpbase = 0; - return as; + return as; } -void -as_destroy(struct addrspace *as) -{ - dumbvm_can_sleep(); - kfree(as); +void as_destroy(struct addrspace *as) { + dumbvm_can_sleep(); + kfree(as); } -void -as_activate(void) -{ - int i, spl; - struct addrspace *as; +void as_activate(void) { + int i, spl; + struct addrspace *as; - as = proc_getas(); - if (as == NULL) { - return; - } + as = proc_getas(); + if (as == NULL) { + return; + } - /* Disable interrupts on this CPU while frobbing the TLB. */ - spl = splhigh(); + /* Disable interrupts on this CPU while frobbing the TLB. */ + spl = splhigh(); - for (i=0; ias_vbase1 == 0) { + as->as_vbase1 = vaddr; + as->as_npages1 = npages; + return 0; + } + + if (as->as_vbase2 == 0) { + as->as_vbase2 = vaddr; + as->as_npages2 = npages; + return 0; + } + + /* + * Support for more than two regions is not available. + */ + kprintf("dumbvm: Warning: too many regions\n"); + return ENOSYS; } -int -as_define_region(struct addrspace *as, vaddr_t vaddr, size_t sz, - int readable, int writeable, int executable) -{ - size_t npages; - - dumbvm_can_sleep(); - - /* Align the region. First, the base... */ - sz += vaddr & ~(vaddr_t)PAGE_FRAME; - vaddr &= PAGE_FRAME; - - /* ...and now the length. */ - sz = (sz + PAGE_SIZE - 1) & PAGE_FRAME; - - npages = sz / PAGE_SIZE; - - /* We don't use these - all pages are read-write */ - (void)readable; - (void)writeable; - (void)executable; - - if (as->as_vbase1 == 0) { - as->as_vbase1 = vaddr; - as->as_npages1 = npages; - return 0; - } - - if (as->as_vbase2 == 0) { - as->as_vbase2 = vaddr; - as->as_npages2 = npages; - return 0; - } - - /* - * Support for more than two regions is not available. - */ - kprintf("dumbvm: Warning: too many regions\n"); - return ENOSYS; +static void as_zero_region(paddr_t paddr, unsigned npages) { + bzero((void *)PADDR_TO_KVADDR(paddr), npages * PAGE_SIZE); } -static -void -as_zero_region(paddr_t paddr, unsigned npages) -{ - bzero((void *)PADDR_TO_KVADDR(paddr), npages * PAGE_SIZE); +int as_prepare_load(struct addrspace *as) { + KASSERT(as->as_pbase1 == 0); + KASSERT(as->as_pbase2 == 0); + KASSERT(as->as_stackpbase == 0); + + dumbvm_can_sleep(); + + as->as_pbase1 = getppages(as->as_npages1); + if (as->as_pbase1 == 0) { + return ENOMEM; + } + + as->as_pbase2 = getppages(as->as_npages2); + if (as->as_pbase2 == 0) { + return ENOMEM; + } + + as->as_stackpbase = getppages(DUMBVM_STACKPAGES); + if (as->as_stackpbase == 0) { + return ENOMEM; + } + + as_zero_region(as->as_pbase1, as->as_npages1); + as_zero_region(as->as_pbase2, as->as_npages2); + as_zero_region(as->as_stackpbase, DUMBVM_STACKPAGES); + + return 0; } -int -as_prepare_load(struct addrspace *as) -{ - KASSERT(as->as_pbase1 == 0); - KASSERT(as->as_pbase2 == 0); - KASSERT(as->as_stackpbase == 0); - - dumbvm_can_sleep(); - - as->as_pbase1 = getppages(as->as_npages1); - if (as->as_pbase1 == 0) { - return ENOMEM; - } - - as->as_pbase2 = getppages(as->as_npages2); - if (as->as_pbase2 == 0) { - return ENOMEM; - } - - as->as_stackpbase = getppages(DUMBVM_STACKPAGES); - if (as->as_stackpbase == 0) { - return ENOMEM; - } - - as_zero_region(as->as_pbase1, as->as_npages1); - as_zero_region(as->as_pbase2, as->as_npages2); - as_zero_region(as->as_stackpbase, DUMBVM_STACKPAGES); - - return 0; +int as_complete_load(struct addrspace *as) { + dumbvm_can_sleep(); + (void)as; + return 0; } -int -as_complete_load(struct addrspace *as) -{ - dumbvm_can_sleep(); - (void)as; - return 0; +int as_define_stack(struct addrspace *as, vaddr_t *stackptr) { + KASSERT(as->as_stackpbase != 0); + + *stackptr = USERSTACK; + return 0; } -int -as_define_stack(struct addrspace *as, vaddr_t *stackptr) -{ - KASSERT(as->as_stackpbase != 0); +int as_copy(struct addrspace *old, struct addrspace **ret) { + struct addrspace *new; - *stackptr = USERSTACK; - return 0; -} - -int -as_copy(struct addrspace *old, struct addrspace **ret) -{ - struct addrspace *new; - - dumbvm_can_sleep(); - - new = as_create(); - if (new==NULL) { - return ENOMEM; - } - - new->as_vbase1 = old->as_vbase1; - new->as_npages1 = old->as_npages1; - new->as_vbase2 = old->as_vbase2; - new->as_npages2 = old->as_npages2; - - /* (Mis)use as_prepare_load to allocate some physical memory. */ - if (as_prepare_load(new)) { - as_destroy(new); - return ENOMEM; - } - - KASSERT(new->as_pbase1 != 0); - KASSERT(new->as_pbase2 != 0); - KASSERT(new->as_stackpbase != 0); - - memmove((void *)PADDR_TO_KVADDR(new->as_pbase1), - (const void *)PADDR_TO_KVADDR(old->as_pbase1), - old->as_npages1*PAGE_SIZE); - - memmove((void *)PADDR_TO_KVADDR(new->as_pbase2), - (const void *)PADDR_TO_KVADDR(old->as_pbase2), - old->as_npages2*PAGE_SIZE); - - memmove((void *)PADDR_TO_KVADDR(new->as_stackpbase), - (const void *)PADDR_TO_KVADDR(old->as_stackpbase), - DUMBVM_STACKPAGES*PAGE_SIZE); - - *ret = new; - return 0; + dumbvm_can_sleep(); + + new = as_create(); + if (new == NULL) { + return ENOMEM; + } + + new->as_vbase1 = old->as_vbase1; + new->as_npages1 = old->as_npages1; + new->as_vbase2 = old->as_vbase2; + new->as_npages2 = old->as_npages2; + + /* (Mis)use as_prepare_load to allocate some physical memory. */ + if (as_prepare_load(new)) { + as_destroy(new); + return ENOMEM; + } + + KASSERT(new->as_pbase1 != 0); + KASSERT(new->as_pbase2 != 0); + KASSERT(new->as_stackpbase != 0); + + memmove((void *)PADDR_TO_KVADDR(new->as_pbase1), + (const void *)PADDR_TO_KVADDR(old->as_pbase1), + old->as_npages1 * PAGE_SIZE); + + memmove((void *)PADDR_TO_KVADDR(new->as_pbase2), + (const void *)PADDR_TO_KVADDR(old->as_pbase2), + old->as_npages2 * PAGE_SIZE); + + memmove((void *)PADDR_TO_KVADDR(new->as_stackpbase), + (const void *)PADDR_TO_KVADDR(old->as_stackpbase), + DUMBVM_STACKPAGES * PAGE_SIZE); + + *ret = new; + return 0; } diff --git a/kern/arch/mips/vm/ram.c b/kern/arch/mips/vm/ram.c index 8b4e4cd..c052960 100644 --- a/kern/arch/mips/vm/ram.c +++ b/kern/arch/mips/vm/ram.c @@ -32,45 +32,41 @@ #include #include +vaddr_t firstfree; /* first free virtual address; set by start.S */ -vaddr_t firstfree; /* first free virtual address; set by start.S */ - -static paddr_t firstpaddr; /* address of first free physical page */ -static paddr_t lastpaddr; /* one past end of last free physical page */ +static paddr_t firstpaddr; /* address of first free physical page */ +static paddr_t lastpaddr; /* one past end of last free physical page */ /* * Called very early in system boot to figure out how much physical * RAM is available. */ -void -ram_bootstrap(void) -{ - size_t ramsize; +void ram_bootstrap(void) { + size_t ramsize; - /* Get size of RAM. */ - ramsize = mainbus_ramsize(); + /* Get size of RAM. */ + ramsize = mainbus_ramsize(); - /* - * This is the same as the last physical address, as long as - * we have less than 512 megabytes of memory. If we had more, - * we wouldn't be able to access it all through kseg0 and - * everything would get a lot more complicated. This is not a - * case we are going to worry about. - */ - if (ramsize > 512*1024*1024) { - ramsize = 512*1024*1024; - } + /* + * This is the same as the last physical address, as long as + * we have less than 512 megabytes of memory. If we had more, + * we wouldn't be able to access it all through kseg0 and + * everything would get a lot more complicated. This is not a + * case we are going to worry about. + */ + if (ramsize > 512 * 1024 * 1024) { + ramsize = 512 * 1024 * 1024; + } - lastpaddr = ramsize; + lastpaddr = ramsize; - /* - * Get first free virtual address from where start.S saved it. - * Convert to physical address. - */ - firstpaddr = firstfree - MIPS_KSEG0; + /* + * Get first free virtual address from where start.S saved it. + * Convert to physical address. + */ + firstpaddr = firstfree - MIPS_KSEG0; - kprintf("%uk physical memory available\n", - (lastpaddr-firstpaddr)/1024); + kprintf("%uk physical memory available\n", (lastpaddr - firstpaddr) / 1024); } /* @@ -91,22 +87,20 @@ ram_bootstrap(void) * This function should not be called once the VM system is initialized, * so it is not synchronized. */ -paddr_t -ram_stealmem(unsigned long npages) -{ - size_t size; - paddr_t paddr; +paddr_t ram_stealmem(unsigned long npages) { + size_t size; + paddr_t paddr; - size = npages * PAGE_SIZE; + size = npages * PAGE_SIZE; - if (firstpaddr + size > lastpaddr) { - return 0; - } + if (firstpaddr + size > lastpaddr) { + return 0; + } - paddr = firstpaddr; - firstpaddr += size; + paddr = firstpaddr; + firstpaddr += size; - return paddr; + return paddr; } /* @@ -124,11 +118,7 @@ ram_stealmem(unsigned long npages) * initialize the VM system, after which the VM system should take * charge of knowing what memory exists. */ -paddr_t -ram_getsize(void) -{ - return lastpaddr; -} +paddr_t ram_getsize(void) { return lastpaddr; } /* * This function is intended to be called by the VM system when it @@ -142,12 +132,10 @@ ram_getsize(void) * This function should not be called once the VM system is initialized, * so it is not synchronized. */ -paddr_t -ram_getfirstfree(void) -{ - paddr_t ret; +paddr_t ram_getfirstfree(void) { + paddr_t ret; - ret = firstpaddr; - firstpaddr = lastpaddr = 0; - return ret; + ret = firstpaddr; + firstpaddr = lastpaddr = 0; + return ret; } diff --git a/kern/arch/sys161/dev/lamebus_machdep.c b/kern/arch/sys161/dev/lamebus_machdep.c index 0cc1fb2..4bfd0c9 100644 --- a/kern/arch/sys161/dev/lamebus_machdep.c +++ b/kern/arch/sys161/dev/lamebus_machdep.c @@ -60,20 +60,16 @@ * matches the c0_compare register, the timer interrupt line is * asserted. Writing to c0_compare again clears the interrupt. */ -static -void -mips_timer_set(uint32_t count) -{ - /* - * $11 == c0_compare; we can't use the symbolic name inside - * the asm string. - */ - __asm volatile( - ".set push;" /* save assembler mode */ - ".set mips32;" /* allow MIPS32 registers */ - "mtc0 %0, $11;" /* do it */ - ".set pop" /* restore assembler mode */ - :: "r" (count)); +static void mips_timer_set(uint32_t count) { + /* + * $11 == c0_compare; we can't use the symbolic name inside + * the asm string. + */ + __asm volatile(".set push;" /* save assembler mode */ + ".set mips32;" /* allow MIPS32 registers */ + "mtc0 %0, $11;" /* do it */ + ".set pop" /* restore assembler mode */ + ::"r"(count)); } /* @@ -83,138 +79,122 @@ mips_timer_set(uint32_t count) */ static struct lamebus_softc *lamebus; -void -mainbus_bootstrap(void) -{ - /* Interrupts should be off (and have been off since startup) */ - KASSERT(curthread->t_curspl > 0); +void mainbus_bootstrap(void) { + /* Interrupts should be off (and have been off since startup) */ + KASSERT(curthread->t_curspl > 0); - /* Initialize the system LAMEbus data */ - lamebus = lamebus_init(); + /* Initialize the system LAMEbus data */ + lamebus = lamebus_init(); - /* Probe CPUs (should these be done as device attachments instead?) */ - lamebus_find_cpus(lamebus); + /* Probe CPUs (should these be done as device attachments instead?) */ + lamebus_find_cpus(lamebus); - /* - * Print the device name for the main bus. - */ - kprintf("lamebus0 (system main bus)\n"); + /* + * Print the device name for the main bus. + */ + kprintf("lamebus0 (system main bus)\n"); - /* - * Now we can take interrupts without croaking, so turn them on. - * Some device probes might require being able to get interrupts. - */ + /* + * Now we can take interrupts without croaking, so turn them on. + * Some device probes might require being able to get interrupts. + */ - spl0(); + spl0(); - /* - * Now probe all the devices attached to the bus. - * (This amounts to all devices.) - */ - autoconf_lamebus(lamebus, 0); + /* + * Now probe all the devices attached to the bus. + * (This amounts to all devices.) + */ + autoconf_lamebus(lamebus, 0); - /* - * Configure the MIPS on-chip timer to interrupt HZ times a second. - */ - mips_timer_set(CPU_FREQUENCY / HZ); + /* + * Configure the MIPS on-chip timer to interrupt HZ times a second. + */ + mips_timer_set(CPU_FREQUENCY / HZ); } /* * Start all secondary CPUs. */ -void -mainbus_start_cpus(void) -{ - lamebus_start_cpus(lamebus); -} +void mainbus_start_cpus(void) { lamebus_start_cpus(lamebus); } /* * Function to generate the memory address (in the uncached segment) * for the specified offset into the specified slot's region of the * LAMEbus. */ -void * -lamebus_map_area(struct lamebus_softc *bus, int slot, uint32_t offset) -{ - uint32_t address; +void *lamebus_map_area(struct lamebus_softc *bus, int slot, uint32_t offset) { + uint32_t address; - (void)bus; // not needed + (void)bus; // not needed - KASSERT(slot >= 0 && slot < LB_NSLOTS); + KASSERT(slot >= 0 && slot < LB_NSLOTS); - address = LB_BASEADDR + slot*LB_SLOT_SIZE + offset; - return (void *)address; + address = LB_BASEADDR + slot * LB_SLOT_SIZE + offset; + return (void *)address; } /* * Read a 32-bit register from a LAMEbus device. */ -uint32_t -lamebus_read_register(struct lamebus_softc *bus, int slot, uint32_t offset) -{ - uint32_t *ptr; +uint32_t lamebus_read_register(struct lamebus_softc *bus, int slot, + uint32_t offset) { + uint32_t *ptr; - ptr = lamebus_map_area(bus, slot, offset); + ptr = lamebus_map_area(bus, slot, offset); - /* - * Make sure the load happens after anything the device has - * been doing. - */ - membar_load_load(); + /* + * Make sure the load happens after anything the device has + * been doing. + */ + membar_load_load(); - return *ptr; + return *ptr; } /* * Write a 32-bit register of a LAMEbus device. */ -void -lamebus_write_register(struct lamebus_softc *bus, int slot, - uint32_t offset, uint32_t val) -{ - uint32_t *ptr; +void lamebus_write_register(struct lamebus_softc *bus, int slot, + uint32_t offset, uint32_t val) { + uint32_t *ptr; - ptr = lamebus_map_area(bus, slot, offset); - *ptr = val; + ptr = lamebus_map_area(bus, slot, offset); + *ptr = val; - /* - * Make sure the store happens before we do anything else to - * the device. - */ - membar_store_store(); + /* + * Make sure the store happens before we do anything else to + * the device. + */ + membar_store_store(); } - /* * Power off the system. */ -void -mainbus_poweroff(void) -{ - /* - * - * Note that lamebus_write_register() doesn't actually access - * the bus argument, so this will still work if we get here - * before the bus is initialized. - */ - lamebus_poweroff(lamebus); +void mainbus_poweroff(void) { + /* + * + * Note that lamebus_write_register() doesn't actually access + * the bus argument, so this will still work if we get here + * before the bus is initialized. + */ + lamebus_poweroff(lamebus); } /* * Reboot the system. */ -void -mainbus_reboot(void) -{ - /* - * The MIPS doesn't appear to have any on-chip reset. - * LAMEbus doesn't have a reset control, so we just - * power off instead of rebooting. This would not be - * so great in a real system, but it's fine for what - * we're doing. - */ - kprintf("Cannot reboot - powering off instead, sorry.\n"); - mainbus_poweroff(); +void mainbus_reboot(void) { + /* + * The MIPS doesn't appear to have any on-chip reset. + * LAMEbus doesn't have a reset control, so we just + * power off instead of rebooting. This would not be + * so great in a real system, but it's fine for what + * we're doing. + */ + kprintf("Cannot reboot - powering off instead, sorry.\n"); + mainbus_poweroff(); } /* @@ -222,11 +202,7 @@ mainbus_reboot(void) * On some systems, this would return to the boot monitor. But we don't * have one. */ -void -mainbus_halt(void) -{ - cpu_halt(); -} +void mainbus_halt(void) { cpu_halt(); } /* * Called to reset the system from panic(). @@ -235,110 +211,94 @@ mainbus_halt(void) * as to panic recursively if we do much of anything. So just power off. * (We'd reboot, but System/161 doesn't do that.) */ -void -mainbus_panic(void) -{ - mainbus_poweroff(); -} +void mainbus_panic(void) { mainbus_poweroff(); } /* * Function to get the size of installed physical RAM from the LAMEbus * controller. */ -uint32_t -mainbus_ramsize(void) -{ - uint32_t ramsize; +uint32_t mainbus_ramsize(void) { + uint32_t ramsize; - ramsize = lamebus_ramsize(); + ramsize = lamebus_ramsize(); - /* - * This is the same as the last physical address, as long as - * we have less than 508 megabytes of memory. The LAMEbus I/O - * area occupies the space between 508 megabytes and 512 - * megabytes, so if we had more RAM than this it would have to - * be discontiguous. This is not a case we are going to worry - * about. - */ - if (ramsize > 508*1024*1024) { - ramsize = 508*1024*1024; - } + /* + * This is the same as the last physical address, as long as + * we have less than 508 megabytes of memory. The LAMEbus I/O + * area occupies the space between 508 megabytes and 512 + * megabytes, so if we had more RAM than this it would have to + * be discontiguous. This is not a case we are going to worry + * about. + */ + if (ramsize > 508 * 1024 * 1024) { + ramsize = 508 * 1024 * 1024; + } - return ramsize; + return ramsize; } /* * Send IPI. */ -void -mainbus_send_ipi(struct cpu *target) -{ - lamebus_assert_ipi(lamebus, target); +void mainbus_send_ipi(struct cpu *target) { + lamebus_assert_ipi(lamebus, target); } /* * Trigger the debugger. */ -void -mainbus_debugger(void) -{ - ltrace_stop(0); -} +void mainbus_debugger(void) { ltrace_stop(0); } /* * Interrupt dispatcher. */ /* Wiring of LAMEbus interrupts to bits in the cause register */ -#define LAMEBUS_IRQ_BIT 0x00000400 /* all system bus slots */ -#define LAMEBUS_IPI_BIT 0x00000800 /* inter-processor interrupt */ -#define MIPS_TIMER_BIT 0x00008000 /* on-chip timer */ +#define LAMEBUS_IRQ_BIT 0x00000400 /* all system bus slots */ +#define LAMEBUS_IPI_BIT 0x00000800 /* inter-processor interrupt */ +#define MIPS_TIMER_BIT 0x00008000 /* on-chip timer */ -void -mainbus_interrupt(struct trapframe *tf) -{ - uint32_t cause; - bool seen = false; +void mainbus_interrupt(struct trapframe *tf) { + uint32_t cause; + bool seen = false; - /* interrupts should be off */ - KASSERT(curthread->t_curspl > 0); + /* interrupts should be off */ + KASSERT(curthread->t_curspl > 0); - cause = tf->tf_cause; - if (cause & LAMEBUS_IRQ_BIT) { - lamebus_interrupt(lamebus); - seen = true; - } - if (cause & LAMEBUS_IPI_BIT) { - interprocessor_interrupt(); - lamebus_clear_ipi(lamebus, curcpu); - seen = true; - } - if (cause & MIPS_TIMER_BIT) { - /* Reset the timer (this clears the interrupt) */ - mips_timer_set(CPU_FREQUENCY / HZ); - /* and call hardclock */ - hardclock(); - seen = true; - } + cause = tf->tf_cause; + if (cause & LAMEBUS_IRQ_BIT) { + lamebus_interrupt(lamebus); + seen = true; + } + if (cause & LAMEBUS_IPI_BIT) { + interprocessor_interrupt(); + lamebus_clear_ipi(lamebus, curcpu); + seen = true; + } + if (cause & MIPS_TIMER_BIT) { + /* Reset the timer (this clears the interrupt) */ + mips_timer_set(CPU_FREQUENCY / HZ); + /* and call hardclock */ + hardclock(); + seen = true; + } - if (!seen) { - if ((cause & CCA_IRQS) == 0) { - /* - * Don't panic here; this can happen if an - * interrupt line asserts (very) briefly and - * turns off again before we get as far as - * reading the cause register. This was - * actually seen... once. - */ - } - else { - /* - * But if we get an interrupt on an interrupt - * line that's not supposed to be wired up, - * complain. - */ - panic("Unknown interrupt; cause register is %08x\n", - cause); - } - } + if (!seen) { + if ((cause & CCA_IRQS) == 0) { + /* + * Don't panic here; this can happen if an + * interrupt line asserts (very) briefly and + * turns off again before we get as far as + * reading the cause register. This was + * actually seen... once. + */ + } else { + /* + * But if we get an interrupt on an interrupt + * line that's not supposed to be wired up, + * complain. + */ + panic("Unknown interrupt; cause register is %08x\n", cause); + } + } } diff --git a/kern/arch/sys161/include/bus.h b/kern/arch/sys161/include/bus.h index e0680b0..397a9a5 100644 --- a/kern/arch/sys161/include/bus.h +++ b/kern/arch/sys161/include/bus.h @@ -37,24 +37,22 @@ * This would need to be a bit more complicated if that weren't the case. */ -#include /* for MIPS_KSEG1 */ -#include /* for LAMEbus definitions */ +#include /* for MIPS_KSEG1 */ +#include /* for LAMEbus definitions */ -#define bus_write_register(bus, slot, offset, val) \ - lamebus_write_register(bus, slot, offset, val) +#define bus_write_register(bus, slot, offset, val) \ + lamebus_write_register(bus, slot, offset, val) -#define bus_read_register(bus, slot, offset) \ - lamebus_read_register(bus, slot, offset) +#define bus_read_register(bus, slot, offset) \ + lamebus_read_register(bus, slot, offset) -#define bus_map_area(bus, slot, offset) \ - lamebus_map_area(bus, slot, offset) +#define bus_map_area(bus, slot, offset) lamebus_map_area(bus, slot, offset) /* * Machine-dependent LAMEbus definitions */ /* Base address of the LAMEbus mapping area */ -#define LB_BASEADDR (MIPS_KSEG1 + 0x1fe00000) - +#define LB_BASEADDR (MIPS_KSEG1 + 0x1fe00000) #endif /* _SYS161_BUS_H_ */ diff --git a/kern/dev/generic/beep.c b/kern/dev/generic/beep.c index 38d7aa9..8021c5f 100644 --- a/kern/dev/generic/beep.c +++ b/kern/dev/generic/beep.c @@ -46,26 +46,21 @@ static struct beep_softc *the_beep = NULL; -int -config_beep(struct beep_softc *bs, int unit) -{ - /* We use only the first beep device. */ - if (unit!=0) { - return ENODEV; - } +int config_beep(struct beep_softc *bs, int unit) { + /* We use only the first beep device. */ + if (unit != 0) { + return ENODEV; + } - KASSERT(the_beep==NULL); - the_beep = bs; - return 0; + KASSERT(the_beep == NULL); + the_beep = bs; + return 0; } -void -beep(void) -{ - if (the_beep!=NULL) { - the_beep->bs_beep(the_beep->bs_devdata); - } - else { - kprintf("beep: Warning: no beep device\n"); - } +void beep(void) { + if (the_beep != NULL) { + the_beep->bs_beep(the_beep->bs_devdata); + } else { + kprintf("beep: Warning: no beep device\n"); + } } diff --git a/kern/dev/generic/beep.h b/kern/dev/generic/beep.h index eff3afa..e51195f 100644 --- a/kern/dev/generic/beep.h +++ b/kern/dev/generic/beep.h @@ -36,8 +36,8 @@ */ struct beep_softc { - void *bs_devdata; - void (*bs_beep)(void *devdata); + void *bs_devdata; + void (*bs_beep)(void *devdata); }; #endif /* _GENERIC_BEEP_H_ */ diff --git a/kern/dev/generic/console.c b/kern/dev/generic/console.c index ff0d771..aa0c147 100644 --- a/kern/dev/generic/console.c +++ b/kern/dev/generic/console.c @@ -79,32 +79,26 @@ static struct lock *con_userlock_write = NULL; * console is set up. Upon console setup they are dumped * to the actual console; thenceforth this space is unused. */ -#define DELAYBUFSIZE 1024 +#define DELAYBUFSIZE 1024 static char delayed_outbuf[DELAYBUFSIZE]; -static size_t delayed_outbuf_pos=0; +static size_t delayed_outbuf_pos = 0; -static -void -putch_delayed(int ch) -{ - /* - * No synchronization needed: called only during system startup - * by main thread. - */ +static void putch_delayed(int ch) { + /* + * No synchronization needed: called only during system startup + * by main thread. + */ - KASSERT(delayed_outbuf_pos < sizeof(delayed_outbuf)); - delayed_outbuf[delayed_outbuf_pos++] = ch; + KASSERT(delayed_outbuf_pos < sizeof(delayed_outbuf)); + delayed_outbuf[delayed_outbuf_pos++] = ch; } -static -void -flush_delay_buf(void) -{ - size_t i; - for (i=0; ics_sendpolled(cs->cs_devdata, ch); +static void putch_polled(struct con_softc *cs, int ch) { + cs->cs_sendpolled(cs->cs_devdata, ch); } ////////////////////////////////////////////////// @@ -125,28 +116,21 @@ putch_polled(struct con_softc *cs, int ch) /* * Print a character, using interrupts to wait for I/O completion. */ -static -void -putch_intr(struct con_softc *cs, int ch) -{ - P(cs->cs_wsem); - cs->cs_send(cs->cs_devdata, ch); +static void putch_intr(struct con_softc *cs, int ch) { + P(cs->cs_wsem); + cs->cs_send(cs->cs_devdata, ch); } /* * Read a character, using interrupts to wait for I/O completion. */ -static -int -getch_intr(struct con_softc *cs) -{ - unsigned char ret; +static int getch_intr(struct con_softc *cs) { + unsigned char ret; - P(cs->cs_rsem); - ret = cs->cs_gotchars[cs->cs_gotchars_tail]; - cs->cs_gotchars_tail = - (cs->cs_gotchars_tail + 1) % CONSOLE_INPUT_BUFFER_SIZE; - return ret; + P(cs->cs_rsem); + ret = cs->cs_gotchars[cs->cs_gotchars_tail]; + cs->cs_gotchars_tail = (cs->cs_gotchars_tail + 1) % CONSOLE_INPUT_BUFFER_SIZE; + return ret; } /* @@ -158,33 +142,29 @@ getch_intr(struct con_softc *cs) * too) would be with a second semaphore used with a nonblocking P, * but we don't have that in OS/161. */ -void -con_input(void *vcs, int ch) -{ - struct con_softc *cs = vcs; - unsigned nexthead; +void con_input(void *vcs, int ch) { + struct con_softc *cs = vcs; + unsigned nexthead; - nexthead = (cs->cs_gotchars_head + 1) % CONSOLE_INPUT_BUFFER_SIZE; - if (nexthead == cs->cs_gotchars_tail) { - /* overflow; drop character */ - return; - } + nexthead = (cs->cs_gotchars_head + 1) % CONSOLE_INPUT_BUFFER_SIZE; + if (nexthead == cs->cs_gotchars_tail) { + /* overflow; drop character */ + return; + } - cs->cs_gotchars[cs->cs_gotchars_head] = ch; - cs->cs_gotchars_head = nexthead; + cs->cs_gotchars[cs->cs_gotchars_head] = ch; + cs->cs_gotchars_head = nexthead; - V(cs->cs_rsem); + V(cs->cs_rsem); } /* * Called from underlying device when a write-done interrupt occurs. */ -void -con_start(void *vcs) -{ - struct con_softc *cs = vcs; +void con_start(void *vcs) { + struct con_softc *cs = vcs; - V(cs->cs_wsem); + V(cs->cs_wsem); } ////////////////////////////////////////////////// @@ -197,32 +177,25 @@ con_start(void *vcs) * not, and does not. */ -void -putch(int ch) -{ - struct con_softc *cs = the_console; +void putch(int ch) { + struct con_softc *cs = the_console; - if (cs==NULL) { - putch_delayed(ch); - } - else if (curthread->t_in_interrupt || - curthread->t_curspl > 0 || - curcpu->c_spinlocks > 0) { - putch_polled(cs, ch); - } - else { - putch_intr(cs, ch); - } + if (cs == NULL) { + putch_delayed(ch); + } else if (curthread->t_in_interrupt || curthread->t_curspl > 0 || + curcpu->c_spinlocks > 0) { + putch_polled(cs, ch); + } else { + putch_intr(cs, ch); + } } -int -getch(void) -{ - struct con_softc *cs = the_console; - KASSERT(cs != NULL); - KASSERT(!curthread->t_in_interrupt && curthread->t_iplhigh_count == 0); +int getch(void) { + struct con_softc *cs = the_console; + KASSERT(cs != NULL); + KASSERT(!curthread->t_in_interrupt && curthread->t_iplhigh_count == 0); - return getch_intr(cs); + return getch_intr(cs); } //////////////////////////////////////////////////////////// @@ -231,107 +204,93 @@ getch(void) * VFS interface functions */ -static -int -con_eachopen(struct device *dev, int openflags) -{ - (void)dev; - (void)openflags; - return 0; +static int con_eachopen(struct device *dev, int openflags) { + (void)dev; + (void)openflags; + return 0; } -static -int -con_io(struct device *dev, struct uio *uio) -{ - int result; - char ch; - struct lock *lk; +static int con_io(struct device *dev, struct uio *uio) { + int result; + char ch; + struct lock *lk; - (void)dev; // unused + (void)dev; // unused - if (uio->uio_rw==UIO_READ) { - lk = con_userlock_read; - } - else { - lk = con_userlock_write; - } + if (uio->uio_rw == UIO_READ) { + lk = con_userlock_read; + } else { + lk = con_userlock_write; + } - KASSERT(lk != NULL); - lock_acquire(lk); + KASSERT(lk != NULL); + lock_acquire(lk); - while (uio->uio_resid > 0) { - if (uio->uio_rw==UIO_READ) { - ch = getch(); - if (ch=='\r') { - ch = '\n'; - } - result = uiomove(&ch, 1, uio); - if (result) { - lock_release(lk); - return result; - } - if (ch=='\n') { - break; - } - } - else { - result = uiomove(&ch, 1, uio); - if (result) { - lock_release(lk); - return result; - } - if (ch=='\n') { - putch('\r'); - } - putch(ch); - } - } - lock_release(lk); - return 0; + while (uio->uio_resid > 0) { + if (uio->uio_rw == UIO_READ) { + ch = getch(); + if (ch == '\r') { + ch = '\n'; + } + result = uiomove(&ch, 1, uio); + if (result) { + lock_release(lk); + return result; + } + if (ch == '\n') { + break; + } + } else { + result = uiomove(&ch, 1, uio); + if (result) { + lock_release(lk); + return result; + } + if (ch == '\n') { + putch('\r'); + } + putch(ch); + } + } + lock_release(lk); + return 0; } -static -int -con_ioctl(struct device *dev, int op, userptr_t data) -{ - /* No ioctls. */ - (void)dev; - (void)op; - (void)data; - return EINVAL; +static int con_ioctl(struct device *dev, int op, userptr_t data) { + /* No ioctls. */ + (void)dev; + (void)op; + (void)data; + return EINVAL; } static const struct device_ops console_devops = { - .devop_eachopen = con_eachopen, - .devop_io = con_io, - .devop_ioctl = con_ioctl, + .devop_eachopen = con_eachopen, + .devop_io = con_io, + .devop_ioctl = con_ioctl, }; -static -int -attach_console_to_vfs(struct con_softc *cs) -{ - struct device *dev; - int result; +static int attach_console_to_vfs(struct con_softc *cs) { + struct device *dev; + int result; - dev = kmalloc(sizeof(*dev)); - if (dev==NULL) { - return ENOMEM; - } + dev = kmalloc(sizeof(*dev)); + if (dev == NULL) { + return ENOMEM; + } - dev->d_ops = &console_devops; - dev->d_blocks = 0; - dev->d_blocksize = 1; - dev->d_data = cs; + dev->d_ops = &console_devops; + dev->d_blocks = 0; + dev->d_blocksize = 1; + dev->d_data = cs; - result = vfs_adddev("con", dev, 0); - if (result) { - kfree(dev); - return result; - } + result = vfs_adddev("con", dev, 0); + if (result) { + kfree(dev); + return result; + } - return 0; + return 0; } //////////////////////////////////////////////////////////// @@ -340,58 +299,56 @@ attach_console_to_vfs(struct con_softc *cs) * Config routine called by autoconf.c after we are attached to something. */ -int -config_con(struct con_softc *cs, int unit) -{ - struct semaphore *rsem, *wsem; - struct lock *rlk, *wlk; +int config_con(struct con_softc *cs, int unit) { + struct semaphore *rsem, *wsem; + struct lock *rlk, *wlk; - /* - * Only allow one system console. - * Further devices that could be the system console are ignored. - * - * Do not hardwire the console to be "con1" instead of "con0", - * or these asserts will go off. - */ - if (unit>0) { - KASSERT(the_console!=NULL); - return ENODEV; - } - KASSERT(the_console==NULL); + /* + * Only allow one system console. + * Further devices that could be the system console are ignored. + * + * Do not hardwire the console to be "con1" instead of "con0", + * or these asserts will go off. + */ + if (unit > 0) { + KASSERT(the_console != NULL); + return ENODEV; + } + KASSERT(the_console == NULL); - rsem = sem_create("console read", 0); - if (rsem == NULL) { - return ENOMEM; - } - wsem = sem_create("console write", 1); - if (wsem == NULL) { - sem_destroy(rsem); - return ENOMEM; - } - rlk = lock_create("console-lock-read"); - if (rlk == NULL) { - sem_destroy(rsem); - sem_destroy(wsem); - return ENOMEM; - } - wlk = lock_create("console-lock-write"); - if (wlk == NULL) { - lock_destroy(rlk); - sem_destroy(rsem); - sem_destroy(wsem); - return ENOMEM; - } + rsem = sem_create("console read", 0); + if (rsem == NULL) { + return ENOMEM; + } + wsem = sem_create("console write", 1); + if (wsem == NULL) { + sem_destroy(rsem); + return ENOMEM; + } + rlk = lock_create("console-lock-read"); + if (rlk == NULL) { + sem_destroy(rsem); + sem_destroy(wsem); + return ENOMEM; + } + wlk = lock_create("console-lock-write"); + if (wlk == NULL) { + lock_destroy(rlk); + sem_destroy(rsem); + sem_destroy(wsem); + return ENOMEM; + } - cs->cs_rsem = rsem; - cs->cs_wsem = wsem; - cs->cs_gotchars_head = 0; - cs->cs_gotchars_tail = 0; + cs->cs_rsem = rsem; + cs->cs_wsem = wsem; + cs->cs_gotchars_head = 0; + cs->cs_gotchars_tail = 0; - the_console = cs; - con_userlock_read = rlk; - con_userlock_write = wlk; + the_console = cs; + con_userlock_read = rlk; + con_userlock_write = wlk; - flush_delay_buf(); + flush_delay_buf(); - return attach_console_to_vfs(cs); + return attach_console_to_vfs(cs); } diff --git a/kern/dev/generic/console.h b/kern/dev/generic/console.h index 0d7f4bd..56c995d 100644 --- a/kern/dev/generic/console.h +++ b/kern/dev/generic/console.h @@ -40,17 +40,17 @@ #define CONSOLE_INPUT_BUFFER_SIZE 32 struct con_softc { - /* initialized by attach routine */ - void *cs_devdata; - void (*cs_send)(void *devdata, int ch); - void (*cs_sendpolled)(void *devdata, int ch); + /* initialized by attach routine */ + void *cs_devdata; + void (*cs_send)(void *devdata, int ch); + void (*cs_sendpolled)(void *devdata, int ch); - /* initialized by config routine */ - struct semaphore *cs_rsem; - struct semaphore *cs_wsem; - unsigned char cs_gotchars[CONSOLE_INPUT_BUFFER_SIZE]; - unsigned cs_gotchars_head; /* next slot to put a char in */ - unsigned cs_gotchars_tail; /* next slot to take a char out */ + /* initialized by config routine */ + struct semaphore *cs_rsem; + struct semaphore *cs_wsem; + unsigned char cs_gotchars[CONSOLE_INPUT_BUFFER_SIZE]; + unsigned cs_gotchars_head; /* next slot to put a char in */ + unsigned cs_gotchars_tail; /* next slot to take a char out */ }; /* diff --git a/kern/dev/generic/random.c b/kern/dev/generic/random.c index 3caf8c0..83c6c7d 100644 --- a/kern/dev/generic/random.c +++ b/kern/dev/generic/random.c @@ -53,106 +53,90 @@ static struct random_softc *the_random = NULL; * VFS device functions. * open: allow reading only. */ -static -int -randeachopen(struct device *dev, int openflags) -{ - (void)dev; +static int randeachopen(struct device *dev, int openflags) { + (void)dev; - if (openflags != O_RDONLY) { - return EIO; - } + if (openflags != O_RDONLY) { + return EIO; + } - return 0; + return 0; } /* * VFS I/O function. Hand off to implementation. */ -static -int -randio(struct device *dev, struct uio *uio) -{ - struct random_softc *rs = dev->d_data; +static int randio(struct device *dev, struct uio *uio) { + struct random_softc *rs = dev->d_data; - if (uio->uio_rw != UIO_READ) { - return EIO; - } + if (uio->uio_rw != UIO_READ) { + return EIO; + } - return rs->rs_read(rs->rs_devdata, uio); + return rs->rs_read(rs->rs_devdata, uio); } /* * VFS ioctl function. */ -static -int -randioctl(struct device *dev, int op, userptr_t data) -{ - /* - * We don't support any ioctls. - */ - (void)dev; - (void)op; - (void)data; - return EIOCTL; +static int randioctl(struct device *dev, int op, userptr_t data) { + /* + * We don't support any ioctls. + */ + (void)dev; + (void)op; + (void)data; + return EIOCTL; } static const struct device_ops random_devops = { - .devop_eachopen = randeachopen, - .devop_io = randio, - .devop_ioctl = randioctl, + .devop_eachopen = randeachopen, + .devop_io = randio, + .devop_ioctl = randioctl, }; /* * Config function. */ -int -config_random(struct random_softc *rs, int unit) -{ - int result; +int config_random(struct random_softc *rs, int unit) { + int result; - /* We use only the first random device. */ - if (unit!=0) { - return ENODEV; - } + /* We use only the first random device. */ + if (unit != 0) { + return ENODEV; + } - KASSERT(the_random==NULL); - the_random = rs; + KASSERT(the_random == NULL); + the_random = rs; - rs->rs_dev.d_ops = &random_devops; - rs->rs_dev.d_blocks = 0; - rs->rs_dev.d_blocksize = 1; - rs->rs_dev.d_data = rs; + rs->rs_dev.d_ops = &random_devops; + rs->rs_dev.d_blocks = 0; + rs->rs_dev.d_blocksize = 1; + rs->rs_dev.d_data = rs; - /* Add the VFS device structure to the VFS device list. */ - result = vfs_adddev("random", &rs->rs_dev, 0); - if (result) { - return result; - } + /* Add the VFS device structure to the VFS device list. */ + result = vfs_adddev("random", &rs->rs_dev, 0); + if (result) { + return result; + } - return 0; + return 0; } - /* * Random number functions exported to the rest of the kernel. */ -uint32_t -random(void) -{ - if (the_random==NULL) { - panic("No random device\n"); - } - return the_random->rs_random(the_random->rs_devdata); +uint32_t random(void) { + if (the_random == NULL) { + panic("No random device\n"); + } + return the_random->rs_random(the_random->rs_devdata); } -uint32_t -randmax(void) -{ - if (the_random==NULL) { - panic("No random device\n"); - } - return the_random->rs_randmax(the_random->rs_devdata); +uint32_t randmax(void) { + if (the_random == NULL) { + panic("No random device\n"); + } + return the_random->rs_randmax(the_random->rs_devdata); } diff --git a/kern/dev/generic/random.h b/kern/dev/generic/random.h index d23336c..0c0c876 100644 --- a/kern/dev/generic/random.h +++ b/kern/dev/generic/random.h @@ -34,13 +34,13 @@ struct uio; struct random_softc { - /* Initialized by lower-level attach routine */ - void *rs_devdata; - uint32_t (*rs_random)(void *devdata); - uint32_t (*rs_randmax)(void *devdata); - int (*rs_read)(void *devdata, struct uio *uio); + /* Initialized by lower-level attach routine */ + void *rs_devdata; + uint32_t (*rs_random)(void *devdata); + uint32_t (*rs_randmax)(void *devdata); + int (*rs_read)(void *devdata, struct uio *uio); - struct device rs_dev; + struct device rs_dev; }; #endif /* _GENERIC_RANDOM_H_ */ diff --git a/kern/dev/generic/rtclock.c b/kern/dev/generic/rtclock.c index ab1cd68..8ff799d 100644 --- a/kern/dev/generic/rtclock.c +++ b/kern/dev/generic/rtclock.c @@ -49,22 +49,18 @@ static struct rtclock_softc *the_clock = NULL; -int -config_rtclock(struct rtclock_softc *rtc, int unit) -{ - /* We use only the first clock device. */ - if (unit!=0) { - return ENODEV; - } +int config_rtclock(struct rtclock_softc *rtc, int unit) { + /* We use only the first clock device. */ + if (unit != 0) { + return ENODEV; + } - KASSERT(the_clock==NULL); - the_clock = rtc; - return 0; + KASSERT(the_clock == NULL); + the_clock = rtc; + return 0; } -void -gettime(struct timespec *ts) -{ - KASSERT(the_clock!=NULL); - the_clock->rtc_gettime(the_clock->rtc_devdata, ts); +void gettime(struct timespec *ts) { + KASSERT(the_clock != NULL); + the_clock->rtc_gettime(the_clock->rtc_devdata, ts); } diff --git a/kern/dev/generic/rtclock.h b/kern/dev/generic/rtclock.h index 98fc63a..51b79d1 100644 --- a/kern/dev/generic/rtclock.h +++ b/kern/dev/generic/rtclock.h @@ -38,8 +38,8 @@ struct timespec; struct rtclock_softc { - void *rtc_devdata; - void (*rtc_gettime)(void *devdata, struct timespec *); + void *rtc_devdata; + void (*rtc_gettime)(void *devdata, struct timespec *); }; #endif /* _GENERIC_RTCLOCK_H_ */ diff --git a/kern/dev/lamebus/beep_ltimer.c b/kern/dev/lamebus/beep_ltimer.c index 5115d30..d48c049 100644 --- a/kern/dev/lamebus/beep_ltimer.c +++ b/kern/dev/lamebus/beep_ltimer.c @@ -38,18 +38,16 @@ #include #include "autoconf.h" -struct beep_softc * -attach_beep_to_ltimer(int beepno, struct ltimer_softc *ls) -{ - struct beep_softc *bs = kmalloc(sizeof(struct beep_softc)); - if (bs==NULL) { - return NULL; - } +struct beep_softc *attach_beep_to_ltimer(int beepno, struct ltimer_softc *ls) { + struct beep_softc *bs = kmalloc(sizeof(struct beep_softc)); + if (bs == NULL) { + return NULL; + } - (void)beepno; // unused + (void)beepno; // unused - bs->bs_devdata = ls; - bs->bs_beep = ltimer_beep; + bs->bs_devdata = ls; + bs->bs_beep = ltimer_beep; - return bs; + return bs; } diff --git a/kern/dev/lamebus/con_lscreen.c b/kern/dev/lamebus/con_lscreen.c index e3bc68e..065ae9c 100644 --- a/kern/dev/lamebus/con_lscreen.c +++ b/kern/dev/lamebus/con_lscreen.c @@ -38,22 +38,19 @@ #include #include "autoconf.h" -struct con_softc * -attach_con_to_lscreen(int consno, struct lscreen_softc *ls) -{ - struct con_softc *cs = kmalloc(sizeof(struct con_softc)); - if (cs==NULL) { - return NULL; - } +struct con_softc *attach_con_to_lscreen(int consno, struct lscreen_softc *ls) { + struct con_softc *cs = kmalloc(sizeof(struct con_softc)); + if (cs == NULL) { + return NULL; + } - cs->cs_devdata = ls; - cs->cs_send = lscreen_write; - cs->cs_sendpolled = lscreen_write; + cs->cs_devdata = ls; + cs->cs_send = lscreen_write; + cs->cs_sendpolled = lscreen_write; - ls->ls_devdata = cs; - ls->ls_start = con_start; - ls->ls_input = con_input; + ls->ls_devdata = cs; + ls->ls_start = con_start; + ls->ls_input = con_input; - return cs; + return cs; } - diff --git a/kern/dev/lamebus/con_lser.c b/kern/dev/lamebus/con_lser.c index c5fdb7a..23ecadc 100644 --- a/kern/dev/lamebus/con_lser.c +++ b/kern/dev/lamebus/con_lser.c @@ -38,24 +38,21 @@ #include #include "autoconf.h" -struct con_softc * -attach_con_to_lser(int consno, struct lser_softc *ls) -{ - struct con_softc *cs = kmalloc(sizeof(struct con_softc)); - if (cs==NULL) { - return NULL; - } +struct con_softc *attach_con_to_lser(int consno, struct lser_softc *ls) { + struct con_softc *cs = kmalloc(sizeof(struct con_softc)); + if (cs == NULL) { + return NULL; + } - (void)consno; // unused + (void)consno; // unused - cs->cs_devdata = ls; - cs->cs_send = lser_write; - cs->cs_sendpolled = lser_writepolled; + cs->cs_devdata = ls; + cs->cs_send = lser_write; + cs->cs_sendpolled = lser_writepolled; - ls->ls_devdata = cs; - ls->ls_start = con_start; - ls->ls_input = con_input; + ls->ls_devdata = cs; + ls->ls_start = con_start; + ls->ls_input = con_input; - return cs; + return cs; } - diff --git a/kern/dev/lamebus/emu.c b/kern/dev/lamebus/emu.c index 676fb6f..e5026b8 100644 --- a/kern/dev/lamebus/emu.c +++ b/kern/dev/lamebus/emu.c @@ -56,40 +56,40 @@ #include "autoconf.h" /* Register offsets */ -#define REG_HANDLE 0 -#define REG_OFFSET 4 -#define REG_IOLEN 8 -#define REG_OPER 12 -#define REG_RESULT 16 +#define REG_HANDLE 0 +#define REG_OFFSET 4 +#define REG_IOLEN 8 +#define REG_OPER 12 +#define REG_RESULT 16 /* I/O buffer offset */ -#define EMU_BUFFER 32768 +#define EMU_BUFFER 32768 /* Operation codes for REG_OPER */ -#define EMU_OP_OPEN 1 -#define EMU_OP_CREATE 2 -#define EMU_OP_EXCLCREATE 3 -#define EMU_OP_CLOSE 4 -#define EMU_OP_READ 5 -#define EMU_OP_READDIR 6 -#define EMU_OP_WRITE 7 -#define EMU_OP_GETSIZE 8 -#define EMU_OP_TRUNC 9 +#define EMU_OP_OPEN 1 +#define EMU_OP_CREATE 2 +#define EMU_OP_EXCLCREATE 3 +#define EMU_OP_CLOSE 4 +#define EMU_OP_READ 5 +#define EMU_OP_READDIR 6 +#define EMU_OP_WRITE 7 +#define EMU_OP_GETSIZE 8 +#define EMU_OP_TRUNC 9 /* Result codes for REG_RESULT */ -#define EMU_RES_SUCCESS 1 -#define EMU_RES_BADHANDLE 2 -#define EMU_RES_BADOP 3 -#define EMU_RES_BADPATH 4 -#define EMU_RES_BADSIZE 5 -#define EMU_RES_EXISTS 6 -#define EMU_RES_ISDIR 7 -#define EMU_RES_MEDIA 8 -#define EMU_RES_NOHANDLES 9 -#define EMU_RES_NOSPACE 10 -#define EMU_RES_NOTDIR 11 -#define EMU_RES_UNKNOWN 12 -#define EMU_RES_UNSUPP 13 +#define EMU_RES_SUCCESS 1 +#define EMU_RES_BADHANDLE 2 +#define EMU_RES_BADOP 3 +#define EMU_RES_BADPATH 4 +#define EMU_RES_BADSIZE 5 +#define EMU_RES_EXISTS 6 +#define EMU_RES_ISDIR 7 +#define EMU_RES_MEDIA 8 +#define EMU_RES_NOHANDLES 9 +#define EMU_RES_NOSPACE 10 +#define EMU_RES_NOTDIR 11 +#define EMU_RES_UNKNOWN 12 +#define EMU_RES_UNSUPP 13 //////////////////////////////////////////////////////////// // @@ -99,76 +99,70 @@ /* * Shortcut for reading a register */ -static -inline -uint32_t -emu_rreg(struct emu_softc *sc, uint32_t reg) -{ - return bus_read_register(sc->e_busdata, sc->e_buspos, reg); +static inline uint32_t emu_rreg(struct emu_softc *sc, uint32_t reg) { + return bus_read_register(sc->e_busdata, sc->e_buspos, reg); } /* * Shortcut for writing a register */ -static -inline -void -emu_wreg(struct emu_softc *sc, uint32_t reg, uint32_t val) -{ - bus_write_register(sc->e_busdata, sc->e_buspos, reg, val); +static inline void emu_wreg(struct emu_softc *sc, uint32_t reg, uint32_t val) { + bus_write_register(sc->e_busdata, sc->e_buspos, reg, val); } /* * Called by the underlying bus code when an interrupt happens */ -void -emu_irq(void *dev) -{ - struct emu_softc *sc = dev; +void emu_irq(void *dev) { + struct emu_softc *sc = dev; - sc->e_result = emu_rreg(sc, REG_RESULT); - emu_wreg(sc, REG_RESULT, 0); + sc->e_result = emu_rreg(sc, REG_RESULT); + emu_wreg(sc, REG_RESULT, 0); - V(sc->e_sem); + V(sc->e_sem); } /* * Convert the error codes reported by the "hardware" to errnos. * Or, on cases that indicate a programming error in emu.c, panic. */ -static -uint32_t -translate_err(struct emu_softc *sc, uint32_t code) -{ - switch (code) { - case EMU_RES_SUCCESS: return 0; - case EMU_RES_BADHANDLE: - case EMU_RES_BADOP: - case EMU_RES_BADSIZE: - panic("emu%d: got fatal result code %d\n", sc->e_unit, code); - case EMU_RES_BADPATH: return ENOENT; - case EMU_RES_EXISTS: return EEXIST; - case EMU_RES_ISDIR: return EISDIR; - case EMU_RES_MEDIA: return EIO; - case EMU_RES_NOHANDLES: return ENFILE; - case EMU_RES_NOSPACE: return ENOSPC; - case EMU_RES_NOTDIR: return ENOTDIR; - case EMU_RES_UNKNOWN: return EIO; - case EMU_RES_UNSUPP: return ENOSYS; - } - kprintf("emu%d: Unknown result code %d\n", sc->e_unit, code); - return EAGAIN; +static uint32_t translate_err(struct emu_softc *sc, uint32_t code) { + switch (code) { + case EMU_RES_SUCCESS: + return 0; + case EMU_RES_BADHANDLE: + case EMU_RES_BADOP: + case EMU_RES_BADSIZE: + panic("emu%d: got fatal result code %d\n", sc->e_unit, code); + case EMU_RES_BADPATH: + return ENOENT; + case EMU_RES_EXISTS: + return EEXIST; + case EMU_RES_ISDIR: + return EISDIR; + case EMU_RES_MEDIA: + return EIO; + case EMU_RES_NOHANDLES: + return ENFILE; + case EMU_RES_NOSPACE: + return ENOSPC; + case EMU_RES_NOTDIR: + return ENOTDIR; + case EMU_RES_UNKNOWN: + return EIO; + case EMU_RES_UNSUPP: + return ENOSYS; + } + kprintf("emu%d: Unknown result code %d\n", sc->e_unit, code); + return EAGAIN; } /* * Wait for an operation to complete, and return an errno for the result. */ -static -int -emu_waitdone(struct emu_softc *sc) -{ - P(sc->e_sem); - return translate_err(sc, sc->e_result); +static int emu_waitdone(struct emu_softc *sc) { + P(sc->e_sem); + return translate_err(sc, sc->e_result); } /* @@ -177,48 +171,43 @@ emu_waitdone(struct emu_softc *sc) * order to look at them, so by the time VOP_EACHOPEN is called the * files are already open. */ -static -int -emu_open(struct emu_softc *sc, uint32_t handle, const char *name, - bool create, bool excl, mode_t mode, - uint32_t *newhandle, int *newisdir) -{ - uint32_t op; - int result; +static int emu_open(struct emu_softc *sc, uint32_t handle, const char *name, + bool create, bool excl, mode_t mode, uint32_t *newhandle, + int *newisdir) { + uint32_t op; + int result; - if (strlen(name)+1 > EMU_MAXIO) { - return ENAMETOOLONG; - } + if (strlen(name) + 1 > EMU_MAXIO) { + return ENAMETOOLONG; + } - if (create && excl) { - op = EMU_OP_EXCLCREATE; - } - else if (create) { - op = EMU_OP_CREATE; - } - else { - op = EMU_OP_OPEN; - } + if (create && excl) { + op = EMU_OP_EXCLCREATE; + } else if (create) { + op = EMU_OP_CREATE; + } else { + op = EMU_OP_OPEN; + } - /* mode isn't supported (yet?) */ - (void)mode; + /* mode isn't supported (yet?) */ + (void)mode; - lock_acquire(sc->e_lock); + lock_acquire(sc->e_lock); - strcpy(sc->e_iobuf, name); - membar_store_store(); - emu_wreg(sc, REG_IOLEN, strlen(name)); - emu_wreg(sc, REG_HANDLE, handle); - emu_wreg(sc, REG_OPER, op); - result = emu_waitdone(sc); + strcpy(sc->e_iobuf, name); + membar_store_store(); + emu_wreg(sc, REG_IOLEN, strlen(name)); + emu_wreg(sc, REG_HANDLE, handle); + emu_wreg(sc, REG_OPER, op); + result = emu_waitdone(sc); - if (result==0) { - *newhandle = emu_rreg(sc, REG_HANDLE); - *newisdir = emu_rreg(sc, REG_IOLEN)>0; - } + if (result == 0) { + *newhandle = emu_rreg(sc, REG_HANDLE); + *newisdir = emu_rreg(sc, REG_IOLEN) > 0; + } - lock_release(sc->e_lock); - return result; + lock_release(sc->e_lock); + return result; } /* @@ -226,179 +215,157 @@ emu_open(struct emu_softc *sc, uint32_t handle, const char *name, * This is not necessarily called at VOP_LASTCLOSE time; it's called * at VOP_RECLAIM time. */ -static -int -emu_close(struct emu_softc *sc, uint32_t handle) -{ - int result; - bool mine; - int retries = 0; +static int emu_close(struct emu_softc *sc, uint32_t handle) { + int result; + bool mine; + int retries = 0; - mine = lock_do_i_hold(sc->e_lock); - if (!mine) { - lock_acquire(sc->e_lock); - } + mine = lock_do_i_hold(sc->e_lock); + if (!mine) { + lock_acquire(sc->e_lock); + } - while (1) { - /* Retry operation up to 10 times */ + while (1) { + /* Retry operation up to 10 times */ - emu_wreg(sc, REG_HANDLE, handle); - emu_wreg(sc, REG_OPER, EMU_OP_CLOSE); - result = emu_waitdone(sc); + emu_wreg(sc, REG_HANDLE, handle); + emu_wreg(sc, REG_OPER, EMU_OP_CLOSE); + result = emu_waitdone(sc); - if (result==EIO && retries < 10) { - kprintf("emu%d: I/O error on close, retrying\n", - sc->e_unit); - retries++; - continue; - } - break; - } + if (result == EIO && retries < 10) { + kprintf("emu%d: I/O error on close, retrying\n", sc->e_unit); + retries++; + continue; + } + break; + } - if (!mine) { - lock_release(sc->e_lock); - } - return result; + if (!mine) { + lock_release(sc->e_lock); + } + return result; } /* * Common code for read and readdir. */ -static -int -emu_doread(struct emu_softc *sc, uint32_t handle, uint32_t len, - uint32_t op, struct uio *uio) -{ - int result; +static int emu_doread(struct emu_softc *sc, uint32_t handle, uint32_t len, + uint32_t op, struct uio *uio) { + int result; - KASSERT(uio->uio_rw == UIO_READ); + KASSERT(uio->uio_rw == UIO_READ); - if (uio->uio_offset > (off_t)0xffffffff) { - /* beyond the largest size the file can have; generate EOF */ - return 0; - } + if (uio->uio_offset > (off_t)0xffffffff) { + /* beyond the largest size the file can have; generate EOF */ + return 0; + } - lock_acquire(sc->e_lock); + lock_acquire(sc->e_lock); - emu_wreg(sc, REG_HANDLE, handle); - emu_wreg(sc, REG_IOLEN, len); - emu_wreg(sc, REG_OFFSET, uio->uio_offset); - emu_wreg(sc, REG_OPER, op); - result = emu_waitdone(sc); - if (result) { - goto out; - } + emu_wreg(sc, REG_HANDLE, handle); + emu_wreg(sc, REG_IOLEN, len); + emu_wreg(sc, REG_OFFSET, uio->uio_offset); + emu_wreg(sc, REG_OPER, op); + result = emu_waitdone(sc); + if (result) { + goto out; + } - membar_load_load(); - result = uiomove(sc->e_iobuf, emu_rreg(sc, REG_IOLEN), uio); + membar_load_load(); + result = uiomove(sc->e_iobuf, emu_rreg(sc, REG_IOLEN), uio); - uio->uio_offset = emu_rreg(sc, REG_OFFSET); + uio->uio_offset = emu_rreg(sc, REG_OFFSET); - out: - lock_release(sc->e_lock); - return result; +out: + lock_release(sc->e_lock); + return result; } /* * Read from a hardware-level file handle. */ -static -int -emu_read(struct emu_softc *sc, uint32_t handle, uint32_t len, - struct uio *uio) -{ - return emu_doread(sc, handle, len, EMU_OP_READ, uio); +static int emu_read(struct emu_softc *sc, uint32_t handle, uint32_t len, + struct uio *uio) { + return emu_doread(sc, handle, len, EMU_OP_READ, uio); } /* * Read a directory entry from a hardware-level file handle. */ -static -int -emu_readdir(struct emu_softc *sc, uint32_t handle, uint32_t len, - struct uio *uio) -{ - return emu_doread(sc, handle, len, EMU_OP_READDIR, uio); +static int emu_readdir(struct emu_softc *sc, uint32_t handle, uint32_t len, + struct uio *uio) { + return emu_doread(sc, handle, len, EMU_OP_READDIR, uio); } /* * Write to a hardware-level file handle. */ -static -int -emu_write(struct emu_softc *sc, uint32_t handle, uint32_t len, - struct uio *uio) -{ - int result; +static int emu_write(struct emu_softc *sc, uint32_t handle, uint32_t len, + struct uio *uio) { + int result; - KASSERT(uio->uio_rw == UIO_WRITE); + KASSERT(uio->uio_rw == UIO_WRITE); - if (uio->uio_offset > (off_t)0xffffffff) { - return EFBIG; - } + if (uio->uio_offset > (off_t)0xffffffff) { + return EFBIG; + } - lock_acquire(sc->e_lock); + lock_acquire(sc->e_lock); - emu_wreg(sc, REG_HANDLE, handle); - emu_wreg(sc, REG_IOLEN, len); - emu_wreg(sc, REG_OFFSET, uio->uio_offset); + emu_wreg(sc, REG_HANDLE, handle); + emu_wreg(sc, REG_IOLEN, len); + emu_wreg(sc, REG_OFFSET, uio->uio_offset); - result = uiomove(sc->e_iobuf, len, uio); - membar_store_store(); - if (result) { - goto out; - } + result = uiomove(sc->e_iobuf, len, uio); + membar_store_store(); + if (result) { + goto out; + } - emu_wreg(sc, REG_OPER, EMU_OP_WRITE); - result = emu_waitdone(sc); + emu_wreg(sc, REG_OPER, EMU_OP_WRITE); + result = emu_waitdone(sc); - out: - lock_release(sc->e_lock); - return result; +out: + lock_release(sc->e_lock); + return result; } /* * Get the file size associated with a hardware-level file handle. */ -static -int -emu_getsize(struct emu_softc *sc, uint32_t handle, off_t *retval) -{ - int result; +static int emu_getsize(struct emu_softc *sc, uint32_t handle, off_t *retval) { + int result; - lock_acquire(sc->e_lock); + lock_acquire(sc->e_lock); - emu_wreg(sc, REG_HANDLE, handle); - emu_wreg(sc, REG_OPER, EMU_OP_GETSIZE); - result = emu_waitdone(sc); - if (result==0) { - *retval = emu_rreg(sc, REG_IOLEN); - } + emu_wreg(sc, REG_HANDLE, handle); + emu_wreg(sc, REG_OPER, EMU_OP_GETSIZE); + result = emu_waitdone(sc); + if (result == 0) { + *retval = emu_rreg(sc, REG_IOLEN); + } - lock_release(sc->e_lock); - return result; + lock_release(sc->e_lock); + return result; } /* * Truncate a hardware-level file handle. */ -static -int -emu_trunc(struct emu_softc *sc, uint32_t handle, off_t len) -{ - int result; +static int emu_trunc(struct emu_softc *sc, uint32_t handle, off_t len) { + int result; - KASSERT(len >= 0); + KASSERT(len >= 0); - lock_acquire(sc->e_lock); + lock_acquire(sc->e_lock); - emu_wreg(sc, REG_HANDLE, handle); - emu_wreg(sc, REG_IOLEN, len); - emu_wreg(sc, REG_OPER, EMU_OP_TRUNC); - result = emu_waitdone(sc); + emu_wreg(sc, REG_HANDLE, handle); + emu_wreg(sc, REG_IOLEN, len); + emu_wreg(sc, REG_OPER, EMU_OP_TRUNC); + result = emu_waitdone(sc); - lock_release(sc->e_lock); - return result; + lock_release(sc->e_lock); + return result; } // @@ -412,50 +379,44 @@ emu_trunc(struct emu_softc *sc, uint32_t handle, off_t len) // at bottom of this section static int emufs_loadvnode(struct emufs_fs *ef, uint32_t handle, int isdir, - struct emufs_vnode **ret); + struct emufs_vnode **ret); /* * VOP_EACHOPEN on files */ -static -int -emufs_eachopen(struct vnode *v, int openflags) -{ - /* - * At this level we do not need to handle O_CREAT, O_EXCL, - * O_TRUNC, or O_APPEND. - * - * Any of O_RDONLY, O_WRONLY, and O_RDWR are valid, so we don't need - * to check that either. - */ +static int emufs_eachopen(struct vnode *v, int openflags) { + /* + * At this level we do not need to handle O_CREAT, O_EXCL, + * O_TRUNC, or O_APPEND. + * + * Any of O_RDONLY, O_WRONLY, and O_RDWR are valid, so we don't need + * to check that either. + */ - (void)v; - (void)openflags; + (void)v; + (void)openflags; - return 0; + return 0; } /* * VOP_EACHOPEN on directories */ -static -int -emufs_eachopendir(struct vnode *v, int openflags) -{ - switch (openflags & O_ACCMODE) { - case O_RDONLY: - break; - case O_WRONLY: - case O_RDWR: - default: - return EISDIR; - } - if (openflags & O_APPEND) { - return EISDIR; - } +static int emufs_eachopendir(struct vnode *v, int openflags) { + switch (openflags & O_ACCMODE) { + case O_RDONLY: + break; + case O_WRONLY: + case O_RDWR: + default: + return EISDIR; + } + if (openflags & O_APPEND) { + return EISDIR; + } - (void)v; - return 0; + (void)v; + return 0; } /* @@ -463,395 +424,347 @@ emufs_eachopendir(struct vnode *v, int openflags) * * Reclaim should make an effort to returning errors other than EBUSY. */ -static -int -emufs_reclaim(struct vnode *v) -{ - struct emufs_vnode *ev = v->vn_data; - struct emufs_fs *ef = v->vn_fs->fs_data; - unsigned ix, i, num; - int result; +static int emufs_reclaim(struct vnode *v) { + struct emufs_vnode *ev = v->vn_data; + struct emufs_fs *ef = v->vn_fs->fs_data; + unsigned ix, i, num; + int result; - /* - * Need all of these locks, e_lock to protect the device, - * vfs_biglock to protect the fs-related material, and - * vn_countlock for the reference count. - */ + /* + * Need all of these locks, e_lock to protect the device, + * vfs_biglock to protect the fs-related material, and + * vn_countlock for the reference count. + */ - vfs_biglock_acquire(); - lock_acquire(ef->ef_emu->e_lock); - spinlock_acquire(&ev->ev_v.vn_countlock); + vfs_biglock_acquire(); + lock_acquire(ef->ef_emu->e_lock); + spinlock_acquire(&ev->ev_v.vn_countlock); - if (ev->ev_v.vn_refcount > 1) { - /* consume the reference VOP_DECREF passed us */ - ev->ev_v.vn_refcount--; + if (ev->ev_v.vn_refcount > 1) { + /* consume the reference VOP_DECREF passed us */ + ev->ev_v.vn_refcount--; - spinlock_release(&ev->ev_v.vn_countlock); - lock_release(ef->ef_emu->e_lock); - vfs_biglock_release(); - return EBUSY; - } - KASSERT(ev->ev_v.vn_refcount == 1); + spinlock_release(&ev->ev_v.vn_countlock); + lock_release(ef->ef_emu->e_lock); + vfs_biglock_release(); + return EBUSY; + } + KASSERT(ev->ev_v.vn_refcount == 1); - /* - * Since we hold e_lock and are the last ref, nobody can increment - * the refcount, so we can release vn_countlock. - */ - spinlock_release(&ev->ev_v.vn_countlock); + /* + * Since we hold e_lock and are the last ref, nobody can increment + * the refcount, so we can release vn_countlock. + */ + spinlock_release(&ev->ev_v.vn_countlock); - /* emu_close retries on I/O error */ - result = emu_close(ev->ev_emu, ev->ev_handle); - if (result) { - lock_release(ef->ef_emu->e_lock); - vfs_biglock_release(); - return result; - } + /* emu_close retries on I/O error */ + result = emu_close(ev->ev_emu, ev->ev_handle); + if (result) { + lock_release(ef->ef_emu->e_lock); + vfs_biglock_release(); + return result; + } - num = vnodearray_num(ef->ef_vnodes); - ix = num; - for (i=0; ief_vnodes); + ix = num; + for (i = 0; i < num; i++) { + struct vnode *vx; - vx = vnodearray_get(ef->ef_vnodes, i); - if (vx == v) { - ix = i; - break; - } - } - if (ix == num) { - panic("emu%d: reclaim vnode %u not in vnode pool\n", - ef->ef_emu->e_unit, ev->ev_handle); - } + vx = vnodearray_get(ef->ef_vnodes, i); + if (vx == v) { + ix = i; + break; + } + } + if (ix == num) { + panic("emu%d: reclaim vnode %u not in vnode pool\n", ef->ef_emu->e_unit, + ev->ev_handle); + } - vnodearray_remove(ef->ef_vnodes, ix); - vnode_cleanup(&ev->ev_v); + vnodearray_remove(ef->ef_vnodes, ix); + vnode_cleanup(&ev->ev_v); - lock_release(ef->ef_emu->e_lock); - vfs_biglock_release(); + lock_release(ef->ef_emu->e_lock); + vfs_biglock_release(); - kfree(ev); - return 0; + kfree(ev); + return 0; } /* * VOP_READ */ -static -int -emufs_read(struct vnode *v, struct uio *uio) -{ - struct emufs_vnode *ev = v->vn_data; - uint32_t amt; - size_t oldresid; - int result; +static int emufs_read(struct vnode *v, struct uio *uio) { + struct emufs_vnode *ev = v->vn_data; + uint32_t amt; + size_t oldresid; + int result; - KASSERT(uio->uio_rw==UIO_READ); + KASSERT(uio->uio_rw == UIO_READ); - while (uio->uio_resid > 0) { - amt = uio->uio_resid; - if (amt > EMU_MAXIO) { - amt = EMU_MAXIO; - } + while (uio->uio_resid > 0) { + amt = uio->uio_resid; + if (amt > EMU_MAXIO) { + amt = EMU_MAXIO; + } - oldresid = uio->uio_resid; + oldresid = uio->uio_resid; - result = emu_read(ev->ev_emu, ev->ev_handle, amt, uio); - if (result) { - return result; - } + result = emu_read(ev->ev_emu, ev->ev_handle, amt, uio); + if (result) { + return result; + } - if (uio->uio_resid == oldresid) { - /* nothing read - EOF */ - break; - } - } + if (uio->uio_resid == oldresid) { + /* nothing read - EOF */ + break; + } + } - return 0; + return 0; } /* * VOP_READDIR */ -static -int -emufs_getdirentry(struct vnode *v, struct uio *uio) -{ - struct emufs_vnode *ev = v->vn_data; - uint32_t amt; +static int emufs_getdirentry(struct vnode *v, struct uio *uio) { + struct emufs_vnode *ev = v->vn_data; + uint32_t amt; - KASSERT(uio->uio_rw==UIO_READ); + KASSERT(uio->uio_rw == UIO_READ); - amt = uio->uio_resid; - if (amt > EMU_MAXIO) { - amt = EMU_MAXIO; - } + amt = uio->uio_resid; + if (amt > EMU_MAXIO) { + amt = EMU_MAXIO; + } - return emu_readdir(ev->ev_emu, ev->ev_handle, amt, uio); + return emu_readdir(ev->ev_emu, ev->ev_handle, amt, uio); } /* * VOP_WRITE */ -static -int -emufs_write(struct vnode *v, struct uio *uio) -{ - struct emufs_vnode *ev = v->vn_data; - uint32_t amt; - size_t oldresid; - int result; +static int emufs_write(struct vnode *v, struct uio *uio) { + struct emufs_vnode *ev = v->vn_data; + uint32_t amt; + size_t oldresid; + int result; - KASSERT(uio->uio_rw==UIO_WRITE); + KASSERT(uio->uio_rw == UIO_WRITE); - while (uio->uio_resid > 0) { - amt = uio->uio_resid; - if (amt > EMU_MAXIO) { - amt = EMU_MAXIO; - } + while (uio->uio_resid > 0) { + amt = uio->uio_resid; + if (amt > EMU_MAXIO) { + amt = EMU_MAXIO; + } - oldresid = uio->uio_resid; + oldresid = uio->uio_resid; - result = emu_write(ev->ev_emu, ev->ev_handle, amt, uio); - if (result) { - return result; - } + result = emu_write(ev->ev_emu, ev->ev_handle, amt, uio); + if (result) { + return result; + } - if (uio->uio_resid == oldresid) { - /* nothing written...? */ - break; - } - } + if (uio->uio_resid == oldresid) { + /* nothing written...? */ + break; + } + } - return 0; + return 0; } /* * VOP_IOCTL */ -static -int -emufs_ioctl(struct vnode *v, int op, userptr_t data) -{ - /* - * No ioctls. - */ +static int emufs_ioctl(struct vnode *v, int op, userptr_t data) { + /* + * No ioctls. + */ - (void)v; - (void)op; - (void)data; + (void)v; + (void)op; + (void)data; - return EINVAL; + return EINVAL; } /* * VOP_STAT */ -static -int -emufs_stat(struct vnode *v, struct stat *statbuf) -{ - struct emufs_vnode *ev = v->vn_data; - int result; +static int emufs_stat(struct vnode *v, struct stat *statbuf) { + struct emufs_vnode *ev = v->vn_data; + int result; - bzero(statbuf, sizeof(struct stat)); + bzero(statbuf, sizeof(struct stat)); - result = emu_getsize(ev->ev_emu, ev->ev_handle, &statbuf->st_size); - if (result) { - return result; - } + result = emu_getsize(ev->ev_emu, ev->ev_handle, &statbuf->st_size); + if (result) { + return result; + } - result = VOP_GETTYPE(v, &statbuf->st_mode); - if (result) { - return result; - } - statbuf->st_mode |= 0644; /* possibly a lie */ - statbuf->st_nlink = 1; /* might be a lie, but doesn't matter much */ - statbuf->st_blocks = 0; /* almost certainly a lie */ + result = VOP_GETTYPE(v, &statbuf->st_mode); + if (result) { + return result; + } + statbuf->st_mode |= 0644; /* possibly a lie */ + statbuf->st_nlink = 1; /* might be a lie, but doesn't matter much */ + statbuf->st_blocks = 0; /* almost certainly a lie */ - return 0; + return 0; } /* * VOP_GETTYPE for files */ -static -int -emufs_file_gettype(struct vnode *v, uint32_t *result) -{ - (void)v; - *result = S_IFREG; - return 0; +static int emufs_file_gettype(struct vnode *v, uint32_t *result) { + (void)v; + *result = S_IFREG; + return 0; } /* * VOP_GETTYPE for directories */ -static -int -emufs_dir_gettype(struct vnode *v, uint32_t *result) -{ - (void)v; - *result = S_IFDIR; - return 0; +static int emufs_dir_gettype(struct vnode *v, uint32_t *result) { + (void)v; + *result = S_IFDIR; + return 0; } /* * VOP_ISSEEKABLE */ -static -bool -emufs_isseekable(struct vnode *v) -{ - (void)v; - return true; +static bool emufs_isseekable(struct vnode *v) { + (void)v; + return true; } /* * VOP_FSYNC */ -static -int -emufs_fsync(struct vnode *v) -{ - (void)v; - return 0; +static int emufs_fsync(struct vnode *v) { + (void)v; + return 0; } /* * VOP_TRUNCATE */ -static -int -emufs_truncate(struct vnode *v, off_t len) -{ - struct emufs_vnode *ev = v->vn_data; - return emu_trunc(ev->ev_emu, ev->ev_handle, len); +static int emufs_truncate(struct vnode *v, off_t len) { + struct emufs_vnode *ev = v->vn_data; + return emu_trunc(ev->ev_emu, ev->ev_handle, len); } /* * VOP_CREAT */ -static -int -emufs_creat(struct vnode *dir, const char *name, bool excl, mode_t mode, - struct vnode **ret) -{ - struct emufs_vnode *ev = dir->vn_data; - struct emufs_fs *ef = dir->vn_fs->fs_data; - struct emufs_vnode *newguy; - uint32_t handle; - int result; - int isdir; +static int emufs_creat(struct vnode *dir, const char *name, bool excl, + mode_t mode, struct vnode **ret) { + struct emufs_vnode *ev = dir->vn_data; + struct emufs_fs *ef = dir->vn_fs->fs_data; + struct emufs_vnode *newguy; + uint32_t handle; + int result; + int isdir; - result = emu_open(ev->ev_emu, ev->ev_handle, name, true, excl, mode, - &handle, &isdir); - if (result) { - return result; - } + result = emu_open(ev->ev_emu, ev->ev_handle, name, true, excl, mode, &handle, + &isdir); + if (result) { + return result; + } - result = emufs_loadvnode(ef, handle, isdir, &newguy); - if (result) { - emu_close(ev->ev_emu, handle); - return result; - } + result = emufs_loadvnode(ef, handle, isdir, &newguy); + if (result) { + emu_close(ev->ev_emu, handle); + return result; + } - *ret = &newguy->ev_v; - return 0; + *ret = &newguy->ev_v; + return 0; } /* * VOP_LOOKUP */ -static -int -emufs_lookup(struct vnode *dir, char *pathname, struct vnode **ret) -{ - struct emufs_vnode *ev = dir->vn_data; - struct emufs_fs *ef = dir->vn_fs->fs_data; - struct emufs_vnode *newguy; - uint32_t handle; - int result; - int isdir; +static int emufs_lookup(struct vnode *dir, char *pathname, struct vnode **ret) { + struct emufs_vnode *ev = dir->vn_data; + struct emufs_fs *ef = dir->vn_fs->fs_data; + struct emufs_vnode *newguy; + uint32_t handle; + int result; + int isdir; - result = emu_open(ev->ev_emu, ev->ev_handle, pathname, false, false, 0, - &handle, &isdir); - if (result) { - return result; - } + result = emu_open(ev->ev_emu, ev->ev_handle, pathname, false, false, 0, + &handle, &isdir); + if (result) { + return result; + } - result = emufs_loadvnode(ef, handle, isdir, &newguy); - if (result) { - emu_close(ev->ev_emu, handle); - return result; - } + result = emufs_loadvnode(ef, handle, isdir, &newguy); + if (result) { + emu_close(ev->ev_emu, handle); + return result; + } - *ret = &newguy->ev_v; - return 0; + *ret = &newguy->ev_v; + return 0; } /* * VOP_LOOKPARENT */ -static -int -emufs_lookparent(struct vnode *dir, char *pathname, struct vnode **ret, - char *buf, size_t len) -{ - char *s; +static int emufs_lookparent(struct vnode *dir, char *pathname, + struct vnode **ret, char *buf, size_t len) { + char *s; - s = strrchr(pathname, '/'); - if (s==NULL) { - /* just a last component, no directory part */ - if (strlen(pathname)+1 > len) { - return ENAMETOOLONG; - } - VOP_INCREF(dir); - *ret = dir; - strcpy(buf, pathname); - return 0; - } + s = strrchr(pathname, '/'); + if (s == NULL) { + /* just a last component, no directory part */ + if (strlen(pathname) + 1 > len) { + return ENAMETOOLONG; + } + VOP_INCREF(dir); + *ret = dir; + strcpy(buf, pathname); + return 0; + } - *s = 0; - s++; - if (strlen(s)+1 > len) { - return ENAMETOOLONG; - } - strcpy(buf, s); + *s = 0; + s++; + if (strlen(s) + 1 > len) { + return ENAMETOOLONG; + } + strcpy(buf, s); - return emufs_lookup(dir, pathname, ret); + return emufs_lookup(dir, pathname, ret); } /* * VOP_NAMEFILE */ -static -int -emufs_namefile(struct vnode *v, struct uio *uio) -{ - struct emufs_vnode *ev = v->vn_data; - struct emufs_fs *ef = v->vn_fs->fs_data; +static int emufs_namefile(struct vnode *v, struct uio *uio) { + struct emufs_vnode *ev = v->vn_data; + struct emufs_fs *ef = v->vn_fs->fs_data; - if (ev == ef->ef_root) { - /* - * Root directory - name is empty string - */ - return 0; - } + if (ev == ef->ef_root) { + /* + * Root directory - name is empty string + */ + return 0; + } - (void)uio; + (void)uio; - return ENOSYS; + return ENOSYS; } /* * VOP_MMAP */ -static -int -emufs_mmap(struct vnode *v) -{ - (void)v; - return ENOSYS; +static int emufs_mmap(struct vnode *v) { + (void)v; + return ENOSYS; } ////////////////////////////// @@ -860,64 +773,47 @@ emufs_mmap(struct vnode *v) * Bits not implemented at all on emufs */ -static -int -emufs_symlink(struct vnode *v, const char *contents, const char *name) -{ - (void)v; - (void)contents; - (void)name; - return ENOSYS; +static int emufs_symlink(struct vnode *v, const char *contents, + const char *name) { + (void)v; + (void)contents; + (void)name; + return ENOSYS; } -static -int -emufs_mkdir(struct vnode *v, const char *name, mode_t mode) -{ - (void)v; - (void)name; - (void)mode; - return ENOSYS; +static int emufs_mkdir(struct vnode *v, const char *name, mode_t mode) { + (void)v; + (void)name; + (void)mode; + return ENOSYS; } -static -int -emufs_link(struct vnode *v, const char *name, struct vnode *target) -{ - (void)v; - (void)name; - (void)target; - return ENOSYS; +static int emufs_link(struct vnode *v, const char *name, struct vnode *target) { + (void)v; + (void)name; + (void)target; + return ENOSYS; } -static -int -emufs_remove(struct vnode *v, const char *name) -{ - (void)v; - (void)name; - return ENOSYS; +static int emufs_remove(struct vnode *v, const char *name) { + (void)v; + (void)name; + return ENOSYS; } -static -int -emufs_rmdir(struct vnode *v, const char *name) -{ - (void)v; - (void)name; - return ENOSYS; +static int emufs_rmdir(struct vnode *v, const char *name) { + (void)v; + (void)name; + return ENOSYS; } -static -int -emufs_rename(struct vnode *v1, const char *n1, - struct vnode *v2, const char *n2) -{ - (void)v1; - (void)n1; - (void)v2; - (void)n2; - return ENOSYS; +static int emufs_rename(struct vnode *v1, const char *n1, struct vnode *v2, + const char *n2) { + (void)v1; + (void)n1; + (void)v2; + (void)n2; + return ENOSYS; } ////////////////////////////// @@ -935,136 +831,100 @@ emufs_rename(struct vnode *v1, const char *n1, * problem but is otherwise not very appealing. */ -static -int -emufs_void_op_isdir(struct vnode *v) -{ - (void)v; - return EISDIR; +static int emufs_void_op_isdir(struct vnode *v) { + (void)v; + return EISDIR; } -static -int -emufs_uio_op_isdir(struct vnode *v, struct uio *uio) -{ - (void)v; - (void)uio; - return EISDIR; +static int emufs_uio_op_isdir(struct vnode *v, struct uio *uio) { + (void)v; + (void)uio; + return EISDIR; } -static -int -emufs_uio_op_notdir(struct vnode *v, struct uio *uio) -{ - (void)v; - (void)uio; - return ENOTDIR; +static int emufs_uio_op_notdir(struct vnode *v, struct uio *uio) { + (void)v; + (void)uio; + return ENOTDIR; } -static -int -emufs_name_op_notdir(struct vnode *v, const char *name) -{ - (void)v; - (void)name; - return ENOTDIR; +static int emufs_name_op_notdir(struct vnode *v, const char *name) { + (void)v; + (void)name; + return ENOTDIR; } -static -int -emufs_readlink_notlink(struct vnode *v, struct uio *uio) -{ - (void)v; - (void)uio; - return EINVAL; +static int emufs_readlink_notlink(struct vnode *v, struct uio *uio) { + (void)v; + (void)uio; + return EINVAL; } -static -int -emufs_creat_notdir(struct vnode *v, const char *name, bool excl, mode_t mode, - struct vnode **retval) -{ - (void)v; - (void)name; - (void)excl; - (void)mode; - (void)retval; - return ENOTDIR; +static int emufs_creat_notdir(struct vnode *v, const char *name, bool excl, + mode_t mode, struct vnode **retval) { + (void)v; + (void)name; + (void)excl; + (void)mode; + (void)retval; + return ENOTDIR; } -static -int -emufs_symlink_notdir(struct vnode *v, const char *contents, const char *name) -{ - (void)v; - (void)contents; - (void)name; - return ENOTDIR; +static int emufs_symlink_notdir(struct vnode *v, const char *contents, + const char *name) { + (void)v; + (void)contents; + (void)name; + return ENOTDIR; } -static -int -emufs_mkdir_notdir(struct vnode *v, const char *name, mode_t mode) -{ - (void)v; - (void)name; - (void)mode; - return ENOTDIR; +static int emufs_mkdir_notdir(struct vnode *v, const char *name, mode_t mode) { + (void)v; + (void)name; + (void)mode; + return ENOTDIR; } -static -int -emufs_link_notdir(struct vnode *v, const char *name, struct vnode *target) -{ - (void)v; - (void)name; - (void)target; - return ENOTDIR; +static int emufs_link_notdir(struct vnode *v, const char *name, + struct vnode *target) { + (void)v; + (void)name; + (void)target; + return ENOTDIR; } -static -int -emufs_rename_notdir(struct vnode *v1, const char *n1, - struct vnode *v2, const char *n2) -{ - (void)v1; - (void)n1; - (void)v2; - (void)n2; - return ENOTDIR; +static int emufs_rename_notdir(struct vnode *v1, const char *n1, + struct vnode *v2, const char *n2) { + (void)v1; + (void)n1; + (void)v2; + (void)n2; + return ENOTDIR; } -static -int -emufs_lookup_notdir(struct vnode *v, char *pathname, struct vnode **result) -{ - (void)v; - (void)pathname; - (void)result; - return ENOTDIR; +static int emufs_lookup_notdir(struct vnode *v, char *pathname, + struct vnode **result) { + (void)v; + (void)pathname; + (void)result; + return ENOTDIR; } -static -int -emufs_lookparent_notdir(struct vnode *v, char *pathname, struct vnode **result, - char *buf, size_t len) -{ - (void)v; - (void)pathname; - (void)result; - (void)buf; - (void)len; - return ENOTDIR; +static int emufs_lookparent_notdir(struct vnode *v, char *pathname, + struct vnode **result, char *buf, + size_t len) { + (void)v; + (void)pathname; + (void)result; + (void)buf; + (void)len; + return ENOTDIR; } - -static -int -emufs_truncate_isdir(struct vnode *v, off_t len) -{ - (void)v; - (void)len; - return ENOTDIR; +static int emufs_truncate_isdir(struct vnode *v, off_t len) { + (void)v; + (void)len; + return ENOTDIR; } ////////////////////////////// @@ -1073,137 +933,134 @@ emufs_truncate_isdir(struct vnode *v, off_t len) * Function table for emufs files. */ static const struct vnode_ops emufs_fileops = { - .vop_magic = VOP_MAGIC, /* mark this a valid vnode ops table */ + .vop_magic = VOP_MAGIC, /* mark this a valid vnode ops table */ - .vop_eachopen = emufs_eachopen, - .vop_reclaim = emufs_reclaim, + .vop_eachopen = emufs_eachopen, + .vop_reclaim = emufs_reclaim, - .vop_read = emufs_read, - .vop_readlink = emufs_readlink_notlink, - .vop_getdirentry = emufs_uio_op_notdir, - .vop_write = emufs_write, - .vop_ioctl = emufs_ioctl, - .vop_stat = emufs_stat, - .vop_gettype = emufs_file_gettype, - .vop_isseekable = emufs_isseekable, - .vop_fsync = emufs_fsync, - .vop_mmap = emufs_mmap, - .vop_truncate = emufs_truncate, - .vop_namefile = emufs_uio_op_notdir, + .vop_read = emufs_read, + .vop_readlink = emufs_readlink_notlink, + .vop_getdirentry = emufs_uio_op_notdir, + .vop_write = emufs_write, + .vop_ioctl = emufs_ioctl, + .vop_stat = emufs_stat, + .vop_gettype = emufs_file_gettype, + .vop_isseekable = emufs_isseekable, + .vop_fsync = emufs_fsync, + .vop_mmap = emufs_mmap, + .vop_truncate = emufs_truncate, + .vop_namefile = emufs_uio_op_notdir, - .vop_creat = emufs_creat_notdir, - .vop_symlink = emufs_symlink_notdir, - .vop_mkdir = emufs_mkdir_notdir, - .vop_link = emufs_link_notdir, - .vop_remove = emufs_name_op_notdir, - .vop_rmdir = emufs_name_op_notdir, - .vop_rename = emufs_rename_notdir, + .vop_creat = emufs_creat_notdir, + .vop_symlink = emufs_symlink_notdir, + .vop_mkdir = emufs_mkdir_notdir, + .vop_link = emufs_link_notdir, + .vop_remove = emufs_name_op_notdir, + .vop_rmdir = emufs_name_op_notdir, + .vop_rename = emufs_rename_notdir, - .vop_lookup = emufs_lookup_notdir, - .vop_lookparent = emufs_lookparent_notdir, + .vop_lookup = emufs_lookup_notdir, + .vop_lookparent = emufs_lookparent_notdir, }; /* * Function table for emufs directories. */ static const struct vnode_ops emufs_dirops = { - .vop_magic = VOP_MAGIC, /* mark this a valid vnode ops table */ + .vop_magic = VOP_MAGIC, /* mark this a valid vnode ops table */ - .vop_eachopen = emufs_eachopendir, - .vop_reclaim = emufs_reclaim, + .vop_eachopen = emufs_eachopendir, + .vop_reclaim = emufs_reclaim, - .vop_read = emufs_uio_op_isdir, - .vop_readlink = emufs_uio_op_isdir, - .vop_getdirentry = emufs_getdirentry, - .vop_write = emufs_uio_op_isdir, - .vop_ioctl = emufs_ioctl, - .vop_stat = emufs_stat, - .vop_gettype = emufs_dir_gettype, - .vop_isseekable = emufs_isseekable, - .vop_fsync = emufs_void_op_isdir, - .vop_mmap = emufs_void_op_isdir, - .vop_truncate = emufs_truncate_isdir, - .vop_namefile = emufs_namefile, + .vop_read = emufs_uio_op_isdir, + .vop_readlink = emufs_uio_op_isdir, + .vop_getdirentry = emufs_getdirentry, + .vop_write = emufs_uio_op_isdir, + .vop_ioctl = emufs_ioctl, + .vop_stat = emufs_stat, + .vop_gettype = emufs_dir_gettype, + .vop_isseekable = emufs_isseekable, + .vop_fsync = emufs_void_op_isdir, + .vop_mmap = emufs_void_op_isdir, + .vop_truncate = emufs_truncate_isdir, + .vop_namefile = emufs_namefile, - .vop_creat = emufs_creat, - .vop_symlink = emufs_symlink, - .vop_mkdir = emufs_mkdir, - .vop_link = emufs_link, - .vop_remove = emufs_remove, - .vop_rmdir = emufs_rmdir, - .vop_rename = emufs_rename, + .vop_creat = emufs_creat, + .vop_symlink = emufs_symlink, + .vop_mkdir = emufs_mkdir, + .vop_link = emufs_link, + .vop_remove = emufs_remove, + .vop_rmdir = emufs_rmdir, + .vop_rename = emufs_rename, - .vop_lookup = emufs_lookup, - .vop_lookparent = emufs_lookparent, + .vop_lookup = emufs_lookup, + .vop_lookparent = emufs_lookparent, }; /* * Function to load a vnode into memory. */ -static -int -emufs_loadvnode(struct emufs_fs *ef, uint32_t handle, int isdir, - struct emufs_vnode **ret) -{ - struct vnode *v; - struct emufs_vnode *ev; - unsigned i, num; - int result; +static int emufs_loadvnode(struct emufs_fs *ef, uint32_t handle, int isdir, + struct emufs_vnode **ret) { + struct vnode *v; + struct emufs_vnode *ev; + unsigned i, num; + int result; - vfs_biglock_acquire(); - lock_acquire(ef->ef_emu->e_lock); + vfs_biglock_acquire(); + lock_acquire(ef->ef_emu->e_lock); - num = vnodearray_num(ef->ef_vnodes); - for (i=0; ief_vnodes, i); - ev = v->vn_data; - if (ev->ev_handle == handle) { - /* Found */ + num = vnodearray_num(ef->ef_vnodes); + for (i = 0; i < num; i++) { + v = vnodearray_get(ef->ef_vnodes, i); + ev = v->vn_data; + if (ev->ev_handle == handle) { + /* Found */ - VOP_INCREF(&ev->ev_v); + VOP_INCREF(&ev->ev_v); - lock_release(ef->ef_emu->e_lock); - vfs_biglock_release(); - *ret = ev; - return 0; - } - } + lock_release(ef->ef_emu->e_lock); + vfs_biglock_release(); + *ret = ev; + return 0; + } + } - /* Didn't have one; create it */ + /* Didn't have one; create it */ - ev = kmalloc(sizeof(struct emufs_vnode)); - if (ev==NULL) { - lock_release(ef->ef_emu->e_lock); - return ENOMEM; - } + ev = kmalloc(sizeof(struct emufs_vnode)); + if (ev == NULL) { + lock_release(ef->ef_emu->e_lock); + return ENOMEM; + } - ev->ev_emu = ef->ef_emu; - ev->ev_handle = handle; + ev->ev_emu = ef->ef_emu; + ev->ev_handle = handle; - result = vnode_init(&ev->ev_v, isdir ? &emufs_dirops : &emufs_fileops, - &ef->ef_fs, ev); - if (result) { - lock_release(ef->ef_emu->e_lock); - vfs_biglock_release(); - kfree(ev); - return result; - } + result = vnode_init(&ev->ev_v, isdir ? &emufs_dirops : &emufs_fileops, + &ef->ef_fs, ev); + if (result) { + lock_release(ef->ef_emu->e_lock); + vfs_biglock_release(); + kfree(ev); + return result; + } - result = vnodearray_add(ef->ef_vnodes, &ev->ev_v, NULL); - if (result) { - /* note: vnode_cleanup undoes vnode_init - it does not kfree */ - vnode_cleanup(&ev->ev_v); - lock_release(ef->ef_emu->e_lock); - vfs_biglock_release(); - kfree(ev); - return result; - } + result = vnodearray_add(ef->ef_vnodes, &ev->ev_v, NULL); + if (result) { + /* note: vnode_cleanup undoes vnode_init - it does not kfree */ + vnode_cleanup(&ev->ev_v); + lock_release(ef->ef_emu->e_lock); + vfs_biglock_release(); + kfree(ev); + return result; + } - lock_release(ef->ef_emu->e_lock); - vfs_biglock_release(); + lock_release(ef->ef_emu->e_lock); + vfs_biglock_release(); - *ret = ev; - return 0; + *ret = ev; + return 0; } // @@ -1217,67 +1074,55 @@ emufs_loadvnode(struct emufs_fs *ef, uint32_t handle, int isdir, /* * FSOP_SYNC */ -static -int -emufs_sync(struct fs *fs) -{ - (void)fs; - return 0; +static int emufs_sync(struct fs *fs) { + (void)fs; + return 0; } /* * FSOP_GETVOLNAME */ -static -const char * -emufs_getvolname(struct fs *fs) -{ - /* We don't have a volume name beyond the device name */ - (void)fs; - return NULL; +static const char *emufs_getvolname(struct fs *fs) { + /* We don't have a volume name beyond the device name */ + (void)fs; + return NULL; } /* * FSOP_GETROOT */ -static -int -emufs_getroot(struct fs *fs, struct vnode **ret) -{ - struct emufs_fs *ef; +static int emufs_getroot(struct fs *fs, struct vnode **ret) { + struct emufs_fs *ef; - KASSERT(fs != NULL); + KASSERT(fs != NULL); - ef = fs->fs_data; + ef = fs->fs_data; - KASSERT(ef != NULL); - KASSERT(ef->ef_root != NULL); + KASSERT(ef != NULL); + KASSERT(ef->ef_root != NULL); - VOP_INCREF(&ef->ef_root->ev_v); - *ret = &ef->ef_root->ev_v; - return 0; + VOP_INCREF(&ef->ef_root->ev_v); + *ret = &ef->ef_root->ev_v; + return 0; } /* * FSOP_UNMOUNT */ -static -int -emufs_unmount(struct fs *fs) -{ - /* Always prohibit unmount, as we're not really "mounted" */ - (void)fs; - return EBUSY; +static int emufs_unmount(struct fs *fs) { + /* Always prohibit unmount, as we're not really "mounted" */ + (void)fs; + return EBUSY; } /* * Function table for the emufs file system. */ static const struct fs_ops emufs_fsops = { - .fsop_sync = emufs_sync, - .fsop_getvolname = emufs_getvolname, - .fsop_getroot = emufs_getroot, - .fsop_unmount = emufs_unmount, + .fsop_sync = emufs_sync, + .fsop_getvolname = emufs_getvolname, + .fsop_getroot = emufs_getroot, + .fsop_unmount = emufs_unmount, }; /* @@ -1287,43 +1132,40 @@ static const struct fs_ops emufs_fsops = { * * Basically, we just add ourselves to the name list in the VFS layer. */ -static -int -emufs_addtovfs(struct emu_softc *sc, const char *devname) -{ - struct emufs_fs *ef; - int result; +static int emufs_addtovfs(struct emu_softc *sc, const char *devname) { + struct emufs_fs *ef; + int result; - ef = kmalloc(sizeof(struct emufs_fs)); - if (ef==NULL) { - return ENOMEM; - } + ef = kmalloc(sizeof(struct emufs_fs)); + if (ef == NULL) { + return ENOMEM; + } - ef->ef_fs.fs_data = ef; - ef->ef_fs.fs_ops = &emufs_fsops; + ef->ef_fs.fs_data = ef; + ef->ef_fs.fs_ops = &emufs_fsops; - ef->ef_emu = sc; - ef->ef_root = NULL; - ef->ef_vnodes = vnodearray_create(); - if (ef->ef_vnodes == NULL) { - kfree(ef); - return ENOMEM; - } + ef->ef_emu = sc; + ef->ef_root = NULL; + ef->ef_vnodes = vnodearray_create(); + if (ef->ef_vnodes == NULL) { + kfree(ef); + return ENOMEM; + } - result = emufs_loadvnode(ef, EMU_ROOTHANDLE, 1, &ef->ef_root); - if (result) { - kfree(ef); - return result; - } + result = emufs_loadvnode(ef, EMU_ROOTHANDLE, 1, &ef->ef_root); + if (result) { + kfree(ef); + return result; + } - KASSERT(ef->ef_root!=NULL); + KASSERT(ef->ef_root != NULL); - result = vfs_addfs(devname, &ef->ef_fs); - if (result) { - VOP_DECREF(&ef->ef_root->ev_v); - kfree(ef); - } - return result; + result = vfs_addfs(devname, &ef->ef_fs); + if (result) { + VOP_DECREF(&ef->ef_root->ev_v); + kfree(ef); + } + return result; } // @@ -1334,24 +1176,22 @@ emufs_addtovfs(struct emu_softc *sc, const char *devname) * * Initialize our data, then add ourselves to the VFS layer. */ -int -config_emu(struct emu_softc *sc, int emuno) -{ - char name[32]; +int config_emu(struct emu_softc *sc, int emuno) { + char name[32]; - sc->e_lock = lock_create("emufs-lock"); - if (sc->e_lock == NULL) { - return ENOMEM; - } - sc->e_sem = sem_create("emufs-sem", 0); - if (sc->e_sem == NULL) { - lock_destroy(sc->e_lock); - sc->e_lock = NULL; - return ENOMEM; - } - sc->e_iobuf = bus_map_area(sc->e_busdata, sc->e_buspos, EMU_BUFFER); + sc->e_lock = lock_create("emufs-lock"); + if (sc->e_lock == NULL) { + return ENOMEM; + } + sc->e_sem = sem_create("emufs-sem", 0); + if (sc->e_sem == NULL) { + lock_destroy(sc->e_lock); + sc->e_lock = NULL; + return ENOMEM; + } + sc->e_iobuf = bus_map_area(sc->e_busdata, sc->e_buspos, EMU_BUFFER); - snprintf(name, sizeof(name), "emu%d", emuno); + snprintf(name, sizeof(name), "emu%d", emuno); - return emufs_addtovfs(sc, name); + return emufs_addtovfs(sc, name); } diff --git a/kern/dev/lamebus/emu.h b/kern/dev/lamebus/emu.h index 7c9563e..6d707ea 100644 --- a/kern/dev/lamebus/emu.h +++ b/kern/dev/lamebus/emu.h @@ -30,9 +30,8 @@ #ifndef _LAMEBUS_EMU_H_ #define _LAMEBUS_EMU_H_ - -#define EMU_MAXIO 16384 -#define EMU_ROOTHANDLE 0 +#define EMU_MAXIO 16384 +#define EMU_ROOTHANDLE 0 /* * The per-device data used by the emufs device driver. @@ -41,22 +40,21 @@ */ struct emu_softc { - /* Initialized by lower-level attach code */ - void *e_busdata; - uint32_t e_buspos; - int e_unit; + /* Initialized by lower-level attach code */ + void *e_busdata; + uint32_t e_buspos; + int e_unit; - /* Initialized by config_emu() */ - struct lock *e_lock; - struct semaphore *e_sem; - void *e_iobuf; + /* Initialized by config_emu() */ + struct lock *e_lock; + struct semaphore *e_sem; + void *e_iobuf; - /* Written by the interrupt handler */ - uint32_t e_result; + /* Written by the interrupt handler */ + uint32_t e_result; }; /* Functions called by lower-level drivers */ void emu_irq(/*struct emu_softc*/ void *); - #endif /* _LAMEBUS_EMU_H_ */ diff --git a/kern/dev/lamebus/emu_att.c b/kern/dev/lamebus/emu_att.c index f3eb653..2706c5f 100644 --- a/kern/dev/lamebus/emu_att.c +++ b/kern/dev/lamebus/emu_att.c @@ -38,29 +38,27 @@ #include "autoconf.h" /* Lowest revision we support */ -#define LOW_VERSION 1 +#define LOW_VERSION 1 -struct emu_softc * -attach_emu_to_lamebus(int emuno, struct lamebus_softc *sc) -{ - struct emu_softc *es; - int slot = lamebus_probe(sc, LB_VENDOR_CS161, LBCS161_EMUFS, - LOW_VERSION, NULL); - if (slot < 0) { - return NULL; - } +struct emu_softc *attach_emu_to_lamebus(int emuno, struct lamebus_softc *sc) { + struct emu_softc *es; + int slot = + lamebus_probe(sc, LB_VENDOR_CS161, LBCS161_EMUFS, LOW_VERSION, NULL); + if (slot < 0) { + return NULL; + } - es = kmalloc(sizeof(struct emu_softc)); - if (es==NULL) { - return NULL; - } + es = kmalloc(sizeof(struct emu_softc)); + if (es == NULL) { + return NULL; + } - es->e_busdata = sc; - es->e_buspos = slot; - es->e_unit = emuno; + es->e_busdata = sc; + es->e_buspos = slot; + es->e_unit = emuno; - lamebus_mark(sc, slot); - lamebus_attach_interrupt(sc, slot, es, emu_irq); + lamebus_mark(sc, slot); + lamebus_attach_interrupt(sc, slot, es, emu_irq); - return es; + return es; } diff --git a/kern/dev/lamebus/lamebus.c b/kern/dev/lamebus/lamebus.c index 1b1809d..645d727 100644 --- a/kern/dev/lamebus/lamebus.c +++ b/kern/dev/lamebus/lamebus.c @@ -40,147 +40,124 @@ #include /* Register offsets within each config region */ -#define CFGREG_VID 0 /* Vendor ID */ -#define CFGREG_DID 4 /* Device ID */ -#define CFGREG_DRL 8 /* Device Revision Level */ +#define CFGREG_VID 0 /* Vendor ID */ +#define CFGREG_DID 4 /* Device ID */ +#define CFGREG_DRL 8 /* Device Revision Level */ /* LAMEbus controller private registers (offsets within its config region) */ -#define CTLREG_RAMSZ 0x200 -#define CTLREG_IRQS 0x204 -#define CTLREG_PWR 0x208 -#define CTLREG_IRQE 0x20c -#define CTLREG_CPUS 0x210 -#define CTLREG_CPUE 0x214 -#define CTLREG_SELF 0x218 +#define CTLREG_RAMSZ 0x200 +#define CTLREG_IRQS 0x204 +#define CTLREG_PWR 0x208 +#define CTLREG_IRQE 0x20c +#define CTLREG_CPUS 0x210 +#define CTLREG_CPUE 0x214 +#define CTLREG_SELF 0x218 /* LAMEbus CPU control registers (offsets within each per-cpu region) */ -#define CTLCPU_CIRQE 0x000 -#define CTLCPU_CIPI 0x004 -#define CTLCPU_CRAM 0x300 - +#define CTLCPU_CIRQE 0x000 +#define CTLCPU_CIPI 0x004 +#define CTLCPU_CRAM 0x300 /* * Read a config register for the given slot. */ -static -inline -uint32_t -read_cfg_register(struct lamebus_softc *lb, int slot, uint32_t offset) -{ - /* Note that lb might be NULL on some platforms in some contexts. */ - offset += LB_CONFIG_SIZE*slot; - return lamebus_read_register(lb, LB_CONTROLLER_SLOT, offset); +static inline uint32_t read_cfg_register(struct lamebus_softc *lb, int slot, + uint32_t offset) { + /* Note that lb might be NULL on some platforms in some contexts. */ + offset += LB_CONFIG_SIZE * slot; + return lamebus_read_register(lb, LB_CONTROLLER_SLOT, offset); } /* * Write a config register for a given slot. */ -static -inline -void -write_cfg_register(struct lamebus_softc *lb, int slot, uint32_t offset, - uint32_t val) -{ - offset += LB_CONFIG_SIZE*slot; - lamebus_write_register(lb, LB_CONTROLLER_SLOT, offset, val); +static inline void write_cfg_register(struct lamebus_softc *lb, int slot, + uint32_t offset, uint32_t val) { + offset += LB_CONFIG_SIZE * slot; + lamebus_write_register(lb, LB_CONTROLLER_SLOT, offset, val); } /* * Read one of the bus controller's registers. */ -static -inline -uint32_t -read_ctl_register(struct lamebus_softc *lb, uint32_t offset) -{ - /* Note that lb might be NULL on some platforms in some contexts. */ - return read_cfg_register(lb, LB_CONTROLLER_SLOT, offset); +static inline uint32_t read_ctl_register(struct lamebus_softc *lb, + uint32_t offset) { + /* Note that lb might be NULL on some platforms in some contexts. */ + return read_cfg_register(lb, LB_CONTROLLER_SLOT, offset); } /* * Write one of the bus controller's registers. */ -static -inline -void -write_ctl_register(struct lamebus_softc *lb, uint32_t offset, uint32_t val) -{ - write_cfg_register(lb, LB_CONTROLLER_SLOT, offset, val); +static inline void write_ctl_register(struct lamebus_softc *lb, uint32_t offset, + uint32_t val) { + write_cfg_register(lb, LB_CONTROLLER_SLOT, offset, val); } /* * Write one of the bus controller's CPU control registers. */ -static -inline -void -write_ctlcpu_register(struct lamebus_softc *lb, unsigned hw_cpunum, - uint32_t offset, uint32_t val) -{ - offset += LB_CTLCPU_OFFSET + hw_cpunum * LB_CTLCPU_SIZE; - lamebus_write_register(lb, LB_CONTROLLER_SLOT, offset, val); +static inline void write_ctlcpu_register(struct lamebus_softc *lb, + unsigned hw_cpunum, uint32_t offset, + uint32_t val) { + offset += LB_CTLCPU_OFFSET + hw_cpunum * LB_CTLCPU_SIZE; + lamebus_write_register(lb, LB_CONTROLLER_SLOT, offset, val); } /* * Find and create secondary CPUs. */ -void -lamebus_find_cpus(struct lamebus_softc *lamebus) -{ - uint32_t mainboard_vid, mainboard_did; - uint32_t cpumask, self, bit, val; - unsigned i, numcpus, bootcpu; - unsigned hwnum[32]; +void lamebus_find_cpus(struct lamebus_softc *lamebus) { + uint32_t mainboard_vid, mainboard_did; + uint32_t cpumask, self, bit, val; + unsigned i, numcpus, bootcpu; + unsigned hwnum[32]; - mainboard_vid = read_cfg_register(lamebus, LB_CONTROLLER_SLOT, - CFGREG_VID); - mainboard_did = read_cfg_register(lamebus, LB_CONTROLLER_SLOT, - CFGREG_DID); - if (mainboard_vid == LB_VENDOR_CS161 && - mainboard_did == LBCS161_UPBUSCTL) { - /* Old uniprocessor mainboard; no cpu registers. */ - lamebus->ls_uniprocessor = 1; - return; - } + mainboard_vid = read_cfg_register(lamebus, LB_CONTROLLER_SLOT, CFGREG_VID); + mainboard_did = read_cfg_register(lamebus, LB_CONTROLLER_SLOT, CFGREG_DID); + if (mainboard_vid == LB_VENDOR_CS161 && mainboard_did == LBCS161_UPBUSCTL) { + /* Old uniprocessor mainboard; no cpu registers. */ + lamebus->ls_uniprocessor = 1; + return; + } - cpumask = read_ctl_register(lamebus, CTLREG_CPUS); - self = read_ctl_register(lamebus, CTLREG_SELF); + cpumask = read_ctl_register(lamebus, CTLREG_CPUS); + self = read_ctl_register(lamebus, CTLREG_SELF); - numcpus = 0; - bootcpu = 0; - for (i=0; i<32; i++) { - bit = (uint32_t)1 << i; - if ((cpumask & bit) != 0) { - if (self & bit) { - bootcpu = numcpus; - curcpu->c_hardware_number = i; - } - hwnum[numcpus] = i; - numcpus++; - } - } + numcpus = 0; + bootcpu = 0; + for (i = 0; i < 32; i++) { + bit = (uint32_t)1 << i; + if ((cpumask & bit) != 0) { + if (self & bit) { + bootcpu = numcpus; + curcpu->c_hardware_number = i; + } + hwnum[numcpus] = i; + numcpus++; + } + } - for (i=0; ils_uniprocessor) { - return; - } + if (lamebus->ls_uniprocessor) { + return; + } - cpumask = read_ctl_register(lamebus, CTLREG_CPUS); - self = read_ctl_register(lamebus, CTLREG_SELF); + cpumask = read_ctl_register(lamebus, CTLREG_CPUS); + self = read_ctl_register(lamebus, CTLREG_SELF); - /* Poke in the startup address. */ - cpunum = 1; - for (i=0; i<32; i++) { - bit = (uint32_t)1 << i; - if ((cpumask & bit) != 0) { - if (self & bit) { - continue; - } - ctlcpuoffset = LB_CTLCPU_OFFSET + i * LB_CTLCPU_SIZE; - cram = lamebus_map_area(lamebus, - LB_CONTROLLER_SLOT, - ctlcpuoffset + CTLCPU_CRAM); - cram[0] = (uint32_t)cpu_start_secondary; - cram[1] = cpunum++; - } - } - /* Ensure all the above writes get flushed. */ - membar_store_store(); + /* Poke in the startup address. */ + cpunum = 1; + for (i = 0; i < 32; i++) { + bit = (uint32_t)1 << i; + if ((cpumask & bit) != 0) { + if (self & bit) { + continue; + } + ctlcpuoffset = LB_CTLCPU_OFFSET + i * LB_CTLCPU_SIZE; + cram = lamebus_map_area(lamebus, LB_CONTROLLER_SLOT, + ctlcpuoffset + CTLCPU_CRAM); + cram[0] = (uint32_t)cpu_start_secondary; + cram[1] = cpunum++; + } + } + /* Ensure all the above writes get flushed. */ + membar_store_store(); - /* Now, enable them all. */ - write_ctl_register(lamebus, CTLREG_CPUE, cpumask); + /* Now, enable them all. */ + write_ctl_register(lamebus, CTLREG_CPUE, cpumask); } /* @@ -247,58 +221,55 @@ lamebus_start_cpus(struct lamebus_softc *lamebus) * more specific checks. */ -int -lamebus_probe(struct lamebus_softc *sc, - uint32_t vendorid, uint32_t deviceid, - uint32_t lowver, uint32_t *version_ret) -{ - int slot; - uint32_t val; +int lamebus_probe(struct lamebus_softc *sc, uint32_t vendorid, + uint32_t deviceid, uint32_t lowver, uint32_t *version_ret) { + int slot; + uint32_t val; - /* - * Because the slot information in sc is used when dispatching - * interrupts, disable interrupts while working with it. - */ + /* + * Because the slot information in sc is used when dispatching + * interrupts, disable interrupts while working with it. + */ - spinlock_acquire(&sc->ls_lock); + spinlock_acquire(&sc->ls_lock); - for (slot=0; slotls_slotsinuse & (1<ls_slotsinuse & (1 << slot)) { + /* Slot already in use; skip */ + continue; + } - val = read_cfg_register(sc, slot, CFGREG_VID); - if (val!=vendorid) { - /* Wrong vendor id */ - continue; - } + val = read_cfg_register(sc, slot, CFGREG_VID); + if (val != vendorid) { + /* Wrong vendor id */ + continue; + } - val = read_cfg_register(sc, slot, CFGREG_DID); - if (val != deviceid) { - /* Wrong device id */ - continue; - } + val = read_cfg_register(sc, slot, CFGREG_DID); + if (val != deviceid) { + /* Wrong device id */ + continue; + } - val = read_cfg_register(sc, slot, CFGREG_DRL); - if (val < lowver) { - /* Unsupported device revision */ - continue; - } - if (version_ret != NULL) { - *version_ret = val; - } + val = read_cfg_register(sc, slot, CFGREG_DRL); + if (val < lowver) { + /* Unsupported device revision */ + continue; + } + if (version_ret != NULL) { + *version_ret = val; + } - /* Found something */ + /* Found something */ - spinlock_release(&sc->ls_lock); - return slot; - } + spinlock_release(&sc->ls_lock); + return slot; + } - /* Found nothing */ + /* Found nothing */ - spinlock_release(&sc->ls_lock); - return -1; + spinlock_release(&sc->ls_lock); + return -1; } /* @@ -306,360 +277,328 @@ lamebus_probe(struct lamebus_softc *sc, * This prevents the probe routine from returning the same device over * and over again. */ -void -lamebus_mark(struct lamebus_softc *sc, int slot) -{ - uint32_t mask = ((uint32_t)1) << slot; - KASSERT(slot>=0 && slot < LB_NSLOTS); +void lamebus_mark(struct lamebus_softc *sc, int slot) { + uint32_t mask = ((uint32_t)1) << slot; + KASSERT(slot >= 0 && slot < LB_NSLOTS); - spinlock_acquire(&sc->ls_lock); + spinlock_acquire(&sc->ls_lock); - if ((sc->ls_slotsinuse & mask)!=0) { - panic("lamebus_mark: slot %d already in use\n", slot); - } + if ((sc->ls_slotsinuse & mask) != 0) { + panic("lamebus_mark: slot %d already in use\n", slot); + } - sc->ls_slotsinuse |= mask; + sc->ls_slotsinuse |= mask; - spinlock_release(&sc->ls_lock); + spinlock_release(&sc->ls_lock); } /* * Mark that a slot is no longer in use. */ -void -lamebus_unmark(struct lamebus_softc *sc, int slot) -{ - uint32_t mask = ((uint32_t)1) << slot; - KASSERT(slot>=0 && slot < LB_NSLOTS); +void lamebus_unmark(struct lamebus_softc *sc, int slot) { + uint32_t mask = ((uint32_t)1) << slot; + KASSERT(slot >= 0 && slot < LB_NSLOTS); - spinlock_acquire(&sc->ls_lock); + spinlock_acquire(&sc->ls_lock); - if ((sc->ls_slotsinuse & mask)==0) { - panic("lamebus_mark: slot %d not marked in use\n", slot); - } + if ((sc->ls_slotsinuse & mask) == 0) { + panic("lamebus_mark: slot %d not marked in use\n", slot); + } - sc->ls_slotsinuse &= ~mask; + sc->ls_slotsinuse &= ~mask; - spinlock_release(&sc->ls_lock); + spinlock_release(&sc->ls_lock); } /* * Register a function (and a device context pointer) to be called * when a particular slot signals an interrupt. */ -void -lamebus_attach_interrupt(struct lamebus_softc *sc, int slot, - void *devdata, - void (*irqfunc)(void *devdata)) -{ - uint32_t mask = ((uint32_t)1) << slot; - KASSERT(slot>=0 && slot < LB_NSLOTS); +void lamebus_attach_interrupt(struct lamebus_softc *sc, int slot, void *devdata, + void (*irqfunc)(void *devdata)) { + uint32_t mask = ((uint32_t)1) << slot; + KASSERT(slot >= 0 && slot < LB_NSLOTS); - spinlock_acquire(&sc->ls_lock); + spinlock_acquire(&sc->ls_lock); - if ((sc->ls_slotsinuse & mask)==0) { - panic("lamebus_attach_interrupt: slot %d not marked in use\n", - slot); - } + if ((sc->ls_slotsinuse & mask) == 0) { + panic("lamebus_attach_interrupt: slot %d not marked in use\n", slot); + } - KASSERT(sc->ls_devdata[slot]==NULL); - KASSERT(sc->ls_irqfuncs[slot]==NULL); + KASSERT(sc->ls_devdata[slot] == NULL); + KASSERT(sc->ls_irqfuncs[slot] == NULL); - sc->ls_devdata[slot] = devdata; - sc->ls_irqfuncs[slot] = irqfunc; + sc->ls_devdata[slot] = devdata; + sc->ls_irqfuncs[slot] = irqfunc; - spinlock_release(&sc->ls_lock); + spinlock_release(&sc->ls_lock); } /* * Unregister a function that was being called when a particular slot * signaled an interrupt. */ -void -lamebus_detach_interrupt(struct lamebus_softc *sc, int slot) -{ - uint32_t mask = ((uint32_t)1) << slot; - KASSERT(slot>=0 && slot < LB_NSLOTS); +void lamebus_detach_interrupt(struct lamebus_softc *sc, int slot) { + uint32_t mask = ((uint32_t)1) << slot; + KASSERT(slot >= 0 && slot < LB_NSLOTS); - spinlock_acquire(&sc->ls_lock); + spinlock_acquire(&sc->ls_lock); - if ((sc->ls_slotsinuse & mask)==0) { - panic("lamebus_detach_interrupt: slot %d not marked in use\n", - slot); - } + if ((sc->ls_slotsinuse & mask) == 0) { + panic("lamebus_detach_interrupt: slot %d not marked in use\n", slot); + } - KASSERT(sc->ls_irqfuncs[slot]!=NULL); + KASSERT(sc->ls_irqfuncs[slot] != NULL); - sc->ls_devdata[slot] = NULL; - sc->ls_irqfuncs[slot] = NULL; + sc->ls_devdata[slot] = NULL; + sc->ls_irqfuncs[slot] = NULL; - spinlock_release(&sc->ls_lock); + spinlock_release(&sc->ls_lock); } /* * Mask/unmask an interrupt using the global IRQE register. */ -void -lamebus_mask_interrupt(struct lamebus_softc *lamebus, int slot) -{ - uint32_t bits, mask = ((uint32_t)1) << slot; - KASSERT(slot >= 0 && slot < LB_NSLOTS); +void lamebus_mask_interrupt(struct lamebus_softc *lamebus, int slot) { + uint32_t bits, mask = ((uint32_t)1) << slot; + KASSERT(slot >= 0 && slot < LB_NSLOTS); - spinlock_acquire(&lamebus->ls_lock); - bits = read_ctl_register(lamebus, CTLREG_IRQE); - bits &= ~mask; - write_ctl_register(lamebus, CTLREG_IRQE, bits); - spinlock_release(&lamebus->ls_lock); + spinlock_acquire(&lamebus->ls_lock); + bits = read_ctl_register(lamebus, CTLREG_IRQE); + bits &= ~mask; + write_ctl_register(lamebus, CTLREG_IRQE, bits); + spinlock_release(&lamebus->ls_lock); } -void -lamebus_unmask_interrupt(struct lamebus_softc *lamebus, int slot) -{ - uint32_t bits, mask = ((uint32_t)1) << slot; - KASSERT(slot >= 0 && slot < LB_NSLOTS); +void lamebus_unmask_interrupt(struct lamebus_softc *lamebus, int slot) { + uint32_t bits, mask = ((uint32_t)1) << slot; + KASSERT(slot >= 0 && slot < LB_NSLOTS); - spinlock_acquire(&lamebus->ls_lock); - bits = read_ctl_register(lamebus, CTLREG_IRQE); - bits |= mask; - write_ctl_register(lamebus, CTLREG_IRQE, bits); - spinlock_release(&lamebus->ls_lock); + spinlock_acquire(&lamebus->ls_lock); + bits = read_ctl_register(lamebus, CTLREG_IRQE); + bits |= mask; + write_ctl_register(lamebus, CTLREG_IRQE, bits); + spinlock_release(&lamebus->ls_lock); } - /* * LAMEbus interrupt handling function. (Machine-independent!) */ -void -lamebus_interrupt(struct lamebus_softc *lamebus) -{ - /* - * Note that despite the fact that "spl" stands for "set - * priority level", we don't actually support interrupt - * priorities. When an interrupt happens, we look through the - * slots to find the first interrupting device and call its - * interrupt routine, no matter what that device is. - * - * Note that the entire LAMEbus uses only one on-cpu interrupt line. - * Thus, we do not use any on-cpu interrupt priority system either. - */ +void lamebus_interrupt(struct lamebus_softc *lamebus) { + /* + * Note that despite the fact that "spl" stands for "set + * priority level", we don't actually support interrupt + * priorities. When an interrupt happens, we look through the + * slots to find the first interrupting device and call its + * interrupt routine, no matter what that device is. + * + * Note that the entire LAMEbus uses only one on-cpu interrupt line. + * Thus, we do not use any on-cpu interrupt priority system either. + */ - int slot; - uint32_t mask; - uint32_t irqs; - void (*handler)(void *); - void *data; + int slot; + uint32_t mask; + uint32_t irqs; + void (*handler)(void *); + void *data; - /* For keeping track of how many bogus things happen in a row. */ - static int duds = 0; - int duds_this_time = 0; + /* For keeping track of how many bogus things happen in a row. */ + static int duds = 0; + int duds_this_time = 0; - /* and we better have a valid bus instance. */ - KASSERT(lamebus != NULL); + /* and we better have a valid bus instance. */ + KASSERT(lamebus != NULL); - /* Lock the softc */ - spinlock_acquire(&lamebus->ls_lock); + /* Lock the softc */ + spinlock_acquire(&lamebus->ls_lock); - /* - * Read the LAMEbus controller register that tells us which - * slots are asserting an interrupt condition. - */ - irqs = read_ctl_register(lamebus, CTLREG_IRQS); + /* + * Read the LAMEbus controller register that tells us which + * slots are asserting an interrupt condition. + */ + irqs = read_ctl_register(lamebus, CTLREG_IRQS); - if (irqs == 0) { - /* - * Huh? None of them? Must be a glitch. - */ - kprintf("lamebus: stray interrupt on cpu %u\n", - curcpu->c_number); - duds++; - duds_this_time++; + if (irqs == 0) { + /* + * Huh? None of them? Must be a glitch. + */ + kprintf("lamebus: stray interrupt on cpu %u\n", curcpu->c_number); + duds++; + duds_this_time++; - /* - * We could just return now, but instead we'll - * continue ahead. Because irqs == 0, nothing in the - * loop will execute, and passing through it gets us - * to the code that checks how many duds we've - * seen. This is important, because we just might get - * a stray interrupt that latches itself on. If that - * happens, we're pretty much toast, but it's better - * to panic and hopefully reset the system than to - * loop forever printing "stray interrupt". - */ - } + /* + * We could just return now, but instead we'll + * continue ahead. Because irqs == 0, nothing in the + * loop will execute, and passing through it gets us + * to the code that checks how many duds we've + * seen. This is important, because we just might get + * a stray interrupt that latches itself on. If that + * happens, we're pretty much toast, but it's better + * to panic and hopefully reset the system than to + * loop forever printing "stray interrupt". + */ + } - /* - * Go through the bits in the value we got back to see which - * ones are set. - */ + /* + * Go through the bits in the value we got back to see which + * ones are set. + */ - for (mask=1, slot=0; slotls_slotsinuse & mask)==0) { - /* - * No device driver is using this slot. - */ - duds++; - duds_this_time++; - continue; - } + if ((lamebus->ls_slotsinuse & mask) == 0) { + /* + * No device driver is using this slot. + */ + duds++; + duds_this_time++; + continue; + } - if (lamebus->ls_irqfuncs[slot]==NULL) { - /* - * The device driver hasn't installed an interrupt - * handler. - */ - duds++; - duds_this_time++; - continue; - } + if (lamebus->ls_irqfuncs[slot] == NULL) { + /* + * The device driver hasn't installed an interrupt + * handler. + */ + duds++; + duds_this_time++; + continue; + } - /* - * Call the interrupt handler. Release the spinlock - * while we do so, in case other CPUs are handling - * interrupts on other devices. - */ - handler = lamebus->ls_irqfuncs[slot]; - data = lamebus->ls_devdata[slot]; - spinlock_release(&lamebus->ls_lock); + /* + * Call the interrupt handler. Release the spinlock + * while we do so, in case other CPUs are handling + * interrupts on other devices. + */ + handler = lamebus->ls_irqfuncs[slot]; + data = lamebus->ls_devdata[slot]; + spinlock_release(&lamebus->ls_lock); - handler(data); + handler(data); - spinlock_acquire(&lamebus->ls_lock); + spinlock_acquire(&lamebus->ls_lock); - /* - * Reload the mask of pending IRQs - if we just called - * hardclock, we might not have come back to this - * context for some time, and it might have changed. - */ + /* + * Reload the mask of pending IRQs - if we just called + * hardclock, we might not have come back to this + * context for some time, and it might have changed. + */ - irqs = read_ctl_register(lamebus, CTLREG_IRQS); - } + irqs = read_ctl_register(lamebus, CTLREG_IRQS); + } + /* + * If we get interrupts for a slot with no driver or no + * interrupt handler, it's fairly serious. Because LAMEbus + * uses level-triggered interrupts, if we don't shut off the + * condition, we'll keep getting interrupted continuously and + * the system will make no progress. But we don't know how to + * do that if there's no driver or no interrupt handler. + * + * So, if we get too many dud interrupts, panic, since it's + * better to panic and reset than to hang. + * + * If we get through here without seeing any duds this time, + * the condition, whatever it was, has gone away. It might be + * some stupid device we don't have a driver for, or it might + * have been an electrical transient. In any case, warn and + * clear the dud count. + */ - /* - * If we get interrupts for a slot with no driver or no - * interrupt handler, it's fairly serious. Because LAMEbus - * uses level-triggered interrupts, if we don't shut off the - * condition, we'll keep getting interrupted continuously and - * the system will make no progress. But we don't know how to - * do that if there's no driver or no interrupt handler. - * - * So, if we get too many dud interrupts, panic, since it's - * better to panic and reset than to hang. - * - * If we get through here without seeing any duds this time, - * the condition, whatever it was, has gone away. It might be - * some stupid device we don't have a driver for, or it might - * have been an electrical transient. In any case, warn and - * clear the dud count. - */ + if (duds_this_time == 0 && duds > 0) { + kprintf("lamebus: %d dud interrupts\n", duds); + duds = 0; + } - if (duds_this_time == 0 && duds > 0) { - kprintf("lamebus: %d dud interrupts\n", duds); - duds = 0; - } + if (duds > 10000) { + panic("lamebus: too many (%d) dud interrupts\n", duds); + } - if (duds > 10000) { - panic("lamebus: too many (%d) dud interrupts\n", duds); - } - - /* Unlock the softc */ - spinlock_release(&lamebus->ls_lock); + /* Unlock the softc */ + spinlock_release(&lamebus->ls_lock); } /* * Have the bus controller power the system off. */ -void -lamebus_poweroff(struct lamebus_softc *lamebus) -{ - /* - * Write 0 to the power register to shut the system off. - */ +void lamebus_poweroff(struct lamebus_softc *lamebus) { + /* + * Write 0 to the power register to shut the system off. + */ - cpu_irqoff(); - write_ctl_register(lamebus, CTLREG_PWR, 0); + cpu_irqoff(); + write_ctl_register(lamebus, CTLREG_PWR, 0); - /* The power doesn't go off instantly... so halt the cpu. */ - cpu_halt(); + /* The power doesn't go off instantly... so halt the cpu. */ + cpu_halt(); } /* * Ask the bus controller how much memory we have. */ -uint32_t -lamebus_ramsize(void) -{ - /* - * Note that this has to work before bus initialization. - * On machines where lamebus_read_register doesn't work - * before bus initialization, this function can't be used - * for initial RAM size lookup. - */ +uint32_t lamebus_ramsize(void) { + /* + * Note that this has to work before bus initialization. + * On machines where lamebus_read_register doesn't work + * before bus initialization, this function can't be used + * for initial RAM size lookup. + */ - return read_ctl_register(NULL, CTLREG_RAMSZ); + return read_ctl_register(NULL, CTLREG_RAMSZ); } /* * Turn on or off the interprocessor interrupt line for a given CPU. */ -void -lamebus_assert_ipi(struct lamebus_softc *lamebus, struct cpu *target) -{ - if (lamebus->ls_uniprocessor) { - return; - } - write_ctlcpu_register(lamebus, target->c_hardware_number, - CTLCPU_CIPI, 1); +void lamebus_assert_ipi(struct lamebus_softc *lamebus, struct cpu *target) { + if (lamebus->ls_uniprocessor) { + return; + } + write_ctlcpu_register(lamebus, target->c_hardware_number, CTLCPU_CIPI, 1); } -void -lamebus_clear_ipi(struct lamebus_softc *lamebus, struct cpu *target) -{ - if (lamebus->ls_uniprocessor) { - return; - } - write_ctlcpu_register(lamebus, target->c_hardware_number, - CTLCPU_CIPI, 0); +void lamebus_clear_ipi(struct lamebus_softc *lamebus, struct cpu *target) { + if (lamebus->ls_uniprocessor) { + return; + } + write_ctlcpu_register(lamebus, target->c_hardware_number, CTLCPU_CIPI, 0); } /* * Initial setup. * Should be called from mainbus_bootstrap(). */ -struct lamebus_softc * -lamebus_init(void) -{ - struct lamebus_softc *lamebus; - int i; +struct lamebus_softc *lamebus_init(void) { + struct lamebus_softc *lamebus; + int i; - /* Allocate space for lamebus data */ - lamebus = kmalloc(sizeof(struct lamebus_softc)); - if (lamebus==NULL) { - panic("lamebus_init: Out of memory\n"); - } + /* Allocate space for lamebus data */ + lamebus = kmalloc(sizeof(struct lamebus_softc)); + if (lamebus == NULL) { + panic("lamebus_init: Out of memory\n"); + } - spinlock_init(&lamebus->ls_lock); + spinlock_init(&lamebus->ls_lock); - /* - * Initialize the LAMEbus data structure. - */ - lamebus->ls_slotsinuse = 1 << LB_CONTROLLER_SLOT; + /* + * Initialize the LAMEbus data structure. + */ + lamebus->ls_slotsinuse = 1 << LB_CONTROLLER_SLOT; - for (i=0; ils_devdata[i] = NULL; - lamebus->ls_irqfuncs[i] = NULL; - } + for (i = 0; i < LB_NSLOTS; i++) { + lamebus->ls_devdata[i] = NULL; + lamebus->ls_irqfuncs[i] = NULL; + } - lamebus->ls_uniprocessor = 0; + lamebus->ls_uniprocessor = 0; - return lamebus; + return lamebus; } diff --git a/kern/dev/lamebus/lamebus.h b/kern/dev/lamebus/lamebus.h index 1575759..6bdb7b2 100644 --- a/kern/dev/lamebus/lamebus.h +++ b/kern/dev/lamebus/lamebus.h @@ -39,39 +39,38 @@ * Machine-independent definitions. */ - /* Vendors */ -#define LB_VENDOR_CS161 1 +#define LB_VENDOR_CS161 1 /* CS161 devices */ -#define LBCS161_UPBUSCTL 1 -#define LBCS161_TIMER 2 -#define LBCS161_DISK 3 -#define LBCS161_SERIAL 4 -#define LBCS161_SCREEN 5 -#define LBCS161_NET 6 -#define LBCS161_EMUFS 7 -#define LBCS161_TRACE 8 -#define LBCS161_RANDOM 9 -#define LBCS161_MPBUSCTL 10 +#define LBCS161_UPBUSCTL 1 +#define LBCS161_TIMER 2 +#define LBCS161_DISK 3 +#define LBCS161_SERIAL 4 +#define LBCS161_SCREEN 5 +#define LBCS161_NET 6 +#define LBCS161_EMUFS 7 +#define LBCS161_TRACE 8 +#define LBCS161_RANDOM 9 +#define LBCS161_MPBUSCTL 10 /* LAMEbus controller always goes in slot 31 */ -#define LB_CONTROLLER_SLOT 31 +#define LB_CONTROLLER_SLOT 31 /* Number of slots */ -#define LB_NSLOTS 32 +#define LB_NSLOTS 32 /* LAMEbus controller per-slot config space */ -#define LB_CONFIG_SIZE 1024 +#define LB_CONFIG_SIZE 1024 /* LAMEbus controller per-cpu control space */ -#define LB_CTLCPU_SIZE 1024 +#define LB_CTLCPU_SIZE 1024 /* LAMEbus controller slot offset to per-cpu control space */ -#define LB_CTLCPU_OFFSET 32768 +#define LB_CTLCPU_OFFSET 32768 /* LAMEbus mapping size per slot */ -#define LB_SLOT_SIZE 65536 +#define LB_SLOT_SIZE 65536 /* Pointer to kind of function called on interrupt */ typedef void (*lb_irqfunc)(void *devdata); @@ -80,15 +79,15 @@ typedef void (*lb_irqfunc)(void *devdata); * Driver data */ struct lamebus_softc { - struct spinlock ls_lock; + struct spinlock ls_lock; - /* Accessed from interrupts; synchronized with ls_lock */ - uint32_t ls_slotsinuse; - void *ls_devdata[LB_NSLOTS]; - lb_irqfunc ls_irqfuncs[LB_NSLOTS]; + /* Accessed from interrupts; synchronized with ls_lock */ + uint32_t ls_slotsinuse; + void *ls_devdata[LB_NSLOTS]; + lb_irqfunc ls_irqfuncs[LB_NSLOTS]; - /* Read-only once set early in boot */ - unsigned ls_uniprocessor; + /* Read-only once set early in boot */ + unsigned ls_uniprocessor; }; /* @@ -113,9 +112,8 @@ void lamebus_start_cpus(struct lamebus_softc *lamebus); * * Returns a slot number (0-31) or -1 if no such device is found. */ -int lamebus_probe(struct lamebus_softc *, - uint32_t vendorid, uint32_t deviceid, - uint32_t lowver, uint32_t *version_ret); +int lamebus_probe(struct lamebus_softc *, uint32_t vendorid, uint32_t deviceid, + uint32_t lowver, uint32_t *version_ret); /* * Mark a slot in-use (that is, has a device driver attached to it), @@ -128,9 +126,8 @@ void lamebus_unmark(struct lamebus_softc *, int slot); /* * Attach to an interrupt. */ -void lamebus_attach_interrupt(struct lamebus_softc *, int slot, - void *devdata, - void (*irqfunc)(void *devdata)); +void lamebus_attach_interrupt(struct lamebus_softc *, int slot, void *devdata, + void (*irqfunc)(void *devdata)); /* * Detach from interrupt. */ @@ -168,15 +165,13 @@ void lamebus_clear_ipi(struct lamebus_softc *, struct cpu *targetcpu); * (Machine dependent.) */ uint32_t lamebus_read_register(struct lamebus_softc *, int slot, - uint32_t offset); -void lamebus_write_register(struct lamebus_softc *, int slot, - uint32_t offset, uint32_t val); + uint32_t offset); +void lamebus_write_register(struct lamebus_softc *, int slot, uint32_t offset, + uint32_t val); /* * Map a buffer that starts at offset OFFSET within slot SLOT. */ -void *lamebus_map_area(struct lamebus_softc *, int slot, - uint32_t offset); - +void *lamebus_map_area(struct lamebus_softc *, int slot, uint32_t offset); #endif /* _LAMEBUS_H_ */ diff --git a/kern/dev/lamebus/lhd.c b/kern/dev/lamebus/lhd.c index 9d9d9b5..97d2f9a 100644 --- a/kern/dev/lamebus/lhd.c +++ b/kern/dev/lamebus/lhd.c @@ -43,68 +43,60 @@ #include "autoconf.h" /* Registers (offsets within slot) */ -#define LHD_REG_NSECT 0 /* Number of sectors */ -#define LHD_REG_STAT 4 /* Status */ -#define LHD_REG_SECT 8 /* Sector for I/O */ -#define LHD_REG_RPM 12 /* Disk rotation speed (revs per minute) */ +#define LHD_REG_NSECT 0 /* Number of sectors */ +#define LHD_REG_STAT 4 /* Status */ +#define LHD_REG_SECT 8 /* Sector for I/O */ +#define LHD_REG_RPM 12 /* Disk rotation speed (revs per minute) */ /* Status codes */ -#define LHD_IDLE 0 /* Device idle */ -#define LHD_WORKING 1 /* Operation in progress */ -#define LHD_OK 4 /* Operation succeeded */ -#define LHD_INVSECT 12 /* Invalid sector requested */ -#define LHD_MEDIA 20 /* Media error */ -#define LHD_ISWRITE 2 /* OR with above: I/O is a write */ -#define LHD_STATEMASK 0x1d /* mask for masking out LHD_ISWRITE */ +#define LHD_IDLE 0 /* Device idle */ +#define LHD_WORKING 1 /* Operation in progress */ +#define LHD_OK 4 /* Operation succeeded */ +#define LHD_INVSECT 12 /* Invalid sector requested */ +#define LHD_MEDIA 20 /* Media error */ +#define LHD_ISWRITE 2 /* OR with above: I/O is a write */ +#define LHD_STATEMASK 0x1d /* mask for masking out LHD_ISWRITE */ /* Buffer (offset within slot) */ -#define LHD_BUFFER 32768 +#define LHD_BUFFER 32768 /* * Shortcut for reading a register. */ -static -inline -uint32_t lhd_rdreg(struct lhd_softc *lh, uint32_t reg) -{ - return bus_read_register(lh->lh_busdata, lh->lh_buspos, reg); +static inline uint32_t lhd_rdreg(struct lhd_softc *lh, uint32_t reg) { + return bus_read_register(lh->lh_busdata, lh->lh_buspos, reg); } /* * Shortcut for writing a register. */ -static -inline -void lhd_wreg(struct lhd_softc *lh, uint32_t reg, uint32_t val) -{ - bus_write_register(lh->lh_busdata, lh->lh_buspos, reg, val); +static inline void lhd_wreg(struct lhd_softc *lh, uint32_t reg, uint32_t val) { + bus_write_register(lh->lh_busdata, lh->lh_buspos, reg, val); } /* * Convert a result code from the hardware to an errno value. */ -static -int lhd_code_to_errno(struct lhd_softc *lh, int code) -{ - switch (code & LHD_STATEMASK) { - case LHD_OK: return 0; - case LHD_INVSECT: return EINVAL; - case LHD_MEDIA: return EIO; - } - kprintf("lhd%d: Unknown result code %d\n", lh->lh_unit, code); - return EAGAIN; +static int lhd_code_to_errno(struct lhd_softc *lh, int code) { + switch (code & LHD_STATEMASK) { + case LHD_OK: + return 0; + case LHD_INVSECT: + return EINVAL; + case LHD_MEDIA: + return EIO; + } + kprintf("lhd%d: Unknown result code %d\n", lh->lh_unit, code); + return EAGAIN; } /* * Record that an I/O has completed: save the result and poke the * completion semaphore. */ -static -void -lhd_iodone(struct lhd_softc *lh, int err) -{ - lh->lh_result = err; - V(lh->lh_done); +static void lhd_iodone(struct lhd_softc *lh, int err) { + lh->lh_result = err; + V(lh->lh_done); } /* @@ -112,57 +104,49 @@ lhd_iodone(struct lhd_softc *lh, int err) * Read the status register; if an operation finished, clear the status * register and report completion. */ -void -lhd_irq(void *vlh) -{ - struct lhd_softc *lh = vlh; - uint32_t val; +void lhd_irq(void *vlh) { + struct lhd_softc *lh = vlh; + uint32_t val; - val = lhd_rdreg(lh, LHD_REG_STAT); + val = lhd_rdreg(lh, LHD_REG_STAT); - switch (val & LHD_STATEMASK) { - case LHD_IDLE: - case LHD_WORKING: - break; - case LHD_OK: - case LHD_INVSECT: - case LHD_MEDIA: - lhd_wreg(lh, LHD_REG_STAT, 0); - lhd_iodone(lh, lhd_code_to_errno(lh, val)); - break; - } + switch (val & LHD_STATEMASK) { + case LHD_IDLE: + case LHD_WORKING: + break; + case LHD_OK: + case LHD_INVSECT: + case LHD_MEDIA: + lhd_wreg(lh, LHD_REG_STAT, 0); + lhd_iodone(lh, lhd_code_to_errno(lh, val)); + break; + } } /* * Function called when we are open()'d. */ -static -int -lhd_eachopen(struct device *d, int openflags) -{ - /* - * Don't need to do anything. - */ - (void)d; - (void)openflags; +static int lhd_eachopen(struct device *d, int openflags) { + /* + * Don't need to do anything. + */ + (void)d; + (void)openflags; - return 0; + return 0; } /* * Function for handling ioctls. */ -static -int -lhd_ioctl(struct device *d, int op, userptr_t data) -{ - /* - * We don't support any ioctls. - */ - (void)d; - (void)op; - (void)data; - return EIOCTL; +static int lhd_ioctl(struct device *d, int op, userptr_t data) { + /* + * We don't support any ioctls. + */ + (void)d; + (void)op; + (void)data; + return EIOCTL; } #if 0 @@ -182,127 +166,122 @@ lhd_reset(struct lhd_softc *lh) /* * I/O function (for both reads and writes) */ -static -int -lhd_io(struct device *d, struct uio *uio) -{ - struct lhd_softc *lh = d->d_data; +static int lhd_io(struct device *d, struct uio *uio) { + struct lhd_softc *lh = d->d_data; - uint32_t sector = uio->uio_offset / LHD_SECTSIZE; - uint32_t sectoff = uio->uio_offset % LHD_SECTSIZE; - uint32_t len = uio->uio_resid / LHD_SECTSIZE; - uint32_t lenoff = uio->uio_resid % LHD_SECTSIZE; - uint32_t i; - uint32_t statval = LHD_WORKING; - int result; + uint32_t sector = uio->uio_offset / LHD_SECTSIZE; + uint32_t sectoff = uio->uio_offset % LHD_SECTSIZE; + uint32_t len = uio->uio_resid / LHD_SECTSIZE; + uint32_t lenoff = uio->uio_resid % LHD_SECTSIZE; + uint32_t i; + uint32_t statval = LHD_WORKING; + int result; - /* Don't allow I/O that isn't sector-aligned. */ - if (sectoff != 0 || lenoff != 0) { - return EINVAL; - } + /* Don't allow I/O that isn't sector-aligned. */ + if (sectoff != 0 || lenoff != 0) { + return EINVAL; + } - /* Don't allow I/O past the end of the disk. */ - /* XXX this check can overflow */ - if (sector+len > lh->lh_dev.d_blocks) { - return EINVAL; - } + /* Don't allow I/O past the end of the disk. */ + /* XXX this check can overflow */ + if (sector + len > lh->lh_dev.d_blocks) { + return EINVAL; + } - /* Set up the value to write into the status register. */ - if (uio->uio_rw==UIO_WRITE) { - statval |= LHD_ISWRITE; - } + /* Set up the value to write into the status register. */ + if (uio->uio_rw == UIO_WRITE) { + statval |= LHD_ISWRITE; + } - /* Loop over all the sectors we were asked to do. */ - for (i=0; ilh_clear); + /* Wait until nobody else is using the device. */ + P(lh->lh_clear); - /* - * Are we writing? If so, transfer the data to the - * on-card buffer. - */ - if (uio->uio_rw == UIO_WRITE) { - result = uiomove(lh->lh_buf, LHD_SECTSIZE, uio); - membar_store_store(); - if (result) { - V(lh->lh_clear); - return result; - } - } + /* + * Are we writing? If so, transfer the data to the + * on-card buffer. + */ + if (uio->uio_rw == UIO_WRITE) { + result = uiomove(lh->lh_buf, LHD_SECTSIZE, uio); + membar_store_store(); + if (result) { + V(lh->lh_clear); + return result; + } + } - /* Tell it what sector we want... */ - lhd_wreg(lh, LHD_REG_SECT, sector+i); + /* Tell it what sector we want... */ + lhd_wreg(lh, LHD_REG_SECT, sector + i); - /* and start the operation. */ - lhd_wreg(lh, LHD_REG_STAT, statval); + /* and start the operation. */ + lhd_wreg(lh, LHD_REG_STAT, statval); - /* Now wait until the interrupt handler tells us we're done. */ - P(lh->lh_done); + /* Now wait until the interrupt handler tells us we're done. */ + P(lh->lh_done); - /* Get the result value saved by the interrupt handler. */ - result = lh->lh_result; + /* Get the result value saved by the interrupt handler. */ + result = lh->lh_result; - /* - * Are we reading? If so, and if we succeeded, - * transfer the data out of the on-card buffer. - */ - if (result==0 && uio->uio_rw==UIO_READ) { - membar_load_load(); - result = uiomove(lh->lh_buf, LHD_SECTSIZE, uio); - } + /* + * Are we reading? If so, and if we succeeded, + * transfer the data out of the on-card buffer. + */ + if (result == 0 && uio->uio_rw == UIO_READ) { + membar_load_load(); + result = uiomove(lh->lh_buf, LHD_SECTSIZE, uio); + } - /* Tell another thread it's cleared to go ahead. */ - V(lh->lh_clear); + /* Tell another thread it's cleared to go ahead. */ + V(lh->lh_clear); - /* If we failed, return the error. */ - if (result) { - return result; - } - } + /* If we failed, return the error. */ + if (result) { + return result; + } + } - return 0; + return 0; } static const struct device_ops lhd_devops = { - .devop_eachopen = lhd_eachopen, - .devop_io = lhd_io, - .devop_ioctl = lhd_ioctl, + .devop_eachopen = lhd_eachopen, + .devop_io = lhd_io, + .devop_ioctl = lhd_ioctl, }; /* * Setup routine called by autoconf.c when an lhd is found. */ -int -config_lhd(struct lhd_softc *lh, int lhdno) -{ - char name[32]; +int config_lhd(struct lhd_softc *lh, int lhdno) { + char name[32]; - /* Figure out what our name is. */ - snprintf(name, sizeof(name), "lhd%d", lhdno); + /* Figure out what our name is. */ + snprintf(name, sizeof(name), "lhd%d", lhdno); - /* Get a pointer to the on-chip buffer. */ - lh->lh_buf = bus_map_area(lh->lh_busdata, lh->lh_buspos, LHD_BUFFER); + /* Get a pointer to the on-chip buffer. */ + lh->lh_buf = bus_map_area(lh->lh_busdata, lh->lh_buspos, LHD_BUFFER); - /* Create the semaphores. */ - lh->lh_clear = sem_create("lhd-clear", 1); - if (lh->lh_clear == NULL) { - return ENOMEM; - } - lh->lh_done = sem_create("lhd-done", 0); - if (lh->lh_done == NULL) { - sem_destroy(lh->lh_clear); - lh->lh_clear = NULL; - return ENOMEM; - } + /* Create the semaphores. */ + lh->lh_clear = sem_create("lhd-clear", 1); + if (lh->lh_clear == NULL) { + return ENOMEM; + } + lh->lh_done = sem_create("lhd-done", 0); + if (lh->lh_done == NULL) { + sem_destroy(lh->lh_clear); + lh->lh_clear = NULL; + return ENOMEM; + } - /* Set up the VFS device structure. */ - lh->lh_dev.d_ops = &lhd_devops; - lh->lh_dev.d_blocks = bus_read_register(lh->lh_busdata, lh->lh_buspos, - LHD_REG_NSECT); - lh->lh_dev.d_blocksize = LHD_SECTSIZE; - lh->lh_dev.d_data = lh; + /* Set up the VFS device structure. */ + lh->lh_dev.d_ops = &lhd_devops; + lh->lh_dev.d_blocks = + bus_read_register(lh->lh_busdata, lh->lh_buspos, LHD_REG_NSECT); + lh->lh_dev.d_blocksize = LHD_SECTSIZE; + lh->lh_dev.d_data = lh; - /* Add the VFS device structure to the VFS device list. */ - return vfs_adddev(name, &lh->lh_dev, 1); + /* Add the VFS device structure to the VFS device list. */ + return vfs_adddev(name, &lh->lh_dev, 1); } diff --git a/kern/dev/lamebus/lhd.h b/kern/dev/lamebus/lhd.h index d03ef8a..7a2a4f6 100644 --- a/kern/dev/lamebus/lhd.h +++ b/kern/dev/lamebus/lhd.h @@ -35,30 +35,30 @@ /* * Our sector size */ -#define LHD_SECTSIZE 512 +#define LHD_SECTSIZE 512 /* * Hardware device data associated with lhd (LAMEbus hard disk) */ struct lhd_softc { - /* Initialized by lower-level attach code */ - void *lh_busdata; /* The bus we're on */ - uint32_t lh_buspos; /* Our slot on that bus */ - int lh_unit; /* What number lhd we are */ + /* Initialized by lower-level attach code */ + void *lh_busdata; /* The bus we're on */ + uint32_t lh_buspos; /* Our slot on that bus */ + int lh_unit; /* What number lhd we are */ - /* - * Initialized by config_lhd - */ + /* + * Initialized by config_lhd + */ - void *lh_buf; /* Pointer to on-card I/O buffer */ - int lh_result; /* Result from I/O operation */ - struct semaphore *lh_clear; /* Synchronization */ - struct semaphore *lh_done; + void *lh_buf; /* Pointer to on-card I/O buffer */ + int lh_result; /* Result from I/O operation */ + struct semaphore *lh_clear; /* Synchronization */ + struct semaphore *lh_done; - struct device lh_dev; /* VFS device structure */ + struct device lh_dev; /* VFS device structure */ }; /* Functions called by lower-level drivers */ -void lhd_irq(/*struct lhd_softc*/ void *); /* Interrupt handler */ +void lhd_irq(/*struct lhd_softc*/ void *); /* Interrupt handler */ #endif /* _LAMEBUS_LHD_H_ */ diff --git a/kern/dev/lamebus/lhd_att.c b/kern/dev/lamebus/lhd_att.c index 161387b..7d80b87 100644 --- a/kern/dev/lamebus/lhd_att.c +++ b/kern/dev/lamebus/lhd_att.c @@ -37,33 +37,31 @@ #include "autoconf.h" /* Lowest revision we support */ -#define LOW_VERSION 2 +#define LOW_VERSION 2 -struct lhd_softc * -attach_lhd_to_lamebus(int lhdno, struct lamebus_softc *sc) -{ - struct lhd_softc *lh; - int slot = lamebus_probe(sc, LB_VENDOR_CS161, LBCS161_DISK, - LOW_VERSION, NULL); - if (slot < 0) { - /* None found */ - return NULL; - } +struct lhd_softc *attach_lhd_to_lamebus(int lhdno, struct lamebus_softc *sc) { + struct lhd_softc *lh; + int slot = + lamebus_probe(sc, LB_VENDOR_CS161, LBCS161_DISK, LOW_VERSION, NULL); + if (slot < 0) { + /* None found */ + return NULL; + } - lh = kmalloc(sizeof(struct lhd_softc)); - if (lh==NULL) { - /* Out of memory */ - return NULL; - } + lh = kmalloc(sizeof(struct lhd_softc)); + if (lh == NULL) { + /* Out of memory */ + return NULL; + } - /* Record what the lhd is attached to */ - lh->lh_busdata = sc; - lh->lh_buspos = slot; - lh->lh_unit = lhdno; + /* Record what the lhd is attached to */ + lh->lh_busdata = sc; + lh->lh_buspos = slot; + lh->lh_unit = lhdno; - /* Mark the slot in use and collect interrupts */ - lamebus_mark(sc, slot); - lamebus_attach_interrupt(sc, slot, lh, lhd_irq); + /* Mark the slot in use and collect interrupts */ + lamebus_mark(sc, slot); + lamebus_attach_interrupt(sc, slot, lh, lhd_irq); - return lh; + return lh; } diff --git a/kern/dev/lamebus/lnet.c b/kern/dev/lamebus/lnet.c index d8af40b..710e14d 100644 --- a/kern/dev/lamebus/lnet.c +++ b/kern/dev/lamebus/lnet.c @@ -33,14 +33,10 @@ /*#include */ /* not yet */ #include "autoconf.h" -int -config_lnet(struct lnet_softc *sc, int lnetno) -{ - (void)sc; +int config_lnet(struct lnet_softc *sc, int lnetno) { + (void)sc; - kprintf("lnet%d: No network support in system\n", lnetno); + kprintf("lnet%d: No network support in system\n", lnetno); - return ENODEV; + return ENODEV; } - - diff --git a/kern/dev/lamebus/lnet_att.c b/kern/dev/lamebus/lnet_att.c index 0a84133..0e2e954 100644 --- a/kern/dev/lamebus/lnet_att.c +++ b/kern/dev/lamebus/lnet_att.c @@ -33,20 +33,19 @@ #include "autoconf.h" /* Lowest revision we support */ -#define LOW_VERSION 1 +#define LOW_VERSION 1 /* Highest revision we support */ -#define HIGH_VERSION 1 +#define HIGH_VERSION 1 -struct lnet_softc * -attach_lnet_to_lamebus(int lnetno, struct lamebus_softc *sc) -{ - int slot = lamebus_probe(sc, LB_VENDOR_CS161, LBCS161_NET, - LOW_VERSION, HIGH_VERSION); - if (slot < 0) { - return NULL; - } +struct lnet_softc *attach_lnet_to_lamebus(int lnetno, + struct lamebus_softc *sc) { + int slot = lamebus_probe(sc, LB_VENDOR_CS161, LBCS161_NET, LOW_VERSION, + HIGH_VERSION); + if (slot < 0) { + return NULL; + } - kprintf("lnet%d: No network support in system\n", lnetno); + kprintf("lnet%d: No network support in system\n", lnetno); - return NULL; + return NULL; } diff --git a/kern/dev/lamebus/lrandom.c b/kern/dev/lamebus/lrandom.c index e997e27..b1c1caf 100644 --- a/kern/dev/lamebus/lrandom.c +++ b/kern/dev/lamebus/lrandom.c @@ -38,48 +38,39 @@ #include "autoconf.h" /* Registers (offsets within slot) */ -#define LR_REG_RAND 0 /* random register */ +#define LR_REG_RAND 0 /* random register */ /* Constants */ -#define LR_RANDMAX 0xffffffff +#define LR_RANDMAX 0xffffffff -int -config_lrandom(struct lrandom_softc *lr, int lrandomno) -{ - (void)lrandomno; - (void)lr; - return 0; +int config_lrandom(struct lrandom_softc *lr, int lrandomno) { + (void)lrandomno; + (void)lr; + return 0; } -uint32_t -lrandom_random(void *devdata) -{ - struct lrandom_softc *lr = devdata; - return bus_read_register(lr->lr_bus, lr->lr_buspos, LR_REG_RAND); +uint32_t lrandom_random(void *devdata) { + struct lrandom_softc *lr = devdata; + return bus_read_register(lr->lr_bus, lr->lr_buspos, LR_REG_RAND); } -uint32_t -lrandom_randmax(void *devdata) -{ - (void)devdata; - return LR_RANDMAX; +uint32_t lrandom_randmax(void *devdata) { + (void)devdata; + return LR_RANDMAX; } -int -lrandom_read(void *devdata, struct uio *uio) -{ - struct lrandom_softc *lr = devdata; - uint32_t val; - int result; +int lrandom_read(void *devdata, struct uio *uio) { + struct lrandom_softc *lr = devdata; + uint32_t val; + int result; - while (uio->uio_resid > 0) { - val = bus_read_register(lr->lr_bus, lr->lr_buspos, - LR_REG_RAND); - result = uiomove(&val, sizeof(val), uio); - if (result) { - return result; - } - } + while (uio->uio_resid > 0) { + val = bus_read_register(lr->lr_bus, lr->lr_buspos, LR_REG_RAND); + result = uiomove(&val, sizeof(val), uio); + if (result) { + return result; + } + } - return 0; + return 0; } diff --git a/kern/dev/lamebus/lrandom.h b/kern/dev/lamebus/lrandom.h index 4087fd0..53438ad 100644 --- a/kern/dev/lamebus/lrandom.h +++ b/kern/dev/lamebus/lrandom.h @@ -33,9 +33,9 @@ struct uio; struct lrandom_softc { - /* Initialized by lower-level attach routine */ - void *lr_bus; - uint32_t lr_buspos; + /* Initialized by lower-level attach routine */ + void *lr_bus; + uint32_t lr_buspos; }; /* Functions called by higher-level drivers */ diff --git a/kern/dev/lamebus/lrandom_att.c b/kern/dev/lamebus/lrandom_att.c index 8cb2176..924965a 100644 --- a/kern/dev/lamebus/lrandom_att.c +++ b/kern/dev/lamebus/lrandom_att.c @@ -34,29 +34,28 @@ #include "autoconf.h" /* Lowest revision we support */ -#define LOW_VERSION 1 +#define LOW_VERSION 1 -struct lrandom_softc * -attach_lrandom_to_lamebus(int lrandomno, struct lamebus_softc *sc) -{ - struct lrandom_softc *lr; - int slot = lamebus_probe(sc, LB_VENDOR_CS161, LBCS161_RANDOM, - LOW_VERSION, NULL); - if (slot < 0) { - return NULL; - } +struct lrandom_softc *attach_lrandom_to_lamebus(int lrandomno, + struct lamebus_softc *sc) { + struct lrandom_softc *lr; + int slot = + lamebus_probe(sc, LB_VENDOR_CS161, LBCS161_RANDOM, LOW_VERSION, NULL); + if (slot < 0) { + return NULL; + } - lr = kmalloc(sizeof(struct lrandom_softc)); - if (lr==NULL) { - return NULL; - } + lr = kmalloc(sizeof(struct lrandom_softc)); + if (lr == NULL) { + return NULL; + } - (void)lrandomno; // unused + (void)lrandomno; // unused - lr->lr_bus = sc; - lr->lr_buspos = slot; + lr->lr_bus = sc; + lr->lr_buspos = slot; - lamebus_mark(sc, slot); + lamebus_mark(sc, slot); - return lr; + return lr; } diff --git a/kern/dev/lamebus/lscreen.c b/kern/dev/lamebus/lscreen.c index 9bdee81..c7ed008 100644 --- a/kern/dev/lamebus/lscreen.c +++ b/kern/dev/lamebus/lscreen.c @@ -41,37 +41,29 @@ #include "autoconf.h" /* Registers (offsets within slot) */ -#define LSCR_REG_POSN 0 /* Cursor position */ -#define LSCR_REG_SIZE 4 /* Display size */ -#define LSCR_REG_CHAR 8 /* Character in */ -#define LSCR_REG_RIRQ 12 /* Read interrupt status */ +#define LSCR_REG_POSN 0 /* Cursor position */ +#define LSCR_REG_SIZE 4 /* Display size */ +#define LSCR_REG_CHAR 8 /* Character in */ +#define LSCR_REG_RIRQ 12 /* Read interrupt status */ /* Bits in the IRQ registers */ -#define LSCR_IRQ_ENABLE 1 -#define LSCR_IRQ_ACTIVE 2 +#define LSCR_IRQ_ENABLE 1 +#define LSCR_IRQ_ACTIVE 2 /* Offset within slot of screen buffer */ -#define LSCR_SCREEN 32768 +#define LSCR_SCREEN 32768 /* Convert a 32-bit X/Y pair to X and Y coordinates. */ -static -inline -void -splitxy(uint32_t xy, unsigned *x, unsigned *y) -{ - *x = xy >> 16; - *y = xy & 0xffff; +static inline void splitxy(uint32_t xy, unsigned *x, unsigned *y) { + *x = xy >> 16; + *y = xy & 0xffff; } /* Convert X and Y coordinates to a single 32-bit value. */ -static -inline -uint32_t -mergexy(unsigned x, unsigned y) -{ - uint32_t val = x; +static inline uint32_t mergexy(unsigned x, unsigned y) { + uint32_t val = x; - return (val << 16) | y; + return (val << 16) | y; } //////////////////////////////////////////////////////////// @@ -79,29 +71,25 @@ mergexy(unsigned x, unsigned y) /* * Interrupt handler. */ -void -lscreen_irq(void *vsc) -{ - struct lscreen_softc *sc = vsc; - uint32_t ch, x; +void lscreen_irq(void *vsc) { + struct lscreen_softc *sc = vsc; + uint32_t ch, x; - spinlock_acquire(&sc->ls_lock); + spinlock_acquire(&sc->ls_lock); - x = bus_read_register(sc->ls_busdata, sc->ls_buspos, LSCR_REG_RIRQ); - if (x & LSCR_IRQ_ACTIVE) { - ch = bus_read_register(sc->ls_busdata, sc->ls_buspos, - LSCR_REG_CHAR); - bus_write_register(sc->ls_busdata, sc->ls_buspos, - LSCR_REG_RIRQ, LSCR_IRQ_ENABLE); + x = bus_read_register(sc->ls_busdata, sc->ls_buspos, LSCR_REG_RIRQ); + if (x & LSCR_IRQ_ACTIVE) { + ch = bus_read_register(sc->ls_busdata, sc->ls_buspos, LSCR_REG_CHAR); + bus_write_register(sc->ls_busdata, sc->ls_buspos, LSCR_REG_RIRQ, + LSCR_IRQ_ENABLE); - spinlock_release(&sc->ls_lock); - if (sc->ls_input) { - sc->ls_input(sc->ls_devdata, ch); - } - } - else { - spinlock_release(&sc->ls_lock); - } + spinlock_release(&sc->ls_lock); + if (sc->ls_input) { + sc->ls_input(sc->ls_devdata, ch); + } + } else { + spinlock_release(&sc->ls_lock); + } } //////////////////////////////////////////////////////////// @@ -109,74 +97,68 @@ lscreen_irq(void *vsc) /* * Handle a newline on the screen. */ -static -void -lscreen_newline(struct lscreen_softc *sc) -{ - if (sc->ls_cy >= sc->ls_height-1) { - /* - * Scroll - */ +static void lscreen_newline(struct lscreen_softc *sc) { + if (sc->ls_cy >= sc->ls_height - 1) { + /* + * Scroll + */ - memmove(sc->ls_screen, sc->ls_screen + sc->ls_width, - sc->ls_width * (sc->ls_height-1)); - bzero(sc->ls_screen + sc->ls_width * (sc->ls_height-1), - sc->ls_width); - } - else { - sc->ls_cy++; - } - sc->ls_cx=0; + memmove(sc->ls_screen, sc->ls_screen + sc->ls_width, + sc->ls_width * (sc->ls_height - 1)); + bzero(sc->ls_screen + sc->ls_width * (sc->ls_height - 1), sc->ls_width); + } else { + sc->ls_cy++; + } + sc->ls_cx = 0; } /* * Handle a printable character being written to the screen. */ -static -void -lscreen_char(struct lscreen_softc *sc, int ch) -{ - if (sc->ls_cx >= sc->ls_width) { - lscreen_newline(sc); - } +static void lscreen_char(struct lscreen_softc *sc, int ch) { + if (sc->ls_cx >= sc->ls_width) { + lscreen_newline(sc); + } - sc->ls_screen[sc->ls_cy*sc->ls_width + sc->ls_cx] = ch; - sc->ls_cx++; + sc->ls_screen[sc->ls_cy * sc->ls_width + sc->ls_cx] = ch; + sc->ls_cx++; } /* * Send a character to the screen. * This should probably know about backspace and tab. */ -void -lscreen_write(void *vsc, int ch) -{ - struct lscreen_softc *sc = vsc; - int ccx, ccy; +void lscreen_write(void *vsc, int ch) { + struct lscreen_softc *sc = vsc; + int ccx, ccy; - spinlock_acquire(&sc->ls_lock); + spinlock_acquire(&sc->ls_lock); - switch (ch) { - case '\n': lscreen_newline(sc); break; - default: lscreen_char(sc, ch); break; - } + switch (ch) { + case '\n': + lscreen_newline(sc); + break; + default: + lscreen_char(sc, ch); + break; + } - /* - * ccx/ccy = corrected cursor position - * (The cursor marks the next space text will appear in. But - * at the very end of the line, it should not move off the edge.) - */ - ccx = sc->ls_cx; - ccy = sc->ls_cy; - if (ccx==sc->ls_width) { - ccx--; - } + /* + * ccx/ccy = corrected cursor position + * (The cursor marks the next space text will appear in. But + * at the very end of the line, it should not move off the edge.) + */ + ccx = sc->ls_cx; + ccy = sc->ls_cy; + if (ccx == sc->ls_width) { + ccx--; + } - /* Set the cursor position */ - bus_write_register(sc->ls_busdata, sc->ls_buspos, - LSCR_REG_POSN, mergexy(ccx, ccy)); + /* Set the cursor position */ + bus_write_register(sc->ls_busdata, sc->ls_buspos, LSCR_REG_POSN, + mergexy(ccx, ccy)); - spinlock_release(&sc->ls_lock); + spinlock_release(&sc->ls_lock); } //////////////////////////////////////////////////////////// @@ -184,42 +166,36 @@ lscreen_write(void *vsc, int ch) /* * Setup routine called by autoconf.c when an lscreen is found. */ -int -config_lscreen(struct lscreen_softc *sc, int lscreenno) -{ - uint32_t val; +int config_lscreen(struct lscreen_softc *sc, int lscreenno) { + uint32_t val; - (void)lscreenno; + (void)lscreenno; - spinlock_init(&sc->ls_lock); + spinlock_init(&sc->ls_lock); - /* - * Enable interrupting. - */ + /* + * Enable interrupting. + */ - bus_write_register(sc->ls_busdata, sc->ls_buspos, - LSCR_REG_RIRQ, LSCR_IRQ_ENABLE); + bus_write_register(sc->ls_busdata, sc->ls_buspos, LSCR_REG_RIRQ, + LSCR_IRQ_ENABLE); - /* - * Get screen size. - */ - val = bus_read_register(sc->ls_busdata, sc->ls_buspos, - LSCR_REG_SIZE); - splitxy(val, &sc->ls_width, &sc->ls_height); + /* + * Get screen size. + */ + val = bus_read_register(sc->ls_busdata, sc->ls_buspos, LSCR_REG_SIZE); + splitxy(val, &sc->ls_width, &sc->ls_height); - /* - * Get cursor position. - */ - val = bus_read_register(sc->ls_busdata, sc->ls_buspos, - LSCR_REG_POSN); - splitxy(val, &sc->ls_cx, &sc->ls_cy); + /* + * Get cursor position. + */ + val = bus_read_register(sc->ls_busdata, sc->ls_buspos, LSCR_REG_POSN); + splitxy(val, &sc->ls_cx, &sc->ls_cy); - /* - * Get a pointer to the memory-mapped screen area. - */ - sc->ls_screen = bus_map_area(sc->ls_busdata, sc->ls_buspos, - LSCR_SCREEN); + /* + * Get a pointer to the memory-mapped screen area. + */ + sc->ls_screen = bus_map_area(sc->ls_busdata, sc->ls_buspos, LSCR_SCREEN); - return 0; + return 0; } - diff --git a/kern/dev/lamebus/lscreen.h b/kern/dev/lamebus/lscreen.h index 16fa405..98df6fa 100644 --- a/kern/dev/lamebus/lscreen.h +++ b/kern/dev/lamebus/lscreen.h @@ -34,24 +34,24 @@ * Hardware device data for memory-mapped fullscreen text console. */ struct lscreen_softc { - /* Initialized by config function */ - struct spinlock ls_lock; // protects data and device regs - unsigned ls_width, ls_height; // screen size - unsigned ls_cx, ls_cy; // cursor position - char *ls_screen; // memory-mapped screen buffer + /* Initialized by config function */ + struct spinlock ls_lock; // protects data and device regs + unsigned ls_width, ls_height; // screen size + unsigned ls_cx, ls_cy; // cursor position + char *ls_screen; // memory-mapped screen buffer - /* Initialized by lower-level attachment function */ - void *ls_busdata; // bus we're on - uint32_t ls_buspos; // position on that bus + /* Initialized by lower-level attachment function */ + void *ls_busdata; // bus we're on + uint32_t ls_buspos; // position on that bus - /* Initialized by higher-level attachment function */ - void *ls_devdata; // data and functions for - void (*ls_start)(void *devdata); // upper device (perhaps - void (*ls_input)(void *devdata, int ch); // console) + /* Initialized by higher-level attachment function */ + void *ls_devdata; // data and functions for + void (*ls_start)(void *devdata); // upper device (perhaps + void (*ls_input)(void *devdata, int ch); // console) }; /* Functions called by lower-level drivers */ -void lscreen_irq(/*struct lser_softc*/ void *sc); // interrupt handler +void lscreen_irq(/*struct lser_softc*/ void *sc); // interrupt handler /* Functions called by higher-level drivers */ void lscreen_write(/*struct lser_softc*/ void *sc, int ch); // output function diff --git a/kern/dev/lamebus/lscreen_att.c b/kern/dev/lamebus/lscreen_att.c index 07d9845..163f15a 100644 --- a/kern/dev/lamebus/lscreen_att.c +++ b/kern/dev/lamebus/lscreen_att.c @@ -37,34 +37,33 @@ #include "autoconf.h" /* Lowest revision we support */ -#define LOW_VERSION 1 +#define LOW_VERSION 1 /* Highest revision we support */ -#define HIGH_VERSION 1 +#define HIGH_VERSION 1 -struct lscreen_softc * -attach_lscreen_to_lamebus(int lscreenno, struct lamebus_softc *sc) -{ - struct lscreen_softc *ls; - int slot = lamebus_probe(sc, LB_VENDOR_CS161, LBCS161_SCREEN, - LOW_VERSION, HIGH_VERSION); - if (slot < 0) { - /* Not found */ - return NULL; - } +struct lscreen_softc *attach_lscreen_to_lamebus(int lscreenno, + struct lamebus_softc *sc) { + struct lscreen_softc *ls; + int slot = lamebus_probe(sc, LB_VENDOR_CS161, LBCS161_SCREEN, LOW_VERSION, + HIGH_VERSION); + if (slot < 0) { + /* Not found */ + return NULL; + } - ls = kmalloc(sizeof(struct lscreen_softc)); - if (ls==NULL) { - /* Out of memory */ - return NULL; - } + ls = kmalloc(sizeof(struct lscreen_softc)); + if (ls == NULL) { + /* Out of memory */ + return NULL; + } - /* Record what it's attached to */ - ls->ls_busdata = sc; - ls->ls_buspos = slot; + /* Record what it's attached to */ + ls->ls_busdata = sc; + ls->ls_buspos = slot; - /* Mark the slot in use and hook the interrupt */ - lamebus_mark(sc, slot); - lamebus_attach_interrupt(sc, slot, ls, lscreen_irq); + /* Mark the slot in use and hook the interrupt */ + lamebus_mark(sc, slot); + lamebus_attach_interrupt(sc, slot, ls, lscreen_irq); - return ls; + return ls; } diff --git a/kern/dev/lamebus/lser.c b/kern/dev/lamebus/lser.c index 178d22f..d7ddfe7 100644 --- a/kern/dev/lamebus/lser.c +++ b/kern/dev/lamebus/lser.c @@ -35,158 +35,139 @@ #include "autoconf.h" /* Registers (offsets within slot) */ -#define LSER_REG_CHAR 0 /* Character in/out */ -#define LSER_REG_WIRQ 4 /* Write interrupt status */ -#define LSER_REG_RIRQ 8 /* Read interrupt status */ +#define LSER_REG_CHAR 0 /* Character in/out */ +#define LSER_REG_WIRQ 4 /* Write interrupt status */ +#define LSER_REG_RIRQ 8 /* Read interrupt status */ /* Bits in the IRQ registers */ -#define LSER_IRQ_ENABLE 1 -#define LSER_IRQ_ACTIVE 2 -#define LSER_IRQ_FORCE 4 +#define LSER_IRQ_ENABLE 1 +#define LSER_IRQ_ACTIVE 2 +#define LSER_IRQ_FORCE 4 -void -lser_irq(void *vsc) -{ - struct lser_softc *sc = vsc; - uint32_t x; - bool clear_to_write = false; - bool got_a_read = false; - uint32_t ch = 0; +void lser_irq(void *vsc) { + struct lser_softc *sc = vsc; + uint32_t x; + bool clear_to_write = false; + bool got_a_read = false; + uint32_t ch = 0; - spinlock_acquire(&sc->ls_lock); + spinlock_acquire(&sc->ls_lock); - x = bus_read_register(sc->ls_busdata, sc->ls_buspos, LSER_REG_WIRQ); - if (x & LSER_IRQ_ACTIVE) { - x = LSER_IRQ_ENABLE; - sc->ls_wbusy = 0; - clear_to_write = true; - bus_write_register(sc->ls_busdata, sc->ls_buspos, - LSER_REG_WIRQ, x); - } + x = bus_read_register(sc->ls_busdata, sc->ls_buspos, LSER_REG_WIRQ); + if (x & LSER_IRQ_ACTIVE) { + x = LSER_IRQ_ENABLE; + sc->ls_wbusy = 0; + clear_to_write = true; + bus_write_register(sc->ls_busdata, sc->ls_buspos, LSER_REG_WIRQ, x); + } - x = bus_read_register(sc->ls_busdata, sc->ls_buspos, LSER_REG_RIRQ); - if (x & LSER_IRQ_ACTIVE) { - x = LSER_IRQ_ENABLE; - ch = bus_read_register(sc->ls_busdata, sc->ls_buspos, - LSER_REG_CHAR); - got_a_read = true; - bus_write_register(sc->ls_busdata, sc->ls_buspos, - LSER_REG_RIRQ, x); - } + x = bus_read_register(sc->ls_busdata, sc->ls_buspos, LSER_REG_RIRQ); + if (x & LSER_IRQ_ACTIVE) { + x = LSER_IRQ_ENABLE; + ch = bus_read_register(sc->ls_busdata, sc->ls_buspos, LSER_REG_CHAR); + got_a_read = true; + bus_write_register(sc->ls_busdata, sc->ls_buspos, LSER_REG_RIRQ, x); + } - spinlock_release(&sc->ls_lock); + spinlock_release(&sc->ls_lock); - if (clear_to_write && sc->ls_start != NULL) { - sc->ls_start(sc->ls_devdata); - } - if (got_a_read && sc->ls_input != NULL) { - sc->ls_input(sc->ls_devdata, ch); - } + if (clear_to_write && sc->ls_start != NULL) { + sc->ls_start(sc->ls_devdata); + } + if (got_a_read && sc->ls_input != NULL) { + sc->ls_input(sc->ls_devdata, ch); + } } -void -lser_write(void *vls, int ch) -{ - struct lser_softc *ls = vls; +void lser_write(void *vls, int ch) { + struct lser_softc *ls = vls; - spinlock_acquire(&ls->ls_lock); + spinlock_acquire(&ls->ls_lock); - if (ls->ls_wbusy) { - /* - * We're not clear to write. - * - * This should not happen. It's the job of the driver - * attached to us to not write until we call - * ls->ls_start. - * - * (Note: if we're the console, the panic will go to - * lser_writepolled for printing, because we hold a - * spinlock and interrupts are off; it won't recurse.) - */ - panic("lser: Not clear to write\n"); - } - ls->ls_wbusy = true; + if (ls->ls_wbusy) { + /* + * We're not clear to write. + * + * This should not happen. It's the job of the driver + * attached to us to not write until we call + * ls->ls_start. + * + * (Note: if we're the console, the panic will go to + * lser_writepolled for printing, because we hold a + * spinlock and interrupts are off; it won't recurse.) + */ + panic("lser: Not clear to write\n"); + } + ls->ls_wbusy = true; - bus_write_register(ls->ls_busdata, ls->ls_buspos, LSER_REG_CHAR, ch); + bus_write_register(ls->ls_busdata, ls->ls_buspos, LSER_REG_CHAR, ch); - spinlock_release(&ls->ls_lock); + spinlock_release(&ls->ls_lock); } -static -void -lser_poll_until_write(struct lser_softc *sc) -{ - uint32_t val; +static void lser_poll_until_write(struct lser_softc *sc) { + uint32_t val; - KASSERT(spinlock_do_i_hold(&sc->ls_lock)); + KASSERT(spinlock_do_i_hold(&sc->ls_lock)); - do { - val = bus_read_register(sc->ls_busdata, sc->ls_buspos, - LSER_REG_WIRQ); - } - while ((val & LSER_IRQ_ACTIVE) == 0); + do { + val = bus_read_register(sc->ls_busdata, sc->ls_buspos, LSER_REG_WIRQ); + } while ((val & LSER_IRQ_ACTIVE) == 0); } -void -lser_writepolled(void *vsc, int ch) -{ - struct lser_softc *sc = vsc; - bool irqpending; +void lser_writepolled(void *vsc, int ch) { + struct lser_softc *sc = vsc; + bool irqpending; - spinlock_acquire(&sc->ls_lock); + spinlock_acquire(&sc->ls_lock); - if (sc->ls_wbusy) { - irqpending = true; - lser_poll_until_write(sc); - /* Clear the ready condition, but leave the IRQ asserted */ - bus_write_register(sc->ls_busdata, sc->ls_buspos, - LSER_REG_WIRQ, - LSER_IRQ_FORCE|LSER_IRQ_ENABLE); - } - else { - irqpending = false; - /* Clear the interrupt enable bit */ - bus_write_register(sc->ls_busdata, sc->ls_buspos, - LSER_REG_WIRQ, 0); - } + if (sc->ls_wbusy) { + irqpending = true; + lser_poll_until_write(sc); + /* Clear the ready condition, but leave the IRQ asserted */ + bus_write_register(sc->ls_busdata, sc->ls_buspos, LSER_REG_WIRQ, + LSER_IRQ_FORCE | LSER_IRQ_ENABLE); + } else { + irqpending = false; + /* Clear the interrupt enable bit */ + bus_write_register(sc->ls_busdata, sc->ls_buspos, LSER_REG_WIRQ, 0); + } - /* Send the character. */ - bus_write_register(sc->ls_busdata, sc->ls_buspos, LSER_REG_CHAR, ch); + /* Send the character. */ + bus_write_register(sc->ls_busdata, sc->ls_buspos, LSER_REG_CHAR, ch); - /* Wait until it's done. */ - lser_poll_until_write(sc); + /* Wait until it's done. */ + lser_poll_until_write(sc); - /* - * If there wasn't already an IRQ pending, clear the ready - * condition and turn interruption back on. But if there was, - * leave the register alone, with the ready condition set (and - * the force bit still on); in due course we'll get to the - * interrupt handler and they'll be cleared. - */ - if (!irqpending) { - bus_write_register(sc->ls_busdata, sc->ls_buspos, - LSER_REG_WIRQ, LSER_IRQ_ENABLE); - } + /* + * If there wasn't already an IRQ pending, clear the ready + * condition and turn interruption back on. But if there was, + * leave the register alone, with the ready condition set (and + * the force bit still on); in due course we'll get to the + * interrupt handler and they'll be cleared. + */ + if (!irqpending) { + bus_write_register(sc->ls_busdata, sc->ls_buspos, LSER_REG_WIRQ, + LSER_IRQ_ENABLE); + } - spinlock_release(&sc->ls_lock); + spinlock_release(&sc->ls_lock); } -int -config_lser(struct lser_softc *sc, int lserno) -{ - (void)lserno; +int config_lser(struct lser_softc *sc, int lserno) { + (void)lserno; - /* - * Enable interrupting. - */ + /* + * Enable interrupting. + */ - spinlock_init(&sc->ls_lock); - sc->ls_wbusy = false; + spinlock_init(&sc->ls_lock); + sc->ls_wbusy = false; - bus_write_register(sc->ls_busdata, sc->ls_buspos, - LSER_REG_RIRQ, LSER_IRQ_ENABLE); - bus_write_register(sc->ls_busdata, sc->ls_buspos, - LSER_REG_WIRQ, LSER_IRQ_ENABLE); + bus_write_register(sc->ls_busdata, sc->ls_buspos, LSER_REG_RIRQ, + LSER_IRQ_ENABLE); + bus_write_register(sc->ls_busdata, sc->ls_buspos, LSER_REG_WIRQ, + LSER_IRQ_ENABLE); - return 0; + return 0; } diff --git a/kern/dev/lamebus/lser.h b/kern/dev/lamebus/lser.h index be45670..638d320 100644 --- a/kern/dev/lamebus/lser.h +++ b/kern/dev/lamebus/lser.h @@ -33,18 +33,18 @@ #include struct lser_softc { - /* Initialized by config function */ - struct spinlock ls_lock; /* protects ls_wbusy and device regs */ - volatile bool ls_wbusy; /* true if write in progress */ + /* Initialized by config function */ + struct spinlock ls_lock; /* protects ls_wbusy and device regs */ + volatile bool ls_wbusy; /* true if write in progress */ - /* Initialized by lower-level attachment function */ - void *ls_busdata; - uint32_t ls_buspos; + /* Initialized by lower-level attachment function */ + void *ls_busdata; + uint32_t ls_buspos; - /* Initialized by higher-level attachment function */ - void *ls_devdata; - void (*ls_start)(void *devdata); - void (*ls_input)(void *devdata, int ch); + /* Initialized by higher-level attachment function */ + void *ls_devdata; + void (*ls_start)(void *devdata); + void (*ls_input)(void *devdata, int ch); }; /* Functions called by lower-level drivers */ diff --git a/kern/dev/lamebus/lser_att.c b/kern/dev/lamebus/lser_att.c index cff43c1..40b6cf5 100644 --- a/kern/dev/lamebus/lser_att.c +++ b/kern/dev/lamebus/lser_att.c @@ -34,30 +34,29 @@ #include "autoconf.h" /* Lowest revision we support */ -#define LOW_VERSION 1 +#define LOW_VERSION 1 -struct lser_softc * -attach_lser_to_lamebus(int lserno, struct lamebus_softc *sc) -{ - struct lser_softc *ls; - int slot = lamebus_probe(sc, LB_VENDOR_CS161, LBCS161_SERIAL, - LOW_VERSION, NULL); - if (slot < 0) { - return NULL; - } +struct lser_softc *attach_lser_to_lamebus(int lserno, + struct lamebus_softc *sc) { + struct lser_softc *ls; + int slot = + lamebus_probe(sc, LB_VENDOR_CS161, LBCS161_SERIAL, LOW_VERSION, NULL); + if (slot < 0) { + return NULL; + } - ls = kmalloc(sizeof(struct lser_softc)); - if (ls==NULL) { - return NULL; - } + ls = kmalloc(sizeof(struct lser_softc)); + if (ls == NULL) { + return NULL; + } - (void)lserno; // unused + (void)lserno; // unused - ls->ls_busdata = sc; - ls->ls_buspos = slot; + ls->ls_busdata = sc; + ls->ls_buspos = slot; - lamebus_mark(sc, slot); - lamebus_attach_interrupt(sc, slot, ls, lser_irq); + lamebus_mark(sc, slot); + lamebus_attach_interrupt(sc, slot, ls, lser_irq); - return ls; + return ls; } diff --git a/kern/dev/lamebus/ltimer.c b/kern/dev/lamebus/ltimer.c index bb123d8..b33a355 100644 --- a/kern/dev/lamebus/ltimer.c +++ b/kern/dev/lamebus/ltimer.c @@ -39,92 +39,87 @@ #include "autoconf.h" /* Registers (offsets within slot) */ -#define LT_REG_SEC 0 /* time of day: seconds */ -#define LT_REG_NSEC 4 /* time of day: nanoseconds */ -#define LT_REG_ROE 8 /* Restart On countdown-timer Expiry flag */ -#define LT_REG_IRQ 12 /* Interrupt status register */ -#define LT_REG_COUNT 16 /* Time for countdown timer (usec) */ -#define LT_REG_SPKR 20 /* Beep control */ +#define LT_REG_SEC 0 /* time of day: seconds */ +#define LT_REG_NSEC 4 /* time of day: nanoseconds */ +#define LT_REG_ROE 8 /* Restart On countdown-timer Expiry flag */ +#define LT_REG_IRQ 12 /* Interrupt status register */ +#define LT_REG_COUNT 16 /* Time for countdown timer (usec) */ +#define LT_REG_SPKR 20 /* Beep control */ /* Granularity of countdown timer (usec) */ -#define LT_GRANULARITY 1000000 +#define LT_GRANULARITY 1000000 static bool havetimerclock; /* * Setup routine called by autoconf stuff when an ltimer is found. */ -int -config_ltimer(struct ltimer_softc *lt, int ltimerno) -{ - /* - * Running on System/161 2.x, we always use the processor - * on-chip timer for hardclock and we don't need ltimer as - * hardclock. - * - * Ideally there should be code here that will use an ltimer - * for hardclock if nothing else is available; e.g. if we - * wanted to make OS/161 2.x run on System/161 1.x. However, - * that requires a good bit more infrastructure for handling - * timers than we have and it doesn't seem worthwhile. - * - * It would also require some hacking, because all CPUs need - * to receive timer interrupts. (Exercise: how would you make - * sure all CPUs receive exactly one timer interrupt? Remember - * that LAMEbus uses level-triggered interrupts, so the - * hardware interrupt line will cause repeated interrupts if - * it's not reset on the device; but if it's reset on the - * device before all CPUs manage to see it, those CPUs won't - * be interrupted at all.) - * - * Note that the beep and rtclock devices *do* attach to - * ltimer. - */ - (void)ltimerno; - lt->lt_hardclock = 0; +int config_ltimer(struct ltimer_softc *lt, int ltimerno) { + /* + * Running on System/161 2.x, we always use the processor + * on-chip timer for hardclock and we don't need ltimer as + * hardclock. + * + * Ideally there should be code here that will use an ltimer + * for hardclock if nothing else is available; e.g. if we + * wanted to make OS/161 2.x run on System/161 1.x. However, + * that requires a good bit more infrastructure for handling + * timers than we have and it doesn't seem worthwhile. + * + * It would also require some hacking, because all CPUs need + * to receive timer interrupts. (Exercise: how would you make + * sure all CPUs receive exactly one timer interrupt? Remember + * that LAMEbus uses level-triggered interrupts, so the + * hardware interrupt line will cause repeated interrupts if + * it's not reset on the device; but if it's reset on the + * device before all CPUs manage to see it, those CPUs won't + * be interrupted at all.) + * + * Note that the beep and rtclock devices *do* attach to + * ltimer. + */ + (void)ltimerno; + lt->lt_hardclock = 0; - /* - * We do, however, use ltimer for the timer clock, since the - * on-chip timer can't do that. - */ - if (!havetimerclock) { - havetimerclock = true; - lt->lt_timerclock = 1; + /* + * We do, however, use ltimer for the timer clock, since the + * on-chip timer can't do that. + */ + if (!havetimerclock) { + havetimerclock = true; + lt->lt_timerclock = 1; - /* Wire it to go off once every second. */ - bus_write_register(lt->lt_bus, lt->lt_buspos, LT_REG_ROE, 1); - bus_write_register(lt->lt_bus, lt->lt_buspos, LT_REG_COUNT, - LT_GRANULARITY); - } + /* Wire it to go off once every second. */ + bus_write_register(lt->lt_bus, lt->lt_buspos, LT_REG_ROE, 1); + bus_write_register(lt->lt_bus, lt->lt_buspos, LT_REG_COUNT, LT_GRANULARITY); + } - return 0; + return 0; } /* * Interrupt handler. */ -void -ltimer_irq(void *vlt) -{ - struct ltimer_softc *lt = vlt; - uint32_t val; +void ltimer_irq(void *vlt) { + struct ltimer_softc *lt = vlt; + uint32_t val; - val = bus_read_register(lt->lt_bus, lt->lt_buspos, LT_REG_IRQ); - if (val) { - /* - * Only call hardclock if we're responsible for hardclock. - * (Any additional timer devices are unused.) - */ - if (lt->lt_hardclock) { - hardclock(); - } - /* - * Likewise for timerclock. - */ - if (lt->lt_timerclock) { - timerclock(); - } - } + val = bus_read_register(lt->lt_bus, lt->lt_buspos, LT_REG_IRQ); + if (val) { + /* + * Only call hardclock if we're responsible for hardclock. + * (Any additional timer devices are unused.) + */ + if (lt->lt_hardclock) { + hardclock(); + } + /* + * Likewise for timerclock. + */ + if (lt->lt_timerclock) { + timerclock(); + } + } } /* @@ -132,12 +127,10 @@ ltimer_irq(void *vlt) * doesn't matter what value you write. This function is called if * the beep device is attached to this timer. */ -void -ltimer_beep(void *vlt) -{ - struct ltimer_softc *lt = vlt; +void ltimer_beep(void *vlt) { + struct ltimer_softc *lt = vlt; - bus_write_register(lt->lt_bus, lt->lt_buspos, LT_REG_SPKR, 440); + bus_write_register(lt->lt_bus, lt->lt_buspos, LT_REG_SPKR, 440); } /* @@ -145,43 +138,37 @@ ltimer_beep(void *vlt) * This function gets called if the rtclock device is attached * to this timer. */ -void -ltimer_gettime(void *vlt, struct timespec *ts) -{ - struct ltimer_softc *lt = vlt; - uint32_t secs1, secs2; - int spl; +void ltimer_gettime(void *vlt, struct timespec *ts) { + struct ltimer_softc *lt = vlt; + uint32_t secs1, secs2; + int spl; - /* - * Read the seconds twice, on either side of the nanoseconds. - * If nsecs is small, use the *later* value of seconds, in case - * the nanoseconds turned over between the time we got the earlier - * value and the time we got nsecs. - * - * Note that the clock in the ltimer device is accurate down - * to a single processor cycle, so this might actually matter - * now and then. - * - * Do it with interrupts off on the current processor to avoid - * getting garbage if we get an interrupt among the register - * reads. - */ + /* + * Read the seconds twice, on either side of the nanoseconds. + * If nsecs is small, use the *later* value of seconds, in case + * the nanoseconds turned over between the time we got the earlier + * value and the time we got nsecs. + * + * Note that the clock in the ltimer device is accurate down + * to a single processor cycle, so this might actually matter + * now and then. + * + * Do it with interrupts off on the current processor to avoid + * getting garbage if we get an interrupt among the register + * reads. + */ - spl = splhigh(); + spl = splhigh(); - secs1 = bus_read_register(lt->lt_bus, lt->lt_buspos, - LT_REG_SEC); - ts->tv_nsec = bus_read_register(lt->lt_bus, lt->lt_buspos, - LT_REG_NSEC); - secs2 = bus_read_register(lt->lt_bus, lt->lt_buspos, - LT_REG_SEC); + secs1 = bus_read_register(lt->lt_bus, lt->lt_buspos, LT_REG_SEC); + ts->tv_nsec = bus_read_register(lt->lt_bus, lt->lt_buspos, LT_REG_NSEC); + secs2 = bus_read_register(lt->lt_bus, lt->lt_buspos, LT_REG_SEC); - splx(spl); + splx(spl); - if (ts->tv_nsec < 5000000) { - ts->tv_sec = secs2; - } - else { - ts->tv_sec = secs1; - } + if (ts->tv_nsec < 5000000) { + ts->tv_sec = secs2; + } else { + ts->tv_sec = secs1; + } } diff --git a/kern/dev/lamebus/ltimer.h b/kern/dev/lamebus/ltimer.h index 3fdd70f..9978574 100644 --- a/kern/dev/lamebus/ltimer.h +++ b/kern/dev/lamebus/ltimer.h @@ -36,21 +36,21 @@ struct timespec; * Hardware device data for LAMEbus timer device */ struct ltimer_softc { - /* Initialized by config function */ - int lt_hardclock; /* true if we should call hardclock() */ - int lt_timerclock; /* true if we should call timerclock() */ + /* Initialized by config function */ + int lt_hardclock; /* true if we should call hardclock() */ + int lt_timerclock; /* true if we should call timerclock() */ - /* Initialized by lower-level attach routine */ - void *lt_bus; /* bus we're on */ - uint32_t lt_buspos; /* position (slot) on that bus */ + /* Initialized by lower-level attach routine */ + void *lt_bus; /* bus we're on */ + uint32_t lt_buspos; /* position (slot) on that bus */ }; /* Functions called by lower-level drivers */ -void ltimer_irq(/*struct ltimer_softc*/ void *lt); // interrupt handler +void ltimer_irq(/*struct ltimer_softc*/ void *lt); // interrupt handler /* Functions called by higher-level devices */ -void ltimer_beep(/*struct ltimer_softc*/ void *devdata); // for beep device +void ltimer_beep(/*struct ltimer_softc*/ void *devdata); // for beep device void ltimer_gettime(/*struct ltimer_softc*/ void *devdata, - struct timespec *ts); // for rtclock + struct timespec *ts); // for rtclock #endif /* _LAMEBUS_LTIMER_H_ */ diff --git a/kern/dev/lamebus/ltimer_att.c b/kern/dev/lamebus/ltimer_att.c index 2507d6a..76a5b5f 100644 --- a/kern/dev/lamebus/ltimer_att.c +++ b/kern/dev/lamebus/ltimer_att.c @@ -37,34 +37,33 @@ #include "autoconf.h" /* Lowest revision we support */ -#define LOW_VERSION 1 +#define LOW_VERSION 1 -struct ltimer_softc * -attach_ltimer_to_lamebus(int ltimerno, struct lamebus_softc *sc) -{ - struct ltimer_softc *lt; - int slot = lamebus_probe(sc, LB_VENDOR_CS161, LBCS161_TIMER, - LOW_VERSION, NULL); - if (slot < 0) { - /* No ltimer (or no additional ltimer) found */ - return NULL; - } +struct ltimer_softc *attach_ltimer_to_lamebus(int ltimerno, + struct lamebus_softc *sc) { + struct ltimer_softc *lt; + int slot = + lamebus_probe(sc, LB_VENDOR_CS161, LBCS161_TIMER, LOW_VERSION, NULL); + if (slot < 0) { + /* No ltimer (or no additional ltimer) found */ + return NULL; + } - lt = kmalloc(sizeof(struct ltimer_softc)); - if (lt==NULL) { - /* out of memory */ - return NULL; - } + lt = kmalloc(sizeof(struct ltimer_softc)); + if (lt == NULL) { + /* out of memory */ + return NULL; + } - (void)ltimerno; // unused + (void)ltimerno; // unused - /* Record what bus it's on */ - lt->lt_bus = sc; - lt->lt_buspos = slot; + /* Record what bus it's on */ + lt->lt_bus = sc; + lt->lt_buspos = slot; - /* Mark the slot in use and hook that slot's interrupt */ - lamebus_mark(sc, slot); - lamebus_attach_interrupt(sc, slot, lt, ltimer_irq); + /* Mark the slot in use and hook that slot's interrupt */ + lamebus_mark(sc, slot); + lamebus_attach_interrupt(sc, slot, lt, ltimer_irq); - return lt; + return lt; } diff --git a/kern/dev/lamebus/ltrace.c b/kern/dev/lamebus/ltrace.c index d9f7a49..e94adcf 100644 --- a/kern/dev/lamebus/ltrace.c +++ b/kern/dev/lamebus/ltrace.c @@ -34,83 +34,67 @@ #include "autoconf.h" /* Registers (offsets within slot) */ -#define LTRACE_REG_TRON 0 /* trace on */ -#define LTRACE_REG_TROFF 4 /* trace off */ -#define LTRACE_REG_DEBUG 8 /* debug code */ -#define LTRACE_REG_DUMP 12 /* dump the system */ -#define LTRACE_REG_STOP 16 /* stop for the debugger */ -#define LTRACE_REG_PROFEN 20 /* turn profiling on/off */ -#define LTRACE_REG_PROFCL 24 /* clear the profile */ +#define LTRACE_REG_TRON 0 /* trace on */ +#define LTRACE_REG_TROFF 4 /* trace off */ +#define LTRACE_REG_DEBUG 8 /* debug code */ +#define LTRACE_REG_DUMP 12 /* dump the system */ +#define LTRACE_REG_STOP 16 /* stop for the debugger */ +#define LTRACE_REG_PROFEN 20 /* turn profiling on/off */ +#define LTRACE_REG_PROFCL 24 /* clear the profile */ static struct ltrace_softc *the_trace; -void -ltrace_on(uint32_t code) -{ - if (the_trace != NULL) { - bus_write_register(the_trace->lt_busdata, the_trace->lt_buspos, - LTRACE_REG_TRON, code); - } +void ltrace_on(uint32_t code) { + if (the_trace != NULL) { + bus_write_register(the_trace->lt_busdata, the_trace->lt_buspos, + LTRACE_REG_TRON, code); + } } -void -ltrace_off(uint32_t code) -{ - if (the_trace != NULL) { - bus_write_register(the_trace->lt_busdata, the_trace->lt_buspos, - LTRACE_REG_TROFF, code); - } +void ltrace_off(uint32_t code) { + if (the_trace != NULL) { + bus_write_register(the_trace->lt_busdata, the_trace->lt_buspos, + LTRACE_REG_TROFF, code); + } } -void -ltrace_debug(uint32_t code) -{ - if (the_trace != NULL) { - bus_write_register(the_trace->lt_busdata, the_trace->lt_buspos, - LTRACE_REG_DEBUG, code); - } +void ltrace_debug(uint32_t code) { + if (the_trace != NULL) { + bus_write_register(the_trace->lt_busdata, the_trace->lt_buspos, + LTRACE_REG_DEBUG, code); + } } -void -ltrace_dump(uint32_t code) -{ - if (the_trace != NULL) { - bus_write_register(the_trace->lt_busdata, the_trace->lt_buspos, - LTRACE_REG_DUMP, code); - } +void ltrace_dump(uint32_t code) { + if (the_trace != NULL) { + bus_write_register(the_trace->lt_busdata, the_trace->lt_buspos, + LTRACE_REG_DUMP, code); + } } -void -ltrace_stop(uint32_t code) -{ - if (the_trace != NULL && the_trace->lt_canstop) { - bus_write_register(the_trace->lt_busdata, the_trace->lt_buspos, - LTRACE_REG_STOP, code); - } +void ltrace_stop(uint32_t code) { + if (the_trace != NULL && the_trace->lt_canstop) { + bus_write_register(the_trace->lt_busdata, the_trace->lt_buspos, + LTRACE_REG_STOP, code); + } } -void -ltrace_setprof(uint32_t onoff) -{ - if (the_trace != NULL && the_trace->lt_canprof) { - bus_write_register(the_trace->lt_busdata, the_trace->lt_buspos, - LTRACE_REG_PROFEN, onoff); - } +void ltrace_setprof(uint32_t onoff) { + if (the_trace != NULL && the_trace->lt_canprof) { + bus_write_register(the_trace->lt_busdata, the_trace->lt_buspos, + LTRACE_REG_PROFEN, onoff); + } } -void -ltrace_eraseprof(void) -{ - if (the_trace != NULL && the_trace->lt_canprof) { - bus_write_register(the_trace->lt_busdata, the_trace->lt_buspos, - LTRACE_REG_PROFCL, 1); - } +void ltrace_eraseprof(void) { + if (the_trace != NULL && the_trace->lt_canprof) { + bus_write_register(the_trace->lt_busdata, the_trace->lt_buspos, + LTRACE_REG_PROFCL, 1); + } } -int -config_ltrace(struct ltrace_softc *sc, int ltraceno) -{ - (void)ltraceno; - the_trace = sc; - return 0; +int config_ltrace(struct ltrace_softc *sc, int ltraceno) { + (void)ltraceno; + the_trace = sc; + return 0; } diff --git a/kern/dev/lamebus/ltrace.h b/kern/dev/lamebus/ltrace.h index 14c9d06..e78479c 100644 --- a/kern/dev/lamebus/ltrace.h +++ b/kern/dev/lamebus/ltrace.h @@ -31,11 +31,11 @@ #define _LAMEBUS_LTRACE_H_ struct ltrace_softc { - /* Initialized by lower-level attachment function */ - void *lt_busdata; - uint32_t lt_buspos; - bool lt_canstop; - bool lt_canprof; + /* Initialized by lower-level attachment function */ + void *lt_busdata; + uint32_t lt_buspos; + bool lt_canstop; + bool lt_canprof; }; /* diff --git a/kern/dev/lamebus/ltrace_att.c b/kern/dev/lamebus/ltrace_att.c index 69e7e76..ea59e12 100644 --- a/kern/dev/lamebus/ltrace_att.c +++ b/kern/dev/lamebus/ltrace_att.c @@ -34,36 +34,35 @@ #include "autoconf.h" /* Lowest revision we support */ -#define LOW_VERSION 1 +#define LOW_VERSION 1 /* Revision that supports ltrace_stop() */ -#define STOP_VERSION 2 +#define STOP_VERSION 2 /* Revision that supports ltrace_prof() */ -#define PROF_VERSION 3 +#define PROF_VERSION 3 -struct ltrace_softc * -attach_ltrace_to_lamebus(int ltraceno, struct lamebus_softc *sc) -{ - struct ltrace_softc *lt; - uint32_t drl; - int slot = lamebus_probe(sc, LB_VENDOR_CS161, LBCS161_TRACE, - LOW_VERSION, &drl); - if (slot < 0) { - return NULL; - } +struct ltrace_softc *attach_ltrace_to_lamebus(int ltraceno, + struct lamebus_softc *sc) { + struct ltrace_softc *lt; + uint32_t drl; + int slot = + lamebus_probe(sc, LB_VENDOR_CS161, LBCS161_TRACE, LOW_VERSION, &drl); + if (slot < 0) { + return NULL; + } - lt = kmalloc(sizeof(struct ltrace_softc)); - if (lt==NULL) { - return NULL; - } + lt = kmalloc(sizeof(struct ltrace_softc)); + if (lt == NULL) { + return NULL; + } - (void)ltraceno; // unused + (void)ltraceno; // unused - lt->lt_busdata = sc; - lt->lt_buspos = slot; - lt->lt_canstop = drl >= STOP_VERSION; - lt->lt_canprof = drl >= PROF_VERSION; + lt->lt_busdata = sc; + lt->lt_buspos = slot; + lt->lt_canstop = drl >= STOP_VERSION; + lt->lt_canprof = drl >= PROF_VERSION; - lamebus_mark(sc, slot); + lamebus_mark(sc, slot); - return lt; + return lt; } diff --git a/kern/dev/lamebus/random_lrandom.c b/kern/dev/lamebus/random_lrandom.c index 145fd74..681532c 100644 --- a/kern/dev/lamebus/random_lrandom.c +++ b/kern/dev/lamebus/random_lrandom.c @@ -38,20 +38,19 @@ #include #include "autoconf.h" -struct random_softc * -attach_random_to_lrandom(int randomno, struct lrandom_softc *ls) -{ - struct random_softc *rs = kmalloc(sizeof(struct random_softc)); - if (rs==NULL) { - return NULL; - } +struct random_softc *attach_random_to_lrandom(int randomno, + struct lrandom_softc *ls) { + struct random_softc *rs = kmalloc(sizeof(struct random_softc)); + if (rs == NULL) { + return NULL; + } - (void)randomno; // unused + (void)randomno; // unused - rs->rs_devdata = ls; - rs->rs_random = lrandom_random; - rs->rs_randmax = lrandom_randmax; - rs->rs_read = lrandom_read; + rs->rs_devdata = ls; + rs->rs_random = lrandom_random; + rs->rs_randmax = lrandom_randmax; + rs->rs_read = lrandom_read; - return rs; + return rs; } diff --git a/kern/dev/lamebus/rtclock_ltimer.c b/kern/dev/lamebus/rtclock_ltimer.c index 10ccb23..78eb577 100644 --- a/kern/dev/lamebus/rtclock_ltimer.c +++ b/kern/dev/lamebus/rtclock_ltimer.c @@ -44,23 +44,22 @@ #include #include "autoconf.h" -struct rtclock_softc * -attach_rtclock_to_ltimer(int rtclockno, struct ltimer_softc *ls) -{ - /* - * No need to probe; ltimer always has a clock. - * Just allocate the rtclock, set our fields, and return it. - */ - struct rtclock_softc *rtc = kmalloc(sizeof(struct rtclock_softc)); - if (rtc==NULL) { - /* Out of memory */ - return NULL; - } +struct rtclock_softc *attach_rtclock_to_ltimer(int rtclockno, + struct ltimer_softc *ls) { + /* + * No need to probe; ltimer always has a clock. + * Just allocate the rtclock, set our fields, and return it. + */ + struct rtclock_softc *rtc = kmalloc(sizeof(struct rtclock_softc)); + if (rtc == NULL) { + /* Out of memory */ + return NULL; + } - (void)rtclockno; // unused + (void)rtclockno; // unused - rtc->rtc_devdata = ls; - rtc->rtc_gettime = ltimer_gettime; + rtc->rtc_devdata = ls; + rtc->rtc_gettime = ltimer_gettime; - return rtc; + return rtc; } diff --git a/kern/fs/semfs/semfs.h b/kern/fs/semfs/semfs.h index 93d153c..4046425 100644 --- a/kern/fs/semfs/semfs.h +++ b/kern/fs/semfs/semfs.h @@ -42,7 +42,7 @@ * Constants */ -#define SEMFS_ROOTDIR 0xffffffffU /* semnum for root dir */ +#define SEMFS_ROOTDIR 0xffffffffU /* semnum for root dir */ /* * A user-facing semaphore. @@ -52,11 +52,11 @@ * XXX: or would we? review once all this is done. */ struct semfs_sem { - struct lock *sems_lock; /* Lock to protect count */ - struct cv *sems_cv; /* CV to wait */ - unsigned sems_count; /* Semaphore count */ - bool sems_hasvnode; /* The vnode exists */ - bool sems_linked; /* In the directory */ + struct lock *sems_lock; /* Lock to protect count */ + struct cv *sems_cv; /* CV to wait */ + unsigned sems_count; /* Semaphore count */ + bool sems_hasvnode; /* The vnode exists */ + bool sems_linked; /* In the directory */ }; DECLARRAY(semfs_sem, SEMFS_INLINE); @@ -64,8 +64,8 @@ DECLARRAY(semfs_sem, SEMFS_INLINE); * Directory entry; name and reference to a semaphore. */ struct semfs_direntry { - char *semd_name; /* Name */ - unsigned semd_semnum; /* Which semaphore */ + char *semd_name; /* Name */ + unsigned semd_semnum; /* Which semaphore */ }; DECLARRAY(semfs_direntry, SEMFS_INLINE); @@ -77,9 +77,9 @@ DECLARRAY(semfs_direntry, SEMFS_INLINE); * practice. XXX: review after finishing) */ struct semfs_vnode { - struct vnode semv_absvn; /* Abstract vnode */ - struct semfs *semv_semfs; /* Back-pointer to fs */ - unsigned semv_semnum; /* Which semaphore */ + struct vnode semv_absvn; /* Abstract vnode */ + struct semfs *semv_semfs; /* Back-pointer to fs */ + unsigned semv_semnum; /* Which semaphore */ }; /* @@ -87,14 +87,14 @@ struct semfs_vnode { * is only one of these. */ struct semfs { - struct fs semfs_absfs; /* Abstract fs object */ + struct fs semfs_absfs; /* Abstract fs object */ - struct lock *semfs_tablelock; /* Lock for following */ - struct vnodearray *semfs_vnodes; /* Currently extant vnodes */ - struct semfs_semarray *semfs_sems; /* Semaphores */ + struct lock *semfs_tablelock; /* Lock for following */ + struct vnodearray *semfs_vnodes; /* Currently extant vnodes */ + struct semfs_semarray *semfs_sems; /* Semaphores */ - struct lock *semfs_dirlock; /* Lock for following */ - struct semfs_direntryarray *semfs_dents; /* The root directory */ + struct lock *semfs_dirlock; /* Lock for following */ + struct semfs_direntryarray *semfs_dents; /* The root directory */ }; /* @@ -104,7 +104,6 @@ struct semfs { DEFARRAY(semfs_sem, SEMFS_INLINE); DEFARRAY(semfs_direntry, SEMFS_INLINE); - /* * Functions. */ @@ -119,5 +118,4 @@ void semfs_direntry_destroy(struct semfs_direntry *); /* in semfs_vnops.c */ int semfs_getvnode(struct semfs *, unsigned, struct vnode **ret); - #endif /* SEMFS_H */ diff --git a/kern/fs/semfs/semfs_fsops.c b/kern/fs/semfs/semfs_fsops.c index 7fcf4ac..528237b 100644 --- a/kern/fs/semfs/semfs_fsops.c +++ b/kern/fs/semfs/semfs_fsops.c @@ -42,185 +42,163 @@ /* * Sync doesn't need to do anything. */ -static -int -semfs_sync(struct fs *fs) -{ - (void)fs; - return 0; +static int semfs_sync(struct fs *fs) { + (void)fs; + return 0; } /* * We have only one volume name and it's hardwired. */ -static -const char * -semfs_getvolname(struct fs *fs) -{ - (void)fs; - return "sem"; +static const char *semfs_getvolname(struct fs *fs) { + (void)fs; + return "sem"; } /* * Get the root directory vnode. */ -static -int -semfs_getroot(struct fs *fs, struct vnode **ret) -{ - struct semfs *semfs = fs->fs_data; - struct vnode *vn; - int result; +static int semfs_getroot(struct fs *fs, struct vnode **ret) { + struct semfs *semfs = fs->fs_data; + struct vnode *vn; + int result; - result = semfs_getvnode(semfs, SEMFS_ROOTDIR, &vn); - if (result) { - kprintf("semfs: couldn't load root vnode: %s\n", - strerror(result)); - return result; - } - *ret = vn; - return 0; + result = semfs_getvnode(semfs, SEMFS_ROOTDIR, &vn); + if (result) { + kprintf("semfs: couldn't load root vnode: %s\n", strerror(result)); + return result; + } + *ret = vn; + return 0; } //////////////////////////////////////////////////////////// // mount and unmount logic - /* * Destructor for struct semfs. */ -static -void -semfs_destroy(struct semfs *semfs) -{ - struct semfs_sem *sem; - struct semfs_direntry *dent; - unsigned i, num; +static void semfs_destroy(struct semfs *semfs) { + struct semfs_sem *sem; + struct semfs_direntry *dent; + unsigned i, num; - num = semfs_semarray_num(semfs->semfs_sems); - for (i=0; isemfs_sems, i); - semfs_sem_destroy(sem); - } - semfs_semarray_setsize(semfs->semfs_sems, 0); + num = semfs_semarray_num(semfs->semfs_sems); + for (i = 0; i < num; i++) { + sem = semfs_semarray_get(semfs->semfs_sems, i); + semfs_sem_destroy(sem); + } + semfs_semarray_setsize(semfs->semfs_sems, 0); - num = semfs_direntryarray_num(semfs->semfs_dents); - for (i=0; isemfs_dents, i); - semfs_direntry_destroy(dent); - } - semfs_direntryarray_setsize(semfs->semfs_dents, 0); + num = semfs_direntryarray_num(semfs->semfs_dents); + for (i = 0; i < num; i++) { + dent = semfs_direntryarray_get(semfs->semfs_dents, i); + semfs_direntry_destroy(dent); + } + semfs_direntryarray_setsize(semfs->semfs_dents, 0); - semfs_direntryarray_destroy(semfs->semfs_dents); - lock_destroy(semfs->semfs_dirlock); - semfs_semarray_destroy(semfs->semfs_sems); - vnodearray_destroy(semfs->semfs_vnodes); - lock_destroy(semfs->semfs_tablelock); - kfree(semfs); + semfs_direntryarray_destroy(semfs->semfs_dents); + lock_destroy(semfs->semfs_dirlock); + semfs_semarray_destroy(semfs->semfs_sems); + vnodearray_destroy(semfs->semfs_vnodes); + lock_destroy(semfs->semfs_tablelock); + kfree(semfs); } /* * Unmount routine. XXX: Since semfs is attached at boot and can't be * remounted, maybe unmounting it shouldn't be allowed. */ -static -int -semfs_unmount(struct fs *fs) -{ - struct semfs *semfs = fs->fs_data; +static int semfs_unmount(struct fs *fs) { + struct semfs *semfs = fs->fs_data; - lock_acquire(semfs->semfs_tablelock); - if (vnodearray_num(semfs->semfs_vnodes) > 0) { - lock_release(semfs->semfs_tablelock); - return EBUSY; - } + lock_acquire(semfs->semfs_tablelock); + if (vnodearray_num(semfs->semfs_vnodes) > 0) { + lock_release(semfs->semfs_tablelock); + return EBUSY; + } - lock_release(semfs->semfs_tablelock); - semfs_destroy(semfs); + lock_release(semfs->semfs_tablelock); + semfs_destroy(semfs); - return 0; + return 0; } /* * Operations table. */ static const struct fs_ops semfs_fsops = { - .fsop_sync = semfs_sync, - .fsop_getvolname = semfs_getvolname, - .fsop_getroot = semfs_getroot, - .fsop_unmount = semfs_unmount, + .fsop_sync = semfs_sync, + .fsop_getvolname = semfs_getvolname, + .fsop_getroot = semfs_getroot, + .fsop_unmount = semfs_unmount, }; /* * Constructor for struct semfs. */ -static -struct semfs * -semfs_create(void) -{ - struct semfs *semfs; +static struct semfs *semfs_create(void) { + struct semfs *semfs; - semfs = kmalloc(sizeof(*semfs)); - if (semfs == NULL) { - goto fail_total; - } + semfs = kmalloc(sizeof(*semfs)); + if (semfs == NULL) { + goto fail_total; + } - semfs->semfs_tablelock = lock_create("semfs_table"); - if (semfs->semfs_tablelock == NULL) { - goto fail_semfs; - } - semfs->semfs_vnodes = vnodearray_create(); - if (semfs->semfs_vnodes == NULL) { - goto fail_tablelock; - } - semfs->semfs_sems = semfs_semarray_create(); - if (semfs->semfs_sems == NULL) { - goto fail_vnodes; - } + semfs->semfs_tablelock = lock_create("semfs_table"); + if (semfs->semfs_tablelock == NULL) { + goto fail_semfs; + } + semfs->semfs_vnodes = vnodearray_create(); + if (semfs->semfs_vnodes == NULL) { + goto fail_tablelock; + } + semfs->semfs_sems = semfs_semarray_create(); + if (semfs->semfs_sems == NULL) { + goto fail_vnodes; + } - semfs->semfs_dirlock = lock_create("semfs_dir"); - if (semfs->semfs_dirlock == NULL) { - goto fail_sems; - } - semfs->semfs_dents = semfs_direntryarray_create(); - if (semfs->semfs_dents == NULL) { - goto fail_dirlock; - } + semfs->semfs_dirlock = lock_create("semfs_dir"); + if (semfs->semfs_dirlock == NULL) { + goto fail_sems; + } + semfs->semfs_dents = semfs_direntryarray_create(); + if (semfs->semfs_dents == NULL) { + goto fail_dirlock; + } - semfs->semfs_absfs.fs_data = semfs; - semfs->semfs_absfs.fs_ops = &semfs_fsops; - return semfs; + semfs->semfs_absfs.fs_data = semfs; + semfs->semfs_absfs.fs_ops = &semfs_fsops; + return semfs; - fail_dirlock: - lock_destroy(semfs->semfs_dirlock); - fail_sems: - semfs_semarray_destroy(semfs->semfs_sems); - fail_vnodes: - vnodearray_destroy(semfs->semfs_vnodes); - fail_tablelock: - lock_destroy(semfs->semfs_tablelock); - fail_semfs: - kfree(semfs); - fail_total: - return NULL; +fail_dirlock: + lock_destroy(semfs->semfs_dirlock); +fail_sems: + semfs_semarray_destroy(semfs->semfs_sems); +fail_vnodes: + vnodearray_destroy(semfs->semfs_vnodes); +fail_tablelock: + lock_destroy(semfs->semfs_tablelock); +fail_semfs: + kfree(semfs); +fail_total: + return NULL; } /* * Create the semfs. There is only one semfs and it's attached as * "sem:" during bootup. */ -void -semfs_bootstrap(void) -{ - struct semfs *semfs; - int result; +void semfs_bootstrap(void) { + struct semfs *semfs; + int result; - semfs = semfs_create(); - if (semfs == NULL) { - panic("Out of memory creating semfs\n"); - } - result = vfs_addfs("sem", &semfs->semfs_absfs); - if (result) { - panic("Attaching semfs: %s\n", strerror(result)); - } + semfs = semfs_create(); + if (semfs == NULL) { + panic("Out of memory creating semfs\n"); + } + result = vfs_addfs("sem", &semfs->semfs_absfs); + if (result) { + panic("Attaching semfs: %s\n", strerror(result)); + } } diff --git a/kern/fs/semfs/semfs_obj.c b/kern/fs/semfs/semfs_obj.c index 9f8018a..47b4f93 100644 --- a/kern/fs/semfs/semfs_obj.c +++ b/kern/fs/semfs/semfs_obj.c @@ -40,74 +40,69 @@ /* * Constructor for semfs_sem. */ -struct semfs_sem * -semfs_sem_create(const char *name) -{ - struct semfs_sem *sem; - char lockname[32]; - char cvname[32]; +struct semfs_sem *semfs_sem_create(const char *name) { + struct semfs_sem *sem; + char lockname[32]; + char cvname[32]; - snprintf(lockname, sizeof(lockname), "sem:l.%s", name); - snprintf(cvname, sizeof(cvname), "sem:%s", name); + snprintf(lockname, sizeof(lockname), "sem:l.%s", name); + snprintf(cvname, sizeof(cvname), "sem:%s", name); - sem = kmalloc(sizeof(*sem)); - if (sem == NULL) { - goto fail_return; - } - sem->sems_lock = lock_create(lockname); - if (sem->sems_lock == NULL) { - goto fail_sem; - } - sem->sems_cv = cv_create(cvname); - if (sem->sems_cv == NULL) { - goto fail_lock; - } - sem->sems_count = 0; - sem->sems_hasvnode = false; - sem->sems_linked = false; - return sem; + sem = kmalloc(sizeof(*sem)); + if (sem == NULL) { + goto fail_return; + } + sem->sems_lock = lock_create(lockname); + if (sem->sems_lock == NULL) { + goto fail_sem; + } + sem->sems_cv = cv_create(cvname); + if (sem->sems_cv == NULL) { + goto fail_lock; + } + sem->sems_count = 0; + sem->sems_hasvnode = false; + sem->sems_linked = false; + return sem; - fail_lock: - lock_destroy(sem->sems_lock); - fail_sem: - kfree(sem); - fail_return: - return NULL; +fail_lock: + lock_destroy(sem->sems_lock); +fail_sem: + kfree(sem); +fail_return: + return NULL; } /* * Destructor for semfs_sem. */ -void -semfs_sem_destroy(struct semfs_sem *sem) -{ - cv_destroy(sem->sems_cv); - lock_destroy(sem->sems_lock); - kfree(sem); +void semfs_sem_destroy(struct semfs_sem *sem) { + cv_destroy(sem->sems_cv); + lock_destroy(sem->sems_lock); + kfree(sem); } /* * Helper to insert a semfs_sem into the semaphore table. */ -int -semfs_sem_insert(struct semfs *semfs, struct semfs_sem *sem, unsigned *ret) -{ - unsigned i, num; +int semfs_sem_insert(struct semfs *semfs, struct semfs_sem *sem, + unsigned *ret) { + unsigned i, num; - KASSERT(lock_do_i_hold(semfs->semfs_tablelock)); - num = semfs_semarray_num(semfs->semfs_sems); - if (num == SEMFS_ROOTDIR) { - /* Too many */ - return ENOSPC; - } - for (i=0; isemfs_sems, i) == NULL) { - semfs_semarray_set(semfs->semfs_sems, i, sem); - *ret = i; - return 0; - } - } - return semfs_semarray_add(semfs->semfs_sems, sem, ret); + KASSERT(lock_do_i_hold(semfs->semfs_tablelock)); + num = semfs_semarray_num(semfs->semfs_sems); + if (num == SEMFS_ROOTDIR) { + /* Too many */ + return ENOSPC; + } + for (i = 0; i < num; i++) { + if (semfs_semarray_get(semfs->semfs_sems, i) == NULL) { + semfs_semarray_set(semfs->semfs_sems, i, sem); + *ret = i; + return 0; + } + } + return semfs_semarray_add(semfs->semfs_sems, sem, ret); } //////////////////////////////////////////////////////////// @@ -116,30 +111,27 @@ semfs_sem_insert(struct semfs *semfs, struct semfs_sem *sem, unsigned *ret) /* * Constructor for semfs_direntry. */ -struct semfs_direntry * -semfs_direntry_create(const char *name, unsigned semnum) -{ - struct semfs_direntry *dent; +struct semfs_direntry *semfs_direntry_create(const char *name, + unsigned semnum) { + struct semfs_direntry *dent; - dent = kmalloc(sizeof(*dent)); - if (dent == NULL) { - return NULL; - } - dent->semd_name = kstrdup(name); - if (dent->semd_name == NULL) { - kfree(dent); - return NULL; - } - dent->semd_semnum = semnum; - return dent; + dent = kmalloc(sizeof(*dent)); + if (dent == NULL) { + return NULL; + } + dent->semd_name = kstrdup(name); + if (dent->semd_name == NULL) { + kfree(dent); + return NULL; + } + dent->semd_semnum = semnum; + return dent; } /* * Destructor for semfs_direntry. */ -void -semfs_direntry_destroy(struct semfs_direntry *dent) -{ - kfree(dent->semd_name); - kfree(dent); +void semfs_direntry_destroy(struct semfs_direntry *dent) { + kfree(dent->semd_name); + kfree(dent); } diff --git a/kern/fs/semfs/semfs_vnops.c b/kern/fs/semfs/semfs_vnops.c index 8813f71..70a4558 100644 --- a/kern/fs/semfs/semfs_vnops.c +++ b/kern/fs/semfs/semfs_vnops.c @@ -44,63 +44,48 @@ //////////////////////////////////////////////////////////// // basic ops -static -int -semfs_eachopen(struct vnode *vn, int openflags) -{ - struct semfs_vnode *semv = vn->vn_data; +static int semfs_eachopen(struct vnode *vn, int openflags) { + struct semfs_vnode *semv = vn->vn_data; - if (semv->semv_semnum == SEMFS_ROOTDIR) { - if ((openflags & O_ACCMODE) != O_RDONLY) { - return EISDIR; - } - if (openflags & O_APPEND) { - return EISDIR; - } - } + if (semv->semv_semnum == SEMFS_ROOTDIR) { + if ((openflags & O_ACCMODE) != O_RDONLY) { + return EISDIR; + } + if (openflags & O_APPEND) { + return EISDIR; + } + } - return 0; + return 0; } -static -int -semfs_ioctl(struct vnode *vn, int op, userptr_t data) -{ - (void)vn; - (void)op; - (void)data; - return EINVAL; +static int semfs_ioctl(struct vnode *vn, int op, userptr_t data) { + (void)vn; + (void)op; + (void)data; + return EINVAL; } -static -int -semfs_gettype(struct vnode *vn, mode_t *ret) -{ - struct semfs_vnode *semv = vn->vn_data; +static int semfs_gettype(struct vnode *vn, mode_t *ret) { + struct semfs_vnode *semv = vn->vn_data; - *ret = semv->semv_semnum == SEMFS_ROOTDIR ? S_IFDIR : S_IFREG; - return 0; + *ret = semv->semv_semnum == SEMFS_ROOTDIR ? S_IFDIR : S_IFREG; + return 0; } -static -bool -semfs_isseekable(struct vnode *vn) -{ - struct semfs_vnode *semv = vn->vn_data; +static bool semfs_isseekable(struct vnode *vn) { + struct semfs_vnode *semv = vn->vn_data; - if (semv->semv_semnum != SEMFS_ROOTDIR) { - /* seeking a semaphore doesn't mean anything */ - return false; - } - return true; + if (semv->semv_semnum != SEMFS_ROOTDIR) { + /* seeking a semaphore doesn't mean anything */ + return false; + } + return true; } -static -int -semfs_fsync(struct vnode *vn) -{ - (void)vn; - return 0; +static int semfs_fsync(struct vnode *vn) { + (void)vn; + return 0; } //////////////////////////////////////////////////////////// @@ -110,26 +95,21 @@ semfs_fsync(struct vnode *vn) * XXX fold these two together */ -static -struct semfs_sem * -semfs_getsembynum(struct semfs *semfs, unsigned semnum) -{ - struct semfs_sem *sem; +static struct semfs_sem *semfs_getsembynum(struct semfs *semfs, + unsigned semnum) { + struct semfs_sem *sem; - lock_acquire(semfs->semfs_tablelock); - sem = semfs_semarray_get(semfs->semfs_sems, semnum); - lock_release(semfs->semfs_tablelock); + lock_acquire(semfs->semfs_tablelock); + sem = semfs_semarray_get(semfs->semfs_sems, semnum); + lock_release(semfs->semfs_tablelock); - return sem; + return sem; } -static -struct semfs_sem * -semfs_getsem(struct semfs_vnode *semv) -{ - struct semfs *semfs = semv->semv_semfs; +static struct semfs_sem *semfs_getsem(struct semfs_vnode *semv) { + struct semfs *semfs = semv->semv_semfs; - return semfs_getsembynum(semfs, semv->semv_semnum); + return semfs_getsembynum(semfs, semv->semv_semnum); } /* @@ -138,121 +118,106 @@ semfs_getsem(struct semfs_vnode *semv) * potentially need to wake more than one sleeper if the new count * will be more than 1. */ -static -void -semfs_wakeup(struct semfs_sem *sem, unsigned newcount) -{ - if (sem->sems_count > 0 || newcount == 0) { - return; - } - if (newcount == 1) { - cv_signal(sem->sems_cv, sem->sems_lock); - } - else { - cv_broadcast(sem->sems_cv, sem->sems_lock); - } +static void semfs_wakeup(struct semfs_sem *sem, unsigned newcount) { + if (sem->sems_count > 0 || newcount == 0) { + return; + } + if (newcount == 1) { + cv_signal(sem->sems_cv, sem->sems_lock); + } else { + cv_broadcast(sem->sems_cv, sem->sems_lock); + } } /* * stat() for semaphore vnodes */ -static -int -semfs_semstat(struct vnode *vn, struct stat *buf) -{ - struct semfs_vnode *semv = vn->vn_data; - struct semfs_sem *sem; +static int semfs_semstat(struct vnode *vn, struct stat *buf) { + struct semfs_vnode *semv = vn->vn_data; + struct semfs_sem *sem; - sem = semfs_getsem(semv); + sem = semfs_getsem(semv); - bzero(buf, sizeof(*buf)); + bzero(buf, sizeof(*buf)); - lock_acquire(sem->sems_lock); - buf->st_size = sem->sems_count; - buf->st_nlink = sem->sems_linked ? 1 : 0; - lock_release(sem->sems_lock); + lock_acquire(sem->sems_lock); + buf->st_size = sem->sems_count; + buf->st_nlink = sem->sems_linked ? 1 : 0; + lock_release(sem->sems_lock); - buf->st_mode = S_IFREG | 0666; - buf->st_blocks = 0; - buf->st_dev = 0; - buf->st_ino = semv->semv_semnum; + buf->st_mode = S_IFREG | 0666; + buf->st_blocks = 0; + buf->st_dev = 0; + buf->st_ino = semv->semv_semnum; - return 0; + return 0; } /* * Read. This is P(); decrease the count by the amount read. * Don't actually bother to transfer any data. */ -static -int -semfs_read(struct vnode *vn, struct uio *uio) -{ - struct semfs_vnode *semv = vn->vn_data; - struct semfs_sem *sem; - size_t consume; +static int semfs_read(struct vnode *vn, struct uio *uio) { + struct semfs_vnode *semv = vn->vn_data; + struct semfs_sem *sem; + size_t consume; - sem = semfs_getsem(semv); + sem = semfs_getsem(semv); - lock_acquire(sem->sems_lock); - while (uio->uio_resid > 0) { - if (sem->sems_count > 0) { - consume = uio->uio_resid; - if (consume > sem->sems_count) { - consume = sem->sems_count; - } - DEBUG(DB_SEMFS, "semfs: sem%u: P, count %u -> %u\n", - semv->semv_semnum, sem->sems_count, - sem->sems_count - consume); - sem->sems_count -= consume; - /* don't bother advancing the uio data pointers */ - uio->uio_offset += consume; - uio->uio_resid -= consume; - } - if (uio->uio_resid == 0) { - break; - } - if (sem->sems_count == 0) { - DEBUG(DB_SEMFS, "semfs: sem%u: blocking\n", - semv->semv_semnum); - cv_wait(sem->sems_cv, sem->sems_lock); - } - } - lock_release(sem->sems_lock); - return 0; + lock_acquire(sem->sems_lock); + while (uio->uio_resid > 0) { + if (sem->sems_count > 0) { + consume = uio->uio_resid; + if (consume > sem->sems_count) { + consume = sem->sems_count; + } + DEBUG(DB_SEMFS, "semfs: sem%u: P, count %u -> %u\n", semv->semv_semnum, + sem->sems_count, sem->sems_count - consume); + sem->sems_count -= consume; + /* don't bother advancing the uio data pointers */ + uio->uio_offset += consume; + uio->uio_resid -= consume; + } + if (uio->uio_resid == 0) { + break; + } + if (sem->sems_count == 0) { + DEBUG(DB_SEMFS, "semfs: sem%u: blocking\n", semv->semv_semnum); + cv_wait(sem->sems_cv, sem->sems_lock); + } + } + lock_release(sem->sems_lock); + return 0; } /* * Write. This is V(); increase the count by the amount written. * Don't actually bother to transfer any data. */ -static -int -semfs_write(struct vnode *vn, struct uio *uio) -{ - struct semfs_vnode *semv = vn->vn_data; - struct semfs_sem *sem; - unsigned newcount; +static int semfs_write(struct vnode *vn, struct uio *uio) { + struct semfs_vnode *semv = vn->vn_data; + struct semfs_sem *sem; + unsigned newcount; - sem = semfs_getsem(semv); + sem = semfs_getsem(semv); - lock_acquire(sem->sems_lock); - while (uio->uio_resid > 0) { - newcount = sem->sems_count + uio->uio_resid; - if (newcount < sem->sems_count) { - /* overflow */ - lock_release(sem->sems_lock); - return EFBIG; - } - DEBUG(DB_SEMFS, "semfs: sem%u: V, count %u -> %u\n", - semv->semv_semnum, sem->sems_count, newcount); - semfs_wakeup(sem, newcount); - sem->sems_count = newcount; - uio->uio_offset += uio->uio_resid; - uio->uio_resid = 0; - } - lock_release(sem->sems_lock); - return 0; + lock_acquire(sem->sems_lock); + while (uio->uio_resid > 0) { + newcount = sem->sems_count + uio->uio_resid; + if (newcount < sem->sems_count) { + /* overflow */ + lock_release(sem->sems_lock); + return EFBIG; + } + DEBUG(DB_SEMFS, "semfs: sem%u: V, count %u -> %u\n", semv->semv_semnum, + sem->sems_count, newcount); + semfs_wakeup(sem, newcount); + sem->sems_count = newcount; + uio->uio_offset += uio->uio_resid; + uio->uio_resid = 0; + } + lock_release(sem->sems_lock); + return 0; } /* @@ -262,33 +227,30 @@ semfs_write(struct vnode *vn, struct uio *uio) * semaphore as one would expect. Also it allows creating semaphores * and then initializing their counts to values other than zero. */ -static -int -semfs_truncate(struct vnode *vn, off_t len) -{ - /* We should just use UINT_MAX but we don't have it in the kernel */ - const unsigned max = (unsigned)-1; +static int semfs_truncate(struct vnode *vn, off_t len) { + /* We should just use UINT_MAX but we don't have it in the kernel */ + const unsigned max = (unsigned)-1; - struct semfs_vnode *semv = vn->vn_data; - struct semfs_sem *sem; - unsigned newcount; + struct semfs_vnode *semv = vn->vn_data; + struct semfs_sem *sem; + unsigned newcount; - if (len < 0) { - return EINVAL; - } - if (len > (off_t)max) { - return EFBIG; - } - newcount = len; + if (len < 0) { + return EINVAL; + } + if (len > (off_t)max) { + return EFBIG; + } + newcount = len; - sem = semfs_getsem(semv); + sem = semfs_getsem(semv); - lock_acquire(sem->sems_lock); - semfs_wakeup(sem, newcount); - sem->sems_count = newcount; - lock_release(sem->sems_lock); + lock_acquire(sem->sems_lock); + semfs_wakeup(sem, newcount); + sem->sems_count = newcount; + lock_release(sem->sems_lock); - return 0; + return 0; } //////////////////////////////////////////////////////////// @@ -298,280 +260,253 @@ semfs_truncate(struct vnode *vn, off_t len) * Directory read. Note that there's only one directory (the semfs * root) that has all the semaphores in it. */ -static -int -semfs_getdirentry(struct vnode *dirvn, struct uio *uio) -{ - struct semfs_vnode *dirsemv = dirvn->vn_data; - struct semfs *semfs = dirsemv->semv_semfs; - struct semfs_direntry *dent; - unsigned num, pos; - int result; +static int semfs_getdirentry(struct vnode *dirvn, struct uio *uio) { + struct semfs_vnode *dirsemv = dirvn->vn_data; + struct semfs *semfs = dirsemv->semv_semfs; + struct semfs_direntry *dent; + unsigned num, pos; + int result; - KASSERT(uio->uio_offset >= 0); - pos = uio->uio_offset; + KASSERT(uio->uio_offset >= 0); + pos = uio->uio_offset; - lock_acquire(semfs->semfs_dirlock); + lock_acquire(semfs->semfs_dirlock); - num = semfs_direntryarray_num(semfs->semfs_dents); - if (pos >= num) { - /* EOF */ - result = 0; - } - else { - dent = semfs_direntryarray_get(semfs->semfs_dents, pos); - result = uiomove(dent->semd_name, strlen(dent->semd_name), - uio); - } + num = semfs_direntryarray_num(semfs->semfs_dents); + if (pos >= num) { + /* EOF */ + result = 0; + } else { + dent = semfs_direntryarray_get(semfs->semfs_dents, pos); + result = uiomove(dent->semd_name, strlen(dent->semd_name), uio); + } - lock_release(semfs->semfs_dirlock); - return result; + lock_release(semfs->semfs_dirlock); + return result; } /* * stat() for dirs */ -static -int -semfs_dirstat(struct vnode *vn, struct stat *buf) -{ - struct semfs_vnode *semv = vn->vn_data; - struct semfs *semfs = semv->semv_semfs; +static int semfs_dirstat(struct vnode *vn, struct stat *buf) { + struct semfs_vnode *semv = vn->vn_data; + struct semfs *semfs = semv->semv_semfs; - bzero(buf, sizeof(*buf)); + bzero(buf, sizeof(*buf)); - lock_acquire(semfs->semfs_dirlock); - buf->st_size = semfs_direntryarray_num(semfs->semfs_dents); - lock_release(semfs->semfs_dirlock); + lock_acquire(semfs->semfs_dirlock); + buf->st_size = semfs_direntryarray_num(semfs->semfs_dents); + lock_release(semfs->semfs_dirlock); - buf->st_mode = S_IFDIR | 1777; - buf->st_nlink = 2; - buf->st_blocks = 0; - buf->st_dev = 0; - buf->st_ino = SEMFS_ROOTDIR; + buf->st_mode = S_IFDIR | 1777; + buf->st_nlink = 2; + buf->st_blocks = 0; + buf->st_dev = 0; + buf->st_ino = SEMFS_ROOTDIR; - return 0; + return 0; } /* * Backend for getcwd. Since we don't support subdirs, it's easy; send * back the empty string. */ -static -int -semfs_namefile(struct vnode *vn, struct uio *uio) -{ - (void)vn; - (void)uio; - return 0; +static int semfs_namefile(struct vnode *vn, struct uio *uio) { + (void)vn; + (void)uio; + return 0; } /* * Create a semaphore. */ -static -int -semfs_creat(struct vnode *dirvn, const char *name, bool excl, mode_t mode, - struct vnode **resultvn) -{ - struct semfs_vnode *dirsemv = dirvn->vn_data; - struct semfs *semfs = dirsemv->semv_semfs; - struct semfs_direntry *dent; - struct semfs_sem *sem; - unsigned i, num, empty, semnum; - int result; +static int semfs_creat(struct vnode *dirvn, const char *name, bool excl, + mode_t mode, struct vnode **resultvn) { + struct semfs_vnode *dirsemv = dirvn->vn_data; + struct semfs *semfs = dirsemv->semv_semfs; + struct semfs_direntry *dent; + struct semfs_sem *sem; + unsigned i, num, empty, semnum; + int result; - (void)mode; - if (!strcmp(name, ".") || !strcmp(name, "..")) { - return EEXIST; - } + (void)mode; + if (!strcmp(name, ".") || !strcmp(name, "..")) { + return EEXIST; + } - lock_acquire(semfs->semfs_dirlock); - num = semfs_direntryarray_num(semfs->semfs_dents); - empty = num; - for (i=0; isemfs_dents, i); - if (dent == NULL) { - if (empty == num) { - empty = i; - } - continue; - } - if (!strcmp(dent->semd_name, name)) { - /* found */ - if (excl) { - lock_release(semfs->semfs_dirlock); - return EEXIST; - } - result = semfs_getvnode(semfs, dent->semd_semnum, - resultvn); - lock_release(semfs->semfs_dirlock); - return result; - } - } + lock_acquire(semfs->semfs_dirlock); + num = semfs_direntryarray_num(semfs->semfs_dents); + empty = num; + for (i = 0; i < num; i++) { + dent = semfs_direntryarray_get(semfs->semfs_dents, i); + if (dent == NULL) { + if (empty == num) { + empty = i; + } + continue; + } + if (!strcmp(dent->semd_name, name)) { + /* found */ + if (excl) { + lock_release(semfs->semfs_dirlock); + return EEXIST; + } + result = semfs_getvnode(semfs, dent->semd_semnum, resultvn); + lock_release(semfs->semfs_dirlock); + return result; + } + } - /* create it */ - sem = semfs_sem_create(name); - if (sem == NULL) { - result = ENOMEM; - goto fail_unlock; - } - lock_acquire(semfs->semfs_tablelock); - result = semfs_sem_insert(semfs, sem, &semnum); - lock_release(semfs->semfs_tablelock); - if (result) { - goto fail_uncreate; - } + /* create it */ + sem = semfs_sem_create(name); + if (sem == NULL) { + result = ENOMEM; + goto fail_unlock; + } + lock_acquire(semfs->semfs_tablelock); + result = semfs_sem_insert(semfs, sem, &semnum); + lock_release(semfs->semfs_tablelock); + if (result) { + goto fail_uncreate; + } - dent = semfs_direntry_create(name, semnum); - if (dent == NULL) { - goto fail_uninsert; - } + dent = semfs_direntry_create(name, semnum); + if (dent == NULL) { + goto fail_uninsert; + } - if (empty < num) { - semfs_direntryarray_set(semfs->semfs_dents, empty, dent); - } - else { - result = semfs_direntryarray_add(semfs->semfs_dents, dent, - &empty); - if (result) { - goto fail_undent; - } - } + if (empty < num) { + semfs_direntryarray_set(semfs->semfs_dents, empty, dent); + } else { + result = semfs_direntryarray_add(semfs->semfs_dents, dent, &empty); + if (result) { + goto fail_undent; + } + } - result = semfs_getvnode(semfs, semnum, resultvn); - if (result) { - goto fail_undir; - } + result = semfs_getvnode(semfs, semnum, resultvn); + if (result) { + goto fail_undir; + } - sem->sems_linked = true; - lock_release(semfs->semfs_dirlock); - return 0; + sem->sems_linked = true; + lock_release(semfs->semfs_dirlock); + return 0; - fail_undir: - semfs_direntryarray_set(semfs->semfs_dents, empty, NULL); - fail_undent: - semfs_direntry_destroy(dent); - fail_uninsert: - lock_acquire(semfs->semfs_tablelock); - semfs_semarray_set(semfs->semfs_sems, semnum, NULL); - lock_release(semfs->semfs_tablelock); - fail_uncreate: - semfs_sem_destroy(sem); - fail_unlock: - lock_release(semfs->semfs_dirlock); - return result; +fail_undir: + semfs_direntryarray_set(semfs->semfs_dents, empty, NULL); +fail_undent: + semfs_direntry_destroy(dent); +fail_uninsert: + lock_acquire(semfs->semfs_tablelock); + semfs_semarray_set(semfs->semfs_sems, semnum, NULL); + lock_release(semfs->semfs_tablelock); +fail_uncreate: + semfs_sem_destroy(sem); +fail_unlock: + lock_release(semfs->semfs_dirlock); + return result; } /* * Unlink a semaphore. As with other files, it may not actually * go away if it's currently open. */ -static -int -semfs_remove(struct vnode *dirvn, const char *name) -{ - struct semfs_vnode *dirsemv = dirvn->vn_data; - struct semfs *semfs = dirsemv->semv_semfs; - struct semfs_direntry *dent; - struct semfs_sem *sem; - unsigned i, num; - int result; +static int semfs_remove(struct vnode *dirvn, const char *name) { + struct semfs_vnode *dirsemv = dirvn->vn_data; + struct semfs *semfs = dirsemv->semv_semfs; + struct semfs_direntry *dent; + struct semfs_sem *sem; + unsigned i, num; + int result; - if (!strcmp(name, ".") || !strcmp(name, "..")) { - return EINVAL; - } + if (!strcmp(name, ".") || !strcmp(name, "..")) { + return EINVAL; + } - lock_acquire(semfs->semfs_dirlock); - num = semfs_direntryarray_num(semfs->semfs_dents); - for (i=0; isemfs_dents, i); - if (dent == NULL) { - continue; - } - if (!strcmp(name, dent->semd_name)) { - /* found */ - sem = semfs_getsembynum(semfs, dent->semd_semnum); - lock_acquire(sem->sems_lock); - KASSERT(sem->sems_linked); - sem->sems_linked = false; - if (sem->sems_hasvnode == false) { - lock_acquire(semfs->semfs_tablelock); - semfs_semarray_set(semfs->semfs_sems, - dent->semd_semnum, NULL); - lock_release(semfs->semfs_tablelock); - lock_release(sem->sems_lock); - semfs_sem_destroy(sem); - } - else { - lock_release(sem->sems_lock); - } - semfs_direntryarray_set(semfs->semfs_dents, i, NULL); - semfs_direntry_destroy(dent); - result = 0; - goto out; - } - } - result = ENOENT; - out: - lock_release(semfs->semfs_dirlock); - return result; + lock_acquire(semfs->semfs_dirlock); + num = semfs_direntryarray_num(semfs->semfs_dents); + for (i = 0; i < num; i++) { + dent = semfs_direntryarray_get(semfs->semfs_dents, i); + if (dent == NULL) { + continue; + } + if (!strcmp(name, dent->semd_name)) { + /* found */ + sem = semfs_getsembynum(semfs, dent->semd_semnum); + lock_acquire(sem->sems_lock); + KASSERT(sem->sems_linked); + sem->sems_linked = false; + if (sem->sems_hasvnode == false) { + lock_acquire(semfs->semfs_tablelock); + semfs_semarray_set(semfs->semfs_sems, dent->semd_semnum, NULL); + lock_release(semfs->semfs_tablelock); + lock_release(sem->sems_lock); + semfs_sem_destroy(sem); + } else { + lock_release(sem->sems_lock); + } + semfs_direntryarray_set(semfs->semfs_dents, i, NULL); + semfs_direntry_destroy(dent); + result = 0; + goto out; + } + } + result = ENOENT; +out: + lock_release(semfs->semfs_dirlock); + return result; } /* * Lookup: get a semaphore by name. */ -static -int -semfs_lookup(struct vnode *dirvn, char *path, struct vnode **resultvn) -{ - struct semfs_vnode *dirsemv = dirvn->vn_data; - struct semfs *semfs = dirsemv->semv_semfs; - struct semfs_direntry *dent; - unsigned i, num; - int result; +static int semfs_lookup(struct vnode *dirvn, char *path, + struct vnode **resultvn) { + struct semfs_vnode *dirsemv = dirvn->vn_data; + struct semfs *semfs = dirsemv->semv_semfs; + struct semfs_direntry *dent; + unsigned i, num; + int result; - if (!strcmp(path, ".") || !strcmp(path, "..")) { - VOP_INCREF(dirvn); - *resultvn = dirvn; - return 0; - } + if (!strcmp(path, ".") || !strcmp(path, "..")) { + VOP_INCREF(dirvn); + *resultvn = dirvn; + return 0; + } - lock_acquire(semfs->semfs_dirlock); - num = semfs_direntryarray_num(semfs->semfs_dents); - for (i=0; isemfs_dents, i); - if (dent == NULL) { - continue; - } - if (!strcmp(path, dent->semd_name)) { - result = semfs_getvnode(semfs, dent->semd_semnum, - resultvn); - lock_release(semfs->semfs_dirlock); - return result; - } - } - lock_release(semfs->semfs_dirlock); - return ENOENT; + lock_acquire(semfs->semfs_dirlock); + num = semfs_direntryarray_num(semfs->semfs_dents); + for (i = 0; i < num; i++) { + dent = semfs_direntryarray_get(semfs->semfs_dents, i); + if (dent == NULL) { + continue; + } + if (!strcmp(path, dent->semd_name)) { + result = semfs_getvnode(semfs, dent->semd_semnum, resultvn); + lock_release(semfs->semfs_dirlock); + return result; + } + } + lock_release(semfs->semfs_dirlock); + return ENOENT; } /* * Lookparent: because we don't have subdirs, just return the root * dir and copy the name. */ -static -int -semfs_lookparent(struct vnode *dirvn, char *path, - struct vnode **resultdirvn, char *namebuf, size_t bufmax) -{ - if (strlen(path)+1 > bufmax) { - return ENAMETOOLONG; - } - strcpy(namebuf, path); +static int semfs_lookparent(struct vnode *dirvn, char *path, + struct vnode **resultdirvn, char *namebuf, + size_t bufmax) { + if (strlen(path) + 1 > bufmax) { + return ENAMETOOLONG; + } + strcpy(namebuf, path); - VOP_INCREF(dirvn); - *resultdirvn = dirvn; - return 0; + VOP_INCREF(dirvn); + *resultdirvn = dirvn; + return 0; } //////////////////////////////////////////////////////////// @@ -580,220 +515,207 @@ semfs_lookparent(struct vnode *dirvn, char *path, /* * Destructor for semfs_vnode. */ -static -void -semfs_vnode_destroy(struct semfs_vnode *semv) -{ - vnode_cleanup(&semv->semv_absvn); - kfree(semv); +static void semfs_vnode_destroy(struct semfs_vnode *semv) { + vnode_cleanup(&semv->semv_absvn); + kfree(semv); } /* * Reclaim - drop a vnode that's no longer in use. */ -static -int -semfs_reclaim(struct vnode *vn) -{ - struct semfs_vnode *semv = vn->vn_data; - struct semfs *semfs = semv->semv_semfs; - struct vnode *vn2; - struct semfs_sem *sem; - unsigned i, num; +static int semfs_reclaim(struct vnode *vn) { + struct semfs_vnode *semv = vn->vn_data; + struct semfs *semfs = semv->semv_semfs; + struct vnode *vn2; + struct semfs_sem *sem; + unsigned i, num; - lock_acquire(semfs->semfs_tablelock); + lock_acquire(semfs->semfs_tablelock); - /* vnode refcount is protected by the vnode's ->vn_countlock */ - spinlock_acquire(&vn->vn_countlock); - if (vn->vn_refcount > 1) { - /* consume the reference VOP_DECREF passed us */ - vn->vn_refcount--; + /* vnode refcount is protected by the vnode's ->vn_countlock */ + spinlock_acquire(&vn->vn_countlock); + if (vn->vn_refcount > 1) { + /* consume the reference VOP_DECREF passed us */ + vn->vn_refcount--; - spinlock_release(&vn->vn_countlock); - lock_release(semfs->semfs_tablelock); - return EBUSY; - } + spinlock_release(&vn->vn_countlock); + lock_release(semfs->semfs_tablelock); + return EBUSY; + } - spinlock_release(&vn->vn_countlock); + spinlock_release(&vn->vn_countlock); - /* remove from the table */ - num = vnodearray_num(semfs->semfs_vnodes); - for (i=0; isemfs_vnodes, i); - if (vn2 == vn) { - vnodearray_remove(semfs->semfs_vnodes, i); - break; - } - } + /* remove from the table */ + num = vnodearray_num(semfs->semfs_vnodes); + for (i = 0; i < num; i++) { + vn2 = vnodearray_get(semfs->semfs_vnodes, i); + if (vn2 == vn) { + vnodearray_remove(semfs->semfs_vnodes, i); + break; + } + } - if (semv->semv_semnum != SEMFS_ROOTDIR) { - sem = semfs_semarray_get(semfs->semfs_sems, semv->semv_semnum); - KASSERT(sem->sems_hasvnode); - sem->sems_hasvnode = false; - if (sem->sems_linked == false) { - semfs_semarray_set(semfs->semfs_sems, - semv->semv_semnum, NULL); - semfs_sem_destroy(sem); - } - } + if (semv->semv_semnum != SEMFS_ROOTDIR) { + sem = semfs_semarray_get(semfs->semfs_sems, semv->semv_semnum); + KASSERT(sem->sems_hasvnode); + sem->sems_hasvnode = false; + if (sem->sems_linked == false) { + semfs_semarray_set(semfs->semfs_sems, semv->semv_semnum, NULL); + semfs_sem_destroy(sem); + } + } - /* done with the table */ - lock_release(semfs->semfs_tablelock); + /* done with the table */ + lock_release(semfs->semfs_tablelock); - /* destroy it */ - semfs_vnode_destroy(semv); - return 0; + /* destroy it */ + semfs_vnode_destroy(semv); + return 0; } /* * Vnode ops table for dirs. */ static const struct vnode_ops semfs_dirops = { - .vop_magic = VOP_MAGIC, + .vop_magic = VOP_MAGIC, - .vop_eachopen = semfs_eachopen, - .vop_reclaim = semfs_reclaim, + .vop_eachopen = semfs_eachopen, + .vop_reclaim = semfs_reclaim, - .vop_read = vopfail_uio_isdir, - .vop_readlink = vopfail_uio_isdir, - .vop_getdirentry = semfs_getdirentry, - .vop_write = vopfail_uio_isdir, - .vop_ioctl = semfs_ioctl, - .vop_stat = semfs_dirstat, - .vop_gettype = semfs_gettype, - .vop_isseekable = semfs_isseekable, - .vop_fsync = semfs_fsync, - .vop_mmap = vopfail_mmap_isdir, - .vop_truncate = vopfail_truncate_isdir, - .vop_namefile = semfs_namefile, + .vop_read = vopfail_uio_isdir, + .vop_readlink = vopfail_uio_isdir, + .vop_getdirentry = semfs_getdirentry, + .vop_write = vopfail_uio_isdir, + .vop_ioctl = semfs_ioctl, + .vop_stat = semfs_dirstat, + .vop_gettype = semfs_gettype, + .vop_isseekable = semfs_isseekable, + .vop_fsync = semfs_fsync, + .vop_mmap = vopfail_mmap_isdir, + .vop_truncate = vopfail_truncate_isdir, + .vop_namefile = semfs_namefile, - .vop_creat = semfs_creat, - .vop_symlink = vopfail_symlink_nosys, - .vop_mkdir = vopfail_mkdir_nosys, - .vop_link = vopfail_link_nosys, - .vop_remove = semfs_remove, - .vop_rmdir = vopfail_string_nosys, - .vop_rename = vopfail_rename_nosys, - .vop_lookup = semfs_lookup, - .vop_lookparent = semfs_lookparent, + .vop_creat = semfs_creat, + .vop_symlink = vopfail_symlink_nosys, + .vop_mkdir = vopfail_mkdir_nosys, + .vop_link = vopfail_link_nosys, + .vop_remove = semfs_remove, + .vop_rmdir = vopfail_string_nosys, + .vop_rename = vopfail_rename_nosys, + .vop_lookup = semfs_lookup, + .vop_lookparent = semfs_lookparent, }; /* * Vnode ops table for semaphores (files). */ static const struct vnode_ops semfs_semops = { - .vop_magic = VOP_MAGIC, + .vop_magic = VOP_MAGIC, - .vop_eachopen = semfs_eachopen, - .vop_reclaim = semfs_reclaim, + .vop_eachopen = semfs_eachopen, + .vop_reclaim = semfs_reclaim, - .vop_read = semfs_read, - .vop_readlink = vopfail_uio_inval, - .vop_getdirentry = vopfail_uio_notdir, - .vop_write = semfs_write, - .vop_ioctl = semfs_ioctl, - .vop_stat = semfs_semstat, - .vop_gettype = semfs_gettype, - .vop_isseekable = semfs_isseekable, - .vop_fsync = semfs_fsync, - .vop_mmap = vopfail_mmap_perm, - .vop_truncate = semfs_truncate, - .vop_namefile = vopfail_uio_notdir, + .vop_read = semfs_read, + .vop_readlink = vopfail_uio_inval, + .vop_getdirentry = vopfail_uio_notdir, + .vop_write = semfs_write, + .vop_ioctl = semfs_ioctl, + .vop_stat = semfs_semstat, + .vop_gettype = semfs_gettype, + .vop_isseekable = semfs_isseekable, + .vop_fsync = semfs_fsync, + .vop_mmap = vopfail_mmap_perm, + .vop_truncate = semfs_truncate, + .vop_namefile = vopfail_uio_notdir, - .vop_creat = vopfail_creat_notdir, - .vop_symlink = vopfail_symlink_notdir, - .vop_mkdir = vopfail_mkdir_notdir, - .vop_link = vopfail_link_notdir, - .vop_remove = vopfail_string_notdir, - .vop_rmdir = vopfail_string_notdir, - .vop_rename = vopfail_rename_notdir, - .vop_lookup = vopfail_lookup_notdir, - .vop_lookparent = vopfail_lookparent_notdir, + .vop_creat = vopfail_creat_notdir, + .vop_symlink = vopfail_symlink_notdir, + .vop_mkdir = vopfail_mkdir_notdir, + .vop_link = vopfail_link_notdir, + .vop_remove = vopfail_string_notdir, + .vop_rmdir = vopfail_string_notdir, + .vop_rename = vopfail_rename_notdir, + .vop_lookup = vopfail_lookup_notdir, + .vop_lookparent = vopfail_lookparent_notdir, }; /* * Constructor for semfs vnodes. */ -static -struct semfs_vnode * -semfs_vnode_create(struct semfs *semfs, unsigned semnum) -{ - const struct vnode_ops *optable; - struct semfs_vnode *semv; - int result; +static struct semfs_vnode *semfs_vnode_create(struct semfs *semfs, + unsigned semnum) { + const struct vnode_ops *optable; + struct semfs_vnode *semv; + int result; - if (semnum == SEMFS_ROOTDIR) { - optable = &semfs_dirops; - } - else { - optable = &semfs_semops; - } + if (semnum == SEMFS_ROOTDIR) { + optable = &semfs_dirops; + } else { + optable = &semfs_semops; + } - semv = kmalloc(sizeof(*semv)); - if (semv == NULL) { - return NULL; - } + semv = kmalloc(sizeof(*semv)); + if (semv == NULL) { + return NULL; + } - semv->semv_semfs = semfs; - semv->semv_semnum = semnum; + semv->semv_semfs = semfs; + semv->semv_semnum = semnum; - result = vnode_init(&semv->semv_absvn, optable, - &semfs->semfs_absfs, semv); - /* vnode_init doesn't actually fail */ - KASSERT(result == 0); + result = vnode_init(&semv->semv_absvn, optable, &semfs->semfs_absfs, semv); + /* vnode_init doesn't actually fail */ + KASSERT(result == 0); - return semv; + return semv; } /* * Look up the vnode for a semaphore by number; if it doesn't exist, * create it. */ -int -semfs_getvnode(struct semfs *semfs, unsigned semnum, struct vnode **ret) -{ - struct vnode *vn; - struct semfs_vnode *semv; - struct semfs_sem *sem; - unsigned i, num; - int result; +int semfs_getvnode(struct semfs *semfs, unsigned semnum, struct vnode **ret) { + struct vnode *vn; + struct semfs_vnode *semv; + struct semfs_sem *sem; + unsigned i, num; + int result; - /* Lock the vnode table */ - lock_acquire(semfs->semfs_tablelock); + /* Lock the vnode table */ + lock_acquire(semfs->semfs_tablelock); - /* Look for it */ - num = vnodearray_num(semfs->semfs_vnodes); - for (i=0; isemfs_vnodes, i); - semv = vn->vn_data; - if (semv->semv_semnum == semnum) { - VOP_INCREF(vn); - lock_release(semfs->semfs_tablelock); - *ret = vn; - return 0; - } - } + /* Look for it */ + num = vnodearray_num(semfs->semfs_vnodes); + for (i = 0; i < num; i++) { + vn = vnodearray_get(semfs->semfs_vnodes, i); + semv = vn->vn_data; + if (semv->semv_semnum == semnum) { + VOP_INCREF(vn); + lock_release(semfs->semfs_tablelock); + *ret = vn; + return 0; + } + } - /* Make it */ - semv = semfs_vnode_create(semfs, semnum); - if (semv == NULL) { - lock_release(semfs->semfs_tablelock); - return ENOMEM; - } - result = vnodearray_add(semfs->semfs_vnodes, &semv->semv_absvn, NULL); - if (result) { - semfs_vnode_destroy(semv); - lock_release(semfs->semfs_tablelock); - return ENOMEM; - } - if (semnum != SEMFS_ROOTDIR) { - sem = semfs_semarray_get(semfs->semfs_sems, semnum); - KASSERT(sem != NULL); - KASSERT(sem->sems_hasvnode == false); - sem->sems_hasvnode = true; - } - lock_release(semfs->semfs_tablelock); + /* Make it */ + semv = semfs_vnode_create(semfs, semnum); + if (semv == NULL) { + lock_release(semfs->semfs_tablelock); + return ENOMEM; + } + result = vnodearray_add(semfs->semfs_vnodes, &semv->semv_absvn, NULL); + if (result) { + semfs_vnode_destroy(semv); + lock_release(semfs->semfs_tablelock); + return ENOMEM; + } + if (semnum != SEMFS_ROOTDIR) { + sem = semfs_semarray_get(semfs->semfs_sems, semnum); + KASSERT(sem != NULL); + KASSERT(sem->sems_hasvnode == false); + sem->sems_hasvnode = true; + } + lock_release(semfs->semfs_tablelock); - *ret = &semv->semv_absvn; - return 0; + *ret = &semv->semv_absvn; + return 0; } diff --git a/kern/fs/sfs/sfs_balloc.c b/kern/fs/sfs/sfs_balloc.c index b931aa0..5d5be61 100644 --- a/kern/fs/sfs/sfs_balloc.c +++ b/kern/fs/sfs/sfs_balloc.c @@ -41,63 +41,53 @@ /* * Zero out a disk block. */ -static -int -sfs_clearblock(struct sfs_fs *sfs, daddr_t block) -{ - /* static -> automatically initialized to zero */ - static char zeros[SFS_BLOCKSIZE]; +static int sfs_clearblock(struct sfs_fs *sfs, daddr_t block) { + /* static -> automatically initialized to zero */ + static char zeros[SFS_BLOCKSIZE]; - return sfs_writeblock(sfs, block, zeros, SFS_BLOCKSIZE); + return sfs_writeblock(sfs, block, zeros, SFS_BLOCKSIZE); } /* * Allocate a block. */ -int -sfs_balloc(struct sfs_fs *sfs, daddr_t *diskblock) -{ - int result; +int sfs_balloc(struct sfs_fs *sfs, daddr_t *diskblock) { + int result; - result = bitmap_alloc(sfs->sfs_freemap, diskblock); - if (result) { - return result; - } - sfs->sfs_freemapdirty = true; + result = bitmap_alloc(sfs->sfs_freemap, diskblock); + if (result) { + return result; + } + sfs->sfs_freemapdirty = true; - if (*diskblock >= sfs->sfs_sb.sb_nblocks) { - panic("sfs: %s: balloc: invalid block %u\n", - sfs->sfs_sb.sb_volname, *diskblock); - } + if (*diskblock >= sfs->sfs_sb.sb_nblocks) { + panic("sfs: %s: balloc: invalid block %u\n", sfs->sfs_sb.sb_volname, + *diskblock); + } - /* Clear block before returning it */ - result = sfs_clearblock(sfs, *diskblock); - if (result) { - bitmap_unmark(sfs->sfs_freemap, *diskblock); - } - return result; + /* Clear block before returning it */ + result = sfs_clearblock(sfs, *diskblock); + if (result) { + bitmap_unmark(sfs->sfs_freemap, *diskblock); + } + return result; } /* * Free a block. */ -void -sfs_bfree(struct sfs_fs *sfs, daddr_t diskblock) -{ - bitmap_unmark(sfs->sfs_freemap, diskblock); - sfs->sfs_freemapdirty = true; +void sfs_bfree(struct sfs_fs *sfs, daddr_t diskblock) { + bitmap_unmark(sfs->sfs_freemap, diskblock); + sfs->sfs_freemapdirty = true; } /* * Check if a block is in use. */ -int -sfs_bused(struct sfs_fs *sfs, daddr_t diskblock) -{ - if (diskblock >= sfs->sfs_sb.sb_nblocks) { - panic("sfs: %s: sfs_bused called on out of range block %u\n", - sfs->sfs_sb.sb_volname, diskblock); - } - return bitmap_isset(sfs->sfs_freemap, diskblock); +int sfs_bused(struct sfs_fs *sfs, daddr_t diskblock) { + if (diskblock >= sfs->sfs_sb.sb_nblocks) { + panic("sfs: %s: sfs_bused called on out of range block %u\n", + sfs->sfs_sb.sb_volname, diskblock); + } + return bitmap_isset(sfs->sfs_freemap, diskblock); } - diff --git a/kern/fs/sfs/sfs_bmap.c b/kern/fs/sfs/sfs_bmap.c index 5352a38..afa0fbd 100644 --- a/kern/fs/sfs/sfs_bmap.c +++ b/kern/fs/sfs/sfs_bmap.c @@ -45,259 +45,250 @@ * file. If DOALLOC is set, and no such block exists, one will be * allocated. */ -int -sfs_bmap(struct sfs_vnode *sv, uint32_t fileblock, bool doalloc, - daddr_t *diskblock) -{ - /* - * I/O buffer for handling indirect blocks. - * - * Note: in real life (and when you've done the fs assignment) - * you would get space from the disk buffer cache for this, - * not use a static area. - */ - static uint32_t idbuf[SFS_DBPERIDB]; +int sfs_bmap(struct sfs_vnode *sv, uint32_t fileblock, bool doalloc, + daddr_t *diskblock) { + /* + * I/O buffer for handling indirect blocks. + * + * Note: in real life (and when you've done the fs assignment) + * you would get space from the disk buffer cache for this, + * not use a static area. + */ + static uint32_t idbuf[SFS_DBPERIDB]; - struct sfs_fs *sfs = sv->sv_absvn.vn_fs->fs_data; - daddr_t block; - daddr_t idblock; - uint32_t idnum, idoff; - int result; + struct sfs_fs *sfs = sv->sv_absvn.vn_fs->fs_data; + daddr_t block; + daddr_t idblock; + uint32_t idnum, idoff; + int result; - KASSERT(sizeof(idbuf)==SFS_BLOCKSIZE); + KASSERT(sizeof(idbuf) == SFS_BLOCKSIZE); - /* Since we're using a static buffer, we'd better be locked. */ - KASSERT(vfs_biglock_do_i_hold()); + /* Since we're using a static buffer, we'd better be locked. */ + KASSERT(vfs_biglock_do_i_hold()); - /* - * If the block we want is one of the direct blocks... - */ - if (fileblock < SFS_NDIRECT) { - /* - * Get the block number - */ - block = sv->sv_i.sfi_direct[fileblock]; + /* + * If the block we want is one of the direct blocks... + */ + if (fileblock < SFS_NDIRECT) { + /* + * Get the block number + */ + block = sv->sv_i.sfi_direct[fileblock]; - /* - * Do we need to allocate? - */ - if (block==0 && doalloc) { - result = sfs_balloc(sfs, &block); - if (result) { - return result; - } + /* + * Do we need to allocate? + */ + if (block == 0 && doalloc) { + result = sfs_balloc(sfs, &block); + if (result) { + return result; + } - /* Remember what we allocated; mark inode dirty */ - sv->sv_i.sfi_direct[fileblock] = block; - sv->sv_dirty = true; - } + /* Remember what we allocated; mark inode dirty */ + sv->sv_i.sfi_direct[fileblock] = block; + sv->sv_dirty = true; + } - /* - * Hand back the block - */ - if (block != 0 && !sfs_bused(sfs, block)) { - panic("sfs: %s: Data block %u (block %u of file %u) " - "marked free\n", sfs->sfs_sb.sb_volname, - block, fileblock, sv->sv_ino); - } - *diskblock = block; - return 0; - } + /* + * Hand back the block + */ + if (block != 0 && !sfs_bused(sfs, block)) { + panic("sfs: %s: Data block %u (block %u of file %u) " + "marked free\n", + sfs->sfs_sb.sb_volname, block, fileblock, sv->sv_ino); + } + *diskblock = block; + return 0; + } - /* - * It's not a direct block; it must be in the indirect block. - * Subtract off the number of direct blocks, so FILEBLOCK is - * now the offset into the indirect block space. - */ + /* + * It's not a direct block; it must be in the indirect block. + * Subtract off the number of direct blocks, so FILEBLOCK is + * now the offset into the indirect block space. + */ - fileblock -= SFS_NDIRECT; + fileblock -= SFS_NDIRECT; - /* Get the indirect block number and offset w/i that indirect block */ - idnum = fileblock / SFS_DBPERIDB; - idoff = fileblock % SFS_DBPERIDB; + /* Get the indirect block number and offset w/i that indirect block */ + idnum = fileblock / SFS_DBPERIDB; + idoff = fileblock % SFS_DBPERIDB; - /* - * We only have one indirect block. If the offset we were asked for - * is too large, we can't handle it, so fail. - */ - if (idnum >= SFS_NINDIRECT) { - return EFBIG; - } + /* + * We only have one indirect block. If the offset we were asked for + * is too large, we can't handle it, so fail. + */ + if (idnum >= SFS_NINDIRECT) { + return EFBIG; + } - /* Get the disk block number of the indirect block. */ - idblock = sv->sv_i.sfi_indirect; + /* Get the disk block number of the indirect block. */ + idblock = sv->sv_i.sfi_indirect; - if (idblock==0 && !doalloc) { - /* - * There's no indirect block allocated. We weren't - * asked to allocate anything, so pretend the indirect - * block was filled with all zeros. - */ - *diskblock = 0; - return 0; - } - else if (idblock==0) { - /* - * There's no indirect block allocated, but we need to - * allocate a block whose number needs to be stored in - * the indirect block. Thus, we need to allocate an - * indirect block. - */ - result = sfs_balloc(sfs, &idblock); - if (result) { - return result; - } + if (idblock == 0 && !doalloc) { + /* + * There's no indirect block allocated. We weren't + * asked to allocate anything, so pretend the indirect + * block was filled with all zeros. + */ + *diskblock = 0; + return 0; + } else if (idblock == 0) { + /* + * There's no indirect block allocated, but we need to + * allocate a block whose number needs to be stored in + * the indirect block. Thus, we need to allocate an + * indirect block. + */ + result = sfs_balloc(sfs, &idblock); + if (result) { + return result; + } - /* Remember the block we just allocated */ - sv->sv_i.sfi_indirect = idblock; + /* Remember the block we just allocated */ + sv->sv_i.sfi_indirect = idblock; - /* Mark the inode dirty */ - sv->sv_dirty = true; + /* Mark the inode dirty */ + sv->sv_dirty = true; - /* Clear the indirect block buffer */ - bzero(idbuf, sizeof(idbuf)); - } - else { - /* - * We already have an indirect block allocated; load it. - */ - result = sfs_readblock(sfs, idblock, idbuf, sizeof(idbuf)); - if (result) { - return result; - } - } + /* Clear the indirect block buffer */ + bzero(idbuf, sizeof(idbuf)); + } else { + /* + * We already have an indirect block allocated; load it. + */ + result = sfs_readblock(sfs, idblock, idbuf, sizeof(idbuf)); + if (result) { + return result; + } + } - /* Get the block out of the indirect block buffer */ - block = idbuf[idoff]; + /* Get the block out of the indirect block buffer */ + block = idbuf[idoff]; - /* If there's no block there, allocate one */ - if (block==0 && doalloc) { - result = sfs_balloc(sfs, &block); - if (result) { - return result; - } + /* If there's no block there, allocate one */ + if (block == 0 && doalloc) { + result = sfs_balloc(sfs, &block); + if (result) { + return result; + } - /* Remember the block we allocated */ - idbuf[idoff] = block; + /* Remember the block we allocated */ + idbuf[idoff] = block; - /* The indirect block is now dirty; write it back */ - result = sfs_writeblock(sfs, idblock, idbuf, sizeof(idbuf)); - if (result) { - return result; - } - } + /* The indirect block is now dirty; write it back */ + result = sfs_writeblock(sfs, idblock, idbuf, sizeof(idbuf)); + if (result) { + return result; + } + } - /* Hand back the result and return. */ - if (block != 0 && !sfs_bused(sfs, block)) { - panic("sfs: %s: Data block %u (block %u of file %u) " - "marked free\n", sfs->sfs_sb.sb_volname, - block, fileblock, sv->sv_ino); - } - *diskblock = block; - return 0; + /* Hand back the result and return. */ + if (block != 0 && !sfs_bused(sfs, block)) { + panic("sfs: %s: Data block %u (block %u of file %u) " + "marked free\n", + sfs->sfs_sb.sb_volname, block, fileblock, sv->sv_ino); + } + *diskblock = block; + return 0; } /* * Called for ftruncate() and from sfs_reclaim. */ -int -sfs_itrunc(struct sfs_vnode *sv, off_t len) -{ - /* - * I/O buffer for handling the indirect block. - * - * Note: in real life (and when you've done the fs assignment) - * you would get space from the disk buffer cache for this, - * not use a static area. - */ - static uint32_t idbuf[SFS_DBPERIDB]; +int sfs_itrunc(struct sfs_vnode *sv, off_t len) { + /* + * I/O buffer for handling the indirect block. + * + * Note: in real life (and when you've done the fs assignment) + * you would get space from the disk buffer cache for this, + * not use a static area. + */ + static uint32_t idbuf[SFS_DBPERIDB]; - struct sfs_fs *sfs = sv->sv_absvn.vn_fs->fs_data; + struct sfs_fs *sfs = sv->sv_absvn.vn_fs->fs_data; - /* Length in blocks (divide rounding up) */ - uint32_t blocklen = DIVROUNDUP(len, SFS_BLOCKSIZE); + /* Length in blocks (divide rounding up) */ + uint32_t blocklen = DIVROUNDUP(len, SFS_BLOCKSIZE); - uint32_t i, j; - daddr_t block, idblock; - uint32_t baseblock, highblock; - int result; - int hasnonzero, iddirty; + uint32_t i, j; + daddr_t block, idblock; + uint32_t baseblock, highblock; + int result; + int hasnonzero, iddirty; - KASSERT(sizeof(idbuf)==SFS_BLOCKSIZE); + KASSERT(sizeof(idbuf) == SFS_BLOCKSIZE); - vfs_biglock_acquire(); + vfs_biglock_acquire(); - /* - * Go through the direct blocks. Discard any that are - * past the limit we're truncating to. - */ - for (i=0; isv_i.sfi_direct[i]; - if (i >= blocklen && block != 0) { - sfs_bfree(sfs, block); - sv->sv_i.sfi_direct[i] = 0; - sv->sv_dirty = true; - } - } + /* + * Go through the direct blocks. Discard any that are + * past the limit we're truncating to. + */ + for (i = 0; i < SFS_NDIRECT; i++) { + block = sv->sv_i.sfi_direct[i]; + if (i >= blocklen && block != 0) { + sfs_bfree(sfs, block); + sv->sv_i.sfi_direct[i] = 0; + sv->sv_dirty = true; + } + } - /* Indirect block number */ - idblock = sv->sv_i.sfi_indirect; + /* Indirect block number */ + idblock = sv->sv_i.sfi_indirect; - /* The lowest block in the indirect block */ - baseblock = SFS_NDIRECT; + /* The lowest block in the indirect block */ + baseblock = SFS_NDIRECT; - /* The highest block in the indirect block */ - highblock = baseblock + SFS_DBPERIDB - 1; + /* The highest block in the indirect block */ + highblock = baseblock + SFS_DBPERIDB - 1; - if (blocklen < highblock && idblock != 0) { - /* We're past the proposed EOF; may need to free stuff */ + if (blocklen < highblock && idblock != 0) { + /* We're past the proposed EOF; may need to free stuff */ - /* Read the indirect block */ - result = sfs_readblock(sfs, idblock, idbuf, sizeof(idbuf)); - if (result) { - vfs_biglock_release(); - return result; - } + /* Read the indirect block */ + result = sfs_readblock(sfs, idblock, idbuf, sizeof(idbuf)); + if (result) { + vfs_biglock_release(); + return result; + } - hasnonzero = 0; - iddirty = 0; - for (j=0; jsv_i.sfi_indirect = 0; - sv->sv_dirty = true; - } - else if (iddirty) { - /* The indirect block is dirty; write it back */ - result = sfs_writeblock(sfs, idblock, idbuf, - sizeof(idbuf)); - if (result) { - vfs_biglock_release(); - return result; - } - } - } + if (!hasnonzero) { + /* The whole indirect block is empty now; free it */ + sfs_bfree(sfs, idblock); + sv->sv_i.sfi_indirect = 0; + sv->sv_dirty = true; + } else if (iddirty) { + /* The indirect block is dirty; write it back */ + result = sfs_writeblock(sfs, idblock, idbuf, sizeof(idbuf)); + if (result) { + vfs_biglock_release(); + return result; + } + } + } - /* Set the file size */ - sv->sv_i.sfi_size = len; + /* Set the file size */ + sv->sv_i.sfi_size = len; - /* Mark the inode dirty */ - sv->sv_dirty = true; + /* Mark the inode dirty */ + sv->sv_dirty = true; - vfs_biglock_release(); - return 0; + vfs_biglock_release(); + return 0; } - diff --git a/kern/fs/sfs/sfs_dir.c b/kern/fs/sfs/sfs_dir.c index 5e494b0..858bbf0 100644 --- a/kern/fs/sfs/sfs_dir.c +++ b/kern/fs/sfs/sfs_dir.c @@ -43,33 +43,29 @@ * Read the directory entry out of slot SLOT of a directory vnode. * The "slot" is the index of the directory entry, starting at 0. */ -static -int -sfs_readdir(struct sfs_vnode *sv, int slot, struct sfs_direntry *sd) -{ - off_t actualpos; +static int sfs_readdir(struct sfs_vnode *sv, int slot, + struct sfs_direntry *sd) { + off_t actualpos; - /* Compute the actual position in the directory to read. */ - actualpos = slot * sizeof(struct sfs_direntry); + /* Compute the actual position in the directory to read. */ + actualpos = slot * sizeof(struct sfs_direntry); - return sfs_metaio(sv, actualpos, sd, sizeof(*sd), UIO_READ); + return sfs_metaio(sv, actualpos, sd, sizeof(*sd), UIO_READ); } /* * Write (overwrite) the directory entry in slot SLOT of a directory * vnode. */ -static -int -sfs_writedir(struct sfs_vnode *sv, int slot, struct sfs_direntry *sd) -{ - off_t actualpos; +static int sfs_writedir(struct sfs_vnode *sv, int slot, + struct sfs_direntry *sd) { + off_t actualpos; - /* Compute the actual position in the directory. */ - KASSERT(slot>=0); - actualpos = slot * sizeof(struct sfs_direntry); + /* Compute the actual position in the directory. */ + KASSERT(slot >= 0); + actualpos = slot * sizeof(struct sfs_direntry); - return sfs_metaio(sv, actualpos, sd, sizeof(*sd), UIO_WRITE); + return sfs_metaio(sv, actualpos, sd, sizeof(*sd), UIO_WRITE); } /* @@ -77,22 +73,19 @@ sfs_writedir(struct sfs_vnode *sv, int slot, struct sfs_direntry *sd) * This actually computes the number of existing slots, and does not * account for empty slots. */ -static -int -sfs_dir_nentries(struct sfs_vnode *sv) -{ - struct sfs_fs *sfs = sv->sv_absvn.vn_fs->fs_data; - off_t size; +static int sfs_dir_nentries(struct sfs_vnode *sv) { + struct sfs_fs *sfs = sv->sv_absvn.vn_fs->fs_data; + off_t size; - KASSERT(sv->sv_i.sfi_type == SFS_TYPE_DIR); + KASSERT(sv->sv_i.sfi_type == SFS_TYPE_DIR); - size = sv->sv_i.sfi_size; - if (size % sizeof(struct sfs_direntry) != 0) { - panic("sfs: %s: directory %u: Invalid size %llu\n", - sfs->sfs_sb.sb_volname, sv->sv_ino, size); - } + size = sv->sv_i.sfi_size; + if (size % sizeof(struct sfs_direntry) != 0) { + panic("sfs: %s: directory %u: Invalid size %llu\n", sfs->sfs_sb.sb_volname, + sv->sv_ino, size); + } - return size / sizeof(struct sfs_direntry); + return size / sizeof(struct sfs_direntry); } /* @@ -100,140 +93,130 @@ sfs_dir_nentries(struct sfs_vnode *sv) * return its inode number, its slot, and/or the slot number of an * empty directory slot if one is found. */ -int -sfs_dir_findname(struct sfs_vnode *sv, const char *name, - uint32_t *ino, int *slot, int *emptyslot) -{ - struct sfs_direntry tsd; - int found, nentries, i, result; +int sfs_dir_findname(struct sfs_vnode *sv, const char *name, uint32_t *ino, + int *slot, int *emptyslot) { + struct sfs_direntry tsd; + int found, nentries, i, result; - nentries = sfs_dir_nentries(sv); + nentries = sfs_dir_nentries(sv); - /* For each slot... */ - found = 0; - for (i=0; i sizeof(sd.sfd_name)) { - return ENAMETOOLONG; - } + if (strlen(name) + 1 > sizeof(sd.sfd_name)) { + return ENAMETOOLONG; + } - /* If we didn't get an empty slot, add the entry at the end. */ - if (emptyslot < 0) { - emptyslot = sfs_dir_nentries(sv); - } + /* If we didn't get an empty slot, add the entry at the end. */ + if (emptyslot < 0) { + emptyslot = sfs_dir_nentries(sv); + } - /* Set up the entry. */ - bzero(&sd, sizeof(sd)); - sd.sfd_ino = ino; - strcpy(sd.sfd_name, name); + /* Set up the entry. */ + bzero(&sd, sizeof(sd)); + sd.sfd_ino = ino; + strcpy(sd.sfd_name, name); - /* Hand back the slot, if so requested. */ - if (slot) { - *slot = emptyslot; - } + /* Hand back the slot, if so requested. */ + if (slot) { + *slot = emptyslot; + } - /* Write the entry. */ - return sfs_writedir(sv, emptyslot, &sd); + /* Write the entry. */ + return sfs_writedir(sv, emptyslot, &sd); } /* * Unlink a name in a directory, by slot number. */ -int -sfs_dir_unlink(struct sfs_vnode *sv, int slot) -{ - struct sfs_direntry sd; +int sfs_dir_unlink(struct sfs_vnode *sv, int slot) { + struct sfs_direntry sd; - /* Initialize a suitable directory entry... */ - bzero(&sd, sizeof(sd)); - sd.sfd_ino = SFS_NOINO; + /* Initialize a suitable directory entry... */ + bzero(&sd, sizeof(sd)); + sd.sfd_ino = SFS_NOINO; - /* ... and write it */ - return sfs_writedir(sv, slot, &sd); + /* ... and write it */ + return sfs_writedir(sv, slot, &sd); } /* * Look for a name in a directory and hand back a vnode for the * file, if there is one. */ -int -sfs_lookonce(struct sfs_vnode *sv, const char *name, - struct sfs_vnode **ret, - int *slot) -{ - struct sfs_fs *sfs = sv->sv_absvn.vn_fs->fs_data; - uint32_t ino; - int result; +int sfs_lookonce(struct sfs_vnode *sv, const char *name, struct sfs_vnode **ret, + int *slot) { + struct sfs_fs *sfs = sv->sv_absvn.vn_fs->fs_data; + uint32_t ino; + int result; - result = sfs_dir_findname(sv, name, &ino, slot, NULL); - if (result) { - return result; - } + result = sfs_dir_findname(sv, name, &ino, slot, NULL); + if (result) { + return result; + } - result = sfs_loadvnode(sfs, ino, SFS_TYPE_INVAL, ret); - if (result) { - return result; - } + result = sfs_loadvnode(sfs, ino, SFS_TYPE_INVAL, ret); + if (result) { + return result; + } - if ((*ret)->sv_i.sfi_linkcount == 0) { - panic("sfs: %s: name %s (inode %u) in dir %u has " - "linkcount 0\n", sfs->sfs_sb.sb_volname, - name, (*ret)->sv_ino, sv->sv_ino); - } + if ((*ret)->sv_i.sfi_linkcount == 0) { + panic("sfs: %s: name %s (inode %u) in dir %u has " + "linkcount 0\n", + sfs->sfs_sb.sb_volname, name, (*ret)->sv_ino, sv->sv_ino); + } - return 0; + return 0; } - diff --git a/kern/fs/sfs/sfs_fsops.c b/kern/fs/sfs/sfs_fsops.c index fef9927..430ae96 100644 --- a/kern/fs/sfs/sfs_fsops.c +++ b/kern/fs/sfs/sfs_fsops.c @@ -44,11 +44,10 @@ #include #include "sfsprivate.h" - /* Shortcuts for the size macros in kern/sfs.h */ -#define SFS_FS_NBLOCKS(sfs) ((sfs)->sfs_sb.sb_nblocks) -#define SFS_FS_FREEMAPBITS(sfs) SFS_FREEMAPBITS(SFS_FS_NBLOCKS(sfs)) -#define SFS_FS_FREEMAPBLOCKS(sfs) SFS_FREEMAPBLOCKS(SFS_FS_NBLOCKS(sfs)) +#define SFS_FS_NBLOCKS(sfs) ((sfs)->sfs_sb.sb_nblocks) +#define SFS_FS_FREEMAPBITS(sfs) SFS_FREEMAPBITS(SFS_FS_NBLOCKS(sfs)) +#define SFS_FS_FREEMAPBLOCKS(sfs) SFS_FREEMAPBLOCKS(SFS_FS_NBLOCKS(sfs)) /* * Routine for doing I/O (reads or writes) on the free block bitmap. @@ -67,170 +66,152 @@ * The sectors used by the superblock and the bitmap itself are * likewise marked in use by mksfs. */ -static -int -sfs_freemapio(struct sfs_fs *sfs, enum uio_rw rw) -{ - uint32_t j, freemapblocks; - char *freemapdata; - int result; +static int sfs_freemapio(struct sfs_fs *sfs, enum uio_rw rw) { + uint32_t j, freemapblocks; + char *freemapdata; + int result; - /* Number of blocks in the free block bitmap. */ - freemapblocks = SFS_FS_FREEMAPBLOCKS(sfs); + /* Number of blocks in the free block bitmap. */ + freemapblocks = SFS_FS_FREEMAPBLOCKS(sfs); - /* Pointer to our freemap data in memory. */ - freemapdata = bitmap_getdata(sfs->sfs_freemap); + /* Pointer to our freemap data in memory. */ + freemapdata = bitmap_getdata(sfs->sfs_freemap); - /* For each block in the free block bitmap... */ - for (j=0; jsfs_vnodes); - for (i=0; isfs_vnodes, i); - VOP_FSYNC(v); - } - return 0; + /* Go over the array of loaded vnodes, syncing as we go. */ + num = vnodearray_num(sfs->sfs_vnodes); + for (i = 0; i < num; i++) { + struct vnode *v = vnodearray_get(sfs->sfs_vnodes, i); + VOP_FSYNC(v); + } + return 0; } /* * Sync routine for the freemap. */ -static -int -sfs_sync_freemap(struct sfs_fs *sfs) -{ - int result; +static int sfs_sync_freemap(struct sfs_fs *sfs) { + int result; - if (sfs->sfs_freemapdirty) { - result = sfs_freemapio(sfs, UIO_WRITE); - if (result) { - return result; - } - sfs->sfs_freemapdirty = false; - } + if (sfs->sfs_freemapdirty) { + result = sfs_freemapio(sfs, UIO_WRITE); + if (result) { + return result; + } + sfs->sfs_freemapdirty = false; + } - return 0; + return 0; } /* * Sync routine for the superblock. */ -static -int -sfs_sync_superblock(struct sfs_fs *sfs) -{ - int result; +static int sfs_sync_superblock(struct sfs_fs *sfs) { + int result; - if (sfs->sfs_superdirty) { - result = sfs_writeblock(sfs, SFS_SUPER_BLOCK, &sfs->sfs_sb, - sizeof(sfs->sfs_sb)); - if (result) { - return result; - } - sfs->sfs_superdirty = false; - } - return 0; + if (sfs->sfs_superdirty) { + result = + sfs_writeblock(sfs, SFS_SUPER_BLOCK, &sfs->sfs_sb, sizeof(sfs->sfs_sb)); + if (result) { + return result; + } + sfs->sfs_superdirty = false; + } + return 0; } /* * Sync routine. This is what gets invoked if you do FS_SYNC on the * sfs filesystem structure. */ -static -int -sfs_sync(struct fs *fs) -{ - struct sfs_fs *sfs; - int result; +static int sfs_sync(struct fs *fs) { + struct sfs_fs *sfs; + int result; - vfs_biglock_acquire(); + vfs_biglock_acquire(); - /* - * Get the sfs_fs from the generic abstract fs. - * - * Note that the abstract struct fs, which is all the VFS - * layer knows about, is actually a member of struct sfs_fs. - * The pointer in the struct fs points back to the top of the - * struct sfs_fs - essentially the same object. This can be a - * little confusing at first. - * - * The following diagram may help: - * - * struct sfs_fs <-------------\ - * : | - * : sfs_absfs (struct fs) | <------\ - * : : | | - * : : various members | | - * : : | | - * : : fs_data ----------/ | - * : : ...|... - * : . VFS . - * : . layer . - * : other members ....... - * : - * : - * - * This construct is repeated with vnodes and devices and other - * similar things all over the place in OS/161, so taking the - * time to straighten it out in your mind is worthwhile. - */ + /* + * Get the sfs_fs from the generic abstract fs. + * + * Note that the abstract struct fs, which is all the VFS + * layer knows about, is actually a member of struct sfs_fs. + * The pointer in the struct fs points back to the top of the + * struct sfs_fs - essentially the same object. This can be a + * little confusing at first. + * + * The following diagram may help: + * + * struct sfs_fs <-------------\ + * : | + * : sfs_absfs (struct fs) | <------\ + * : : | | + * : : various members | | + * : : | | + * : : fs_data ----------/ | + * : : ...|... + * : . VFS . + * : . layer . + * : other members ....... + * : + * : + * + * This construct is repeated with vnodes and devices and other + * similar things all over the place in OS/161, so taking the + * time to straighten it out in your mind is worthwhile. + */ - sfs = fs->fs_data; + sfs = fs->fs_data; - /* If any vnodes need to be written, write them. */ - result = sfs_sync_vnodes(sfs); - if (result) { - vfs_biglock_release(); - return result; - } + /* If any vnodes need to be written, write them. */ + result = sfs_sync_vnodes(sfs); + if (result) { + vfs_biglock_release(); + return result; + } - /* If the free block map needs to be written, write it. */ - result = sfs_sync_freemap(sfs); - if (result) { - vfs_biglock_release(); - return result; - } + /* If the free block map needs to be written, write it. */ + result = sfs_sync_freemap(sfs); + if (result) { + vfs_biglock_release(); + return result; + } - /* If the superblock needs to be written, write it. */ - result = sfs_sync_superblock(sfs); - if (result) { - vfs_biglock_release(); - return result; - } + /* If the superblock needs to be written, write it. */ + result = sfs_sync_superblock(sfs); + if (result) { + vfs_biglock_release(); + return result; + } - vfs_biglock_release(); - return 0; + vfs_biglock_release(); + return 0; } /* @@ -238,33 +219,27 @@ sfs_sync(struct fs *fs) * to by their volume name followed by a colon as well as the name * of the device they're mounted on. */ -static -const char * -sfs_getvolname(struct fs *fs) -{ - struct sfs_fs *sfs = fs->fs_data; - const char *ret; +static const char *sfs_getvolname(struct fs *fs) { + struct sfs_fs *sfs = fs->fs_data; + const char *ret; - vfs_biglock_acquire(); - ret = sfs->sfs_sb.sb_volname; - vfs_biglock_release(); + vfs_biglock_acquire(); + ret = sfs->sfs_sb.sb_volname; + vfs_biglock_release(); - return ret; + return ret; } /* * Destructor for struct sfs_fs. */ -static -void -sfs_fs_destroy(struct sfs_fs *sfs) -{ - if (sfs->sfs_freemap != NULL) { - bitmap_destroy(sfs->sfs_freemap); - } - vnodearray_destroy(sfs->sfs_vnodes); - KASSERT(sfs->sfs_device == NULL); - kfree(sfs); +static void sfs_fs_destroy(struct sfs_fs *sfs) { + if (sfs->sfs_freemap != NULL) { + bitmap_destroy(sfs->sfs_freemap); + } + vnodearray_destroy(sfs->sfs_vnodes); + KASSERT(sfs->sfs_device == NULL); + kfree(sfs); } /* @@ -272,43 +247,40 @@ sfs_fs_destroy(struct sfs_fs *sfs) * * VFS calls FS_SYNC on the filesystem prior to unmounting it. */ -static -int -sfs_unmount(struct fs *fs) -{ - struct sfs_fs *sfs = fs->fs_data; +static int sfs_unmount(struct fs *fs) { + struct sfs_fs *sfs = fs->fs_data; - vfs_biglock_acquire(); + vfs_biglock_acquire(); - /* Do we have any files open? If so, can't unmount. */ - if (vnodearray_num(sfs->sfs_vnodes) > 0) { - vfs_biglock_release(); - return EBUSY; - } + /* Do we have any files open? If so, can't unmount. */ + if (vnodearray_num(sfs->sfs_vnodes) > 0) { + vfs_biglock_release(); + return EBUSY; + } - /* We should have just had sfs_sync called. */ - KASSERT(sfs->sfs_superdirty == false); - KASSERT(sfs->sfs_freemapdirty == false); + /* We should have just had sfs_sync called. */ + KASSERT(sfs->sfs_superdirty == false); + KASSERT(sfs->sfs_freemapdirty == false); - /* The vfs layer takes care of the device for us */ - sfs->sfs_device = NULL; + /* The vfs layer takes care of the device for us */ + sfs->sfs_device = NULL; - /* Destroy the fs object; once we start nuking stuff we can't fail. */ - sfs_fs_destroy(sfs); + /* Destroy the fs object; once we start nuking stuff we can't fail. */ + sfs_fs_destroy(sfs); - /* nothing else to do */ - vfs_biglock_release(); - return 0; + /* nothing else to do */ + vfs_biglock_release(); + return 0; } /* * File system operations table. */ static const struct fs_ops sfs_fsops = { - .fsop_sync = sfs_sync, - .fsop_getvolname = sfs_getvolname, - .fsop_getroot = sfs_getroot, - .fsop_unmount = sfs_unmount, + .fsop_sync = sfs_sync, + .fsop_getvolname = sfs_getvolname, + .fsop_getroot = sfs_getroot, + .fsop_unmount = sfs_unmount, }; /* @@ -316,56 +288,53 @@ static const struct fs_ops sfs_fsops = { * but skips stuff that requires reading the volume, like allocating * the freemap. */ -static -struct sfs_fs * -sfs_fs_create(void) -{ - struct sfs_fs *sfs; +static struct sfs_fs *sfs_fs_create(void) { + struct sfs_fs *sfs; - /* - * Make sure our on-disk structures aren't messed up - */ - COMPILE_ASSERT(sizeof(struct sfs_superblock)==SFS_BLOCKSIZE); - COMPILE_ASSERT(sizeof(struct sfs_dinode)==SFS_BLOCKSIZE); - COMPILE_ASSERT(SFS_BLOCKSIZE % sizeof(struct sfs_direntry) == 0); + /* + * Make sure our on-disk structures aren't messed up + */ + COMPILE_ASSERT(sizeof(struct sfs_superblock) == SFS_BLOCKSIZE); + COMPILE_ASSERT(sizeof(struct sfs_dinode) == SFS_BLOCKSIZE); + COMPILE_ASSERT(SFS_BLOCKSIZE % sizeof(struct sfs_direntry) == 0); - /* Allocate object */ - sfs = kmalloc(sizeof(struct sfs_fs)); - if (sfs==NULL) { - goto fail; - } + /* Allocate object */ + sfs = kmalloc(sizeof(struct sfs_fs)); + if (sfs == NULL) { + goto fail; + } - /* - * Fill in fields - */ + /* + * Fill in fields + */ - /* abstract vfs-level fs */ - sfs->sfs_absfs.fs_data = sfs; - sfs->sfs_absfs.fs_ops = &sfs_fsops; + /* abstract vfs-level fs */ + sfs->sfs_absfs.fs_data = sfs; + sfs->sfs_absfs.fs_ops = &sfs_fsops; - /* superblock */ - /* (ignore sfs_super, we'll read in over it shortly) */ - sfs->sfs_superdirty = false; + /* superblock */ + /* (ignore sfs_super, we'll read in over it shortly) */ + sfs->sfs_superdirty = false; - /* device we mount on */ - sfs->sfs_device = NULL; + /* device we mount on */ + sfs->sfs_device = NULL; - /* vnode table */ - sfs->sfs_vnodes = vnodearray_create(); - if (sfs->sfs_vnodes == NULL) { - goto cleanup_object; - } + /* vnode table */ + sfs->sfs_vnodes = vnodearray_create(); + if (sfs->sfs_vnodes == NULL) { + goto cleanup_object; + } - /* freemap */ - sfs->sfs_freemap = NULL; - sfs->sfs_freemapdirty = false; + /* freemap */ + sfs->sfs_freemap = NULL; + sfs->sfs_freemapdirty = false; - return sfs; + return sfs; cleanup_object: - kfree(sfs); + kfree(sfs); fail: - return NULL; + return NULL; } /* @@ -381,101 +350,95 @@ fail: * filesystems with the same name mounted at once, or two filesystems * mounted on the same device at once. */ -static -int -sfs_domount(void *options, struct device *dev, struct fs **ret) -{ - int result; - struct sfs_fs *sfs; +static int sfs_domount(void *options, struct device *dev, struct fs **ret) { + int result; + struct sfs_fs *sfs; - vfs_biglock_acquire(); + vfs_biglock_acquire(); - /* We don't pass any options through mount */ - (void)options; + /* We don't pass any options through mount */ + (void)options; - /* - * We can't mount on devices with the wrong sector size. - * - * (Note: for all intents and purposes here, "sector" and - * "block" are interchangeable terms. Technically a filesystem - * block may be composed of several hardware sectors, but we - * don't do that in sfs.) - */ - if (dev->d_blocksize != SFS_BLOCKSIZE) { - vfs_biglock_release(); - kprintf("sfs: Cannot mount on device with blocksize %zu\n", - dev->d_blocksize); - return ENXIO; - } + /* + * We can't mount on devices with the wrong sector size. + * + * (Note: for all intents and purposes here, "sector" and + * "block" are interchangeable terms. Technically a filesystem + * block may be composed of several hardware sectors, but we + * don't do that in sfs.) + */ + if (dev->d_blocksize != SFS_BLOCKSIZE) { + vfs_biglock_release(); + kprintf("sfs: Cannot mount on device with blocksize %zu\n", + dev->d_blocksize); + return ENXIO; + } - sfs = sfs_fs_create(); - if (sfs == NULL) { - vfs_biglock_release(); - return ENOMEM; - } + sfs = sfs_fs_create(); + if (sfs == NULL) { + vfs_biglock_release(); + return ENOMEM; + } - /* Set the device so we can use sfs_readblock() */ - sfs->sfs_device = dev; + /* Set the device so we can use sfs_readblock() */ + sfs->sfs_device = dev; - /* Load superblock */ - result = sfs_readblock(sfs, SFS_SUPER_BLOCK, &sfs->sfs_sb, - sizeof(sfs->sfs_sb)); - if (result) { - sfs->sfs_device = NULL; - sfs_fs_destroy(sfs); - vfs_biglock_release(); - return result; - } + /* Load superblock */ + result = + sfs_readblock(sfs, SFS_SUPER_BLOCK, &sfs->sfs_sb, sizeof(sfs->sfs_sb)); + if (result) { + sfs->sfs_device = NULL; + sfs_fs_destroy(sfs); + vfs_biglock_release(); + return result; + } - /* Make some simple sanity checks */ + /* Make some simple sanity checks */ - if (sfs->sfs_sb.sb_magic != SFS_MAGIC) { - kprintf("sfs: Wrong magic number in superblock " - "(0x%x, should be 0x%x)\n", - sfs->sfs_sb.sb_magic, - SFS_MAGIC); - sfs->sfs_device = NULL; - sfs_fs_destroy(sfs); - vfs_biglock_release(); - return EINVAL; - } + if (sfs->sfs_sb.sb_magic != SFS_MAGIC) { + kprintf("sfs: Wrong magic number in superblock " + "(0x%x, should be 0x%x)\n", + sfs->sfs_sb.sb_magic, SFS_MAGIC); + sfs->sfs_device = NULL; + sfs_fs_destroy(sfs); + vfs_biglock_release(); + return EINVAL; + } - if (sfs->sfs_sb.sb_nblocks > dev->d_blocks) { - kprintf("sfs: warning - fs has %u blocks, device has %u\n", - sfs->sfs_sb.sb_nblocks, dev->d_blocks); - } + if (sfs->sfs_sb.sb_nblocks > dev->d_blocks) { + kprintf("sfs: warning - fs has %u blocks, device has %u\n", + sfs->sfs_sb.sb_nblocks, dev->d_blocks); + } - /* Ensure null termination of the volume name */ - sfs->sfs_sb.sb_volname[sizeof(sfs->sfs_sb.sb_volname)-1] = 0; + /* Ensure null termination of the volume name */ + sfs->sfs_sb.sb_volname[sizeof(sfs->sfs_sb.sb_volname) - 1] = 0; - /* Load free block bitmap */ - sfs->sfs_freemap = bitmap_create(SFS_FS_FREEMAPBITS(sfs)); - if (sfs->sfs_freemap == NULL) { - sfs->sfs_device = NULL; - sfs_fs_destroy(sfs); - vfs_biglock_release(); - return ENOMEM; - } - result = sfs_freemapio(sfs, UIO_READ); - if (result) { - sfs->sfs_device = NULL; - sfs_fs_destroy(sfs); - vfs_biglock_release(); - return result; - } + /* Load free block bitmap */ + sfs->sfs_freemap = bitmap_create(SFS_FS_FREEMAPBITS(sfs)); + if (sfs->sfs_freemap == NULL) { + sfs->sfs_device = NULL; + sfs_fs_destroy(sfs); + vfs_biglock_release(); + return ENOMEM; + } + result = sfs_freemapio(sfs, UIO_READ); + if (result) { + sfs->sfs_device = NULL; + sfs_fs_destroy(sfs); + vfs_biglock_release(); + return result; + } - /* Hand back the abstract fs */ - *ret = &sfs->sfs_absfs; + /* Hand back the abstract fs */ + *ret = &sfs->sfs_absfs; - vfs_biglock_release(); - return 0; + vfs_biglock_release(); + return 0; } /* * Actual function called from high-level code to mount an sfs. */ -int -sfs_mount(const char *device) -{ - return vfs_mount(device, NULL, sfs_domount); +int sfs_mount(const char *device) { + return vfs_mount(device, NULL, sfs_domount); } diff --git a/kern/fs/sfs/sfs_inode.c b/kern/fs/sfs/sfs_inode.c index 1649736..246949b 100644 --- a/kern/fs/sfs/sfs_inode.c +++ b/kern/fs/sfs/sfs_inode.c @@ -39,25 +39,21 @@ #include #include "sfsprivate.h" - /* * Write an on-disk inode structure back out to disk. */ -int -sfs_sync_inode(struct sfs_vnode *sv) -{ - struct sfs_fs *sfs = sv->sv_absvn.vn_fs->fs_data; - int result; +int sfs_sync_inode(struct sfs_vnode *sv) { + struct sfs_fs *sfs = sv->sv_absvn.vn_fs->fs_data; + int result; - if (sv->sv_dirty) { - result = sfs_writeblock(sfs, sv->sv_ino, &sv->sv_i, - sizeof(sv->sv_i)); - if (result) { - return result; - } - sv->sv_dirty = false; - } - return 0; + if (sv->sv_dirty) { + result = sfs_writeblock(sfs, sv->sv_ino, &sv->sv_i, sizeof(sv->sv_i)); + if (result) { + return result; + } + sv->sv_dirty = false; + } + return 0; } /* @@ -65,256 +61,249 @@ sfs_sync_inode(struct sfs_vnode *sv) * * This function should try to avoid returning errors other than EBUSY. */ -int -sfs_reclaim(struct vnode *v) -{ - struct sfs_vnode *sv = v->vn_data; - struct sfs_fs *sfs = v->vn_fs->fs_data; - unsigned ix, i, num; - int result; +int sfs_reclaim(struct vnode *v) { + struct sfs_vnode *sv = v->vn_data; + struct sfs_fs *sfs = v->vn_fs->fs_data; + unsigned ix, i, num; + int result; - vfs_biglock_acquire(); + vfs_biglock_acquire(); - /* - * Make sure someone else hasn't picked up the vnode since the - * decision was made to reclaim it. (You must also synchronize - * this with sfs_loadvnode.) - */ - spinlock_acquire(&v->vn_countlock); - if (v->vn_refcount != 1) { + /* + * Make sure someone else hasn't picked up the vnode since the + * decision was made to reclaim it. (You must also synchronize + * this with sfs_loadvnode.) + */ + spinlock_acquire(&v->vn_countlock); + if (v->vn_refcount != 1) { - /* consume the reference VOP_DECREF gave us */ - KASSERT(v->vn_refcount>1); - v->vn_refcount--; + /* consume the reference VOP_DECREF gave us */ + KASSERT(v->vn_refcount > 1); + v->vn_refcount--; - spinlock_release(&v->vn_countlock); - vfs_biglock_release(); - return EBUSY; - } - spinlock_release(&v->vn_countlock); + spinlock_release(&v->vn_countlock); + vfs_biglock_release(); + return EBUSY; + } + spinlock_release(&v->vn_countlock); - /* If there are no on-disk references to the file either, erase it. */ - if (sv->sv_i.sfi_linkcount == 0) { - result = sfs_itrunc(sv, 0); - if (result) { - vfs_biglock_release(); - return result; - } - } + /* If there are no on-disk references to the file either, erase it. */ + if (sv->sv_i.sfi_linkcount == 0) { + result = sfs_itrunc(sv, 0); + if (result) { + vfs_biglock_release(); + return result; + } + } - /* Sync the inode to disk */ - result = sfs_sync_inode(sv); - if (result) { - vfs_biglock_release(); - return result; - } + /* Sync the inode to disk */ + result = sfs_sync_inode(sv); + if (result) { + vfs_biglock_release(); + return result; + } - /* If there are no on-disk references, discard the inode */ - if (sv->sv_i.sfi_linkcount==0) { - sfs_bfree(sfs, sv->sv_ino); - } + /* If there are no on-disk references, discard the inode */ + if (sv->sv_i.sfi_linkcount == 0) { + sfs_bfree(sfs, sv->sv_ino); + } - /* Remove the vnode structure from the table in the struct sfs_fs. */ - num = vnodearray_num(sfs->sfs_vnodes); - ix = num; - for (i=0; isfs_vnodes, i); - struct sfs_vnode *sv2 = v2->vn_data; - if (sv2 == sv) { - ix = i; - break; - } - } - if (ix == num) { - panic("sfs: %s: reclaim vnode %u not in vnode pool\n", - sfs->sfs_sb.sb_volname, sv->sv_ino); - } - vnodearray_remove(sfs->sfs_vnodes, ix); + /* Remove the vnode structure from the table in the struct sfs_fs. */ + num = vnodearray_num(sfs->sfs_vnodes); + ix = num; + for (i = 0; i < num; i++) { + struct vnode *v2 = vnodearray_get(sfs->sfs_vnodes, i); + struct sfs_vnode *sv2 = v2->vn_data; + if (sv2 == sv) { + ix = i; + break; + } + } + if (ix == num) { + panic("sfs: %s: reclaim vnode %u not in vnode pool\n", + sfs->sfs_sb.sb_volname, sv->sv_ino); + } + vnodearray_remove(sfs->sfs_vnodes, ix); - vnode_cleanup(&sv->sv_absvn); + vnode_cleanup(&sv->sv_absvn); - vfs_biglock_release(); + vfs_biglock_release(); - /* Release the storage for the vnode structure itself. */ - kfree(sv); + /* Release the storage for the vnode structure itself. */ + kfree(sv); - /* Done */ - return 0; + /* Done */ + return 0; } /* * Function to load a inode into memory as a vnode, or dig up one * that's already resident. */ -int -sfs_loadvnode(struct sfs_fs *sfs, uint32_t ino, int forcetype, - struct sfs_vnode **ret) -{ - struct vnode *v; - struct sfs_vnode *sv; - const struct vnode_ops *ops; - unsigned i, num; - int result; +int sfs_loadvnode(struct sfs_fs *sfs, uint32_t ino, int forcetype, + struct sfs_vnode **ret) { + struct vnode *v; + struct sfs_vnode *sv; + const struct vnode_ops *ops; + unsigned i, num; + int result; - /* Look in the vnodes table */ - num = vnodearray_num(sfs->sfs_vnodes); + /* Look in the vnodes table */ + num = vnodearray_num(sfs->sfs_vnodes); - /* Linear search. Is this too slow? You decide. */ - for (i=0; isfs_vnodes, i); - sv = v->vn_data; + /* Linear search. Is this too slow? You decide. */ + for (i = 0; i < num; i++) { + v = vnodearray_get(sfs->sfs_vnodes, i); + sv = v->vn_data; - /* Every inode in memory must be in an allocated block */ - if (!sfs_bused(sfs, sv->sv_ino)) { - panic("sfs: %s: Found inode %u in unallocated block\n", - sfs->sfs_sb.sb_volname, sv->sv_ino); - } + /* Every inode in memory must be in an allocated block */ + if (!sfs_bused(sfs, sv->sv_ino)) { + panic("sfs: %s: Found inode %u in unallocated block\n", + sfs->sfs_sb.sb_volname, sv->sv_ino); + } - if (sv->sv_ino==ino) { - /* Found */ + if (sv->sv_ino == ino) { + /* Found */ - /* forcetype is only allowed when creating objects */ - KASSERT(forcetype==SFS_TYPE_INVAL); + /* forcetype is only allowed when creating objects */ + KASSERT(forcetype == SFS_TYPE_INVAL); - VOP_INCREF(&sv->sv_absvn); - *ret = sv; - return 0; - } - } + VOP_INCREF(&sv->sv_absvn); + *ret = sv; + return 0; + } + } - /* Didn't have it loaded; load it */ + /* Didn't have it loaded; load it */ - sv = kmalloc(sizeof(struct sfs_vnode)); - if (sv==NULL) { - return ENOMEM; - } + sv = kmalloc(sizeof(struct sfs_vnode)); + if (sv == NULL) { + return ENOMEM; + } - /* Must be in an allocated block */ - if (!sfs_bused(sfs, ino)) { - panic("sfs: %s: Tried to load inode %u from " - "unallocated block\n", sfs->sfs_sb.sb_volname, ino); - } + /* Must be in an allocated block */ + if (!sfs_bused(sfs, ino)) { + panic("sfs: %s: Tried to load inode %u from " + "unallocated block\n", + sfs->sfs_sb.sb_volname, ino); + } - /* Read the block the inode is in */ - result = sfs_readblock(sfs, ino, &sv->sv_i, sizeof(sv->sv_i)); - if (result) { - kfree(sv); - return result; - } + /* Read the block the inode is in */ + result = sfs_readblock(sfs, ino, &sv->sv_i, sizeof(sv->sv_i)); + if (result) { + kfree(sv); + return result; + } - /* Not dirty yet */ - sv->sv_dirty = false; + /* Not dirty yet */ + sv->sv_dirty = false; - /* - * FORCETYPE is set if we're creating a new file, because the - * block on disk will have been zeroed out by sfs_balloc and - * thus the type recorded there will be SFS_TYPE_INVAL. - */ - if (forcetype != SFS_TYPE_INVAL) { - KASSERT(sv->sv_i.sfi_type == SFS_TYPE_INVAL); - sv->sv_i.sfi_type = forcetype; - sv->sv_dirty = true; - } + /* + * FORCETYPE is set if we're creating a new file, because the + * block on disk will have been zeroed out by sfs_balloc and + * thus the type recorded there will be SFS_TYPE_INVAL. + */ + if (forcetype != SFS_TYPE_INVAL) { + KASSERT(sv->sv_i.sfi_type == SFS_TYPE_INVAL); + sv->sv_i.sfi_type = forcetype; + sv->sv_dirty = true; + } - /* - * Choose the function table based on the object type. - */ - switch (sv->sv_i.sfi_type) { - case SFS_TYPE_FILE: - ops = &sfs_fileops; - break; - case SFS_TYPE_DIR: - ops = &sfs_dirops; - break; - default: - panic("sfs: %s: loadvnode: Invalid inode type " - "(inode %u, type %u)\n", sfs->sfs_sb.sb_volname, - ino, sv->sv_i.sfi_type); - } + /* + * Choose the function table based on the object type. + */ + switch (sv->sv_i.sfi_type) { + case SFS_TYPE_FILE: + ops = &sfs_fileops; + break; + case SFS_TYPE_DIR: + ops = &sfs_dirops; + break; + default: + panic("sfs: %s: loadvnode: Invalid inode type " + "(inode %u, type %u)\n", + sfs->sfs_sb.sb_volname, ino, sv->sv_i.sfi_type); + } - /* Call the common vnode initializer */ - result = vnode_init(&sv->sv_absvn, ops, &sfs->sfs_absfs, sv); - if (result) { - kfree(sv); - return result; - } + /* Call the common vnode initializer */ + result = vnode_init(&sv->sv_absvn, ops, &sfs->sfs_absfs, sv); + if (result) { + kfree(sv); + return result; + } - /* Set the other fields in our vnode structure */ - sv->sv_ino = ino; + /* Set the other fields in our vnode structure */ + sv->sv_ino = ino; - /* Add it to our table */ - result = vnodearray_add(sfs->sfs_vnodes, &sv->sv_absvn, NULL); - if (result) { - vnode_cleanup(&sv->sv_absvn); - kfree(sv); - return result; - } + /* Add it to our table */ + result = vnodearray_add(sfs->sfs_vnodes, &sv->sv_absvn, NULL); + if (result) { + vnode_cleanup(&sv->sv_absvn); + kfree(sv); + return result; + } - /* Hand it back */ - *ret = sv; - return 0; + /* Hand it back */ + *ret = sv; + return 0; } /* * Create a new filesystem object and hand back its vnode. */ -int -sfs_makeobj(struct sfs_fs *sfs, int type, struct sfs_vnode **ret) -{ - uint32_t ino; - int result; +int sfs_makeobj(struct sfs_fs *sfs, int type, struct sfs_vnode **ret) { + uint32_t ino; + int result; - /* - * First, get an inode. (Each inode is a block, and the inode - * number is the block number, so just get a block.) - */ + /* + * First, get an inode. (Each inode is a block, and the inode + * number is the block number, so just get a block.) + */ - result = sfs_balloc(sfs, &ino); - if (result) { - return result; - } + result = sfs_balloc(sfs, &ino); + if (result) { + return result; + } - /* - * Now load a vnode for it. - */ + /* + * Now load a vnode for it. + */ - result = sfs_loadvnode(sfs, ino, type, ret); - if (result) { - sfs_bfree(sfs, ino); - } - return result; + result = sfs_loadvnode(sfs, ino, type, ret); + if (result) { + sfs_bfree(sfs, ino); + } + return result; } /* * Get vnode for the root of the filesystem. * The root vnode is always found in block 1 (SFS_ROOTDIR_INO). */ -int -sfs_getroot(struct fs *fs, struct vnode **ret) -{ - struct sfs_fs *sfs = fs->fs_data; - struct sfs_vnode *sv; - int result; +int sfs_getroot(struct fs *fs, struct vnode **ret) { + struct sfs_fs *sfs = fs->fs_data; + struct sfs_vnode *sv; + int result; - vfs_biglock_acquire(); + vfs_biglock_acquire(); - result = sfs_loadvnode(sfs, SFS_ROOTDIR_INO, SFS_TYPE_INVAL, &sv); - if (result) { - kprintf("sfs: %s: getroot: Cannot load root vnode\n", - sfs->sfs_sb.sb_volname); - vfs_biglock_release(); - return result; - } + result = sfs_loadvnode(sfs, SFS_ROOTDIR_INO, SFS_TYPE_INVAL, &sv); + if (result) { + kprintf("sfs: %s: getroot: Cannot load root vnode\n", + sfs->sfs_sb.sb_volname); + vfs_biglock_release(); + return result; + } - if (sv->sv_i.sfi_type != SFS_TYPE_DIR) { - kprintf("sfs: %s: getroot: not directory (type %u)\n", - sfs->sfs_sb.sb_volname, sv->sv_i.sfi_type); - vfs_biglock_release(); - return EINVAL; - } + if (sv->sv_i.sfi_type != SFS_TYPE_DIR) { + kprintf("sfs: %s: getroot: not directory (type %u)\n", + sfs->sfs_sb.sb_volname, sv->sv_i.sfi_type); + vfs_biglock_release(); + return EINVAL; + } - vfs_biglock_release(); + vfs_biglock_release(); - *ret = &sv->sv_absvn; - return 0; + *ret = &sv->sv_absvn; + return 0; } diff --git a/kern/fs/sfs/sfs_io.c b/kern/fs/sfs/sfs_io.c index 4454d05..f38708b 100644 --- a/kern/fs/sfs/sfs_io.c +++ b/kern/fs/sfs/sfs_io.c @@ -55,80 +55,67 @@ /* * Read or write a block, retrying I/O errors. */ -static -int -sfs_rwblock(struct sfs_fs *sfs, struct uio *uio) -{ - int result; - int tries=0; +static int sfs_rwblock(struct sfs_fs *sfs, struct uio *uio) { + int result; + int tries = 0; - KASSERT(vfs_biglock_do_i_hold()); + KASSERT(vfs_biglock_do_i_hold()); - DEBUG(DB_SFS, "sfs: %s %llu\n", - uio->uio_rw == UIO_READ ? "read" : "write", - uio->uio_offset / SFS_BLOCKSIZE); + DEBUG(DB_SFS, "sfs: %s %llu\n", uio->uio_rw == UIO_READ ? "read" : "write", + uio->uio_offset / SFS_BLOCKSIZE); - retry: - result = DEVOP_IO(sfs->sfs_device, uio); - if (result == EINVAL) { - /* - * This means the sector we requested was out of range, - * or the seek address we gave wasn't sector-aligned, - * or a couple of other things that are our fault. - */ - panic("sfs: %s: DEVOP_IO returned EINVAL\n", - sfs->sfs_sb.sb_volname); - } - if (result == EIO) { - if (tries == 0) { - tries++; - kprintf("sfs: %s: block %llu I/O error, retrying\n", - sfs->sfs_sb.sb_volname, - uio->uio_offset / SFS_BLOCKSIZE); - goto retry; - } - else if (tries < 10) { - tries++; - goto retry; - } - else { - kprintf("sfs: %s: block %llu I/O error, giving up " - "after %d retries\n", - sfs->sfs_sb.sb_volname, - uio->uio_offset / SFS_BLOCKSIZE, tries); - } - } - return result; +retry: + result = DEVOP_IO(sfs->sfs_device, uio); + if (result == EINVAL) { + /* + * This means the sector we requested was out of range, + * or the seek address we gave wasn't sector-aligned, + * or a couple of other things that are our fault. + */ + panic("sfs: %s: DEVOP_IO returned EINVAL\n", sfs->sfs_sb.sb_volname); + } + if (result == EIO) { + if (tries == 0) { + tries++; + kprintf("sfs: %s: block %llu I/O error, retrying\n", + sfs->sfs_sb.sb_volname, uio->uio_offset / SFS_BLOCKSIZE); + goto retry; + } else if (tries < 10) { + tries++; + goto retry; + } else { + kprintf("sfs: %s: block %llu I/O error, giving up " + "after %d retries\n", + sfs->sfs_sb.sb_volname, uio->uio_offset / SFS_BLOCKSIZE, tries); + } + } + return result; } /* * Read a block. */ -int -sfs_readblock(struct sfs_fs *sfs, daddr_t block, void *data, size_t len) -{ - struct iovec iov; - struct uio ku; +int sfs_readblock(struct sfs_fs *sfs, daddr_t block, void *data, size_t len) { + struct iovec iov; + struct uio ku; - KASSERT(len == SFS_BLOCKSIZE); + KASSERT(len == SFS_BLOCKSIZE); - SFSUIO(&iov, &ku, data, block, UIO_READ); - return sfs_rwblock(sfs, &ku); + SFSUIO(&iov, &ku, data, block, UIO_READ); + return sfs_rwblock(sfs, &ku); } /* * Write a block. */ -int -sfs_writeblock(struct sfs_fs *sfs, daddr_t block, void *data, size_t len) -{ - struct iovec iov; - struct uio ku; +int sfs_writeblock(struct sfs_fs *sfs, daddr_t block, void *data, size_t len) { + struct iovec iov; + struct uio ku; - KASSERT(len == SFS_BLOCKSIZE); + KASSERT(len == SFS_BLOCKSIZE); - SFSUIO(&iov, &ku, data, block, UIO_WRITE); - return sfs_rwblock(sfs, &ku); + SFSUIO(&iov, &ku, data, block, UIO_WRITE); + return sfs_rwblock(sfs, &ku); } //////////////////////////////////////////////////////////// @@ -145,247 +132,237 @@ sfs_writeblock(struct sfs_fs *sfs, daddr_t block, void *data, size_t len) * the sector; LEN is the number of bytes to actually read or write. * UIO is the area to do the I/O into. */ -static -int -sfs_partialio(struct sfs_vnode *sv, struct uio *uio, - uint32_t skipstart, uint32_t len) -{ - /* - * I/O buffer for handling partial sectors. - * - * Note: in real life (and when you've done the fs assignment) - * you would get space from the disk buffer cache for this, - * not use a static area. - */ - static char iobuf[SFS_BLOCKSIZE]; +static int sfs_partialio(struct sfs_vnode *sv, struct uio *uio, + uint32_t skipstart, uint32_t len) { + /* + * I/O buffer for handling partial sectors. + * + * Note: in real life (and when you've done the fs assignment) + * you would get space from the disk buffer cache for this, + * not use a static area. + */ + static char iobuf[SFS_BLOCKSIZE]; - struct sfs_fs *sfs = sv->sv_absvn.vn_fs->fs_data; - daddr_t diskblock; - uint32_t fileblock; - int result; + struct sfs_fs *sfs = sv->sv_absvn.vn_fs->fs_data; + daddr_t diskblock; + uint32_t fileblock; + int result; - /* Allocate missing blocks if and only if we're writing */ - bool doalloc = (uio->uio_rw==UIO_WRITE); + /* Allocate missing blocks if and only if we're writing */ + bool doalloc = (uio->uio_rw == UIO_WRITE); - KASSERT(skipstart + len <= SFS_BLOCKSIZE); + KASSERT(skipstart + len <= SFS_BLOCKSIZE); - /* We're using a global static buffer; it had better be locked */ - KASSERT(vfs_biglock_do_i_hold()); + /* We're using a global static buffer; it had better be locked */ + KASSERT(vfs_biglock_do_i_hold()); - /* Compute the block offset of this block in the file */ - fileblock = uio->uio_offset / SFS_BLOCKSIZE; + /* Compute the block offset of this block in the file */ + fileblock = uio->uio_offset / SFS_BLOCKSIZE; - /* Get the disk block number */ - result = sfs_bmap(sv, fileblock, doalloc, &diskblock); - if (result) { - return result; - } + /* Get the disk block number */ + result = sfs_bmap(sv, fileblock, doalloc, &diskblock); + if (result) { + return result; + } - if (diskblock == 0) { - /* - * There was no block mapped at this point in the file. - * Zero the buffer. - */ - KASSERT(uio->uio_rw == UIO_READ); - bzero(iobuf, sizeof(iobuf)); - } - else { - /* - * Read the block. - */ - result = sfs_readblock(sfs, diskblock, iobuf, sizeof(iobuf)); - if (result) { - return result; - } - } + if (diskblock == 0) { + /* + * There was no block mapped at this point in the file. + * Zero the buffer. + */ + KASSERT(uio->uio_rw == UIO_READ); + bzero(iobuf, sizeof(iobuf)); + } else { + /* + * Read the block. + */ + result = sfs_readblock(sfs, diskblock, iobuf, sizeof(iobuf)); + if (result) { + return result; + } + } - /* - * Now perform the requested operation into/out of the buffer. - */ - result = uiomove(iobuf+skipstart, len, uio); - if (result) { - return result; - } + /* + * Now perform the requested operation into/out of the buffer. + */ + result = uiomove(iobuf + skipstart, len, uio); + if (result) { + return result; + } - /* - * If it was a write, write back the modified block. - */ - if (uio->uio_rw == UIO_WRITE) { - result = sfs_writeblock(sfs, diskblock, iobuf, sizeof(iobuf)); - if (result) { - return result; - } - } + /* + * If it was a write, write back the modified block. + */ + if (uio->uio_rw == UIO_WRITE) { + result = sfs_writeblock(sfs, diskblock, iobuf, sizeof(iobuf)); + if (result) { + return result; + } + } - return 0; + return 0; } /* * Do I/O (either read or write) of a single whole block. */ -static -int -sfs_blockio(struct sfs_vnode *sv, struct uio *uio) -{ - struct sfs_fs *sfs = sv->sv_absvn.vn_fs->fs_data; - daddr_t diskblock; - uint32_t fileblock; - int result; - bool doalloc = (uio->uio_rw==UIO_WRITE); - off_t saveoff; - off_t diskoff; - off_t saveres; - off_t diskres; +static int sfs_blockio(struct sfs_vnode *sv, struct uio *uio) { + struct sfs_fs *sfs = sv->sv_absvn.vn_fs->fs_data; + daddr_t diskblock; + uint32_t fileblock; + int result; + bool doalloc = (uio->uio_rw == UIO_WRITE); + off_t saveoff; + off_t diskoff; + off_t saveres; + off_t diskres; - /* Get the block number within the file */ - fileblock = uio->uio_offset / SFS_BLOCKSIZE; + /* Get the block number within the file */ + fileblock = uio->uio_offset / SFS_BLOCKSIZE; - /* Look up the disk block number */ - result = sfs_bmap(sv, fileblock, doalloc, &diskblock); - if (result) { - return result; - } + /* Look up the disk block number */ + result = sfs_bmap(sv, fileblock, doalloc, &diskblock); + if (result) { + return result; + } - if (diskblock == 0) { - /* - * No block - fill with zeros. - * - * We must be reading, or sfs_bmap would have - * allocated a block for us. - */ - KASSERT(uio->uio_rw == UIO_READ); - return uiomovezeros(SFS_BLOCKSIZE, uio); - } + if (diskblock == 0) { + /* + * No block - fill with zeros. + * + * We must be reading, or sfs_bmap would have + * allocated a block for us. + */ + KASSERT(uio->uio_rw == UIO_READ); + return uiomovezeros(SFS_BLOCKSIZE, uio); + } - /* - * Do the I/O directly to the uio region. Save the uio_offset, - * and substitute one that makes sense to the device. - */ - saveoff = uio->uio_offset; - diskoff = diskblock * SFS_BLOCKSIZE; - uio->uio_offset = diskoff; + /* + * Do the I/O directly to the uio region. Save the uio_offset, + * and substitute one that makes sense to the device. + */ + saveoff = uio->uio_offset; + diskoff = diskblock * SFS_BLOCKSIZE; + uio->uio_offset = diskoff; - /* - * Temporarily set the residue to be one block size. - */ - KASSERT(uio->uio_resid >= SFS_BLOCKSIZE); - saveres = uio->uio_resid; - diskres = SFS_BLOCKSIZE; - uio->uio_resid = diskres; + /* + * Temporarily set the residue to be one block size. + */ + KASSERT(uio->uio_resid >= SFS_BLOCKSIZE); + saveres = uio->uio_resid; + diskres = SFS_BLOCKSIZE; + uio->uio_resid = diskres; - result = sfs_rwblock(sfs, uio); + result = sfs_rwblock(sfs, uio); - /* - * Now, restore the original uio_offset and uio_resid and update - * them by the amount of I/O done. - */ - uio->uio_offset = (uio->uio_offset - diskoff) + saveoff; - uio->uio_resid = (uio->uio_resid - diskres) + saveres; + /* + * Now, restore the original uio_offset and uio_resid and update + * them by the amount of I/O done. + */ + uio->uio_offset = (uio->uio_offset - diskoff) + saveoff; + uio->uio_resid = (uio->uio_resid - diskres) + saveres; - return result; + return result; } /* * Do I/O of a whole region of data, whether or not it's block-aligned. */ -int -sfs_io(struct sfs_vnode *sv, struct uio *uio) -{ - uint32_t blkoff; - uint32_t nblocks, i; - int result = 0; - uint32_t origresid, extraresid = 0; +int sfs_io(struct sfs_vnode *sv, struct uio *uio) { + uint32_t blkoff; + uint32_t nblocks, i; + int result = 0; + uint32_t origresid, extraresid = 0; - origresid = uio->uio_resid; + origresid = uio->uio_resid; - /* - * If reading, check for EOF. If we can read a partial area, - * remember how much extra there was in EXTRARESID so we can - * add it back to uio_resid at the end. - */ - if (uio->uio_rw == UIO_READ) { - off_t size = sv->sv_i.sfi_size; - off_t endpos = uio->uio_offset + uio->uio_resid; + /* + * If reading, check for EOF. If we can read a partial area, + * remember how much extra there was in EXTRARESID so we can + * add it back to uio_resid at the end. + */ + if (uio->uio_rw == UIO_READ) { + off_t size = sv->sv_i.sfi_size; + off_t endpos = uio->uio_offset + uio->uio_resid; - if (uio->uio_offset >= size) { - /* At or past EOF - just return */ - return 0; - } + if (uio->uio_offset >= size) { + /* At or past EOF - just return */ + return 0; + } - if (endpos > size) { - extraresid = endpos - size; - KASSERT(uio->uio_resid > extraresid); - uio->uio_resid -= extraresid; - } - } + if (endpos > size) { + extraresid = endpos - size; + KASSERT(uio->uio_resid > extraresid); + uio->uio_resid -= extraresid; + } + } - /* - * First, do any leading partial block. - */ - blkoff = uio->uio_offset % SFS_BLOCKSIZE; - if (blkoff != 0) { - /* Number of bytes at beginning of block to skip */ - uint32_t skip = blkoff; + /* + * First, do any leading partial block. + */ + blkoff = uio->uio_offset % SFS_BLOCKSIZE; + if (blkoff != 0) { + /* Number of bytes at beginning of block to skip */ + uint32_t skip = blkoff; - /* Number of bytes to read/write after that point */ - uint32_t len = SFS_BLOCKSIZE - blkoff; + /* Number of bytes to read/write after that point */ + uint32_t len = SFS_BLOCKSIZE - blkoff; - /* ...which might be less than the rest of the block */ - if (len > uio->uio_resid) { - len = uio->uio_resid; - } + /* ...which might be less than the rest of the block */ + if (len > uio->uio_resid) { + len = uio->uio_resid; + } - /* Call sfs_partialio() to do it. */ - result = sfs_partialio(sv, uio, skip, len); - if (result) { - goto out; - } - } + /* Call sfs_partialio() to do it. */ + result = sfs_partialio(sv, uio, skip, len); + if (result) { + goto out; + } + } - /* If we're done, quit. */ - if (uio->uio_resid==0) { - goto out; - } + /* If we're done, quit. */ + if (uio->uio_resid == 0) { + goto out; + } - /* - * Now we should be block-aligned. Do the remaining whole blocks. - */ - KASSERT(uio->uio_offset % SFS_BLOCKSIZE == 0); - nblocks = uio->uio_resid / SFS_BLOCKSIZE; - for (i=0; iuio_offset % SFS_BLOCKSIZE == 0); + nblocks = uio->uio_resid / SFS_BLOCKSIZE; + for (i = 0; i < nblocks; i++) { + result = sfs_blockio(sv, uio); + if (result) { + goto out; + } + } - /* - * Now do any remaining partial block at the end. - */ - KASSERT(uio->uio_resid < SFS_BLOCKSIZE); + /* + * Now do any remaining partial block at the end. + */ + KASSERT(uio->uio_resid < SFS_BLOCKSIZE); - if (uio->uio_resid > 0) { - result = sfs_partialio(sv, uio, 0, uio->uio_resid); - if (result) { - goto out; - } - } + if (uio->uio_resid > 0) { + result = sfs_partialio(sv, uio, 0, uio->uio_resid); + if (result) { + goto out; + } + } - out: +out: - /* If writing and we did anything, adjust file length */ - if (uio->uio_resid != origresid && - uio->uio_rw == UIO_WRITE && - uio->uio_offset > (off_t)sv->sv_i.sfi_size) { - sv->sv_i.sfi_size = uio->uio_offset; - sv->sv_dirty = true; - } + /* If writing and we did anything, adjust file length */ + if (uio->uio_resid != origresid && uio->uio_rw == UIO_WRITE && + uio->uio_offset > (off_t)sv->sv_i.sfi_size) { + sv->sv_i.sfi_size = uio->uio_offset; + sv->sv_dirty = true; + } - /* Add in any extra amount we couldn't read because of EOF */ - uio->uio_resid += extraresid; + /* Add in any extra amount we couldn't read because of EOF */ + uio->uio_resid += extraresid; - /* Done */ - return result; + /* Done */ + return result; } //////////////////////////////////////////////////////////// @@ -402,79 +379,75 @@ sfs_io(struct sfs_vnode *sv, struct uio *uio) * more advanced things to handle metadata and user data I/O * differently. */ -int -sfs_metaio(struct sfs_vnode *sv, off_t actualpos, void *data, size_t len, - enum uio_rw rw) -{ - struct sfs_fs *sfs = sv->sv_absvn.vn_fs->fs_data; - off_t endpos; - uint32_t vnblock; - uint32_t blockoffset; - daddr_t diskblock; - bool doalloc; - int result; +int sfs_metaio(struct sfs_vnode *sv, off_t actualpos, void *data, size_t len, + enum uio_rw rw) { + struct sfs_fs *sfs = sv->sv_absvn.vn_fs->fs_data; + off_t endpos; + uint32_t vnblock; + uint32_t blockoffset; + daddr_t diskblock; + bool doalloc; + int result; - /* - * I/O buffer for metadata ops. - * - * Note: in real life (and when you've done the fs assignment) you - * would get space from the disk buffer cache for this, not use a - * static area. - */ - static char metaiobuf[SFS_BLOCKSIZE]; + /* + * I/O buffer for metadata ops. + * + * Note: in real life (and when you've done the fs assignment) you + * would get space from the disk buffer cache for this, not use a + * static area. + */ + static char metaiobuf[SFS_BLOCKSIZE]; - /* We're using a global static buffer; it had better be locked */ - KASSERT(vfs_biglock_do_i_hold()); + /* We're using a global static buffer; it had better be locked */ + KASSERT(vfs_biglock_do_i_hold()); - /* Figure out which block of the vnode (directory, whatever) this is */ - vnblock = actualpos / SFS_BLOCKSIZE; - blockoffset = actualpos % SFS_BLOCKSIZE; + /* Figure out which block of the vnode (directory, whatever) this is */ + vnblock = actualpos / SFS_BLOCKSIZE; + blockoffset = actualpos % SFS_BLOCKSIZE; - /* Get the disk block number */ - doalloc = (rw == UIO_WRITE); - result = sfs_bmap(sv, vnblock, doalloc, &diskblock); - if (result) { - return result; - } + /* Get the disk block number */ + doalloc = (rw == UIO_WRITE); + result = sfs_bmap(sv, vnblock, doalloc, &diskblock); + if (result) { + return result; + } - if (diskblock == 0) { - /* Should only get block 0 back if doalloc is false */ - KASSERT(rw == UIO_READ); + if (diskblock == 0) { + /* Should only get block 0 back if doalloc is false */ + KASSERT(rw == UIO_READ); - /* Sparse file, read as zeros. */ - bzero(data, len); - return 0; - } + /* Sparse file, read as zeros. */ + bzero(data, len); + return 0; + } - /* Read the block */ - result = sfs_readblock(sfs, diskblock, metaiobuf, sizeof(metaiobuf)); - if (result) { - return result; - } + /* Read the block */ + result = sfs_readblock(sfs, diskblock, metaiobuf, sizeof(metaiobuf)); + if (result) { + return result; + } - if (rw == UIO_READ) { - /* Copy out the selected region */ - memcpy(data, metaiobuf + blockoffset, len); - } - else { - /* Update the selected region */ - memcpy(metaiobuf + blockoffset, data, len); + if (rw == UIO_READ) { + /* Copy out the selected region */ + memcpy(data, metaiobuf + blockoffset, len); + } else { + /* Update the selected region */ + memcpy(metaiobuf + blockoffset, data, len); - /* Write the block back */ - result = sfs_writeblock(sfs, diskblock, - metaiobuf, sizeof(metaiobuf)); - if (result) { - return result; - } + /* Write the block back */ + result = sfs_writeblock(sfs, diskblock, metaiobuf, sizeof(metaiobuf)); + if (result) { + return result; + } - /* Update the vnode size if needed */ - endpos = actualpos + len; - if (endpos > (off_t)sv->sv_i.sfi_size) { - sv->sv_i.sfi_size = endpos; - sv->sv_dirty = true; - } - } + /* Update the vnode size if needed */ + endpos = actualpos + len; + if (endpos > (off_t)sv->sv_i.sfi_size) { + sv->sv_i.sfi_size = endpos; + sv->sv_dirty = true; + } + } - /* Done */ - return 0; + /* Done */ + return 0; } diff --git a/kern/fs/sfs/sfs_vnops.c b/kern/fs/sfs/sfs_vnops.c index 7500ba7..d5f3fc4 100644 --- a/kern/fs/sfs/sfs_vnops.c +++ b/kern/fs/sfs/sfs_vnops.c @@ -48,210 +48,177 @@ /* * This is called on *each* open(). */ -static -int -sfs_eachopen(struct vnode *v, int openflags) -{ - /* - * At this level we do not need to handle O_CREAT, O_EXCL, - * O_TRUNC, or O_APPEND. - * - * Any of O_RDONLY, O_WRONLY, and O_RDWR are valid, so we don't need - * to check that either. - */ +static int sfs_eachopen(struct vnode *v, int openflags) { + /* + * At this level we do not need to handle O_CREAT, O_EXCL, + * O_TRUNC, or O_APPEND. + * + * Any of O_RDONLY, O_WRONLY, and O_RDWR are valid, so we don't need + * to check that either. + */ - (void)v; - (void)openflags; + (void)v; + (void)openflags; - return 0; + return 0; } /* * This is called on *each* open() of a directory. * Directories may only be open for read. */ -static -int -sfs_eachopendir(struct vnode *v, int openflags) -{ - switch (openflags & O_ACCMODE) { - case O_RDONLY: - break; - case O_WRONLY: - case O_RDWR: - default: - return EISDIR; - } - if (openflags & O_APPEND) { - return EISDIR; - } +static int sfs_eachopendir(struct vnode *v, int openflags) { + switch (openflags & O_ACCMODE) { + case O_RDONLY: + break; + case O_WRONLY: + case O_RDWR: + default: + return EISDIR; + } + if (openflags & O_APPEND) { + return EISDIR; + } - (void)v; - return 0; + (void)v; + return 0; } /* * Called for read(). sfs_io() does the work. */ -static -int -sfs_read(struct vnode *v, struct uio *uio) -{ - struct sfs_vnode *sv = v->vn_data; - int result; +static int sfs_read(struct vnode *v, struct uio *uio) { + struct sfs_vnode *sv = v->vn_data; + int result; - KASSERT(uio->uio_rw==UIO_READ); + KASSERT(uio->uio_rw == UIO_READ); - vfs_biglock_acquire(); - result = sfs_io(sv, uio); - vfs_biglock_release(); + vfs_biglock_acquire(); + result = sfs_io(sv, uio); + vfs_biglock_release(); - return result; + return result; } /* * Called for write(). sfs_io() does the work. */ -static -int -sfs_write(struct vnode *v, struct uio *uio) -{ - struct sfs_vnode *sv = v->vn_data; - int result; +static int sfs_write(struct vnode *v, struct uio *uio) { + struct sfs_vnode *sv = v->vn_data; + int result; - KASSERT(uio->uio_rw==UIO_WRITE); + KASSERT(uio->uio_rw == UIO_WRITE); - vfs_biglock_acquire(); - result = sfs_io(sv, uio); - vfs_biglock_release(); + vfs_biglock_acquire(); + result = sfs_io(sv, uio); + vfs_biglock_release(); - return result; + return result; } /* * Called for ioctl() */ -static -int -sfs_ioctl(struct vnode *v, int op, userptr_t data) -{ - /* - * No ioctls. - */ +static int sfs_ioctl(struct vnode *v, int op, userptr_t data) { + /* + * No ioctls. + */ - (void)v; - (void)op; - (void)data; + (void)v; + (void)op; + (void)data; - return EINVAL; + return EINVAL; } /* * Called for stat/fstat/lstat. */ -static -int -sfs_stat(struct vnode *v, struct stat *statbuf) -{ - struct sfs_vnode *sv = v->vn_data; - int result; +static int sfs_stat(struct vnode *v, struct stat *statbuf) { + struct sfs_vnode *sv = v->vn_data; + int result; - /* Fill in the stat structure */ - bzero(statbuf, sizeof(struct stat)); + /* Fill in the stat structure */ + bzero(statbuf, sizeof(struct stat)); - result = VOP_GETTYPE(v, &statbuf->st_mode); - if (result) { - return result; - } + result = VOP_GETTYPE(v, &statbuf->st_mode); + if (result) { + return result; + } - statbuf->st_size = sv->sv_i.sfi_size; - statbuf->st_nlink = sv->sv_i.sfi_linkcount; + statbuf->st_size = sv->sv_i.sfi_size; + statbuf->st_nlink = sv->sv_i.sfi_linkcount; - /* We don't support this yet */ - statbuf->st_blocks = 0; + /* We don't support this yet */ + statbuf->st_blocks = 0; - /* Fill in other fields as desired/possible... */ + /* Fill in other fields as desired/possible... */ - return 0; + return 0; } /* * Return the type of the file (types as per kern/stat.h) */ -static -int -sfs_gettype(struct vnode *v, uint32_t *ret) -{ - struct sfs_vnode *sv = v->vn_data; - struct sfs_fs *sfs = v->vn_fs->fs_data; +static int sfs_gettype(struct vnode *v, uint32_t *ret) { + struct sfs_vnode *sv = v->vn_data; + struct sfs_fs *sfs = v->vn_fs->fs_data; - vfs_biglock_acquire(); + vfs_biglock_acquire(); - switch (sv->sv_i.sfi_type) { - case SFS_TYPE_FILE: - *ret = S_IFREG; - vfs_biglock_release(); - return 0; - case SFS_TYPE_DIR: - *ret = S_IFDIR; - vfs_biglock_release(); - return 0; - } - panic("sfs: %s: gettype: Invalid inode type (inode %u, type %u)\n", - sfs->sfs_sb.sb_volname, sv->sv_ino, sv->sv_i.sfi_type); - return EINVAL; + switch (sv->sv_i.sfi_type) { + case SFS_TYPE_FILE: + *ret = S_IFREG; + vfs_biglock_release(); + return 0; + case SFS_TYPE_DIR: + *ret = S_IFDIR; + vfs_biglock_release(); + return 0; + } + panic("sfs: %s: gettype: Invalid inode type (inode %u, type %u)\n", + sfs->sfs_sb.sb_volname, sv->sv_ino, sv->sv_i.sfi_type); + return EINVAL; } /* * Check if seeking is allowed. The answer is "yes". */ -static -bool -sfs_isseekable(struct vnode *v) -{ - (void)v; - return true; +static bool sfs_isseekable(struct vnode *v) { + (void)v; + return true; } /* * Called for fsync(), and also on filesystem unmount, global sync(), * and some other cases. */ -static -int -sfs_fsync(struct vnode *v) -{ - struct sfs_vnode *sv = v->vn_data; - int result; +static int sfs_fsync(struct vnode *v) { + struct sfs_vnode *sv = v->vn_data; + int result; - vfs_biglock_acquire(); - result = sfs_sync_inode(sv); - vfs_biglock_release(); + vfs_biglock_acquire(); + result = sfs_sync_inode(sv); + vfs_biglock_release(); - return result; + return result; } /* * Called for mmap(). */ -static -int -sfs_mmap(struct vnode *v /* add stuff as needed */) -{ - (void)v; - return ENOSYS; +static int sfs_mmap(struct vnode *v /* add stuff as needed */) { + (void)v; + return ENOSYS; } /* * Truncate a file. */ -static -int -sfs_truncate(struct vnode *v, off_t len) -{ - struct sfs_vnode *sv = v->vn_data; +static int sfs_truncate(struct vnode *v, off_t len) { + struct sfs_vnode *sv = v->vn_data; - return sfs_itrunc(sv, len); + return sfs_itrunc(sv, len); } /* @@ -260,90 +227,84 @@ sfs_truncate(struct vnode *v, off_t len) * and hand back the empty string. (The VFS layer takes care of the * device name, leading slash, etc.) */ -static -int -sfs_namefile(struct vnode *vv, struct uio *uio) -{ - struct sfs_vnode *sv = vv->vn_data; - KASSERT(sv->sv_ino == SFS_ROOTDIR_INO); +static int sfs_namefile(struct vnode *vv, struct uio *uio) { + struct sfs_vnode *sv = vv->vn_data; + KASSERT(sv->sv_ino == SFS_ROOTDIR_INO); - /* send back the empty string - just return */ + /* send back the empty string - just return */ - (void)uio; + (void)uio; - return 0; + return 0; } /* * Create a file. If EXCL is set, insist that the filename not already * exist; otherwise, if it already exists, just open it. */ -static -int -sfs_creat(struct vnode *v, const char *name, bool excl, mode_t mode, - struct vnode **ret) -{ - struct sfs_fs *sfs = v->vn_fs->fs_data; - struct sfs_vnode *sv = v->vn_data; - struct sfs_vnode *newguy; - uint32_t ino; - int result; +static int sfs_creat(struct vnode *v, const char *name, bool excl, mode_t mode, + struct vnode **ret) { + struct sfs_fs *sfs = v->vn_fs->fs_data; + struct sfs_vnode *sv = v->vn_data; + struct sfs_vnode *newguy; + uint32_t ino; + int result; - vfs_biglock_acquire(); + vfs_biglock_acquire(); - /* Look up the name */ - result = sfs_dir_findname(sv, name, &ino, NULL, NULL); - if (result!=0 && result!=ENOENT) { - vfs_biglock_release(); - return result; - } + /* Look up the name */ + result = sfs_dir_findname(sv, name, &ino, NULL, NULL); + if (result != 0 && result != ENOENT) { + vfs_biglock_release(); + return result; + } - /* If it exists and we didn't want it to, fail */ - if (result==0 && excl) { - vfs_biglock_release(); - return EEXIST; - } + /* If it exists and we didn't want it to, fail */ + if (result == 0 && excl) { + vfs_biglock_release(); + return EEXIST; + } - if (result==0) { - /* We got something; load its vnode and return */ - result = sfs_loadvnode(sfs, ino, SFS_TYPE_INVAL, &newguy); - if (result) { - vfs_biglock_release(); - return result; - } - *ret = &newguy->sv_absvn; - vfs_biglock_release(); - return 0; - } + if (result == 0) { + /* We got something; load its vnode and return */ + result = sfs_loadvnode(sfs, ino, SFS_TYPE_INVAL, &newguy); + if (result) { + vfs_biglock_release(); + return result; + } + *ret = &newguy->sv_absvn; + vfs_biglock_release(); + return 0; + } - /* Didn't exist - create it */ - result = sfs_makeobj(sfs, SFS_TYPE_FILE, &newguy); - if (result) { - vfs_biglock_release(); - return result; - } + /* Didn't exist - create it */ + result = sfs_makeobj(sfs, SFS_TYPE_FILE, &newguy); + if (result) { + vfs_biglock_release(); + return result; + } - /* We don't currently support file permissions; ignore MODE */ - (void)mode; + /* We don't currently support file permissions; ignore MODE */ + (void)mode; - /* Link it into the directory */ - result = sfs_dir_link(sv, name, newguy->sv_ino, NULL); - if (result) { - VOP_DECREF(&newguy->sv_absvn); - vfs_biglock_release(); - return result; - } + /* Link it into the directory */ + result = sfs_dir_link(sv, name, newguy->sv_ino, NULL); + if (result) { + VOP_DECREF(&newguy->sv_absvn); + vfs_biglock_release(); + return result; + } - /* Update the linkcount of the new file */ - newguy->sv_i.sfi_linkcount++; + /* Update the linkcount of the new file */ + newguy->sv_i.sfi_linkcount++; - /* and consequently mark it dirty. */ - newguy->sv_dirty = true; + /* and consequently mark it dirty. */ + newguy->sv_dirty = true; - *ret = &newguy->sv_absvn; + *ret = &newguy->sv_absvn; - vfs_biglock_release(); - return 0; + vfs_biglock_release(); + return 0; } /* @@ -351,74 +312,68 @@ sfs_creat(struct vnode *v, const char *name, bool excl, mode_t mode, * The VFS layer should prevent this being called unless both * vnodes are ours. */ -static -int -sfs_link(struct vnode *dir, const char *name, struct vnode *file) -{ - struct sfs_vnode *sv = dir->vn_data; - struct sfs_vnode *f = file->vn_data; - int result; +static int sfs_link(struct vnode *dir, const char *name, struct vnode *file) { + struct sfs_vnode *sv = dir->vn_data; + struct sfs_vnode *f = file->vn_data; + int result; - KASSERT(file->vn_fs == dir->vn_fs); + KASSERT(file->vn_fs == dir->vn_fs); - vfs_biglock_acquire(); + vfs_biglock_acquire(); - /* Hard links to directories aren't allowed. */ - if (f->sv_i.sfi_type == SFS_TYPE_DIR) { - vfs_biglock_release(); - return EINVAL; - } + /* Hard links to directories aren't allowed. */ + if (f->sv_i.sfi_type == SFS_TYPE_DIR) { + vfs_biglock_release(); + return EINVAL; + } - /* Create the link */ - result = sfs_dir_link(sv, name, f->sv_ino, NULL); - if (result) { - vfs_biglock_release(); - return result; - } + /* Create the link */ + result = sfs_dir_link(sv, name, f->sv_ino, NULL); + if (result) { + vfs_biglock_release(); + return result; + } - /* and update the link count, marking the inode dirty */ - f->sv_i.sfi_linkcount++; - f->sv_dirty = true; + /* and update the link count, marking the inode dirty */ + f->sv_i.sfi_linkcount++; + f->sv_dirty = true; - vfs_biglock_release(); - return 0; + vfs_biglock_release(); + return 0; } /* * Delete a file. */ -static -int -sfs_remove(struct vnode *dir, const char *name) -{ - struct sfs_vnode *sv = dir->vn_data; - struct sfs_vnode *victim; - int slot; - int result; +static int sfs_remove(struct vnode *dir, const char *name) { + struct sfs_vnode *sv = dir->vn_data; + struct sfs_vnode *victim; + int slot; + int result; - vfs_biglock_acquire(); + vfs_biglock_acquire(); - /* Look for the file and fetch a vnode for it. */ - result = sfs_lookonce(sv, name, &victim, &slot); - if (result) { - vfs_biglock_release(); - return result; - } + /* Look for the file and fetch a vnode for it. */ + result = sfs_lookonce(sv, name, &victim, &slot); + if (result) { + vfs_biglock_release(); + return result; + } - /* Erase its directory entry. */ - result = sfs_dir_unlink(sv, slot); - if (result==0) { - /* If we succeeded, decrement the link count. */ - KASSERT(victim->sv_i.sfi_linkcount > 0); - victim->sv_i.sfi_linkcount--; - victim->sv_dirty = true; - } + /* Erase its directory entry. */ + result = sfs_dir_unlink(sv, slot); + if (result == 0) { + /* If we succeeded, decrement the link count. */ + KASSERT(victim->sv_i.sfi_linkcount > 0); + victim->sv_i.sfi_linkcount--; + victim->sv_dirty = true; + } - /* Discard the reference that sfs_lookonce got us */ - VOP_DECREF(&victim->sv_absvn); + /* Discard the reference that sfs_lookonce got us */ + VOP_DECREF(&victim->sv_absvn); - vfs_biglock_release(); - return result; + vfs_biglock_release(); + return result; } /* @@ -427,88 +382,83 @@ sfs_remove(struct vnode *dir, const char *name) * Since we don't support subdirectories, assumes that the two * directories passed are the same. */ -static -int -sfs_rename(struct vnode *d1, const char *n1, - struct vnode *d2, const char *n2) -{ - struct sfs_vnode *sv = d1->vn_data; - struct sfs_fs *sfs = sv->sv_absvn.vn_fs->fs_data; - struct sfs_vnode *g1; - int slot1, slot2; - int result, result2; +static int sfs_rename(struct vnode *d1, const char *n1, struct vnode *d2, + const char *n2) { + struct sfs_vnode *sv = d1->vn_data; + struct sfs_fs *sfs = sv->sv_absvn.vn_fs->fs_data; + struct sfs_vnode *g1; + int slot1, slot2; + int result, result2; - vfs_biglock_acquire(); + vfs_biglock_acquire(); - KASSERT(d1==d2); - KASSERT(sv->sv_ino == SFS_ROOTDIR_INO); + KASSERT(d1 == d2); + KASSERT(sv->sv_ino == SFS_ROOTDIR_INO); - /* Look up the old name of the file and get its inode and slot number*/ - result = sfs_lookonce(sv, n1, &g1, &slot1); - if (result) { - vfs_biglock_release(); - return result; - } + /* Look up the old name of the file and get its inode and slot number*/ + result = sfs_lookonce(sv, n1, &g1, &slot1); + if (result) { + vfs_biglock_release(); + return result; + } - /* We don't support subdirectories */ - KASSERT(g1->sv_i.sfi_type == SFS_TYPE_FILE); + /* We don't support subdirectories */ + KASSERT(g1->sv_i.sfi_type == SFS_TYPE_FILE); - /* - * Link it under the new name. - * - * We could theoretically just overwrite the original - * directory entry, except that we need to check to make sure - * the new name doesn't already exist; might as well use the - * existing link routine. - */ - result = sfs_dir_link(sv, n2, g1->sv_ino, &slot2); - if (result) { - goto puke; - } + /* + * Link it under the new name. + * + * We could theoretically just overwrite the original + * directory entry, except that we need to check to make sure + * the new name doesn't already exist; might as well use the + * existing link routine. + */ + result = sfs_dir_link(sv, n2, g1->sv_ino, &slot2); + if (result) { + goto puke; + } - /* Increment the link count, and mark inode dirty */ - g1->sv_i.sfi_linkcount++; - g1->sv_dirty = true; + /* Increment the link count, and mark inode dirty */ + g1->sv_i.sfi_linkcount++; + g1->sv_dirty = true; - /* Unlink the old slot */ - result = sfs_dir_unlink(sv, slot1); - if (result) { - goto puke_harder; - } + /* Unlink the old slot */ + result = sfs_dir_unlink(sv, slot1); + if (result) { + goto puke_harder; + } - /* - * Decrement the link count again, and mark the inode dirty again, - * in case it's been synced behind our back. - */ - KASSERT(g1->sv_i.sfi_linkcount>0); - g1->sv_i.sfi_linkcount--; - g1->sv_dirty = true; + /* + * Decrement the link count again, and mark the inode dirty again, + * in case it's been synced behind our back. + */ + KASSERT(g1->sv_i.sfi_linkcount > 0); + g1->sv_i.sfi_linkcount--; + g1->sv_dirty = true; - /* Let go of the reference to g1 */ - VOP_DECREF(&g1->sv_absvn); + /* Let go of the reference to g1 */ + VOP_DECREF(&g1->sv_absvn); - vfs_biglock_release(); - return 0; + vfs_biglock_release(); + return 0; - puke_harder: - /* - * Error recovery: try to undo what we already did - */ - result2 = sfs_dir_unlink(sv, slot2); - if (result2) { - kprintf("sfs: %s: rename: %s\n", - sfs->sfs_sb.sb_volname, strerror(result)); - kprintf("sfs: %s: rename: while cleaning up: %s\n", - sfs->sfs_sb.sb_volname, strerror(result2)); - panic("sfs: %s: rename: Cannot recover\n", - sfs->sfs_sb.sb_volname); - } - g1->sv_i.sfi_linkcount--; - puke: - /* Let go of the reference to g1 */ - VOP_DECREF(&g1->sv_absvn); - vfs_biglock_release(); - return result; +puke_harder: + /* + * Error recovery: try to undo what we already did + */ + result2 = sfs_dir_unlink(sv, slot2); + if (result2) { + kprintf("sfs: %s: rename: %s\n", sfs->sfs_sb.sb_volname, strerror(result)); + kprintf("sfs: %s: rename: while cleaning up: %s\n", sfs->sfs_sb.sb_volname, + strerror(result2)); + panic("sfs: %s: rename: Cannot recover\n", sfs->sfs_sb.sb_volname); + } + g1->sv_i.sfi_linkcount--; +puke: + /* Let go of the reference to g1 */ + VOP_DECREF(&g1->sv_absvn); + vfs_biglock_release(); + return result; } /* @@ -518,31 +468,28 @@ sfs_rename(struct vnode *d1, const char *n1, * Since we don't support subdirectories, this is very easy - * return the root dir and copy the path. */ -static -int -sfs_lookparent(struct vnode *v, char *path, struct vnode **ret, - char *buf, size_t buflen) -{ - struct sfs_vnode *sv = v->vn_data; +static int sfs_lookparent(struct vnode *v, char *path, struct vnode **ret, + char *buf, size_t buflen) { + struct sfs_vnode *sv = v->vn_data; - vfs_biglock_acquire(); + vfs_biglock_acquire(); - if (sv->sv_i.sfi_type != SFS_TYPE_DIR) { - vfs_biglock_release(); - return ENOTDIR; - } + if (sv->sv_i.sfi_type != SFS_TYPE_DIR) { + vfs_biglock_release(); + return ENOTDIR; + } - if (strlen(path)+1 > buflen) { - vfs_biglock_release(); - return ENAMETOOLONG; - } - strcpy(buf, path); + if (strlen(path) + 1 > buflen) { + vfs_biglock_release(); + return ENAMETOOLONG; + } + strcpy(buf, path); - VOP_INCREF(&sv->sv_absvn); - *ret = &sv->sv_absvn; + VOP_INCREF(&sv->sv_absvn); + *ret = &sv->sv_absvn; - vfs_biglock_release(); - return 0; + vfs_biglock_release(); + return 0; } /* @@ -551,31 +498,28 @@ sfs_lookparent(struct vnode *v, char *path, struct vnode **ret, * Since we don't support subdirectories, it's easy - just look up the * name. */ -static -int -sfs_lookup(struct vnode *v, char *path, struct vnode **ret) -{ - struct sfs_vnode *sv = v->vn_data; - struct sfs_vnode *final; - int result; +static int sfs_lookup(struct vnode *v, char *path, struct vnode **ret) { + struct sfs_vnode *sv = v->vn_data; + struct sfs_vnode *final; + int result; - vfs_biglock_acquire(); + vfs_biglock_acquire(); - if (sv->sv_i.sfi_type != SFS_TYPE_DIR) { - vfs_biglock_release(); - return ENOTDIR; - } + if (sv->sv_i.sfi_type != SFS_TYPE_DIR) { + vfs_biglock_release(); + return ENOTDIR; + } - result = sfs_lookonce(sv, path, &final, NULL); - if (result) { - vfs_biglock_release(); - return result; - } + result = sfs_lookonce(sv, path, &final, NULL); + if (result) { + vfs_biglock_release(); + return result; + } - *ret = &final->sv_absvn; + *ret = &final->sv_absvn; - vfs_biglock_release(); - return 0; + vfs_biglock_release(); + return 0; } //////////////////////////////////////////////////////////// @@ -585,66 +529,66 @@ sfs_lookup(struct vnode *v, char *path, struct vnode **ret) * Function table for sfs files. */ const struct vnode_ops sfs_fileops = { - .vop_magic = VOP_MAGIC, /* mark this a valid vnode ops table */ + .vop_magic = VOP_MAGIC, /* mark this a valid vnode ops table */ - .vop_eachopen = sfs_eachopen, - .vop_reclaim = sfs_reclaim, + .vop_eachopen = sfs_eachopen, + .vop_reclaim = sfs_reclaim, - .vop_read = sfs_read, - .vop_readlink = vopfail_uio_notdir, - .vop_getdirentry = vopfail_uio_notdir, - .vop_write = sfs_write, - .vop_ioctl = sfs_ioctl, - .vop_stat = sfs_stat, - .vop_gettype = sfs_gettype, - .vop_isseekable = sfs_isseekable, - .vop_fsync = sfs_fsync, - .vop_mmap = sfs_mmap, - .vop_truncate = sfs_truncate, - .vop_namefile = vopfail_uio_notdir, + .vop_read = sfs_read, + .vop_readlink = vopfail_uio_notdir, + .vop_getdirentry = vopfail_uio_notdir, + .vop_write = sfs_write, + .vop_ioctl = sfs_ioctl, + .vop_stat = sfs_stat, + .vop_gettype = sfs_gettype, + .vop_isseekable = sfs_isseekable, + .vop_fsync = sfs_fsync, + .vop_mmap = sfs_mmap, + .vop_truncate = sfs_truncate, + .vop_namefile = vopfail_uio_notdir, - .vop_creat = vopfail_creat_notdir, - .vop_symlink = vopfail_symlink_notdir, - .vop_mkdir = vopfail_mkdir_notdir, - .vop_link = vopfail_link_notdir, - .vop_remove = vopfail_string_notdir, - .vop_rmdir = vopfail_string_notdir, - .vop_rename = vopfail_rename_notdir, + .vop_creat = vopfail_creat_notdir, + .vop_symlink = vopfail_symlink_notdir, + .vop_mkdir = vopfail_mkdir_notdir, + .vop_link = vopfail_link_notdir, + .vop_remove = vopfail_string_notdir, + .vop_rmdir = vopfail_string_notdir, + .vop_rename = vopfail_rename_notdir, - .vop_lookup = vopfail_lookup_notdir, - .vop_lookparent = vopfail_lookparent_notdir, + .vop_lookup = vopfail_lookup_notdir, + .vop_lookparent = vopfail_lookparent_notdir, }; /* * Function table for the sfs directory. */ const struct vnode_ops sfs_dirops = { - .vop_magic = VOP_MAGIC, /* mark this a valid vnode ops table */ + .vop_magic = VOP_MAGIC, /* mark this a valid vnode ops table */ - .vop_eachopen = sfs_eachopendir, - .vop_reclaim = sfs_reclaim, + .vop_eachopen = sfs_eachopendir, + .vop_reclaim = sfs_reclaim, - .vop_read = vopfail_uio_isdir, - .vop_readlink = vopfail_uio_inval, - .vop_getdirentry = vopfail_uio_nosys, - .vop_write = vopfail_uio_isdir, - .vop_ioctl = sfs_ioctl, - .vop_stat = sfs_stat, - .vop_gettype = sfs_gettype, - .vop_isseekable = sfs_isseekable, - .vop_fsync = sfs_fsync, - .vop_mmap = vopfail_mmap_isdir, - .vop_truncate = vopfail_truncate_isdir, - .vop_namefile = sfs_namefile, + .vop_read = vopfail_uio_isdir, + .vop_readlink = vopfail_uio_inval, + .vop_getdirentry = vopfail_uio_nosys, + .vop_write = vopfail_uio_isdir, + .vop_ioctl = sfs_ioctl, + .vop_stat = sfs_stat, + .vop_gettype = sfs_gettype, + .vop_isseekable = sfs_isseekable, + .vop_fsync = sfs_fsync, + .vop_mmap = vopfail_mmap_isdir, + .vop_truncate = vopfail_truncate_isdir, + .vop_namefile = sfs_namefile, - .vop_creat = sfs_creat, - .vop_symlink = vopfail_symlink_nosys, - .vop_mkdir = vopfail_mkdir_nosys, - .vop_link = sfs_link, - .vop_remove = sfs_remove, - .vop_rmdir = vopfail_string_nosys, - .vop_rename = sfs_rename, + .vop_creat = sfs_creat, + .vop_symlink = vopfail_symlink_nosys, + .vop_mkdir = vopfail_mkdir_nosys, + .vop_link = sfs_link, + .vop_remove = sfs_remove, + .vop_rmdir = vopfail_string_nosys, + .vop_rename = sfs_rename, - .vop_lookup = sfs_lookup, - .vop_lookparent = sfs_lookparent, + .vop_lookup = sfs_lookup, + .vop_lookparent = sfs_lookparent, }; diff --git a/kern/fs/sfs/sfsprivate.h b/kern/fs/sfs/sfsprivate.h index dd3d35c..7e8bc14 100644 --- a/kern/fs/sfs/sfsprivate.h +++ b/kern/fs/sfs/sfsprivate.h @@ -32,15 +32,13 @@ #include /* for uio_rw */ - /* ops tables (in sfs_vnops.c) */ extern const struct vnode_ops sfs_fileops; extern const struct vnode_ops sfs_dirops; /* Macro for initializing a uio structure */ -#define SFSUIO(iov, uio, ptr, block, rw) \ - uio_kinit(iov, uio, ptr, SFS_BLOCKSIZE, ((off_t)(block))*SFS_BLOCKSIZE, rw) - +#define SFSUIO(iov, uio, ptr, block, rw) \ + uio_kinit(iov, uio, ptr, SFS_BLOCKSIZE, ((off_t)(block)) * SFS_BLOCKSIZE, rw) /* Functions in sfs_balloc.c */ int sfs_balloc(struct sfs_fs *sfs, daddr_t *diskblock); @@ -49,24 +47,23 @@ int sfs_bused(struct sfs_fs *sfs, daddr_t diskblock); /* Functions in sfs_bmap.c */ int sfs_bmap(struct sfs_vnode *sv, uint32_t fileblock, bool doalloc, - daddr_t *diskblock); + daddr_t *diskblock); int sfs_itrunc(struct sfs_vnode *sv, off_t len); /* Functions in sfs_dir.c */ -int sfs_dir_findname(struct sfs_vnode *sv, const char *name, - uint32_t *ino, int *slot, int *emptyslot); +int sfs_dir_findname(struct sfs_vnode *sv, const char *name, uint32_t *ino, + int *slot, int *emptyslot); int sfs_dir_link(struct sfs_vnode *sv, const char *name, uint32_t ino, - int *slot); + int *slot); int sfs_dir_unlink(struct sfs_vnode *sv, int slot); -int sfs_lookonce(struct sfs_vnode *sv, const char *name, - struct sfs_vnode **ret, - int *slot); +int sfs_lookonce(struct sfs_vnode *sv, const char *name, struct sfs_vnode **ret, + int *slot); /* Functions in sfs_inode.c */ int sfs_sync_inode(struct sfs_vnode *sv); int sfs_reclaim(struct vnode *v); int sfs_loadvnode(struct sfs_fs *sfs, uint32_t ino, int forcetype, - struct sfs_vnode **ret); + struct sfs_vnode **ret); int sfs_makeobj(struct sfs_fs *sfs, int type, struct sfs_vnode **ret); int sfs_getroot(struct fs *fs, struct vnode **ret); @@ -75,7 +72,6 @@ int sfs_readblock(struct sfs_fs *sfs, daddr_t block, void *data, size_t len); int sfs_writeblock(struct sfs_fs *sfs, daddr_t block, void *data, size_t len); int sfs_io(struct sfs_vnode *sv, struct uio *uio); int sfs_metaio(struct sfs_vnode *sv, off_t pos, void *data, size_t len, - enum uio_rw rw); - + enum uio_rw rw); #endif /* _SFSPRIVATE_H_ */ diff --git a/kern/include/addrspace.h b/kern/include/addrspace.h index b1a3b7f..f29303c 100644 --- a/kern/include/addrspace.h +++ b/kern/include/addrspace.h @@ -34,13 +34,11 @@ * Address space structure and operations. */ - #include #include "opt-dumbvm.h" struct vnode; - /* * Address space - data structure associated with the virtual memory * space of a process. @@ -50,15 +48,15 @@ struct vnode; struct addrspace { #if OPT_DUMBVM - vaddr_t as_vbase1; - paddr_t as_pbase1; - size_t as_npages1; - vaddr_t as_vbase2; - paddr_t as_pbase2; - size_t as_npages2; - paddr_t as_stackpbase; + vaddr_t as_vbase1; + paddr_t as_pbase1; + size_t as_npages1; + vaddr_t as_vbase2; + paddr_t as_pbase2; + size_t as_npages2; + paddr_t as_stackpbase; #else - /* Put stuff here for your VM system */ + /* Put stuff here for your VM system */ #endif }; @@ -104,20 +102,16 @@ struct addrspace { */ struct addrspace *as_create(void); -int as_copy(struct addrspace *src, struct addrspace **ret); -void as_activate(void); -void as_deactivate(void); -void as_destroy(struct addrspace *); - -int as_define_region(struct addrspace *as, - vaddr_t vaddr, size_t sz, - int readable, - int writeable, - int executable); -int as_prepare_load(struct addrspace *as); -int as_complete_load(struct addrspace *as); -int as_define_stack(struct addrspace *as, vaddr_t *initstackptr); +int as_copy(struct addrspace *src, struct addrspace **ret); +void as_activate(void); +void as_deactivate(void); +void as_destroy(struct addrspace *); +int as_define_region(struct addrspace *as, vaddr_t vaddr, size_t sz, + int readable, int writeable, int executable); +int as_prepare_load(struct addrspace *as); +int as_complete_load(struct addrspace *as); +int as_define_stack(struct addrspace *as, vaddr_t *initstackptr); /* * Functions in loadelf.c @@ -128,5 +122,4 @@ int as_define_stack(struct addrspace *as, vaddr_t *initstackptr); int load_elf(struct vnode *v, vaddr_t *entrypoint); - #endif /* _ADDRSPACE_H_ */ diff --git a/kern/include/array.h b/kern/include/array.h index 2b12874..ae2d449 100644 --- a/kern/include/array.h +++ b/kern/include/array.h @@ -68,8 +68,8 @@ */ struct array { - void **v; - unsigned num, max; + void **v; + unsigned num, max; }; struct array *array_create(void); @@ -88,42 +88,32 @@ void array_remove(struct array *, unsigned index); * Inlining for base operations */ -ARRAYINLINE unsigned -array_num(const struct array *a) -{ - return a->num; +ARRAYINLINE unsigned array_num(const struct array *a) { return a->num; } + +ARRAYINLINE void *array_get(const struct array *a, unsigned index) { + ARRAYASSERT(index < a->num); + return a->v[index]; } -ARRAYINLINE void * -array_get(const struct array *a, unsigned index) -{ - ARRAYASSERT(index < a->num); - return a->v[index]; +ARRAYINLINE void array_set(const struct array *a, unsigned index, void *val) { + ARRAYASSERT(index < a->num); + a->v[index] = val; } -ARRAYINLINE void -array_set(const struct array *a, unsigned index, void *val) -{ - ARRAYASSERT(index < a->num); - a->v[index] = val; -} +ARRAYINLINE int array_add(struct array *a, void *val, unsigned *index_ret) { + unsigned index; + int ret; -ARRAYINLINE int -array_add(struct array *a, void *val, unsigned *index_ret) -{ - unsigned index; - int ret; - - index = a->num; - ret = array_setsize(a, index+1); - if (ret) { - return ret; - } - a->v[index] = val; - if (index_ret != NULL) { - *index_ret = index; - } - return 0; + index = a->num; + ret = array_setsize(a, index + 1); + if (ret) { + return ret; + } + a->v[index] = val; + if (index_ret != NULL) { + *index_ret = index; + } + return 0; } /* @@ -165,95 +155,69 @@ array_add(struct array *a, void *val, unsigned *index_ret) * the base array, except typed. */ -#define DECLARRAY_BYTYPE(ARRAY, T, INLINE) \ - struct ARRAY { \ - struct array arr; \ - }; \ - \ - INLINE struct ARRAY *ARRAY##_create(void); \ - INLINE void ARRAY##_destroy(struct ARRAY *a); \ - INLINE void ARRAY##_init(struct ARRAY *a); \ - INLINE void ARRAY##_cleanup(struct ARRAY *a); \ - INLINE unsigned ARRAY##_num(const struct ARRAY *a); \ - INLINE T *ARRAY##_get(const struct ARRAY *a, unsigned index); \ - INLINE void ARRAY##_set(struct ARRAY *a, unsigned index, T *val); \ - INLINE int ARRAY##_preallocate(struct ARRAY *a, unsigned num); \ - INLINE int ARRAY##_setsize(struct ARRAY *a, unsigned num); \ - INLINE int ARRAY##_add(struct ARRAY *a, T *val, unsigned *index_ret); \ - INLINE void ARRAY##_remove(struct ARRAY *a, unsigned index) +#define DECLARRAY_BYTYPE(ARRAY, T, INLINE) \ + struct ARRAY { \ + struct array arr; \ + }; \ + \ + INLINE struct ARRAY *ARRAY##_create(void); \ + INLINE void ARRAY##_destroy(struct ARRAY *a); \ + INLINE void ARRAY##_init(struct ARRAY *a); \ + INLINE void ARRAY##_cleanup(struct ARRAY *a); \ + INLINE unsigned ARRAY##_num(const struct ARRAY *a); \ + INLINE T *ARRAY##_get(const struct ARRAY *a, unsigned index); \ + INLINE void ARRAY##_set(struct ARRAY *a, unsigned index, T *val); \ + INLINE int ARRAY##_preallocate(struct ARRAY *a, unsigned num); \ + INLINE int ARRAY##_setsize(struct ARRAY *a, unsigned num); \ + INLINE int ARRAY##_add(struct ARRAY *a, T *val, unsigned *index_ret); \ + INLINE void ARRAY##_remove(struct ARRAY *a, unsigned index) -#define DEFARRAY_BYTYPE(ARRAY, T, INLINE) \ - INLINE struct ARRAY * \ - ARRAY##_create(void) \ - { \ - struct ARRAY *a = kmalloc(sizeof(*a)); \ - if (a == NULL) { \ - return NULL; \ - } \ - array_init(&a->arr); \ - return a; \ - } \ - \ - INLINE void \ - ARRAY##_destroy(struct ARRAY *a) \ - { \ - array_cleanup(&a->arr); \ - kfree(a); \ - } \ - \ - INLINE void \ - ARRAY##_init(struct ARRAY *a) \ - { \ - array_init(&a->arr); \ - } \ - \ - INLINE void \ - ARRAY##_cleanup(struct ARRAY *a) \ - { \ - array_cleanup(&a->arr); \ - } \ - \ - INLINE unsigned \ - ARRAY##_num(const struct ARRAY *a) \ - { \ - return array_num(&a->arr); \ - } \ - \ - INLINE T * \ - ARRAY##_get(const struct ARRAY *a, unsigned index) \ - { \ - return (T *)array_get(&a->arr, index); \ - } \ - \ - INLINE void \ - ARRAY##_set(struct ARRAY *a, unsigned index, T *val) \ - { \ - array_set(&a->arr, index, (void *)val); \ - } \ - \ - INLINE int \ - ARRAY##_preallocate(struct ARRAY *a, unsigned num) \ - { \ - return array_preallocate(&a->arr, num); \ - } \ - \ - INLINE int \ - ARRAY##_setsize(struct ARRAY *a, unsigned num) \ - { \ - return array_setsize(&a->arr, num); \ - } \ - \ - INLINE int \ - ARRAY##_add(struct ARRAY *a, T *val, unsigned *index_ret) \ - { \ - return array_add(&a->arr, (void *)val, index_ret); \ - } \ - \ - INLINE void \ - ARRAY##_remove(struct ARRAY *a, unsigned index) \ - { \ - array_remove(&a->arr, index); \ - } +#define DEFARRAY_BYTYPE(ARRAY, T, INLINE) \ + INLINE struct ARRAY *ARRAY##_create(void) { \ + struct ARRAY *a = kmalloc(sizeof(*a)); \ + if (a == NULL) { \ + return NULL; \ + } \ + array_init(&a->arr); \ + return a; \ + } \ + \ + INLINE void ARRAY##_destroy(struct ARRAY *a) { \ + array_cleanup(&a->arr); \ + kfree(a); \ + } \ + \ + INLINE void ARRAY##_init(struct ARRAY *a) { array_init(&a->arr); } \ + \ + INLINE void ARRAY##_cleanup(struct ARRAY *a) { array_cleanup(&a->arr); } \ + \ + INLINE unsigned ARRAY##_num(const struct ARRAY *a) { \ + return array_num(&a->arr); \ + } \ + \ + INLINE T *ARRAY##_get(const struct ARRAY *a, unsigned index) { \ + return (T *)array_get(&a->arr, index); \ + } \ + \ + INLINE void ARRAY##_set(struct ARRAY *a, unsigned index, T *val) { \ + array_set(&a->arr, index, (void *)val); \ + } \ + \ + INLINE int ARRAY##_preallocate(struct ARRAY *a, unsigned num) { \ + return array_preallocate(&a->arr, num); \ + } \ + \ + INLINE int ARRAY##_setsize(struct ARRAY *a, unsigned num) { \ + return array_setsize(&a->arr, num); \ + } \ + \ + INLINE int ARRAY##_add(struct ARRAY *a, T *val, unsigned *index_ret) { \ + return array_add(&a->arr, (void *)val, index_ret); \ + } \ + \ + INLINE void ARRAY##_remove(struct ARRAY *a, unsigned index) { \ + array_remove(&a->arr, index); \ + } #define DECLARRAY(T, INLINE) DECLARRAY_BYTYPE(T##array, struct T, INLINE) #define DEFARRAY(T, INLINE) DEFARRAY_BYTYPE(T##array, struct T, INLINE) @@ -265,5 +229,4 @@ array_add(struct array *a, void *val, unsigned *index_ret) DECLARRAY_BYTYPE(stringarray, char, ARRAYINLINE); DEFARRAY_BYTYPE(stringarray, char, ARRAYINLINE); - #endif /* ARRAY_H */ diff --git a/kern/include/bitmap.h b/kern/include/bitmap.h index d8df7ea..a26f475 100644 --- a/kern/include/bitmap.h +++ b/kern/include/bitmap.h @@ -44,16 +44,14 @@ * bitmap_destroy - destroy bitmap. */ - -struct bitmap; /* Opaque. */ +struct bitmap; /* Opaque. */ struct bitmap *bitmap_create(unsigned nbits); -void *bitmap_getdata(struct bitmap *); -int bitmap_alloc(struct bitmap *, unsigned *index); -void bitmap_mark(struct bitmap *, unsigned index); -void bitmap_unmark(struct bitmap *, unsigned index); -int bitmap_isset(struct bitmap *, unsigned index); -void bitmap_destroy(struct bitmap *); - +void *bitmap_getdata(struct bitmap *); +int bitmap_alloc(struct bitmap *, unsigned *index); +void bitmap_mark(struct bitmap *, unsigned index); +void bitmap_unmark(struct bitmap *, unsigned index); +int bitmap_isset(struct bitmap *, unsigned index); +void bitmap_destroy(struct bitmap *); #endif /* _BITMAP_H_ */ diff --git a/kern/include/cdefs.h b/kern/include/cdefs.h index 194bd39..c2553e0 100644 --- a/kern/include/cdefs.h +++ b/kern/include/cdefs.h @@ -34,36 +34,32 @@ * Some miscellaneous C language definitions and related matters. */ - /* * Build-time assertion. Doesn't generate any code. The error message * on failure is less than ideal, but you can't have everything. */ -#define COMPILE_ASSERT(x) ((void)sizeof(struct { unsigned : ((x)?1:-1); })) - +#define COMPILE_ASSERT(x) ((void)sizeof(struct { unsigned : ((x) ? 1 : -1); })) /* * Handy macro for the number of elements in a static array. */ #define ARRAYCOUNT(arr) (sizeof(arr) / sizeof((arr)[0])) - /* * Tell GCC how to check printf formats. Also tell it about functions * that don't return, as this is helpful for avoiding bogus warnings * about uninitialized variables. */ #ifdef __GNUC__ -#define __PF(a,b) __attribute__((__format__(__printf__, a, b))) -#define __DEAD __attribute__((__noreturn__)) -#define __UNUSED __attribute__((__unused__)) +#define __PF(a, b) __attribute__((__format__(__printf__, a, b))) +#define __DEAD __attribute__((__noreturn__)) +#define __UNUSED __attribute__((__unused__)) #else -#define __PF(a,b) +#define __PF(a, b) #define __DEAD #define __UNUSED #endif - /* * Material for supporting inline functions. * @@ -137,5 +133,4 @@ #define INLINE static __UNUSED inline #endif - #endif /* _CDEFS_H_ */ diff --git a/kern/include/clock.h b/kern/include/clock.h index c80afd4..ef01307 100644 --- a/kern/include/clock.h +++ b/kern/include/clock.h @@ -36,14 +36,13 @@ #include - /* * hardclock() is called on every CPU HZ times a second, possibly only * when the CPU is not idle, for scheduling. */ /* hardclocks per second */ -#define HZ 100 +#define HZ 100 void hardclock_bootstrap(void); void hardclock(void); @@ -66,12 +65,10 @@ void gettime(struct timespec *ret); * sub: ret = t1 - t2 */ -void timespec_add(const struct timespec *t1, - const struct timespec *t2, - struct timespec *ret); -void timespec_sub(const struct timespec *t1, - const struct timespec *t2, - struct timespec *ret); +void timespec_add(const struct timespec *t1, const struct timespec *t2, + struct timespec *ret); +void timespec_sub(const struct timespec *t1, const struct timespec *t2, + struct timespec *ret); /* * clocksleep() suspends execution for the requested number of seconds, @@ -79,5 +76,4 @@ void timespec_sub(const struct timespec *t1, */ void clocksleep(int seconds); - #endif /* _CLOCK_H_ */ diff --git a/kern/include/copyinout.h b/kern/include/copyinout.h index b6f312b..5d5fcfd 100644 --- a/kern/include/copyinout.h +++ b/kern/include/copyinout.h @@ -30,7 +30,6 @@ #ifndef _COPYINOUT_H_ #define _COPYINOUT_H_ - /* * copyin/copyout/copyinstr/copyoutstr are standard BSD kernel functions. * @@ -69,5 +68,4 @@ int copyout(const void *src, userptr_t userdest, size_t len); int copyinstr(const_userptr_t usersrc, char *dest, size_t len, size_t *got); int copyoutstr(const char *src, userptr_t userdest, size_t len, size_t *got); - #endif /* _COPYINOUT_H_ */ diff --git a/kern/include/cpu.h b/kern/include/cpu.h index 687df77..c98c29b 100644 --- a/kern/include/cpu.h +++ b/kern/include/cpu.h @@ -30,11 +30,9 @@ #ifndef _CPU_H_ #define _CPU_H_ - #include #include -#include /* for TLBSHOOTDOWN_MAX */ - +#include /* for TLBSHOOTDOWN_MAX */ /* * Per-cpu structure @@ -47,51 +45,51 @@ */ struct cpu { - /* - * Fixed after allocation. - */ - struct cpu *c_self; /* Canonical address of this struct */ - unsigned c_number; /* This cpu's cpu number */ - unsigned c_hardware_number; /* Hardware-defined cpu number */ + /* + * Fixed after allocation. + */ + struct cpu *c_self; /* Canonical address of this struct */ + unsigned c_number; /* This cpu's cpu number */ + unsigned c_hardware_number; /* Hardware-defined cpu number */ - /* - * Accessed only by this cpu. - */ - struct thread *c_curthread; /* Current thread on cpu */ - struct threadlist c_zombies; /* List of exited threads */ - unsigned c_hardclocks; /* Counter of hardclock() calls */ - unsigned c_spinlocks; /* Counter of spinlocks held */ + /* + * Accessed only by this cpu. + */ + struct thread *c_curthread; /* Current thread on cpu */ + struct threadlist c_zombies; /* List of exited threads */ + unsigned c_hardclocks; /* Counter of hardclock() calls */ + unsigned c_spinlocks; /* Counter of spinlocks held */ - /* - * Accessed by other cpus. - * Protected by the runqueue lock. - */ - bool c_isidle; /* True if this cpu is idle */ - struct threadlist c_runqueue; /* Run queue for this cpu */ - struct spinlock c_runqueue_lock; + /* + * Accessed by other cpus. + * Protected by the runqueue lock. + */ + bool c_isidle; /* True if this cpu is idle */ + struct threadlist c_runqueue; /* Run queue for this cpu */ + struct spinlock c_runqueue_lock; - /* - * Accessed by other cpus. - * Protected by the IPI lock. - * - * TLB shootdown requests made to this CPU are queued in - * c_shootdown[], with c_numshootdown holding the number of - * requests. TLBSHOOTDOWN_MAX is the maximum number that can - * be queued at once, which is machine-dependent. - * - * The contents of struct tlbshootdown are also machine- - * dependent and might reasonably be either an address space - * and vaddr pair, or a paddr, or something else. - */ - uint32_t c_ipi_pending; /* One bit for each IPI number */ - struct tlbshootdown c_shootdown[TLBSHOOTDOWN_MAX]; - unsigned c_numshootdown; - struct spinlock c_ipi_lock; + /* + * Accessed by other cpus. + * Protected by the IPI lock. + * + * TLB shootdown requests made to this CPU are queued in + * c_shootdown[], with c_numshootdown holding the number of + * requests. TLBSHOOTDOWN_MAX is the maximum number that can + * be queued at once, which is machine-dependent. + * + * The contents of struct tlbshootdown are also machine- + * dependent and might reasonably be either an address space + * and vaddr pair, or a paddr, or something else. + */ + uint32_t c_ipi_pending; /* One bit for each IPI number */ + struct tlbshootdown c_shootdown[TLBSHOOTDOWN_MAX]; + unsigned c_numshootdown; + struct spinlock c_ipi_lock; - /* - * Accessed by other cpus. Protected inside hangman.c. - */ - HANGMAN_ACTOR(c_hangman); + /* + * Accessed by other cpus. Protected inside hangman.c. + */ + HANGMAN_ACTOR(c_hangman); }; /* @@ -161,10 +159,10 @@ void cpu_halt(void); */ /* IPI types */ -#define IPI_PANIC 0 /* System has called panic() */ -#define IPI_OFFLINE 1 /* CPU is requested to go offline */ -#define IPI_UNIDLE 2 /* Runnable threads are available */ -#define IPI_TLBSHOOTDOWN 3 /* MMU mapping(s) need invalidation */ +#define IPI_PANIC 0 /* System has called panic() */ +#define IPI_OFFLINE 1 /* CPU is requested to go offline */ +#define IPI_UNIDLE 2 /* Runnable threads are available */ +#define IPI_TLBSHOOTDOWN 3 /* MMU mapping(s) need invalidation */ void ipi_send(struct cpu *target, int code); void ipi_broadcast(int code); @@ -172,5 +170,4 @@ void ipi_tlbshootdown(struct cpu *target, const struct tlbshootdown *mapping); void interprocessor_interrupt(void); - #endif /* _CPU_H_ */ diff --git a/kern/include/current.h b/kern/include/current.h index fa88971..69c622d 100644 --- a/kern/include/current.h +++ b/kern/include/current.h @@ -89,5 +89,4 @@ #define curproc (curthread->t_proc) - #endif /* _CURRENT_H_ */ diff --git a/kern/include/device.h b/kern/include/device.h index b749351..d646ead 100644 --- a/kern/include/device.h +++ b/kern/include/device.h @@ -34,21 +34,20 @@ * Devices. */ - -struct uio; /* in */ +struct uio; /* in */ /* * Filesystem-namespace-accessible device. */ struct device { - const struct device_ops *d_ops; + const struct device_ops *d_ops; - blkcnt_t d_blocks; - blksize_t d_blocksize; + blkcnt_t d_blocks; + blksize_t d_blocksize; - dev_t d_devnumber; /* serial number for this device */ + dev_t d_devnumber; /* serial number for this device */ - void *d_data; /* device-specific data */ + void *d_data; /* device-specific data */ }; /* @@ -58,18 +57,17 @@ struct device { * devop_ioctl - miscellaneous control operations */ struct device_ops { - int (*devop_eachopen)(struct device *, int flags_from_open); - int (*devop_io)(struct device *, struct uio *); - int (*devop_ioctl)(struct device *, int op, userptr_t data); + int (*devop_eachopen)(struct device *, int flags_from_open); + int (*devop_io)(struct device *, struct uio *); + int (*devop_ioctl)(struct device *, int op, userptr_t data); }; /* * Macros to shorten the calling sequences. */ -#define DEVOP_EACHOPEN(d, f) ((d)->d_ops->devop_eachopen(d, f)) -#define DEVOP_IO(d, u) ((d)->d_ops->devop_io(d, u)) -#define DEVOP_IOCTL(d, op, p) ((d)->d_ops->devop_ioctl(d, op, p)) - +#define DEVOP_EACHOPEN(d, f) ((d)->d_ops->devop_eachopen(d, f)) +#define DEVOP_IO(d, u) ((d)->d_ops->devop_io(d, u)) +#define DEVOP_IOCTL(d, op, p) ((d)->d_ops->devop_ioctl(d, op, p)) /* Create vnode for a vfs-level device. */ struct vnode *dev_create_vnode(struct device *dev); @@ -83,5 +81,4 @@ void devnull_create(void); /* Function that kicks off device probe and attach. */ void dev_bootstrap(void); - #endif /* _DEVICE_H_ */ diff --git a/kern/include/elf.h b/kern/include/elf.h index 7a5ae73..bb1301c 100644 --- a/kern/include/elf.h +++ b/kern/include/elf.h @@ -30,7 +30,6 @@ #ifndef _ELF_H_ #define _ELF_H_ - /* * Simplified ELF definitions for OS/161 and System/161. * @@ -43,121 +42,118 @@ /* Get MD bits */ #include - /* * ELF file header. This appears at the very beginning of an ELF file. */ -#define ELF_NIDENT 16 +#define ELF_NIDENT 16 typedef struct { - unsigned char e_ident[ELF_NIDENT]; /* magic number et al. */ - uint16_t e_type; /* type of file this is */ - uint16_t e_machine; /* processor type file is for */ - uint32_t e_version; /* ELF version */ - uint32_t e_entry; /* address of program entry point */ - uint32_t e_phoff; /* location in file of phdrs */ - uint32_t e_shoff; /* ignore */ - uint32_t e_flags; /* ignore */ - uint16_t e_ehsize; /* actual size of file header */ - uint16_t e_phentsize; /* actual size of phdr */ - uint16_t e_phnum; /* number of phdrs */ - uint16_t e_shentsize; /* ignore */ - uint16_t e_shnum; /* ignore */ - uint16_t e_shstrndx; /* ignore */ + unsigned char e_ident[ELF_NIDENT]; /* magic number et al. */ + uint16_t e_type; /* type of file this is */ + uint16_t e_machine; /* processor type file is for */ + uint32_t e_version; /* ELF version */ + uint32_t e_entry; /* address of program entry point */ + uint32_t e_phoff; /* location in file of phdrs */ + uint32_t e_shoff; /* ignore */ + uint32_t e_flags; /* ignore */ + uint16_t e_ehsize; /* actual size of file header */ + uint16_t e_phentsize; /* actual size of phdr */ + uint16_t e_phnum; /* number of phdrs */ + uint16_t e_shentsize; /* ignore */ + uint16_t e_shnum; /* ignore */ + uint16_t e_shstrndx; /* ignore */ } Elf32_Ehdr; /* Offsets for the 1-byte fields within e_ident[] */ -#define EI_MAG0 0 /* '\177' */ -#define EI_MAG1 1 /* 'E' */ -#define EI_MAG2 2 /* 'L' */ -#define EI_MAG3 3 /* 'F' */ -#define EI_CLASS 4 /* File class - always ELFCLASS32 */ -#define EI_DATA 5 /* Data encoding - ELFDATA2LSB or ELFDATA2MSB*/ -#define EI_VERSION 6 /* ELF version - EV_CURRENT*/ -#define EI_OSABI 7 /* OS/syscall ABI identification */ -#define EI_ABIVERSION 8 /* syscall ABI version */ -#define EI_PAD 9 /* Start of padding bytes up to EI_NIDENT*/ +#define EI_MAG0 0 /* '\177' */ +#define EI_MAG1 1 /* 'E' */ +#define EI_MAG2 2 /* 'L' */ +#define EI_MAG3 3 /* 'F' */ +#define EI_CLASS 4 /* File class - always ELFCLASS32 */ +#define EI_DATA 5 /* Data encoding - ELFDATA2LSB or ELFDATA2MSB*/ +#define EI_VERSION 6 /* ELF version - EV_CURRENT*/ +#define EI_OSABI 7 /* OS/syscall ABI identification */ +#define EI_ABIVERSION 8 /* syscall ABI version */ +#define EI_PAD 9 /* Start of padding bytes up to EI_NIDENT*/ /* Values for these fields */ /* For e_ident[EI_MAG0..3] */ -#define ELFMAG0 0x7f -#define ELFMAG1 'E' -#define ELFMAG2 'L' -#define ELFMAG3 'F' +#define ELFMAG0 0x7f +#define ELFMAG1 'E' +#define ELFMAG2 'L' +#define ELFMAG3 'F' /* For e_ident[EI_CLASS] */ -#define ELFCLASSNONE 0 /* Invalid class */ -#define ELFCLASS32 1 /* 32-bit objects */ -#define ELFCLASS64 2 /* 64-bit objects */ +#define ELFCLASSNONE 0 /* Invalid class */ +#define ELFCLASS32 1 /* 32-bit objects */ +#define ELFCLASS64 2 /* 64-bit objects */ /* e_ident[EI_DATA] */ -#define ELFDATANONE 0 /* Invalid data encoding */ -#define ELFDATA2LSB 1 /* 2's complement values, LSB first */ -#define ELFDATA2MSB 2 /* 2's complement values, MSB first */ +#define ELFDATANONE 0 /* Invalid data encoding */ +#define ELFDATA2LSB 1 /* 2's complement values, LSB first */ +#define ELFDATA2MSB 2 /* 2's complement values, MSB first */ /* e_ident[EI_VERSION] */ -#define EV_NONE 0 /* Invalid version */ -#define EV_CURRENT 1 /* Current version */ +#define EV_NONE 0 /* Invalid version */ +#define EV_CURRENT 1 /* Current version */ /* e_ident[EI_OSABI] */ -#define ELFOSABI_SYSV 0 /* UNIX System V ABI */ -#define ELFOSABI_HPUX 1 /* HP-UX operating system */ -#define ELFOSABI_STANDALONE 255 /* Standalone (embedded) application */ - +#define ELFOSABI_SYSV 0 /* UNIX System V ABI */ +#define ELFOSABI_HPUX 1 /* HP-UX operating system */ +#define ELFOSABI_STANDALONE 255 /* Standalone (embedded) application */ /* * Values for e_type */ -#define ET_NONE 0 /* No file type */ -#define ET_REL 1 /* Relocatable file */ -#define ET_EXEC 2 /* Executable file */ -#define ET_DYN 3 /* Shared object file */ -#define ET_CORE 4 /* Core file */ -#define ET_NUM 5 +#define ET_NONE 0 /* No file type */ +#define ET_REL 1 /* Relocatable file */ +#define ET_EXEC 2 /* Executable file */ +#define ET_DYN 3 /* Shared object file */ +#define ET_CORE 4 /* Core file */ +#define ET_NUM 5 /* * Values for e_machine */ -#define EM_NONE 0 /* No machine */ -#define EM_M32 1 /* AT&T WE 32100 */ -#define EM_SPARC 2 /* SPARC */ -#define EM_386 3 /* Intel 80386 */ -#define EM_68K 4 /* Motorola 68000 */ -#define EM_88K 5 /* Motorola 88000 */ -#define EM_486 6 /* Intel 80486 */ -#define EM_860 7 /* Intel 80860 */ -#define EM_MIPS 8 /* MIPS I Architecture */ -#define EM_S370 9 /* Amdahl UTS on System/370 */ -#define EM_MIPS_RS3_LE 10 /* MIPS RS3000 Little-endian */ -#define EM_RS6000 11 /* IBM RS/6000 XXX reserved */ -#define EM_PARISC 15 /* Hewlett-Packard PA-RISC */ -#define EM_NCUBE 16 /* NCube XXX reserved */ -#define EM_VPP500 17 /* Fujitsu VPP500 */ -#define EM_SPARC32PLUS 18 /* Enhanced instruction set SPARC */ -#define EM_960 19 /* Intel 80960 */ -#define EM_PPC 20 /* PowerPC */ -#define EM_V800 36 /* NEC V800 */ -#define EM_FR20 37 /* Fujitsu FR20 */ -#define EM_RH32 38 /* TRW RH-32 */ -#define EM_RCE 39 /* Motorola RCE */ -#define EM_ARM 40 /* Advanced RISC Machines ARM */ -#define EM_ALPHA 41 /* DIGITAL Alpha */ -#define EM_SH 42 /* Hitachi Super-H */ -#define EM_SPARCV9 43 /* SPARC Version 9 */ -#define EM_TRICORE 44 /* Siemens Tricore */ -#define EM_ARC 45 /* Argonaut RISC Core */ -#define EM_H8_300 46 /* Hitachi H8/300 */ -#define EM_H8_300H 47 /* Hitachi H8/300H */ -#define EM_H8S 48 /* Hitachi H8S */ -#define EM_H8_500 49 /* Hitachi H8/500 */ -#define EM_IA_64 50 /* Intel Merced Processor */ -#define EM_MIPS_X 51 /* Stanford MIPS-X */ -#define EM_COLDFIRE 52 /* Motorola Coldfire */ -#define EM_68HC12 53 /* Motorola MC68HC12 */ -#define EM_VAX 75 /* DIGITAL VAX */ -#define EM_ALPHA_EXP 36902 /* used by NetBSD/alpha; obsolete */ -#define EM_NUM 36903 - +#define EM_NONE 0 /* No machine */ +#define EM_M32 1 /* AT&T WE 32100 */ +#define EM_SPARC 2 /* SPARC */ +#define EM_386 3 /* Intel 80386 */ +#define EM_68K 4 /* Motorola 68000 */ +#define EM_88K 5 /* Motorola 88000 */ +#define EM_486 6 /* Intel 80486 */ +#define EM_860 7 /* Intel 80860 */ +#define EM_MIPS 8 /* MIPS I Architecture */ +#define EM_S370 9 /* Amdahl UTS on System/370 */ +#define EM_MIPS_RS3_LE 10 /* MIPS RS3000 Little-endian */ +#define EM_RS6000 11 /* IBM RS/6000 XXX reserved */ +#define EM_PARISC 15 /* Hewlett-Packard PA-RISC */ +#define EM_NCUBE 16 /* NCube XXX reserved */ +#define EM_VPP500 17 /* Fujitsu VPP500 */ +#define EM_SPARC32PLUS 18 /* Enhanced instruction set SPARC */ +#define EM_960 19 /* Intel 80960 */ +#define EM_PPC 20 /* PowerPC */ +#define EM_V800 36 /* NEC V800 */ +#define EM_FR20 37 /* Fujitsu FR20 */ +#define EM_RH32 38 /* TRW RH-32 */ +#define EM_RCE 39 /* Motorola RCE */ +#define EM_ARM 40 /* Advanced RISC Machines ARM */ +#define EM_ALPHA 41 /* DIGITAL Alpha */ +#define EM_SH 42 /* Hitachi Super-H */ +#define EM_SPARCV9 43 /* SPARC Version 9 */ +#define EM_TRICORE 44 /* Siemens Tricore */ +#define EM_ARC 45 /* Argonaut RISC Core */ +#define EM_H8_300 46 /* Hitachi H8/300 */ +#define EM_H8_300H 47 /* Hitachi H8/300H */ +#define EM_H8S 48 /* Hitachi H8S */ +#define EM_H8_500 49 /* Hitachi H8/500 */ +#define EM_IA_64 50 /* Intel Merced Processor */ +#define EM_MIPS_X 51 /* Stanford MIPS-X */ +#define EM_COLDFIRE 52 /* Motorola Coldfire */ +#define EM_68HC12 53 /* Motorola MC68HC12 */ +#define EM_VAX 75 /* DIGITAL VAX */ +#define EM_ALPHA_EXP 36902 /* used by NetBSD/alpha; obsolete */ +#define EM_NUM 36903 /* * "Program Header" - runtime segment header. @@ -166,35 +162,33 @@ typedef struct { * Note: if p_memsz > p_filesz, the leftover space should be zero-filled. */ typedef struct { - uint32_t p_type; /* Type of segment */ - uint32_t p_offset; /* Location of data within file */ - uint32_t p_vaddr; /* Virtual address */ - uint32_t p_paddr; /* Ignore */ - uint32_t p_filesz; /* Size of data within file */ - uint32_t p_memsz; /* Size of data to be loaded into memory*/ - uint32_t p_flags; /* Flags */ - uint32_t p_align; /* Required alignment - can ignore */ + uint32_t p_type; /* Type of segment */ + uint32_t p_offset; /* Location of data within file */ + uint32_t p_vaddr; /* Virtual address */ + uint32_t p_paddr; /* Ignore */ + uint32_t p_filesz; /* Size of data within file */ + uint32_t p_memsz; /* Size of data to be loaded into memory*/ + uint32_t p_flags; /* Flags */ + uint32_t p_align; /* Required alignment - can ignore */ } Elf32_Phdr; /* values for p_type */ -#define PT_NULL 0 /* Program header table entry unused */ -#define PT_LOAD 1 /* Loadable program segment */ -#define PT_DYNAMIC 2 /* Dynamic linking information */ -#define PT_INTERP 3 /* Program interpreter */ -#define PT_NOTE 4 /* Auxiliary information */ -#define PT_SHLIB 5 /* Reserved, unspecified semantics */ -#define PT_PHDR 6 /* Entry for header table itself */ -#define PT_NUM 7 -#define PT_MIPS_REGINFO 0x70000000 +#define PT_NULL 0 /* Program header table entry unused */ +#define PT_LOAD 1 /* Loadable program segment */ +#define PT_DYNAMIC 2 /* Dynamic linking information */ +#define PT_INTERP 3 /* Program interpreter */ +#define PT_NOTE 4 /* Auxiliary information */ +#define PT_SHLIB 5 /* Reserved, unspecified semantics */ +#define PT_PHDR 6 /* Entry for header table itself */ +#define PT_NUM 7 +#define PT_MIPS_REGINFO 0x70000000 /* values for p_flags */ -#define PF_R 0x4 /* Segment is readable */ -#define PF_W 0x2 /* Segment is writable */ -#define PF_X 0x1 /* Segment is executable */ - +#define PF_R 0x4 /* Segment is readable */ +#define PF_W 0x2 /* Segment is writable */ +#define PF_X 0x1 /* Segment is executable */ typedef Elf32_Ehdr Elf_Ehdr; typedef Elf32_Phdr Elf_Phdr; - #endif /* _ELF_H_ */ diff --git a/kern/include/emufs.h b/kern/include/emufs.h index 1dbb7cb..b59a68b 100644 --- a/kern/include/emufs.h +++ b/kern/include/emufs.h @@ -30,7 +30,6 @@ #ifndef _EMUFS_H_ #define _EMUFS_H_ - /* * Get abstract structure definitions */ @@ -42,17 +41,16 @@ */ struct emufs_vnode { - struct vnode ev_v; /* abstract vnode structure */ - struct emu_softc *ev_emu; /* device */ - uint32_t ev_handle; /* file handle */ + struct vnode ev_v; /* abstract vnode structure */ + struct emu_softc *ev_emu; /* device */ + uint32_t ev_handle; /* file handle */ }; struct emufs_fs { - struct fs ef_fs; /* abstract filesystem structure */ - struct emu_softc *ef_emu; /* device */ - struct emufs_vnode *ef_root; /* root vnode */ - struct vnodearray *ef_vnodes; /* table of loaded vnodes */ + struct fs ef_fs; /* abstract filesystem structure */ + struct emu_softc *ef_emu; /* device */ + struct emufs_vnode *ef_root; /* root vnode */ + struct vnodearray *ef_vnodes; /* table of loaded vnodes */ }; - #endif /* _EMUFS_H_ */ diff --git a/kern/include/endian.h b/kern/include/endian.h index 43ef9da..139bbff 100644 --- a/kern/include/endian.h +++ b/kern/include/endian.h @@ -51,5 +51,4 @@ uint64_t htonll(uint64_t); void join32to64(uint32_t x1, uint32_t x2, uint64_t *y2); void split64to32(uint64_t x, uint32_t *y1, uint32_t *y2); - #endif /* _ENDIAN_H_ */ diff --git a/kern/include/fs.h b/kern/include/fs.h index 09e9880..c4c8082 100644 --- a/kern/include/fs.h +++ b/kern/include/fs.h @@ -32,7 +32,6 @@ struct vnode; /* in vnode.h */ - /* * Abstract file system. (Or device accessible as a file.) * @@ -40,8 +39,8 @@ struct vnode; /* in vnode.h */ */ struct fs { - void *fs_data; - const struct fs_ops *fs_ops; + void *fs_data; + const struct fs_ops *fs_ops; }; /* @@ -70,22 +69,21 @@ struct fs { * filesystem should have been discarded/released. */ struct fs_ops { - int (*fsop_sync)(struct fs *); - const char *(*fsop_getvolname)(struct fs *); - int (*fsop_getroot)(struct fs *, struct vnode **); - int (*fsop_unmount)(struct fs *); + int (*fsop_sync)(struct fs *); + const char *(*fsop_getvolname)(struct fs *); + int (*fsop_getroot)(struct fs *, struct vnode **); + int (*fsop_unmount)(struct fs *); }; /* * Macros to shorten the calling sequences. */ -#define FSOP_SYNC(fs) ((fs)->fs_ops->fsop_sync(fs)) -#define FSOP_GETVOLNAME(fs) ((fs)->fs_ops->fsop_getvolname(fs)) +#define FSOP_SYNC(fs) ((fs)->fs_ops->fsop_sync(fs)) +#define FSOP_GETVOLNAME(fs) ((fs)->fs_ops->fsop_getvolname(fs)) #define FSOP_GETROOT(fs, ret) ((fs)->fs_ops->fsop_getroot(fs, ret)) -#define FSOP_UNMOUNT(fs) ((fs)->fs_ops->fsop_unmount(fs)) +#define FSOP_UNMOUNT(fs) ((fs)->fs_ops->fsop_unmount(fs)) /* Initialization functions for builtin fake file systems. */ void semfs_bootstrap(void); - #endif /* _FS_H_ */ diff --git a/kern/include/hangman.h b/kern/include/hangman.h index 91f3de2..e76e2ad 100644 --- a/kern/include/hangman.h +++ b/kern/include/hangman.h @@ -40,30 +40,30 @@ #if OPT_HANGMAN struct hangman_actor { - const char *a_name; - const struct hangman_lockable *a_waiting; + const char *a_name; + const struct hangman_lockable *a_waiting; }; struct hangman_lockable { - const char *l_name; - const struct hangman_actor *l_holding; + const char *l_name; + const struct hangman_actor *l_holding; }; void hangman_wait(struct hangman_actor *a, struct hangman_lockable *l); void hangman_acquire(struct hangman_actor *a, struct hangman_lockable *l); void hangman_release(struct hangman_actor *a, struct hangman_lockable *l); -#define HANGMAN_ACTOR(sym) struct hangman_actor sym -#define HANGMAN_LOCKABLE(sym) struct hangman_lockable sym +#define HANGMAN_ACTOR(sym) struct hangman_actor sym +#define HANGMAN_LOCKABLE(sym) struct hangman_lockable sym -#define HANGMAN_ACTORINIT(a, n) ((a)->a_name = (n), (a)->a_waiting = NULL) -#define HANGMAN_LOCKABLEINIT(l, n) ((l)->l_name = (n), (l)->l_holding = NULL) +#define HANGMAN_ACTORINIT(a, n) ((a)->a_name = (n), (a)->a_waiting = NULL) +#define HANGMAN_LOCKABLEINIT(l, n) ((l)->l_name = (n), (l)->l_holding = NULL) -#define HANGMAN_LOCKABLE_INITIALIZER { "spinlock", NULL } +#define HANGMAN_LOCKABLE_INITIALIZER {"spinlock", NULL} -#define HANGMAN_WAIT(a, l) hangman_wait(a, l) -#define HANGMAN_ACQUIRE(a, l) hangman_acquire(a, l) -#define HANGMAN_RELEASE(a, l) hangman_release(a, l) +#define HANGMAN_WAIT(a, l) hangman_wait(a, l) +#define HANGMAN_ACQUIRE(a, l) hangman_acquire(a, l) +#define HANGMAN_RELEASE(a, l) hangman_release(a, l) #else diff --git a/kern/include/kern/endian.h b/kern/include/kern/endian.h index 0d83e2b..fd5f10a 100644 --- a/kern/include/kern/endian.h +++ b/kern/include/kern/endian.h @@ -40,11 +40,10 @@ */ #define _LITTLE_ENDIAN 1234 -#define _BIG_ENDIAN 4321 -#define _PDP_ENDIAN 3412 +#define _BIG_ENDIAN 4321 +#define _PDP_ENDIAN 3412 /* This defines _BYTE_ORDER to one of the above. */ #include - #endif /* _KERN_ENDIAN_H_ */ diff --git a/kern/include/kern/errmsg.h b/kern/include/kern/errmsg.h index 097b217..d4246eb 100644 --- a/kern/include/kern/errmsg.h +++ b/kern/include/kern/errmsg.h @@ -39,76 +39,76 @@ * lib/misc.c; for userland it's lib/libc/strerror.c. */ const char *const sys_errlist[] = { - "Operation succeeded", /* 0 */ - "Function not implemented", /* ENOSYS */ - "(undefined error 2)", /* unused */ - "Out of memory", /* ENOMEM */ - "Operation would block", /* EAGAIN (also EWOULDBLOCK) */ - "Interrupted system call", /* EINTR */ - "Bad memory reference", /* EFAULT */ - "String too long", /* ENAMETOOLONG */ - "Invalid argument", /* EINVAL */ - "Operation not permitted", /* EPERM */ - "Permission denied", /* EACCES */ - "Too many processes", /* EMPROC (EPROCLIM in Unix) */ - "Too many processes in system",/* ENPROC */ - "File is not executable", /* ENOEXEC */ - "Argument list too long", /* E2BIG */ - "No such process", /* ESRCH */ - "No child processes", /* ECHILD */ - "Not a directory", /* ENOTDIR */ - "Is a directory", /* EISDIR */ - "No such file or directory", /* ENOENT */ - "Too many levels of symbolic links",/* ELOOP */ - "Directory not empty", /* ENOTEMPTY */ - "File or object exists", /* EEXIST */ - "Too many hard links", /* EMLINK */ - "Cross-device link", /* EXDEV */ - "No such device", /* ENODEV */ - "Device not available", /* ENXIO */ - "Device or resource busy", /* EBUSY */ - "Too many open files", /* EMFILE */ - "Too many open files in system",/* ENFILE */ - "Bad file number", /* EBADF */ - "Invalid or inappropriate ioctl",/* EIOCTL (ENOTTY in Unix) */ - "Input/output error", /* EIO */ - "Illegal seek", /* ESPIPE */ - "Broken pipe", /* EPIPE */ - "Read-only file system", /* EROFS */ - "No space left on device", /* ENOSPC */ - "Disc quota exceeded", /* EDQUOT */ - "File too large", /* EFBIG */ - "Invalid file type or format",/* EFTYPE */ - "Argument out of range", /* EDOM */ - "Result out of range", /* ERANGE */ - "Invalid multibyte character sequence",/* EILSEQ */ - "Not a socket", /* ENOTSOCK */ - "Is a socket", /* EISSOCK (EOPNOTSUPP in Unix) */ - "Socket is already connected",/* EISCONN */ - "Socket is not connected", /* ENOTCONN */ - "Socket has been shut down", /* ESHUTDOWN */ - "Protocol family not supported",/* EPFNOSUPPORT */ - "Socket type not supported", /* ESOCKTNOSUPPORT */ - "Protocol not supported", /* EPROTONOSUPPORT */ - "Protocol wrong type for socket",/* EPROTOTYPE */ - "Address family not supported by protocol family",/* EAFNOSUPPORT */ - "Protocol option not available",/* ENOPROTOOPT */ - "Address already in use", /* EADDRINUSE */ - "Cannot assign requested address",/* EADDRNOTAVAIL */ - "Network is down", /* ENETDOWN */ - "Network is unreachable", /* ENETUNREACH */ - "Host is down", /* EHOSTDOWN */ - "Host is unreachable", /* EHOSTUNREACH */ - "Connection refused", /* ECONNREFUSED */ - "Connection timed out", /* ETIMEDOUT */ - "Connection reset by peer", /* ECONNRESET */ - "Message too large", /* EMSGSIZE */ - "Threads operation not supported",/* ENOTSUP */ + "Operation succeeded", /* 0 */ + "Function not implemented", /* ENOSYS */ + "(undefined error 2)", /* unused */ + "Out of memory", /* ENOMEM */ + "Operation would block", /* EAGAIN (also EWOULDBLOCK) */ + "Interrupted system call", /* EINTR */ + "Bad memory reference", /* EFAULT */ + "String too long", /* ENAMETOOLONG */ + "Invalid argument", /* EINVAL */ + "Operation not permitted", /* EPERM */ + "Permission denied", /* EACCES */ + "Too many processes", /* EMPROC (EPROCLIM in Unix) */ + "Too many processes in system", /* ENPROC */ + "File is not executable", /* ENOEXEC */ + "Argument list too long", /* E2BIG */ + "No such process", /* ESRCH */ + "No child processes", /* ECHILD */ + "Not a directory", /* ENOTDIR */ + "Is a directory", /* EISDIR */ + "No such file or directory", /* ENOENT */ + "Too many levels of symbolic links", /* ELOOP */ + "Directory not empty", /* ENOTEMPTY */ + "File or object exists", /* EEXIST */ + "Too many hard links", /* EMLINK */ + "Cross-device link", /* EXDEV */ + "No such device", /* ENODEV */ + "Device not available", /* ENXIO */ + "Device or resource busy", /* EBUSY */ + "Too many open files", /* EMFILE */ + "Too many open files in system", /* ENFILE */ + "Bad file number", /* EBADF */ + "Invalid or inappropriate ioctl", /* EIOCTL (ENOTTY in Unix) */ + "Input/output error", /* EIO */ + "Illegal seek", /* ESPIPE */ + "Broken pipe", /* EPIPE */ + "Read-only file system", /* EROFS */ + "No space left on device", /* ENOSPC */ + "Disc quota exceeded", /* EDQUOT */ + "File too large", /* EFBIG */ + "Invalid file type or format", /* EFTYPE */ + "Argument out of range", /* EDOM */ + "Result out of range", /* ERANGE */ + "Invalid multibyte character sequence", /* EILSEQ */ + "Not a socket", /* ENOTSOCK */ + "Is a socket", /* EISSOCK (EOPNOTSUPP in Unix) */ + "Socket is already connected", /* EISCONN */ + "Socket is not connected", /* ENOTCONN */ + "Socket has been shut down", /* ESHUTDOWN */ + "Protocol family not supported", /* EPFNOSUPPORT */ + "Socket type not supported", /* ESOCKTNOSUPPORT */ + "Protocol not supported", /* EPROTONOSUPPORT */ + "Protocol wrong type for socket", /* EPROTOTYPE */ + "Address family not supported by protocol family", /* EAFNOSUPPORT */ + "Protocol option not available", /* ENOPROTOOPT */ + "Address already in use", /* EADDRINUSE */ + "Cannot assign requested address", /* EADDRNOTAVAIL */ + "Network is down", /* ENETDOWN */ + "Network is unreachable", /* ENETUNREACH */ + "Host is down", /* EHOSTDOWN */ + "Host is unreachable", /* EHOSTUNREACH */ + "Connection refused", /* ECONNREFUSED */ + "Connection timed out", /* ETIMEDOUT */ + "Connection reset by peer", /* ECONNRESET */ + "Message too large", /* EMSGSIZE */ + "Threads operation not supported", /* ENOTSUP */ }; /* * Number of entries in sys_errlist. */ -const int sys_nerr = sizeof(sys_errlist)/sizeof(const char *); +const int sys_nerr = sizeof(sys_errlist) / sizeof(const char *); #endif /* _KERN_ERRMSG_H_ */ diff --git a/kern/include/kern/errno.h b/kern/include/kern/errno.h index 3c78d5e..9e368ea 100644 --- a/kern/include/kern/errno.h +++ b/kern/include/kern/errno.h @@ -42,70 +42,69 @@ * contain only symbolic constants. */ -#define ENOSYS 1 /* Function not implemented */ +#define ENOSYS 1 /* Function not implemented */ /* unused 2 */ -#define ENOMEM 3 /* Out of memory */ -#define EAGAIN 4 /* Operation would block */ -#define EINTR 5 /* Interrupted system call */ -#define EFAULT 6 /* Bad memory reference */ -#define ENAMETOOLONG 7 /* String too long */ -#define EINVAL 8 /* Invalid argument */ -#define EPERM 9 /* Operation not permitted */ -#define EACCES 10 /* Permission denied */ -#define EMPROC 11 /* Too many processes */ -#define ENPROC 12 /* Too many processes in system */ -#define ENOEXEC 13 /* File is not executable */ -#define E2BIG 14 /* Argument list too long */ -#define ESRCH 15 /* No such process */ -#define ECHILD 16 /* No child processes */ -#define ENOTDIR 17 /* Not a directory */ -#define EISDIR 18 /* Is a directory */ -#define ENOENT 19 /* No such file or directory */ -#define ELOOP 20 /* Too many levels of symbolic links */ -#define ENOTEMPTY 21 /* Directory not empty */ -#define EEXIST 22 /* File or object exists */ -#define EMLINK 23 /* Too many hard links */ -#define EXDEV 24 /* Cross-device link */ -#define ENODEV 25 /* No such device */ -#define ENXIO 26 /* Device not available */ -#define EBUSY 27 /* Device or resource busy */ -#define EMFILE 28 /* Too many open files */ -#define ENFILE 29 /* Too many open files in system */ -#define EBADF 30 /* Bad file number */ -#define EIOCTL 31 /* Invalid or inappropriate ioctl */ -#define EIO 32 /* Input/output error */ -#define ESPIPE 33 /* Illegal seek */ -#define EPIPE 34 /* Broken pipe */ -#define EROFS 35 /* Read-only file system */ -#define ENOSPC 36 /* No space left on device */ -#define EDQUOT 37 /* Disc quota exceeded */ -#define EFBIG 38 /* File too large */ -#define EFTYPE 39 /* Invalid file type or format */ -#define EDOM 40 /* Argument out of range */ -#define ERANGE 41 /* Result out of range */ -#define EILSEQ 42 /* Invalid multibyte character sequence */ -#define ENOTSOCK 43 /* Not a socket */ -#define EISSOCK 44 /* Is a socket */ -#define EISCONN 45 /* Socket is already connected */ -#define ENOTCONN 46 /* Socket is not connected */ -#define ESHUTDOWN 47 /* Socket has been shut down */ -#define EPFNOSUPPORT 48 /* Protocol family not supported */ -#define ESOCKTNOSUPPORT 49 /* Socket type not supported */ -#define EPROTONOSUPPORT 50 /* Protocol not supported */ -#define EPROTOTYPE 51 /* Protocol wrong type for socket */ -#define EAFNOSUPPORT 52 /* Address family not supported by protocol family */ -#define ENOPROTOOPT 53 /* Protocol option not available */ -#define EADDRINUSE 54 /* Address already in use */ -#define EADDRNOTAVAIL 55 /* Cannot assign requested address */ -#define ENETDOWN 56 /* Network is down */ -#define ENETUNREACH 57 /* Network is unreachable */ -#define EHOSTDOWN 58 /* Host is down */ -#define EHOSTUNREACH 59 /* Host is unreachable */ -#define ECONNREFUSED 60 /* Connection refused */ -#define ETIMEDOUT 61 /* Connection timed out */ -#define ECONNRESET 62 /* Connection reset by peer */ -#define EMSGSIZE 63 /* Message too large */ -#define ENOTSUP 64 /* Threads operation not supported */ - +#define ENOMEM 3 /* Out of memory */ +#define EAGAIN 4 /* Operation would block */ +#define EINTR 5 /* Interrupted system call */ +#define EFAULT 6 /* Bad memory reference */ +#define ENAMETOOLONG 7 /* String too long */ +#define EINVAL 8 /* Invalid argument */ +#define EPERM 9 /* Operation not permitted */ +#define EACCES 10 /* Permission denied */ +#define EMPROC 11 /* Too many processes */ +#define ENPROC 12 /* Too many processes in system */ +#define ENOEXEC 13 /* File is not executable */ +#define E2BIG 14 /* Argument list too long */ +#define ESRCH 15 /* No such process */ +#define ECHILD 16 /* No child processes */ +#define ENOTDIR 17 /* Not a directory */ +#define EISDIR 18 /* Is a directory */ +#define ENOENT 19 /* No such file or directory */ +#define ELOOP 20 /* Too many levels of symbolic links */ +#define ENOTEMPTY 21 /* Directory not empty */ +#define EEXIST 22 /* File or object exists */ +#define EMLINK 23 /* Too many hard links */ +#define EXDEV 24 /* Cross-device link */ +#define ENODEV 25 /* No such device */ +#define ENXIO 26 /* Device not available */ +#define EBUSY 27 /* Device or resource busy */ +#define EMFILE 28 /* Too many open files */ +#define ENFILE 29 /* Too many open files in system */ +#define EBADF 30 /* Bad file number */ +#define EIOCTL 31 /* Invalid or inappropriate ioctl */ +#define EIO 32 /* Input/output error */ +#define ESPIPE 33 /* Illegal seek */ +#define EPIPE 34 /* Broken pipe */ +#define EROFS 35 /* Read-only file system */ +#define ENOSPC 36 /* No space left on device */ +#define EDQUOT 37 /* Disc quota exceeded */ +#define EFBIG 38 /* File too large */ +#define EFTYPE 39 /* Invalid file type or format */ +#define EDOM 40 /* Argument out of range */ +#define ERANGE 41 /* Result out of range */ +#define EILSEQ 42 /* Invalid multibyte character sequence */ +#define ENOTSOCK 43 /* Not a socket */ +#define EISSOCK 44 /* Is a socket */ +#define EISCONN 45 /* Socket is already connected */ +#define ENOTCONN 46 /* Socket is not connected */ +#define ESHUTDOWN 47 /* Socket has been shut down */ +#define EPFNOSUPPORT 48 /* Protocol family not supported */ +#define ESOCKTNOSUPPORT 49 /* Socket type not supported */ +#define EPROTONOSUPPORT 50 /* Protocol not supported */ +#define EPROTOTYPE 51 /* Protocol wrong type for socket */ +#define EAFNOSUPPORT 52 /* Address family not supported by protocol family */ +#define ENOPROTOOPT 53 /* Protocol option not available */ +#define EADDRINUSE 54 /* Address already in use */ +#define EADDRNOTAVAIL 55 /* Cannot assign requested address */ +#define ENETDOWN 56 /* Network is down */ +#define ENETUNREACH 57 /* Network is unreachable */ +#define EHOSTDOWN 58 /* Host is down */ +#define EHOSTUNREACH 59 /* Host is unreachable */ +#define ECONNREFUSED 60 /* Connection refused */ +#define ETIMEDOUT 61 /* Connection timed out */ +#define ECONNRESET 62 /* Connection reset by peer */ +#define EMSGSIZE 63 /* Message too large */ +#define ENOTSUP 64 /* Threads operation not supported */ #endif /* _KERN_ERRNO_H_ */ diff --git a/kern/include/kern/fcntl.h b/kern/include/kern/fcntl.h index 4326806..263bfea 100644 --- a/kern/include/kern/fcntl.h +++ b/kern/include/kern/fcntl.h @@ -34,67 +34,65 @@ * Constants for libc's . */ - /* * Important */ /* Flags for open: choose one of these: */ -#define O_RDONLY 0 /* Open for read */ -#define O_WRONLY 1 /* Open for write */ -#define O_RDWR 2 /* Open for read and write */ +#define O_RDONLY 0 /* Open for read */ +#define O_WRONLY 1 /* Open for write */ +#define O_RDWR 2 /* Open for read and write */ /* then or in any of these: */ -#define O_CREAT 4 /* Create file if it doesn't exist */ -#define O_EXCL 8 /* With O_CREAT, fail if file already exists */ -#define O_TRUNC 16 /* Truncate file upon open */ -#define O_APPEND 32 /* All writes happen at EOF (optional feature) */ -#define O_NOCTTY 64 /* Required by POSIX, != 0, but does nothing */ +#define O_CREAT 4 /* Create file if it doesn't exist */ +#define O_EXCL 8 /* With O_CREAT, fail if file already exists */ +#define O_TRUNC 16 /* Truncate file upon open */ +#define O_APPEND 32 /* All writes happen at EOF (optional feature) */ +#define O_NOCTTY 64 /* Required by POSIX, != 0, but does nothing */ /* Additional related definition */ -#define O_ACCMODE 3 /* mask for O_RDONLY/O_WRONLY/O_RDWR */ +#define O_ACCMODE 3 /* mask for O_RDONLY/O_WRONLY/O_RDWR */ /* * Not so important */ /* operation codes for flock() */ -#define LOCK_SH 1 /* shared lock */ -#define LOCK_EX 2 /* exclusive lock */ -#define LOCK_UN 3 /* release the lock */ -#define LOCK_NB 4 /* flag: don't block */ +#define LOCK_SH 1 /* shared lock */ +#define LOCK_EX 2 /* exclusive lock */ +#define LOCK_UN 3 /* release the lock */ +#define LOCK_NB 4 /* flag: don't block */ /* * Mostly pretty useless */ /* fcntl() operations */ -#define F_DUPFD 0 /* like dup() but not quite */ -#define F_GETFD 1 /* get per-handle flags */ -#define F_SETFD 2 /* set per-handle flags */ -#define F_GETFL 3 /* get per-file flags (O_* open flags) */ -#define F_SETFL 4 /* set per-file flags (O_* open flags) */ -#define F_GETOWN 5 /* get process/pgroup for SIGURG and SIGIO */ -#define F_SETOWN 6 /* set process/pgroup for SIGURG and SIGIO */ -#define F_GETLK 7 /* inspect record locks */ -#define F_SETLK 8 /* acquire record locks nonblocking */ -#define F_SETLKW 9 /* acquire record locks and wait */ +#define F_DUPFD 0 /* like dup() but not quite */ +#define F_GETFD 1 /* get per-handle flags */ +#define F_SETFD 2 /* set per-handle flags */ +#define F_GETFL 3 /* get per-file flags (O_* open flags) */ +#define F_SETFL 4 /* set per-file flags (O_* open flags) */ +#define F_GETOWN 5 /* get process/pgroup for SIGURG and SIGIO */ +#define F_SETOWN 6 /* set process/pgroup for SIGURG and SIGIO */ +#define F_GETLK 7 /* inspect record locks */ +#define F_SETLK 8 /* acquire record locks nonblocking */ +#define F_SETLKW 9 /* acquire record locks and wait */ /* flag for F_GETFD and F_SETFD */ -#define FD_CLOEXEC 1 /* close-on-exec */ +#define FD_CLOEXEC 1 /* close-on-exec */ /* modes for fcntl (F_GETLK/SETLK) locking */ -#define F_RDLCK 0 /* shared lock */ -#define F_WRLCK 1 /* exclusive lock */ -#define F_UNLCK 2 /* unlock */ +#define F_RDLCK 0 /* shared lock */ +#define F_WRLCK 1 /* exclusive lock */ +#define F_UNLCK 2 /* unlock */ /* struct for fcntl (F_GETLK/SETLK) locking */ struct flock { - off_t l_start; /* place in file */ - int l_whence; /* SEEK_SET, SEEK_CUR, or SEEK_END */ - int l_type; /* F_RDLCK or F_WRLCK */ - off_t l_len; /* length of locked region */ - pid_t l_pid; /* process that holds the lock */ + off_t l_start; /* place in file */ + int l_whence; /* SEEK_SET, SEEK_CUR, or SEEK_END */ + int l_type; /* F_RDLCK or F_WRLCK */ + off_t l_len; /* length of locked region */ + pid_t l_pid; /* process that holds the lock */ }; - #endif /* _KERN_FCNTL_H_ */ diff --git a/kern/include/kern/iovec.h b/kern/include/kern/iovec.h index 3436557..a2b3b23 100644 --- a/kern/include/kern/iovec.h +++ b/kern/include/kern/iovec.h @@ -36,33 +36,33 @@ */ struct iovec { - /* - * For maximum type safety, when in the kernel, distinguish - * user pointers from kernel pointers. - * - * (A pointer is a user pointer if it *came* from userspace, - * not necessarily if it *points* to userspace. If a system - * call passes 0xdeadbeef, it points to the kernel, but it's - * still a user pointer.) - * - * In userspace, there are only user pointers; also, the name - * iov_base is defined by POSIX. - * - * Note that to work properly (without extra unwanted fiddling - * around) this scheme requires that void* and userptr_t have - * the same machine representation. Machines where this isn't - * true are theoretically possible under the C standard, but - * do not exist in practice. - */ + /* + * For maximum type safety, when in the kernel, distinguish + * user pointers from kernel pointers. + * + * (A pointer is a user pointer if it *came* from userspace, + * not necessarily if it *points* to userspace. If a system + * call passes 0xdeadbeef, it points to the kernel, but it's + * still a user pointer.) + * + * In userspace, there are only user pointers; also, the name + * iov_base is defined by POSIX. + * + * Note that to work properly (without extra unwanted fiddling + * around) this scheme requires that void* and userptr_t have + * the same machine representation. Machines where this isn't + * true are theoretically possible under the C standard, but + * do not exist in practice. + */ #ifdef _KERNEL - union { - userptr_t iov_ubase; /* user-supplied pointer */ - void *iov_kbase; /* kernel-supplied pointer */ - }; + union { + userptr_t iov_ubase; /* user-supplied pointer */ + void *iov_kbase; /* kernel-supplied pointer */ + }; #else - void *iov_base; /* user-supplied pointer */ + void *iov_base; /* user-supplied pointer */ #endif - size_t iov_len; /* Length of data */ + size_t iov_len; /* Length of data */ }; #endif /* _KERN_IOVEC_H_ */ diff --git a/kern/include/kern/limits.h b/kern/include/kern/limits.h index 8699b80..ae33c62 100644 --- a/kern/include/kern/limits.h +++ b/kern/include/kern/limits.h @@ -47,7 +47,6 @@ * implementation. */ - /* * Important, both as part of the system call API and for system behavior. * @@ -57,14 +56,13 @@ */ /* Longest filename (without directory) not including null terminator */ -#define __NAME_MAX 255 +#define __NAME_MAX 255 /* Longest full path name */ -#define __PATH_MAX 1024 +#define __PATH_MAX 1024 /* Max bytes for an exec function (should be at least 16K) */ -#define __ARG_MAX (64 * 1024) - +#define __ARG_MAX (64 * 1024) /* * Important for system behavior, but not a big part of the API. @@ -74,17 +72,16 @@ */ /* Min value for a process ID (that can be assigned to a user process) */ -#define __PID_MIN 2 +#define __PID_MIN 2 /* Max value for a process ID (change this to match your implementation) */ -#define __PID_MAX 32767 +#define __PID_MAX 32767 /* Max open files per process */ -#define __OPEN_MAX 128 +#define __OPEN_MAX 128 /* Max bytes for atomic pipe I/O -- see description in the pipe() man page */ -#define __PIPE_BUF 512 - +#define __PIPE_BUF 512 /* * Not so important parts of the API. (Especially in OS/161 where we @@ -92,18 +89,16 @@ */ /* Max number of supplemental group IDs in process credentials */ -#define __NGROUPS_MAX 32 +#define __NGROUPS_MAX 32 /* Max login name size (for setlogin/getlogin), incl. null */ #define __LOGIN_NAME_MAX 17 - /* * Not very important at all. */ /* Max number of iovec structures at once for readv/writev/preadv/pwritev */ -#define __IOV_MAX 1024 - +#define __IOV_MAX 1024 #endif /* _KERN_LIMITS_H_ */ diff --git a/kern/include/kern/reboot.h b/kern/include/kern/reboot.h index 6130466..1029520 100644 --- a/kern/include/kern/reboot.h +++ b/kern/include/kern/reboot.h @@ -35,11 +35,9 @@ * (Not all that important.) */ - /* Codes for reboot */ -#define RB_REBOOT 0 /* Reboot system */ -#define RB_HALT 1 /* Halt system and do not reboot */ -#define RB_POWEROFF 2 /* Halt system and power off */ - +#define RB_REBOOT 0 /* Reboot system */ +#define RB_HALT 1 /* Halt system and do not reboot */ +#define RB_POWEROFF 2 /* Halt system and power off */ #endif /* _KERN_REBOOT_H_ */ diff --git a/kern/include/kern/resource.h b/kern/include/kern/resource.h index bec2c3b..4301890 100644 --- a/kern/include/kern/resource.h +++ b/kern/include/kern/resource.h @@ -36,57 +36,56 @@ * Not very important. */ - /* priorities for setpriority() */ -#define PRIO_MIN (-20) -#define PRIO_MAX 20 +#define PRIO_MIN (-20) +#define PRIO_MAX 20 /* "which" codes for setpriority() */ -#define PRIO_PROCESS 0 -#define PRIO_PGRP 1 -#define PRIO_USER 2 +#define PRIO_PROCESS 0 +#define PRIO_PGRP 1 +#define PRIO_USER 2 /* flags for getrusage() */ -#define RUSAGE_SELF 0 -#define RUSAGE_CHILDREN (-1) +#define RUSAGE_SELF 0 +#define RUSAGE_CHILDREN (-1) struct rusage { - struct timeval ru_utime; - struct timeval ru_stime; - __size_t ru_maxrss; /* maximum RSS during lifespan (kb) */ - __counter_t ru_ixrss; /* text memory usage (kb-ticks) */ - __counter_t ru_idrss; /* data memory usage (kb-ticks) */ - __counter_t ru_isrss; /* stack memory usage (kb-ticks) */ - __counter_t ru_minflt; /* minor VM faults (count) */ - __counter_t ru_majflt; /* major VM faults (count) */ - __counter_t ru_nswap; /* whole-process swaps (count) */ - __counter_t ru_inblock; /* file blocks read (count) */ - __counter_t ru_oublock; /* file blocks written (count) */ - __counter_t ru_msgrcv; /* socket/pipe packets rcv'd (count) */ - __counter_t ru_msgsnd; /* socket/pipe packets sent (count) */ - __counter_t ru_nsignals; /* signals delivered (count) */ - __counter_t ru_nvcsw; /* voluntary context switches (count)*/ - __counter_t ru_nivcsw; /* involuntary ditto (count) */ + struct timeval ru_utime; + struct timeval ru_stime; + __size_t ru_maxrss; /* maximum RSS during lifespan (kb) */ + __counter_t ru_ixrss; /* text memory usage (kb-ticks) */ + __counter_t ru_idrss; /* data memory usage (kb-ticks) */ + __counter_t ru_isrss; /* stack memory usage (kb-ticks) */ + __counter_t ru_minflt; /* minor VM faults (count) */ + __counter_t ru_majflt; /* major VM faults (count) */ + __counter_t ru_nswap; /* whole-process swaps (count) */ + __counter_t ru_inblock; /* file blocks read (count) */ + __counter_t ru_oublock; /* file blocks written (count) */ + __counter_t ru_msgrcv; /* socket/pipe packets rcv'd (count) */ + __counter_t ru_msgsnd; /* socket/pipe packets sent (count) */ + __counter_t ru_nsignals; /* signals delivered (count) */ + __counter_t ru_nvcsw; /* voluntary context switches (count)*/ + __counter_t ru_nivcsw; /* involuntary ditto (count) */ }; /* limit codes for getrusage/setrusage */ -#define RLIMIT_NPROC 0 /* max procs per user (count) */ -#define RLIMIT_NOFILE 1 /* max open files per proc (count) */ -#define RLIMIT_CPU 2 /* cpu usage (seconds) */ -#define RLIMIT_DATA 3 /* max .data/sbrk size (bytes) */ -#define RLIMIT_STACK 4 /* max stack size (bytes) */ -#define RLIMIT_MEMLOCK 5 /* max locked memory region (bytes) */ -#define RLIMIT_RSS 6 /* max RSS (bytes) */ -#define RLIMIT_CORE 7 /* core file size (bytes) */ -#define RLIMIT_FSIZE 8 /* max file size (bytes) */ -#define __RLIMIT_NUM 9 /* number of limits */ +#define RLIMIT_NPROC 0 /* max procs per user (count) */ +#define RLIMIT_NOFILE 1 /* max open files per proc (count) */ +#define RLIMIT_CPU 2 /* cpu usage (seconds) */ +#define RLIMIT_DATA 3 /* max .data/sbrk size (bytes) */ +#define RLIMIT_STACK 4 /* max stack size (bytes) */ +#define RLIMIT_MEMLOCK 5 /* max locked memory region (bytes) */ +#define RLIMIT_RSS 6 /* max RSS (bytes) */ +#define RLIMIT_CORE 7 /* core file size (bytes) */ +#define RLIMIT_FSIZE 8 /* max file size (bytes) */ +#define __RLIMIT_NUM 9 /* number of limits */ struct rlimit { - __rlim_t rlim_cur; /* soft limit */ - __rlim_t rlim_max; /* hard limit */ + __rlim_t rlim_cur; /* soft limit */ + __rlim_t rlim_max; /* hard limit */ }; -#define RLIM_INFINITY (~(__rlim_t)0) +#define RLIM_INFINITY (~(__rlim_t)0) #endif /* _KERN_RESOURCE_H_ */ diff --git a/kern/include/kern/seek.h b/kern/include/kern/seek.h index cf1cfe6..711d1ab 100644 --- a/kern/include/kern/seek.h +++ b/kern/include/kern/seek.h @@ -39,9 +39,8 @@ * really not recommended. */ -#define SEEK_SET 0 /* Seek relative to beginning of file */ -#define SEEK_CUR 1 /* Seek relative to current position in file */ -#define SEEK_END 2 /* Seek relative to end of file */ - +#define SEEK_SET 0 /* Seek relative to beginning of file */ +#define SEEK_CUR 1 /* Seek relative to current position in file */ +#define SEEK_END 2 /* Seek relative to end of file */ #endif /* _KERN_SEEK_H_ */ diff --git a/kern/include/kern/sfs.h b/kern/include/kern/sfs.h index d151133..4bbc8f2 100644 --- a/kern/include/kern/sfs.h +++ b/kern/include/kern/sfs.h @@ -30,72 +30,70 @@ #ifndef _KERN_SFS_H_ #define _KERN_SFS_H_ - /* * SFS definitions visible to userspace. This covers the on-disk format * and is used by tools that work on SFS volumes, such as mksfs. */ -#define SFS_MAGIC 0xabadf001 /* magic number identifying us */ -#define SFS_BLOCKSIZE 512 /* size of our blocks */ -#define SFS_VOLNAME_SIZE 32 /* max length of volume name */ -#define SFS_NDIRECT 15 /* # of direct blocks in inode */ -#define SFS_NINDIRECT 1 /* # of indirect blocks in inode */ -#define SFS_NDINDIRECT 0 /* # of 2x indirect blocks in inode */ -#define SFS_NTINDIRECT 0 /* # of 3x indirect blocks in inode */ -#define SFS_DBPERIDB 128 /* # direct blks per indirect blk */ -#define SFS_NAMELEN 60 /* max length of filename */ -#define SFS_SUPER_BLOCK 0 /* block the superblock lives in */ -#define SFS_FREEMAP_START 2 /* 1st block of the freemap */ -#define SFS_NOINO 0 /* inode # for free dir entry */ -#define SFS_ROOTDIR_INO 1 /* loc'n of the root dir inode */ +#define SFS_MAGIC 0xabadf001 /* magic number identifying us */ +#define SFS_BLOCKSIZE 512 /* size of our blocks */ +#define SFS_VOLNAME_SIZE 32 /* max length of volume name */ +#define SFS_NDIRECT 15 /* # of direct blocks in inode */ +#define SFS_NINDIRECT 1 /* # of indirect blocks in inode */ +#define SFS_NDINDIRECT 0 /* # of 2x indirect blocks in inode */ +#define SFS_NTINDIRECT 0 /* # of 3x indirect blocks in inode */ +#define SFS_DBPERIDB 128 /* # direct blks per indirect blk */ +#define SFS_NAMELEN 60 /* max length of filename */ +#define SFS_SUPER_BLOCK 0 /* block the superblock lives in */ +#define SFS_FREEMAP_START 2 /* 1st block of the freemap */ +#define SFS_NOINO 0 /* inode # for free dir entry */ +#define SFS_ROOTDIR_INO 1 /* loc'n of the root dir inode */ /* Number of bits in a block */ #define SFS_BITSPERBLOCK (SFS_BLOCKSIZE * CHAR_BIT) /* Utility macro */ -#define SFS_ROUNDUP(a,b) ((((a)+(b)-1)/(b))*b) +#define SFS_ROUNDUP(a, b) ((((a) + (b) - 1) / (b)) * b) /* Size of free block bitmap (in bits) */ #define SFS_FREEMAPBITS(nblocks) SFS_ROUNDUP(nblocks, SFS_BITSPERBLOCK) /* Size of free block bitmap (in blocks) */ -#define SFS_FREEMAPBLOCKS(nblocks) (SFS_FREEMAPBITS(nblocks)/SFS_BITSPERBLOCK) +#define SFS_FREEMAPBLOCKS(nblocks) (SFS_FREEMAPBITS(nblocks) / SFS_BITSPERBLOCK) /* File types for sfi_type */ -#define SFS_TYPE_INVAL 0 /* Should not appear on disk */ -#define SFS_TYPE_FILE 1 -#define SFS_TYPE_DIR 2 +#define SFS_TYPE_INVAL 0 /* Should not appear on disk */ +#define SFS_TYPE_FILE 1 +#define SFS_TYPE_DIR 2 /* * On-disk superblock */ struct sfs_superblock { - uint32_t sb_magic; /* Magic number; should be SFS_MAGIC */ - uint32_t sb_nblocks; /* Number of blocks in fs */ - char sb_volname[SFS_VOLNAME_SIZE]; /* Name of this volume */ - uint32_t reserved[118]; /* unused, set to 0 */ + uint32_t sb_magic; /* Magic number; should be SFS_MAGIC */ + uint32_t sb_nblocks; /* Number of blocks in fs */ + char sb_volname[SFS_VOLNAME_SIZE]; /* Name of this volume */ + uint32_t reserved[118]; /* unused, set to 0 */ }; /* * On-disk inode */ struct sfs_dinode { - uint32_t sfi_size; /* Size of this file (bytes) */ - uint16_t sfi_type; /* One of SFS_TYPE_* above */ - uint16_t sfi_linkcount; /* # hard links to this file */ - uint32_t sfi_direct[SFS_NDIRECT]; /* Direct blocks */ - uint32_t sfi_indirect; /* Indirect block */ - uint32_t sfi_waste[128-3-SFS_NDIRECT]; /* unused space, set to 0 */ + uint32_t sfi_size; /* Size of this file (bytes) */ + uint16_t sfi_type; /* One of SFS_TYPE_* above */ + uint16_t sfi_linkcount; /* # hard links to this file */ + uint32_t sfi_direct[SFS_NDIRECT]; /* Direct blocks */ + uint32_t sfi_indirect; /* Indirect block */ + uint32_t sfi_waste[128 - 3 - SFS_NDIRECT]; /* unused space, set to 0 */ }; /* * On-disk directory entry */ struct sfs_direntry { - uint32_t sfd_ino; /* Inode number */ - char sfd_name[SFS_NAMELEN]; /* Filename */ + uint32_t sfd_ino; /* Inode number */ + char sfd_name[SFS_NAMELEN]; /* Filename */ }; - #endif /* _KERN_SFS_H_ */ diff --git a/kern/include/kern/signal.h b/kern/include/kern/signal.h index 4036bb3..cc78e61 100644 --- a/kern/include/kern/signal.h +++ b/kern/include/kern/signal.h @@ -41,7 +41,6 @@ * Machine-independent definitions for signals. */ - /* * The signals. * @@ -53,68 +52,67 @@ * ways. It is gross. */ -#define SIGHUP 1 /* Hangup */ -#define SIGINT 2 /* Interrupt (^C) */ -#define SIGQUIT 3 /* Quit (typically ^\) */ -#define SIGILL 4 /* Illegal instruction */ -#define SIGTRAP 5 /* Breakpoint trap */ -#define SIGABRT 6 /* abort() call */ -#define SIGEMT 7 /* Emulator trap */ -#define SIGFPE 8 /* Floating point exception */ -#define SIGKILL 9 /* Hard kill (unblockable) */ -#define SIGBUS 10 /* Bus error, typically bad pointer alignment*/ -#define SIGSEGV 11 /* Segmentation fault */ -#define SIGSYS 12 /* Bad system call */ -#define SIGPIPE 13 /* Broken pipe */ -#define SIGALRM 14 /* alarm() expired */ -#define SIGTERM 15 /* Termination requested (default kill) */ -#define SIGURG 16 /* Urgent data on socket */ -#define SIGSTOP 17 /* Hard process stop (unblockable) */ -#define SIGTSTP 18 /* Terminal stop (^Z) */ -#define SIGCONT 19 /* Time to continue after stop */ -#define SIGCHLD 20 /* Child process exited */ -#define SIGTTIN 21 /* Stop on tty read while in background */ -#define SIGTTOU 22 /* Stop on tty write while in background */ -#define SIGIO 23 /* Nonblocking or async I/O is now ready */ -#define SIGXCPU 24 /* CPU time resource limit exceeded */ -#define SIGXFSZ 25 /* File size resource limit exceeded */ -#define SIGVTALRM 26 /* Like SIGALRM but in virtual time */ -#define SIGPROF 27 /* Profiling timer */ -#define SIGWINCH 28 /* Window size change on tty */ -#define SIGINFO 29 /* Information request (typically ^T) */ -#define SIGUSR1 20 /* Application-defined */ -#define SIGUSR2 31 /* Application-defined */ -#define SIGPWR 32 /* Power failure */ -#define _NSIG 32 - +#define SIGHUP 1 /* Hangup */ +#define SIGINT 2 /* Interrupt (^C) */ +#define SIGQUIT 3 /* Quit (typically ^\) */ +#define SIGILL 4 /* Illegal instruction */ +#define SIGTRAP 5 /* Breakpoint trap */ +#define SIGABRT 6 /* abort() call */ +#define SIGEMT 7 /* Emulator trap */ +#define SIGFPE 8 /* Floating point exception */ +#define SIGKILL 9 /* Hard kill (unblockable) */ +#define SIGBUS 10 /* Bus error, typically bad pointer alignment*/ +#define SIGSEGV 11 /* Segmentation fault */ +#define SIGSYS 12 /* Bad system call */ +#define SIGPIPE 13 /* Broken pipe */ +#define SIGALRM 14 /* alarm() expired */ +#define SIGTERM 15 /* Termination requested (default kill) */ +#define SIGURG 16 /* Urgent data on socket */ +#define SIGSTOP 17 /* Hard process stop (unblockable) */ +#define SIGTSTP 18 /* Terminal stop (^Z) */ +#define SIGCONT 19 /* Time to continue after stop */ +#define SIGCHLD 20 /* Child process exited */ +#define SIGTTIN 21 /* Stop on tty read while in background */ +#define SIGTTOU 22 /* Stop on tty write while in background */ +#define SIGIO 23 /* Nonblocking or async I/O is now ready */ +#define SIGXCPU 24 /* CPU time resource limit exceeded */ +#define SIGXFSZ 25 /* File size resource limit exceeded */ +#define SIGVTALRM 26 /* Like SIGALRM but in virtual time */ +#define SIGPROF 27 /* Profiling timer */ +#define SIGWINCH 28 /* Window size change on tty */ +#define SIGINFO 29 /* Information request (typically ^T) */ +#define SIGUSR1 20 /* Application-defined */ +#define SIGUSR2 31 /* Application-defined */ +#define SIGPWR 32 /* Power failure */ +#define _NSIG 32 /* Type for a set of signals; used by e.g. sigprocmask(). */ typedef __u32 sigset_t; /* flags for sigaction.sa_flags */ -#define SA_ONSTACK 1 /* Use sigaltstack() stack. */ -#define SA_RESTART 2 /* Restart syscall instead of interrupting. */ -#define SA_RESETHAND 4 /* Clear handler after one usage. */ +#define SA_ONSTACK 1 /* Use sigaltstack() stack. */ +#define SA_RESTART 2 /* Restart syscall instead of interrupting. */ +#define SA_RESETHAND 4 /* Clear handler after one usage. */ /* codes for sigprocmask() */ -#define SIG_BLOCK 1 /* Block selected signals. */ -#define SIG_UNBLOCK 2 /* Unblock selected signals. */ -#define SIG_SETMASK 3 /* Set mask to the selected signals. */ +#define SIG_BLOCK 1 /* Block selected signals. */ +#define SIG_UNBLOCK 2 /* Unblock selected signals. */ +#define SIG_SETMASK 3 /* Set mask to the selected signals. */ /* Type for a signal handler function. */ typedef void (*__sigfunc)(int); /* Magic values for signal handlers. */ -#define SIG_DFL ((__sigfunc) 0) /* Default behavior. */ -#define SIG_IGN ((__sigfunc) 1) /* Ignore the signal. */ +#define SIG_DFL ((__sigfunc)0) /* Default behavior. */ +#define SIG_IGN ((__sigfunc)1) /* Ignore the signal. */ /* * Struct for sigaction(). */ struct sigaction { - __sigfunc sa_handler; - sigset_t sa_mask; - unsigned sa_flags; + __sigfunc sa_handler; + sigset_t sa_mask; + unsigned sa_flags; }; /* @@ -122,10 +120,9 @@ struct sigaction { * (not very important) */ struct sigaltstack { - void *ss_sp; - size_t ss_size; - unsigned ss_flags; + void *ss_sp; + size_t ss_size; + unsigned ss_flags; }; - #endif /* _KERN_SIGNAL_H_ */ diff --git a/kern/include/kern/socket.h b/kern/include/kern/socket.h index 4796f9a..badc214 100644 --- a/kern/include/kern/socket.h +++ b/kern/include/kern/socket.h @@ -34,27 +34,26 @@ * Socket-related definitions, for . */ - /* * Important */ /* Socket types that we (might) support. */ -#define SOCK_STREAM 1 /* stream */ -#define SOCK_DGRAM 2 /* packet */ -#define SOCK_RAW 3 /* raw packet */ +#define SOCK_STREAM 1 /* stream */ +#define SOCK_DGRAM 2 /* packet */ +#define SOCK_RAW 3 /* raw packet */ /* Address families that we (might) support. */ -#define AF_UNSPEC 0 -#define AF_UNIX 1 -#define AF_INET 2 -#define AF_INET6 3 +#define AF_UNSPEC 0 +#define AF_UNIX 1 +#define AF_INET 2 +#define AF_INET6 3 /* Protocol families. Pointless layer of indirection in the standard API. */ -#define PF_UNSPEC AF_UNSPEC -#define PF_UNIX AF_UNIX -#define PF_INET AF_INET -#define PF_INET6 AF_INET6 +#define PF_UNSPEC AF_UNSPEC +#define PF_UNIX AF_UNIX +#define PF_INET AF_INET +#define PF_INET6 AF_INET6 /* * Socket address structures. Socket addresses are polymorphic, and @@ -71,22 +70,21 @@ */ struct sockaddr { - __u8 sa_len; - __u8 sa_family; + __u8 sa_len; + __u8 sa_family; }; -#define _SS_SIZE 128 +#define _SS_SIZE 128 struct sockaddr_storage { - __u8 ss_len; - __u8 ss_family; - __u8 __ss_pad1; - __u8 __ss_pad2; - __u32 __ss_pad3; - __u64 __ss_pad4; - char __ss_pad5[_SS_SIZE - sizeof(__u64) - sizeof(__u32) - 4*sizeof(__u8)]; + __u8 ss_len; + __u8 ss_family; + __u8 __ss_pad1; + __u8 __ss_pad2; + __u32 __ss_pad3; + __u64 __ss_pad4; + char __ss_pad5[_SS_SIZE - sizeof(__u64) - sizeof(__u32) - 4 * sizeof(__u8)]; }; - /* * Not very important. */ @@ -96,21 +94,20 @@ struct sockaddr_storage { */ struct msghdr { - void *msg_name; /* really sockaddr; address, or null */ - socklen_t msg_namelen; /* size of msg_name object, or 0 */ - struct iovec *msg_iov; /* I/O buffers */ - int msg_iovlen; /* number of iovecs */ - void *msg_control; /* auxiliary data area, or null */ - socklen_t msg_controllen; /* size of msg_control area */ - int msg_flags; /* flags */ + void *msg_name; /* really sockaddr; address, or null */ + socklen_t msg_namelen; /* size of msg_name object, or 0 */ + struct iovec *msg_iov; /* I/O buffers */ + int msg_iovlen; /* number of iovecs */ + void *msg_control; /* auxiliary data area, or null */ + socklen_t msg_controllen; /* size of msg_control area */ + int msg_flags; /* flags */ }; struct cmsghdr { - socklen_t cmsg_len; /* length of control data, including header */ - int cmsg_level; /* protocol layer item originates from */ - int cmsg_type; /* protocol-specific message type */ - /* char cmsg_data[];*/ /* data follows the header */ + socklen_t cmsg_len; /* length of control data, including header */ + int cmsg_level; /* protocol layer item originates from */ + int cmsg_type; /* protocol-specific message type */ + /* char cmsg_data[];*/ /* data follows the header */ }; - #endif /* _KERN_SOCKET_H_ */ diff --git a/kern/include/kern/stat.h b/kern/include/kern/stat.h index 0f6cc54..e5dcfe4 100644 --- a/kern/include/kern/stat.h +++ b/kern/include/kern/stat.h @@ -40,32 +40,32 @@ * The file types are in kern/stattypes.h. */ struct stat { - /* Essential fields */ - off_t st_size; /* file size in bytes */ - mode_t st_mode; /* file type and protection mode */ - nlink_t st_nlink; /* number of hard links */ - blkcnt_t st_blocks; /* number of blocks file is using */ + /* Essential fields */ + off_t st_size; /* file size in bytes */ + mode_t st_mode; /* file type and protection mode */ + nlink_t st_nlink; /* number of hard links */ + blkcnt_t st_blocks; /* number of blocks file is using */ - /* Identity */ - dev_t st_dev; /* device object lives on */ - ino_t st_ino; /* inode number (serial number) of object */ - dev_t st_rdev; /* device object is (if a device) */ + /* Identity */ + dev_t st_dev; /* device object lives on */ + ino_t st_ino; /* inode number (serial number) of object */ + dev_t st_rdev; /* device object is (if a device) */ - /* Timestamps */ - time_t st_atime; /* last access time: seconds */ - time_t st_ctime; /* inode change time: seconds */ - time_t st_mtime; /* modification time: seconds */ - __u32 st_atimensec; /* last access time: nanoseconds */ - __u32 st_ctimensec; /* inode change time: nanoseconds */ - __u32 st_mtimensec; /* modification time: nanoseconds */ + /* Timestamps */ + time_t st_atime; /* last access time: seconds */ + time_t st_ctime; /* inode change time: seconds */ + time_t st_mtime; /* modification time: seconds */ + __u32 st_atimensec; /* last access time: nanoseconds */ + __u32 st_ctimensec; /* inode change time: nanoseconds */ + __u32 st_mtimensec; /* modification time: nanoseconds */ - /* Permissions (also st_mode) */ - uid_t st_uid; /* owner */ - gid_t st_gid; /* group */ + /* Permissions (also st_mode) */ + uid_t st_uid; /* owner */ + gid_t st_gid; /* group */ - /* Other */ - __u32 st_gen; /* file generation number (root only) */ - blksize_t st_blksize; /* recommended I/O block size */ + /* Other */ + __u32 st_gen; /* file generation number (root only) */ + blksize_t st_blksize; /* recommended I/O block size */ }; #endif /* _KERN_STAT_H_ */ diff --git a/kern/include/kern/stattypes.h b/kern/include/kern/stattypes.h index 1192d71..fcae5cf 100644 --- a/kern/include/kern/stattypes.h +++ b/kern/include/kern/stattypes.h @@ -42,14 +42,13 @@ * (kernel) or (userland). */ -#define _S_IFMT 070000 /* mask for type of file */ -#define _S_IFREG 010000 /* ordinary regular file */ -#define _S_IFDIR 020000 /* directory */ -#define _S_IFLNK 030000 /* symbolic link */ -#define _S_IFIFO 040000 /* pipe or named pipe */ -#define _S_IFSOCK 050000 /* socket */ -#define _S_IFCHR 060000 /* character device */ -#define _S_IFBLK 070000 /* block device */ - +#define _S_IFMT 070000 /* mask for type of file */ +#define _S_IFREG 010000 /* ordinary regular file */ +#define _S_IFDIR 020000 /* directory */ +#define _S_IFLNK 030000 /* symbolic link */ +#define _S_IFIFO 040000 /* pipe or named pipe */ +#define _S_IFSOCK 050000 /* socket */ +#define _S_IFCHR 060000 /* character device */ +#define _S_IFBLK 070000 /* block device */ #endif /* _KERN_STATTYPES_H_ */ diff --git a/kern/include/kern/syscall.h b/kern/include/kern/syscall.h index c9b8b2b..53a2b45 100644 --- a/kern/include/kern/syscall.h +++ b/kern/include/kern/syscall.h @@ -47,157 +47,155 @@ /*CALLBEGIN*/ // -- Process-related -- -#define SYS_fork 0 -#define SYS_vfork 1 -#define SYS_execv 2 -#define SYS__exit 3 -#define SYS_waitpid 4 -#define SYS_getpid 5 -#define SYS_getppid 6 +#define SYS_fork 0 +#define SYS_vfork 1 +#define SYS_execv 2 +#define SYS__exit 3 +#define SYS_waitpid 4 +#define SYS_getpid 5 +#define SYS_getppid 6 // (virtual memory) -#define SYS_sbrk 7 -#define SYS_mmap 8 -#define SYS_munmap 9 -#define SYS_mprotect 10 -//#define SYS_madvise 11 -//#define SYS_mincore 12 -//#define SYS_mlock 13 -//#define SYS_munlock 14 -//#define SYS_munlockall 15 -//#define SYS_minherit 16 -// (security/credentials) -#define SYS_umask 17 -#define SYS_issetugid 18 -#define SYS_getresuid 19 -#define SYS_setresuid 20 -#define SYS_getresgid 21 -#define SYS_setresgid 22 -#define SYS_getgroups 23 -#define SYS_setgroups 24 -#define SYS___getlogin 25 -#define SYS___setlogin 26 +#define SYS_sbrk 7 +#define SYS_mmap 8 +#define SYS_munmap 9 +#define SYS_mprotect 10 +// #define SYS_madvise 11 +// #define SYS_mincore 12 +// #define SYS_mlock 13 +// #define SYS_munlock 14 +// #define SYS_munlockall 15 +// #define SYS_minherit 16 +// (security/credentials) +#define SYS_umask 17 +#define SYS_issetugid 18 +#define SYS_getresuid 19 +#define SYS_setresuid 20 +#define SYS_getresgid 21 +#define SYS_setresgid 22 +#define SYS_getgroups 23 +#define SYS_setgroups 24 +#define SYS___getlogin 25 +#define SYS___setlogin 26 // (signals) -#define SYS_kill 27 -#define SYS_sigaction 28 -#define SYS_sigpending 29 -#define SYS_sigprocmask 30 -#define SYS_sigsuspend 31 -#define SYS_sigreturn 32 -//#define SYS_sigaltstack 33 -// (resource tracking and usage) -//#define SYS_wait4 34 -//#define SYS_getrusage 35 -// (resource limits) -//#define SYS_getrlimit 36 -//#define SYS_setrlimit 37 -// (process priority control) -//#define SYS_getpriority 38 -//#define SYS_setpriority 39 -// (process groups, sessions, and job control) -//#define SYS_getpgid 40 -//#define SYS_setpgid 41 -//#define SYS_getsid 42 -//#define SYS_setsid 43 -// (userlevel debugging) -//#define SYS_ptrace 44 +#define SYS_kill 27 +#define SYS_sigaction 28 +#define SYS_sigpending 29 +#define SYS_sigprocmask 30 +#define SYS_sigsuspend 31 +#define SYS_sigreturn 32 +// #define SYS_sigaltstack 33 +// (resource tracking and usage) +// #define SYS_wait4 34 +// #define SYS_getrusage 35 +// (resource limits) +// #define SYS_getrlimit 36 +// #define SYS_setrlimit 37 +// (process priority control) +// #define SYS_getpriority 38 +// #define SYS_setpriority 39 +// (process groups, sessions, and job control) +// #define SYS_getpgid 40 +// #define SYS_setpgid 41 +// #define SYS_getsid 42 +// #define SYS_setsid 43 +// (userlevel debugging) +// #define SYS_ptrace 44 // -- File-handle-related -- -#define SYS_open 45 -#define SYS_pipe 46 -#define SYS_dup 47 -#define SYS_dup2 48 -#define SYS_close 49 -#define SYS_read 50 -#define SYS_pread 51 -//#define SYS_readv 52 -//#define SYS_preadv 53 -#define SYS_getdirentry 54 -#define SYS_write 55 -#define SYS_pwrite 56 -//#define SYS_writev 57 -//#define SYS_pwritev 58 -#define SYS_lseek 59 -#define SYS_flock 60 -#define SYS_ftruncate 61 -#define SYS_fsync 62 -#define SYS_fcntl 63 -#define SYS_ioctl 64 -#define SYS_select 65 -#define SYS_poll 66 +#define SYS_open 45 +#define SYS_pipe 46 +#define SYS_dup 47 +#define SYS_dup2 48 +#define SYS_close 49 +#define SYS_read 50 +#define SYS_pread 51 +// #define SYS_readv 52 +// #define SYS_preadv 53 +#define SYS_getdirentry 54 +#define SYS_write 55 +#define SYS_pwrite 56 +// #define SYS_writev 57 +// #define SYS_pwritev 58 +#define SYS_lseek 59 +#define SYS_flock 60 +#define SYS_ftruncate 61 +#define SYS_fsync 62 +#define SYS_fcntl 63 +#define SYS_ioctl 64 +#define SYS_select 65 +#define SYS_poll 66 // -- Pathname-related -- -#define SYS_link 67 -#define SYS_remove 68 -#define SYS_mkdir 69 -#define SYS_rmdir 70 -#define SYS_mkfifo 71 -#define SYS_rename 72 -#define SYS_access 73 +#define SYS_link 67 +#define SYS_remove 68 +#define SYS_mkdir 69 +#define SYS_rmdir 70 +#define SYS_mkfifo 71 +#define SYS_rename 72 +#define SYS_access 73 // (current directory) -#define SYS_chdir 74 -#define SYS_fchdir 75 -#define SYS___getcwd 76 +#define SYS_chdir 74 +#define SYS_fchdir 75 +#define SYS___getcwd 76 // (symbolic links) -#define SYS_symlink 77 -#define SYS_readlink 78 +#define SYS_symlink 77 +#define SYS_readlink 78 // (mount) -#define SYS_mount 79 -#define SYS_unmount 80 - +#define SYS_mount 79 +#define SYS_unmount 80 // -- Any-file-related -- -#define SYS_stat 81 -#define SYS_fstat 82 -#define SYS_lstat 83 +#define SYS_stat 81 +#define SYS_fstat 82 +#define SYS_lstat 83 // (timestamps) -#define SYS_utimes 84 -#define SYS_futimes 85 -#define SYS_lutimes 86 +#define SYS_utimes 84 +#define SYS_futimes 85 +#define SYS_lutimes 86 // (security/permissions) -#define SYS_chmod 87 -#define SYS_chown 88 -#define SYS_fchmod 89 -#define SYS_fchown 90 -#define SYS_lchmod 91 -#define SYS_lchown 92 +#define SYS_chmod 87 +#define SYS_chown 88 +#define SYS_fchmod 89 +#define SYS_fchown 90 +#define SYS_lchmod 91 +#define SYS_lchown 92 // (file system info) -//#define SYS_statfs 93 -//#define SYS_fstatfs 94 -//#define SYS_getfsstat 95 +// #define SYS_statfs 93 +// #define SYS_fstatfs 94 +// #define SYS_getfsstat 95 // (POSIX dynamic system limits stuff) -//#define SYS_pathconf 96 -//#define SYS_fpathconf 97 +// #define SYS_pathconf 96 +// #define SYS_fpathconf 97 // -- Sockets and networking -- -#define SYS_socket 98 -#define SYS_bind 99 -#define SYS_connect 100 -#define SYS_listen 101 -#define SYS_accept 102 -//#define SYS_socketpair 103 -#define SYS_shutdown 104 -#define SYS_getsockname 105 -#define SYS_getpeername 106 -#define SYS_getsockopt 107 -#define SYS_setsockopt 108 -//#define SYS_recvfrom 109 -//#define SYS_sendto 110 -//#define SYS_recvmsg 111 -//#define SYS_sendmsg 112 +#define SYS_socket 98 +#define SYS_bind 99 +#define SYS_connect 100 +#define SYS_listen 101 +#define SYS_accept 102 +// #define SYS_socketpair 103 +#define SYS_shutdown 104 +#define SYS_getsockname 105 +#define SYS_getpeername 106 +#define SYS_getsockopt 107 +#define SYS_setsockopt 108 +// #define SYS_recvfrom 109 +// #define SYS_sendto 110 +// #define SYS_recvmsg 111 +// #define SYS_sendmsg 112 // -- Time-related -- -#define SYS___time 113 -#define SYS___settime 114 -#define SYS_nanosleep 115 -//#define SYS_getitimer 116 -//#define SYS_setitimer 117 +#define SYS___time 113 +#define SYS___settime 114 +#define SYS_nanosleep 115 +// #define SYS_getitimer 116 +// #define SYS_setitimer 117 // -- Other -- -#define SYS_sync 118 -#define SYS_reboot 119 -//#define SYS___sysctl 120 +#define SYS_sync 118 +#define SYS_reboot 119 +// #define SYS___sysctl 120 /*CALLEND*/ - #endif /* _KERN_SYSCALL_H_ */ diff --git a/kern/include/kern/time.h b/kern/include/kern/time.h index d52076e..9b28422 100644 --- a/kern/include/kern/time.h +++ b/kern/include/kern/time.h @@ -34,37 +34,34 @@ * Time-related definitions, for and others. */ - /* * Time with fractional seconds. Important. Unfortunately, to be * compatible, we need both timeval and timespec. */ struct timeval { - __time_t tv_sec; /* seconds */ - __i32 tv_usec; /* microseconds */ + __time_t tv_sec; /* seconds */ + __i32 tv_usec; /* microseconds */ }; struct timespec { - __time_t tv_sec; /* seconds */ - __i32 tv_nsec; /* nanoseconds */ + __time_t tv_sec; /* seconds */ + __i32 tv_nsec; /* nanoseconds */ }; - /* * Bits for interval timers. Obscure and not really that important. */ /* codes for the various timers */ -#define ITIMER_REAL 0 /* Real (wall-clock) time. */ -#define ITIMER_VIRTUAL 1 /* Virtual (when process is executing) time. */ -#define ITIMER_PROF 2 /* For execution profiling. */ +#define ITIMER_REAL 0 /* Real (wall-clock) time. */ +#define ITIMER_VIRTUAL 1 /* Virtual (when process is executing) time. */ +#define ITIMER_PROF 2 /* For execution profiling. */ /* structure for setitimer/getitimer */ struct itimerval { - struct timeval it_interval; /* Time to reload after expiry. */ - struct timeval it_value; /* Time to count. */ + struct timeval it_interval; /* Time to reload after expiry. */ + struct timeval it_value; /* Time to count. */ }; - #endif /* _KERN_TIME_H_ */ diff --git a/kern/include/kern/types.h b/kern/include/kern/types.h index 002d3b7..68c1d6f 100644 --- a/kern/include/kern/types.h +++ b/kern/include/kern/types.h @@ -61,32 +61,31 @@ * and also various other places as per relevant standards. */ -typedef __u32 __blkcnt_t; /* Count of blocks */ -typedef __u32 __blksize_t; /* Size of an I/O block */ -typedef __u64 __counter_t; /* Event counter */ -typedef __u32 __daddr_t; /* Disk block number */ -typedef __u32 __dev_t; /* Hardware device ID */ -typedef __u32 __fsid_t; /* Filesystem ID */ -typedef __i32 __gid_t; /* Group ID */ -typedef __u32 __in_addr_t; /* Internet address */ -typedef __u32 __in_port_t; /* Internet port number */ -typedef __u32 __ino_t; /* Inode number */ -typedef __u32 __mode_t; /* File access mode */ -typedef __u16 __nlink_t; /* Number of links (intentionally only 16 bits) */ -typedef __i64 __off_t; /* Offset within file */ -typedef __i32 __pid_t; /* Process ID */ -typedef __u64 __rlim_t; /* Resource limit quantity */ -typedef __u8 __sa_family_t;/* Socket address family */ -typedef __i64 __time_t; /* Time in seconds */ -typedef __i32 __uid_t; /* User ID */ +typedef __u32 __blkcnt_t; /* Count of blocks */ +typedef __u32 __blksize_t; /* Size of an I/O block */ +typedef __u64 __counter_t; /* Event counter */ +typedef __u32 __daddr_t; /* Disk block number */ +typedef __u32 __dev_t; /* Hardware device ID */ +typedef __u32 __fsid_t; /* Filesystem ID */ +typedef __i32 __gid_t; /* Group ID */ +typedef __u32 __in_addr_t; /* Internet address */ +typedef __u32 __in_port_t; /* Internet port number */ +typedef __u32 __ino_t; /* Inode number */ +typedef __u32 __mode_t; /* File access mode */ +typedef __u16 __nlink_t; /* Number of links (intentionally only 16 bits) */ +typedef __i64 __off_t; /* Offset within file */ +typedef __i32 __pid_t; /* Process ID */ +typedef __u64 __rlim_t; /* Resource limit quantity */ +typedef __u8 __sa_family_t; /* Socket address family */ +typedef __i64 __time_t; /* Time in seconds */ +typedef __i32 __uid_t; /* User ID */ typedef int __nfds_t; /* Number of file handles */ -typedef int __socklen_t; /* Socket-related length */ +typedef int __socklen_t; /* Socket-related length */ /* See note in */ #ifdef __GNUC__ typedef __builtin_va_list __va_list; #endif - #endif /* _KERN_TYPES_H_ */ diff --git a/kern/include/kern/unistd.h b/kern/include/kern/unistd.h index 30f2678..e81e8c6 100644 --- a/kern/include/kern/unistd.h +++ b/kern/include/kern/unistd.h @@ -31,9 +31,8 @@ #define _KERN_UNISTD_H_ /* Constants for read/write/etc: special file handles */ -#define STDIN_FILENO 0 /* Standard input */ -#define STDOUT_FILENO 1 /* Standard output */ -#define STDERR_FILENO 2 /* Standard error */ - +#define STDIN_FILENO 0 /* Standard input */ +#define STDOUT_FILENO 1 /* Standard output */ +#define STDERR_FILENO 2 /* Standard error */ #endif /* _KERN_UNISTD_H_ */ diff --git a/kern/include/kern/wait.h b/kern/include/kern/wait.h index 06ffab6..fc84b9b 100644 --- a/kern/include/kern/wait.h +++ b/kern/include/kern/wait.h @@ -34,14 +34,13 @@ * Definitions for wait(). */ - /* Flags for waitpid() and equivalent. */ -#define WNOHANG 1 /* Nonblocking. */ -#define WUNTRACED 2 /* Report stopping as well as exiting processes. */ +#define WNOHANG 1 /* Nonblocking. */ +#define WUNTRACED 2 /* Report stopping as well as exiting processes. */ /* Special "pids" to wait for. */ -#define WAIT_ANY (-1) /* Any child process. */ -#define WAIT_MYPGRP 0 /* Any process in the same process group. */ +#define WAIT_ANY (-1) /* Any child process. */ +#define WAIT_MYPGRP 0 /* Any process in the same process group. */ /* * Result encoding. @@ -51,29 +50,29 @@ * is different, wastes most of the bits and can only transmit 8 bits * of exit code... */ -#define _WWHAT(x) ((x)&3) /* lower two bits say what happened */ -#define _WVAL(x) ((x)>>2) /* the rest is the value */ -#define _MKWVAL(x) ((x)<<2) /* encode a value */ +#define _WWHAT(x) ((x) & 3) /* lower two bits say what happened */ +#define _WVAL(x) ((x) >> 2) /* the rest is the value */ +#define _MKWVAL(x) ((x) << 2) /* encode a value */ /* Four things can happen... */ -#define __WEXITED 0 /* Process exited by calling _exit(). */ -#define __WSIGNALED 1 /* Process received a fatal signal. */ -#define __WCORED 2 /* Process dumped core on a fatal signal. */ -#define __WSTOPPED 3 /* Process stopped (and didn't exit). */ +#define __WEXITED 0 /* Process exited by calling _exit(). */ +#define __WSIGNALED 1 /* Process received a fatal signal. */ +#define __WCORED 2 /* Process dumped core on a fatal signal. */ +#define __WSTOPPED 3 /* Process stopped (and didn't exit). */ /* Test macros, used by applications. */ -#define WIFEXITED(x) (_WWHAT(x)==__WEXITED) -#define WIFSIGNALED(x) (_WWHAT(x)==__WSIGNALED || _WWHAT(x)==__WCORED) -#define WIFSTOPPED(x) (_WWHAT(x)==__WSTOPPED) +#define WIFEXITED(x) (_WWHAT(x) == __WEXITED) +#define WIFSIGNALED(x) (_WWHAT(x) == __WSIGNALED || _WWHAT(x) == __WCORED) +#define WIFSTOPPED(x) (_WWHAT(x) == __WSTOPPED) #define WEXITSTATUS(x) (_WVAL(x)) -#define WTERMSIG(x) (_WVAL(x)) -#define WSTOPSIG(x) (_WVAL(x)) -#define WCOREDUMP(x) (_WWHAT(x)==__WCORED) +#define WTERMSIG(x) (_WVAL(x)) +#define WSTOPSIG(x) (_WVAL(x)) +#define WCOREDUMP(x) (_WWHAT(x) == __WCORED) /* Encoding macros, used by the kernel to generate the wait result. */ -#define _MKWAIT_EXIT(x) (_MKWVAL(x)|__WEXITED) -#define _MKWAIT_SIG(x) (_MKWVAL(x)|__WSIGNALED) -#define _MKWAIT_CORE(x) (_MKWVAL(x)|__WCORED) -#define _MKWAIT_STOP(x) (_MKWVAL(x)|__WSTOPPED) +#define _MKWAIT_EXIT(x) (_MKWVAL(x) | __WEXITED) +#define _MKWAIT_SIG(x) (_MKWVAL(x) | __WSIGNALED) +#define _MKWAIT_CORE(x) (_MKWVAL(x) | __WCORED) +#define _MKWAIT_STOP(x) (_MKWVAL(x) | __WSTOPPED) #endif /* _KERN_WAIT_H_ */ diff --git a/kern/include/lib.h b/kern/include/lib.h index 66e5da3..0ad1eb3 100644 --- a/kern/include/lib.h +++ b/kern/include/lib.h @@ -37,7 +37,6 @@ * Note: setjmp and longjmp are in . */ - #include /* @@ -62,33 +61,33 @@ #if OPT_NOASSERTS #define KASSERT(expr) ((void)(expr)) #else -#define KASSERT(expr) \ - ((expr) ? (void)0 : badassert(#expr, __FILE__, __LINE__, __func__)) +#define KASSERT(expr) \ + ((expr) ? (void)0 : badassert(#expr, __FILE__, __LINE__, __func__)) #endif #if 1 /* no debug asserts */ #define DEBUGASSERT(expr) ((void)(expr)) #else -#define DEBUGASSERT(expr) \ - ((expr) ? (void)0 : badassert(#expr, __FILE__, __LINE__, __func__)) +#define DEBUGASSERT(expr) \ + ((expr) ? (void)0 : badassert(#expr, __FILE__, __LINE__, __func__)) #endif /* * Bit flags for DEBUG() */ -#define DB_LOCORE 0x0001 -#define DB_SYSCALL 0x0002 -#define DB_INTERRUPT 0x0004 -#define DB_DEVICE 0x0008 -#define DB_THREADS 0x0010 -#define DB_VM 0x0020 -#define DB_EXEC 0x0040 -#define DB_VFS 0x0080 -#define DB_SEMFS 0x0100 -#define DB_SFS 0x0200 -#define DB_NET 0x0400 -#define DB_NETFS 0x0800 -#define DB_KMALLOC 0x1000 +#define DB_LOCORE 0x0001 +#define DB_SYSCALL 0x0002 +#define DB_INTERRUPT 0x0004 +#define DB_DEVICE 0x0008 +#define DB_THREADS 0x0010 +#define DB_VM 0x0020 +#define DB_EXEC 0x0040 +#define DB_VFS 0x0080 +#define DB_SEMFS 0x0100 +#define DB_SFS 0x0200 +#define DB_NET 0x0400 +#define DB_NETFS 0x0800 +#define DB_KMALLOC 0x1000 extern uint32_t dbflags; @@ -154,7 +153,7 @@ void *memset(void *block, int ch, size_t len); void bzero(void *ptr, size_t len); int atoi(const char *str); -int snprintf(char *buf, size_t maxlen, const char *fmt, ...) __PF(3,4); +int snprintf(char *buf, size_t maxlen, const char *fmt, ...) __PF(3, 4); const char *strerror(int errcode); @@ -178,10 +177,10 @@ void beep(void); * during boot once malloc is available and before any additional * threads are created. */ -int kprintf(const char *format, ...) __PF(1,2); -__DEAD void panic(const char *format, ...) __PF(1,2); -__DEAD void badassert(const char *expr, const char *file, - int line, const char *func); +int kprintf(const char *format, ...) __PF(1, 2); +__DEAD void panic(const char *format, ...) __PF(1, 2); +__DEAD void badassert(const char *expr, const char *file, int line, + const char *func); void kgets(char *buf, size_t maxbuflen); @@ -191,8 +190,7 @@ void kprintf_bootstrap(void); * Other miscellaneous stuff */ -#define DIVROUNDUP(a,b) (((a)+(b)-1)/(b)) -#define ROUNDUP(a,b) (DIVROUNDUP(a,b)*(b)) - +#define DIVROUNDUP(a, b) (((a) + (b) - 1) / (b)) +#define ROUNDUP(a, b) (DIVROUNDUP(a, b) * (b)) #endif /* _LIB_H_ */ diff --git a/kern/include/limits.h b/kern/include/limits.h index 01684c4..009dd86 100644 --- a/kern/include/limits.h +++ b/kern/include/limits.h @@ -38,15 +38,15 @@ #include /* Provide the real names */ -#define NAME_MAX __NAME_MAX -#define PATH_MAX __PATH_MAX -#define ARG_MAX __ARG_MAX -#define PID_MIN __PID_MIN -#define PID_MAX __PID_MAX -#define PIPE_BUF __PIPE_BUF -#define NGROUPS_MAX __NGROUPS_MAX -#define LOGIN_NAME_MAX __LOGIN_NAME_MAX -#define OPEN_MAX __OPEN_MAX -#define IOV_MAX __IOV_MAX +#define NAME_MAX __NAME_MAX +#define PATH_MAX __PATH_MAX +#define ARG_MAX __ARG_MAX +#define PID_MIN __PID_MIN +#define PID_MAX __PID_MAX +#define PIPE_BUF __PIPE_BUF +#define NGROUPS_MAX __NGROUPS_MAX +#define LOGIN_NAME_MAX __LOGIN_NAME_MAX +#define OPEN_MAX __OPEN_MAX +#define IOV_MAX __IOV_MAX #endif /* _LIMITS_H_ */ diff --git a/kern/include/mainbus.h b/kern/include/mainbus.h index 4d7fff0..6616d21 100644 --- a/kern/include/mainbus.h +++ b/kern/include/mainbus.h @@ -34,11 +34,9 @@ * Abstract system bus interface. */ - struct cpu; /* from */ struct trapframe; /* from */ - /* Initialize the system bus and probe and attach hardware devices. */ void mainbus_bootstrap(void); @@ -69,5 +67,4 @@ void mainbus_poweroff(void); void mainbus_reboot(void); void mainbus_panic(void); - #endif /* _MAINBUS_H_ */ diff --git a/kern/include/proc.h b/kern/include/proc.h index f63c48c..aeae575 100644 --- a/kern/include/proc.h +++ b/kern/include/proc.h @@ -60,17 +60,17 @@ struct vnode; * without sleeping. */ struct proc { - char *p_name; /* Name of this process */ - struct spinlock p_lock; /* Lock for this structure */ - unsigned p_numthreads; /* Number of threads in this process */ + char *p_name; /* Name of this process */ + struct spinlock p_lock; /* Lock for this structure */ + unsigned p_numthreads; /* Number of threads in this process */ - /* VM */ - struct addrspace *p_addrspace; /* virtual address space */ + /* VM */ + struct addrspace *p_addrspace; /* virtual address space */ - /* VFS */ - struct vnode *p_cwd; /* current working directory */ + /* VFS */ + struct vnode *p_cwd; /* current working directory */ - /* add more material here as needed */ + /* add more material here as needed */ }; /* This is the process structure for the kernel and for kernel-only threads. */ @@ -97,5 +97,4 @@ struct addrspace *proc_getas(void); /* Change the address space of the current process, and return the old one. */ struct addrspace *proc_setas(struct addrspace *); - #endif /* _PROC_H_ */ diff --git a/kern/include/setjmp.h b/kern/include/setjmp.h index 67fae47..db445d2 100644 --- a/kern/include/setjmp.h +++ b/kern/include/setjmp.h @@ -40,5 +40,4 @@ int setjmp(jmp_buf jb); void longjmp(jmp_buf jb, int retval); - #endif /* _SETJMP_H_ */ diff --git a/kern/include/sfs.h b/kern/include/sfs.h index 3c94d74..0bddebd 100644 --- a/kern/include/sfs.h +++ b/kern/include/sfs.h @@ -30,12 +30,10 @@ #ifndef _SFS_H_ #define _SFS_H_ - /* * Header for SFS, the Simple File System. */ - /* * Get abstract structure definitions */ @@ -52,23 +50,23 @@ * In-memory inode */ struct sfs_vnode { - struct vnode sv_absvn; /* abstract vnode structure */ - struct sfs_dinode sv_i; /* copy of on-disk inode */ - uint32_t sv_ino; /* inode number */ - bool sv_dirty; /* true if sv_i modified */ + struct vnode sv_absvn; /* abstract vnode structure */ + struct sfs_dinode sv_i; /* copy of on-disk inode */ + uint32_t sv_ino; /* inode number */ + bool sv_dirty; /* true if sv_i modified */ }; /* * In-memory info for a whole fs volume */ struct sfs_fs { - struct fs sfs_absfs; /* abstract filesystem structure */ - struct sfs_superblock sfs_sb; /* copy of on-disk superblock */ - bool sfs_superdirty; /* true if superblock modified */ - struct device *sfs_device; /* device mounted on */ - struct vnodearray *sfs_vnodes; /* vnodes loaded into memory */ - struct bitmap *sfs_freemap; /* blocks in use are marked 1 */ - bool sfs_freemapdirty; /* true if freemap modified */ + struct fs sfs_absfs; /* abstract filesystem structure */ + struct sfs_superblock sfs_sb; /* copy of on-disk superblock */ + bool sfs_superdirty; /* true if superblock modified */ + struct device *sfs_device; /* device mounted on */ + struct vnodearray *sfs_vnodes; /* vnodes loaded into memory */ + struct bitmap *sfs_freemap; /* blocks in use are marked 1 */ + bool sfs_freemapdirty; /* true if freemap modified */ }; /* @@ -76,5 +74,4 @@ struct sfs_fs { */ int sfs_mount(const char *device); - #endif /* _SFS_H_ */ diff --git a/kern/include/signal.h b/kern/include/signal.h index 215fa51..f3ac632 100644 --- a/kern/include/signal.h +++ b/kern/include/signal.h @@ -35,5 +35,4 @@ #include #include - #endif /* _SIGNAL_H_ */ diff --git a/kern/include/spinlock.h b/kern/include/spinlock.h index e28ec90..8622e30 100644 --- a/kern/include/spinlock.h +++ b/kern/include/spinlock.h @@ -56,19 +56,19 @@ * the structure directly but always use the spinlock API functions. */ struct spinlock { - volatile spinlock_data_t splk_lock; /* Memory word where we spin. */ - struct cpu *splk_holder; /* CPU holding this lock. */ - HANGMAN_LOCKABLE(splk_hangman); /* Deadlock detector hook. */ + volatile spinlock_data_t splk_lock; /* Memory word where we spin. */ + struct cpu *splk_holder; /* CPU holding this lock. */ + HANGMAN_LOCKABLE(splk_hangman); /* Deadlock detector hook. */ }; /* * Initializer for cases where a spinlock needs to be static or global. */ #ifdef OPT_HANGMAN -#define SPINLOCK_INITIALIZER { SPINLOCK_DATA_INITIALIZER, NULL, \ - HANGMAN_LOCKABLE_INITIALIZER } +#define SPINLOCK_INITIALIZER \ + {SPINLOCK_DATA_INITIALIZER, NULL, HANGMAN_LOCKABLE_INITIALIZER} #else -#define SPINLOCK_INITIALIZER { SPINLOCK_DATA_INITIALIZER, NULL } +#define SPINLOCK_INITIALIZER {SPINLOCK_DATA_INITIALIZER, NULL} #endif /* @@ -91,5 +91,4 @@ void spinlock_release(struct spinlock *lk); bool spinlock_do_i_hold(struct spinlock *lk); - #endif /* _SPINLOCK_H_ */ diff --git a/kern/include/spl.h b/kern/include/spl.h index 2a8d0e3..fe966ce 100644 --- a/kern/include/spl.h +++ b/kern/include/spl.h @@ -74,8 +74,8 @@ int splx(int); /* * Integer interrupt priority levels. */ -#define IPL_NONE 0 -#define IPL_HIGH 1 +#define IPL_NONE 0 +#define IPL_HIGH 1 /* * Lower-level functions for explicitly raising and lowering @@ -92,18 +92,9 @@ void spllower(int oldipl, int newipl); //////////////////////////////////////////////////////////// SPL_INLINE -int -spl0(void) -{ - return splx(IPL_NONE); -} +int spl0(void) { return splx(IPL_NONE); } SPL_INLINE -int -splhigh(void) -{ - return splx(IPL_HIGH); -} - +int splhigh(void) { return splx(IPL_HIGH); } #endif /* _SPL_H_ */ diff --git a/kern/include/stat.h b/kern/include/stat.h index c387576..7991c82 100644 --- a/kern/include/stat.h +++ b/kern/include/stat.h @@ -37,14 +37,13 @@ #include /* Provide non-underscore names. */ -#define S_IFMT _S_IFMT -#define S_IFREG _S_IFREG -#define S_IFDIR _S_IFDIR -#define S_IFLNK _S_IFLNK -#define S_IFIFO _S_IFIFO +#define S_IFMT _S_IFMT +#define S_IFREG _S_IFREG +#define S_IFDIR _S_IFDIR +#define S_IFLNK _S_IFLNK +#define S_IFIFO _S_IFIFO #define S_IFSOCK _S_IFSOCK -#define S_IFCHR _S_IFCHR -#define S_IFBLK _S_IFBLK - +#define S_IFCHR _S_IFCHR +#define S_IFBLK _S_IFBLK #endif /* _STAT_H */ diff --git a/kern/include/stdarg.h b/kern/include/stdarg.h index b4db313..0f25534 100644 --- a/kern/include/stdarg.h +++ b/kern/include/stdarg.h @@ -30,7 +30,6 @@ #ifndef _STDARG_H_ #define _STDARG_H_ - /* Get __PF() for declaring printf-like functions. */ #include @@ -46,13 +45,13 @@ typedef __va_list va_list; #if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8) -#define va_start(ap, fmt) __builtin_stdarg_start(ap, fmt) +#define va_start(ap, fmt) __builtin_stdarg_start(ap, fmt) #else -#define va_start(ap, fmt) __builtin_va_start(ap, fmt) +#define va_start(ap, fmt) __builtin_va_start(ap, fmt) #endif -#define va_arg(ap,t) __builtin_va_arg(ap, t) -#define va_copy(ap1, ap2) __builtin_va_copy(ap1, ap2) -#define va_end(ap) __builtin_va_end(ap) +#define va_arg(ap, t) __builtin_va_arg(ap, t) +#define va_copy(ap1, ap2) __builtin_va_copy(ap1, ap2) +#define va_end(ap) __builtin_va_end(ap) #endif /* @@ -62,8 +61,8 @@ typedef __va_list va_list; * or split the definition of va_list into another header file, none * of which seems entirely desirable. */ -void vkprintf(const char *fmt, va_list ap) __PF(1,0); -int vsnprintf(char *buf, size_t maxlen, const char *fmt, va_list ap) __PF(3,0); +void vkprintf(const char *fmt, va_list ap) __PF(1, 0); +int vsnprintf(char *buf, size_t maxlen, const char *fmt, va_list ap) __PF(3, 0); /* * The printf driver function (shared with libc). @@ -73,7 +72,6 @@ int vsnprintf(char *buf, size_t maxlen, const char *fmt, va_list ap) __PF(3,0); * supplied length should be used explicitly. */ int __vprintf(void (*func)(void *clientdata, const char *str, size_t len), - void *clientdata, const char *format, va_list ap) __PF(3,0); - + void *clientdata, const char *format, va_list ap) __PF(3, 0); #endif /* _STDARG_H_ */ diff --git a/kern/include/synch.h b/kern/include/synch.h index 0431cd3..b1e8d50 100644 --- a/kern/include/synch.h +++ b/kern/include/synch.h @@ -34,7 +34,6 @@ * Header file for synchronization primitives. */ - #include /* @@ -44,10 +43,10 @@ * internally. */ struct semaphore { - char *sem_name; - struct wchan *sem_wchan; - struct spinlock sem_lock; - volatile unsigned sem_count; + char *sem_name; + struct wchan *sem_wchan; + struct spinlock sem_lock; + volatile unsigned sem_count; }; struct semaphore *sem_create(const char *name, unsigned initial_count); @@ -62,7 +61,6 @@ void sem_destroy(struct semaphore *); void P(struct semaphore *); void V(struct semaphore *); - /* * Simple lock for mutual exclusion. * @@ -73,10 +71,10 @@ void V(struct semaphore *); * (should be) made internally. */ struct lock { - char *lk_name; - HANGMAN_LOCKABLE(lk_hangman); /* Deadlock detector hook. */ - // add what you need here - // (don't forget to mark things volatile as needed) + char *lk_name; + HANGMAN_LOCKABLE(lk_hangman); /* Deadlock detector hook. */ + // add what you need here + // (don't forget to mark things volatile as needed) }; struct lock *lock_create(const char *name); @@ -97,7 +95,6 @@ void lock_acquire(struct lock *); void lock_release(struct lock *); bool lock_do_i_hold(struct lock *); - /* * Condition variable. * @@ -113,9 +110,9 @@ bool lock_do_i_hold(struct lock *); */ struct cv { - char *cv_name; - // add what you need here - // (don't forget to mark things volatile as needed) + char *cv_name; + // add what you need here + // (don't forget to mark things volatile as needed) }; struct cv *cv_create(const char *name); @@ -138,5 +135,4 @@ void cv_wait(struct cv *cv, struct lock *lock); void cv_signal(struct cv *cv, struct lock *lock); void cv_broadcast(struct cv *cv, struct lock *lock); - #endif /* _SYNCH_H_ */ diff --git a/kern/include/syscall.h b/kern/include/syscall.h index ad59b0f..6cd517b 100644 --- a/kern/include/syscall.h +++ b/kern/include/syscall.h @@ -30,9 +30,8 @@ #ifndef _SYSCALL_H_ #define _SYSCALL_H_ - #include /* for __DEAD */ -struct trapframe; /* from */ +struct trapframe; /* from */ /* * The system call dispatcher. @@ -49,8 +48,7 @@ void enter_forked_process(struct trapframe *tf); /* Enter user mode. Does not return. */ __DEAD void enter_new_process(int argc, userptr_t argv, userptr_t env, - vaddr_t stackptr, vaddr_t entrypoint); - + vaddr_t stackptr, vaddr_t entrypoint); /* * Prototypes for IN-KERNEL entry points for system call implementations. diff --git a/kern/include/test.h b/kern/include/test.h index 7b02114..809efc8 100644 --- a/kern/include/test.h +++ b/kern/include/test.h @@ -35,7 +35,6 @@ * functions. */ - /* * Test code. */ @@ -104,5 +103,4 @@ void menu(char *argstr); /* The main function, called from start.S. */ void kmain(char *bootstring); - #endif /* _TEST_H_ */ diff --git a/kern/include/thread.h b/kern/include/thread.h index 8017994..b18521d 100644 --- a/kern/include/thread.h +++ b/kern/include/thread.h @@ -45,68 +45,66 @@ struct cpu; /* get machine-dependent defs */ #include - /* Size of kernel stacks; must be power of 2 */ #define STACK_SIZE 4096 /* Mask for extracting the stack base address of a kernel stack pointer */ -#define STACK_MASK (~(vaddr_t)(STACK_SIZE-1)) +#define STACK_MASK (~(vaddr_t)(STACK_SIZE - 1)) /* Macro to test if two addresses are on the same kernel stack */ -#define SAME_STACK(p1, p2) (((p1) & STACK_MASK) == ((p2) & STACK_MASK)) - +#define SAME_STACK(p1, p2) (((p1) & STACK_MASK) == ((p2) & STACK_MASK)) /* States a thread can be in. */ typedef enum { - S_RUN, /* running */ - S_READY, /* ready to run */ - S_SLEEP, /* sleeping */ - S_ZOMBIE, /* zombie; exited but not yet deleted */ + S_RUN, /* running */ + S_READY, /* ready to run */ + S_SLEEP, /* sleeping */ + S_ZOMBIE, /* zombie; exited but not yet deleted */ } threadstate_t; /* Thread structure. */ struct thread { - /* - * These go up front so they're easy to get to even if the - * debugger is messed up. - */ - char *t_name; /* Name of this thread */ - const char *t_wchan_name; /* Name of wait channel, if sleeping */ - threadstate_t t_state; /* State this thread is in */ + /* + * These go up front so they're easy to get to even if the + * debugger is messed up. + */ + char *t_name; /* Name of this thread */ + const char *t_wchan_name; /* Name of wait channel, if sleeping */ + threadstate_t t_state; /* State this thread is in */ - /* - * Thread subsystem internal fields. - */ - struct thread_machdep t_machdep; /* Any machine-dependent goo */ - struct threadlistnode t_listnode; /* Link for run/sleep/zombie lists */ - void *t_stack; /* Kernel-level stack */ - struct switchframe *t_context; /* Saved register context (on stack) */ - struct cpu *t_cpu; /* CPU thread runs on */ - struct proc *t_proc; /* Process thread belongs to */ - HANGMAN_ACTOR(t_hangman); /* Deadlock detector hook */ + /* + * Thread subsystem internal fields. + */ + struct thread_machdep t_machdep; /* Any machine-dependent goo */ + struct threadlistnode t_listnode; /* Link for run/sleep/zombie lists */ + void *t_stack; /* Kernel-level stack */ + struct switchframe *t_context; /* Saved register context (on stack) */ + struct cpu *t_cpu; /* CPU thread runs on */ + struct proc *t_proc; /* Process thread belongs to */ + HANGMAN_ACTOR(t_hangman); /* Deadlock detector hook */ - /* - * Interrupt state fields. - * - * t_in_interrupt is true if current execution is in an - * interrupt handler, which means the thread's normal context - * of execution is stopped somewhere in the middle of doing - * something else. This makes assorted operations unsafe. - * - * See notes in spinlock.c regarding t_curspl and t_iplhigh_count. - * - * Exercise for the student: why is this material per-thread - * rather than per-cpu or global? - */ - bool t_in_interrupt; /* Are we in an interrupt? */ - int t_curspl; /* Current spl*() state */ - int t_iplhigh_count; /* # of times IPL has been raised */ + /* + * Interrupt state fields. + * + * t_in_interrupt is true if current execution is in an + * interrupt handler, which means the thread's normal context + * of execution is stopped somewhere in the middle of doing + * something else. This makes assorted operations unsafe. + * + * See notes in spinlock.c regarding t_curspl and t_iplhigh_count. + * + * Exercise for the student: why is this material per-thread + * rather than per-cpu or global? + */ + bool t_in_interrupt; /* Are we in an interrupt? */ + int t_curspl; /* Current spl*() state */ + int t_iplhigh_count; /* # of times IPL has been raised */ - /* - * Public fields - */ + /* + * Public fields + */ - /* add more here as needed */ + /* add more here as needed */ }; /* @@ -142,8 +140,8 @@ void thread_shutdown(void); * disappear at any time without notice. */ int thread_fork(const char *name, struct proc *proc, - void (*func)(void *, unsigned long), - void *data1, unsigned long data2); + void (*func)(void *, unsigned long), void *data1, + unsigned long data2); /* * Cause the current thread to exit. @@ -169,5 +167,4 @@ void schedule(void); */ void thread_consider_migration(void); - #endif /* _THREAD_H_ */ diff --git a/kern/include/threadlist.h b/kern/include/threadlist.h index c48f2ce..551c01d 100644 --- a/kern/include/threadlist.h +++ b/kern/include/threadlist.h @@ -30,8 +30,7 @@ #ifndef _THREADLIST_H_ #define _THREADLIST_H_ - -struct thread; /* from */ +struct thread; /* from */ /* * AmigaOS-style linked list of threads. @@ -55,15 +54,15 @@ struct thread; /* from */ */ struct threadlistnode { - struct threadlistnode *tln_prev; - struct threadlistnode *tln_next; - struct thread *tln_self; + struct threadlistnode *tln_prev; + struct threadlistnode *tln_next; + struct thread *tln_self; }; struct threadlist { - struct threadlistnode tl_head; - struct threadlistnode tl_tail; - unsigned tl_count; + struct threadlistnode tl_head; + struct threadlistnode tl_tail; + unsigned tl_count; }; /* Initialize and clean up a thread list node. */ @@ -84,22 +83,19 @@ struct thread *threadlist_remhead(struct threadlist *tl); struct thread *threadlist_remtail(struct threadlist *tl); /* Add and remove: in middle. (TL is needed to maintain ->tl_count.) */ -void threadlist_insertafter(struct threadlist *tl, - struct thread *onlist, struct thread *addee); -void threadlist_insertbefore(struct threadlist *tl, - struct thread *addee, struct thread *onlist); +void threadlist_insertafter(struct threadlist *tl, struct thread *onlist, + struct thread *addee); +void threadlist_insertbefore(struct threadlist *tl, struct thread *addee, + struct thread *onlist); void threadlist_remove(struct threadlist *tl, struct thread *t); /* Iteration; itervar should previously be declared as (struct thread *) */ -#define THREADLIST_FORALL(itervar, tl) \ - for ((itervar) = (tl).tl_head.tln_next->tln_self; \ - (itervar) != NULL; \ - (itervar) = (itervar)->t_listnode.tln_next->tln_self) - -#define THREADLIST_FORALL_REV(itervar, tl) \ - for ((itervar) = (tl).tl_tail.tln_prev->tln_self; \ - (itervar) != NULL; \ - (itervar) = (itervar)->t_listnode.tln_prev->tln_self) +#define THREADLIST_FORALL(itervar, tl) \ + for ((itervar) = (tl).tl_head.tln_next->tln_self; (itervar) != NULL; \ + (itervar) = (itervar)->t_listnode.tln_next->tln_self) +#define THREADLIST_FORALL_REV(itervar, tl) \ + for ((itervar) = (tl).tl_tail.tln_prev->tln_self; (itervar) != NULL; \ + (itervar) = (itervar)->t_listnode.tln_prev->tln_self) #endif /* _THREADLIST_H_ */ diff --git a/kern/include/threadprivate.h b/kern/include/threadprivate.h index d07dd07..8205d1c 100644 --- a/kern/include/threadprivate.h +++ b/kern/include/threadprivate.h @@ -30,10 +30,9 @@ #ifndef _THREADPRIVATE_H_ #define _THREADPRIVATE_H_ -struct thread; /* from */ -struct thread_machdep; /* from */ -struct switchframe; /* from */ - +struct thread; /* from */ +struct thread_machdep; /* from */ +struct switchframe; /* from */ /* * Subsystem-private thread defs. @@ -46,14 +45,13 @@ struct switchframe; /* from */ * interfaces. */ - /* * Private thread functions. */ /* Entry point for new threads. */ void thread_startup(void (*entrypoint)(void *data1, unsigned long data2), - void *data1, unsigned long data2); + void *data1, unsigned long data2); /* Initialize or clean up the machine-dependent portion of struct thread */ void thread_machdep_init(struct thread_machdep *tm); @@ -71,8 +69,7 @@ void switchframe_switch(struct switchframe **prev, struct switchframe **next); /* Thread initialization */ void switchframe_init(struct thread *, - void (*entrypoint)(void *data1, unsigned long data2), - void *data1, unsigned long data2); - + void (*entrypoint)(void *data1, unsigned long data2), + void *data1, unsigned long data2); #endif /* _THREADPRIVATE_H_ */ diff --git a/kern/include/types.h b/kern/include/types.h index ef310e0..cabc5e0 100644 --- a/kern/include/types.h +++ b/kern/include/types.h @@ -75,7 +75,6 @@ * this principle produces a workable result. */ - /* Get types visible to userland, both MI and MD. */ #include @@ -87,7 +86,9 @@ * with other pointers. */ -struct __userptr { char _dummy; }; +struct __userptr { + char _dummy; +}; typedef struct __userptr *userptr_t; typedef const struct __userptr *const_userptr_t; @@ -149,7 +150,7 @@ typedef __socklen_t socklen_t; * Boolean. */ typedef _Bool bool; -#define true 1 +#define true 1 #define false 0 #endif /* _TYPES_H_ */ diff --git a/kern/include/uio.h b/kern/include/uio.h index 4c879aa..42a62d7 100644 --- a/kern/include/uio.h +++ b/kern/include/uio.h @@ -59,28 +59,27 @@ /* Direction. */ enum uio_rw { - UIO_READ, /* From kernel to uio_seg */ - UIO_WRITE, /* From uio_seg to kernel */ + UIO_READ, /* From kernel to uio_seg */ + UIO_WRITE, /* From uio_seg to kernel */ }; /* Source/destination. */ enum uio_seg { - UIO_USERISPACE, /* User process code. */ - UIO_USERSPACE, /* User process data. */ - UIO_SYSSPACE, /* Kernel. */ + UIO_USERISPACE, /* User process code. */ + UIO_USERSPACE, /* User process data. */ + UIO_SYSSPACE, /* Kernel. */ }; struct uio { - struct iovec *uio_iov; /* Data blocks */ - unsigned uio_iovcnt; /* Number of iovecs */ - off_t uio_offset; /* Desired offset into object */ - size_t uio_resid; /* Remaining amt of data to xfer */ - enum uio_seg uio_segflg; /* What kind of pointer we have */ - enum uio_rw uio_rw; /* Whether op is a read or write */ - struct addrspace *uio_space; /* Address space for user pointer */ + struct iovec *uio_iov; /* Data blocks */ + unsigned uio_iovcnt; /* Number of iovecs */ + off_t uio_offset; /* Desired offset into object */ + size_t uio_resid; /* Remaining amt of data to xfer */ + enum uio_seg uio_segflg; /* What kind of pointer we have */ + enum uio_rw uio_rw; /* Whether op is a read or write */ + struct addrspace *uio_space; /* Address space for user pointer */ }; - /* * Copy data from a kernel buffer to a data region defined by a uio struct, * updating the uio struct's offset and resid fields. May alter the iovec @@ -135,8 +134,7 @@ int uiomovezeros(size_t len, struct uio *uio); * result = VOP_READ(vn, &myuio); * ... */ -void uio_kinit(struct iovec *, struct uio *, - void *kbuf, size_t len, off_t pos, enum uio_rw rw); - +void uio_kinit(struct iovec *, struct uio *, void *kbuf, size_t len, off_t pos, + enum uio_rw rw); #endif /* _UIO_H_ */ diff --git a/kern/include/version.h b/kern/include/version.h index 4d9fa1c..2d20991 100644 --- a/kern/include/version.h +++ b/kern/include/version.h @@ -34,12 +34,11 @@ * Leave this alone, so we can tell what version of the OS/161 base * code we gave you. */ -#define BASE_VERSION "2.0.3" +#define BASE_VERSION "2.0.3" /* * Change this as you see fit in the course of hacking the system. */ -#define GROUP_VERSION "0" - +#define GROUP_VERSION "0" #endif /* _VERSION_H_ */ diff --git a/kern/include/vfs.h b/kern/include/vfs.h index b4a6cc3..c362e7a 100644 --- a/kern/include/vfs.h +++ b/kern/include/vfs.h @@ -30,10 +30,8 @@ #ifndef _VFS_H_ #define _VFS_H_ - #include - /* * Virtual File System layer functions. * @@ -78,8 +76,7 @@ const char *vfs_getdevname(struct fs *fs); */ int vfs_lookup(char *path, struct vnode **result); -int vfs_lookparent(char *path, struct vnode **result, - char *buf, size_t buflen); +int vfs_lookparent(char *path, struct vnode **result, char *buf, size_t buflen); /* * VFS layer high-level operations on pathnames @@ -175,9 +172,8 @@ int vfs_adddev(const char *devname, struct device *dev, int mountable); int vfs_addfs(const char *devname, struct fs *fs); int vfs_mount(const char *devname, void *data, - int (*mountfunc)(void *data, - struct device *dev, - struct fs **result)); + int (*mountfunc)(void *data, struct device *dev, + struct fs **result)); int vfs_unmount(const char *devname); int vfs_swapon(const char *devname, struct vnode **result); int vfs_swapoff(const char *devname); @@ -201,5 +197,4 @@ void vfs_biglock_acquire(void); void vfs_biglock_release(void); bool vfs_biglock_do_i_hold(void); - #endif /* _VFS_H_ */ diff --git a/kern/include/vm.h b/kern/include/vm.h index abc0cfe..31bf945 100644 --- a/kern/include/vm.h +++ b/kern/include/vm.h @@ -36,14 +36,12 @@ * You'll probably want to add stuff here. */ - #include /* Fault-type arguments to vm_fault() */ -#define VM_FAULT_READ 0 /* A read was attempted */ -#define VM_FAULT_WRITE 1 /* A write was attempted */ -#define VM_FAULT_READONLY 2 /* A write to a readonly page was attempted*/ - +#define VM_FAULT_READ 0 /* A read was attempted */ +#define VM_FAULT_WRITE 1 /* A write was attempted */ +#define VM_FAULT_READONLY 2 /* A write to a readonly page was attempted*/ /* Initialization function */ void vm_bootstrap(void); @@ -58,5 +56,4 @@ void free_kpages(vaddr_t addr); /* TLB shootdown handling called from interprocessor_interrupt */ void vm_tlbshootdown(const struct tlbshootdown *); - #endif /* _VM_H_ */ diff --git a/kern/include/vnode.h b/kern/include/vnode.h index a29ae9a..459a7e3 100644 --- a/kern/include/vnode.h +++ b/kern/include/vnode.h @@ -34,7 +34,6 @@ struct uio; struct stat; - /* * A struct vnode is an abstract representation of a file. * @@ -49,14 +48,14 @@ struct stat; * Note: vn_fs may be null if the vnode refers to a device. */ struct vnode { - int vn_refcount; /* Reference count */ - struct spinlock vn_countlock; /* Lock for vn_refcount */ + int vn_refcount; /* Reference count */ + struct spinlock vn_countlock; /* Lock for vn_refcount */ - struct fs *vn_fs; /* Filesystem vnode belongs to */ + struct fs *vn_fs; /* Filesystem vnode belongs to */ - void *vn_data; /* Filesystem-specific data */ + void *vn_data; /* Filesystem-specific data */ - const struct vnode_ops *vn_ops; /* Functions on this vnode */ + const struct vnode_ops *vn_ops; /* Functions on this vnode */ }; /* @@ -175,82 +174,74 @@ struct vnode { * vnode handed back. */ -#define VOP_MAGIC 0xa2b3c4d5 +#define VOP_MAGIC 0xa2b3c4d5 struct vnode_ops { - unsigned long vop_magic; /* should always be VOP_MAGIC */ + unsigned long vop_magic; /* should always be VOP_MAGIC */ - int (*vop_eachopen)(struct vnode *object, int flags_from_open); - int (*vop_reclaim)(struct vnode *vnode); + int (*vop_eachopen)(struct vnode *object, int flags_from_open); + int (*vop_reclaim)(struct vnode *vnode); + int (*vop_read)(struct vnode *file, struct uio *uio); + int (*vop_readlink)(struct vnode *link, struct uio *uio); + int (*vop_getdirentry)(struct vnode *dir, struct uio *uio); + int (*vop_write)(struct vnode *file, struct uio *uio); + int (*vop_ioctl)(struct vnode *object, int op, userptr_t data); + int (*vop_stat)(struct vnode *object, struct stat *statbuf); + int (*vop_gettype)(struct vnode *object, mode_t *result); + bool (*vop_isseekable)(struct vnode *object); + int (*vop_fsync)(struct vnode *object); + int (*vop_mmap)(struct vnode *file /* add stuff */); + int (*vop_truncate)(struct vnode *file, off_t len); + int (*vop_namefile)(struct vnode *file, struct uio *uio); - int (*vop_read)(struct vnode *file, struct uio *uio); - int (*vop_readlink)(struct vnode *link, struct uio *uio); - int (*vop_getdirentry)(struct vnode *dir, struct uio *uio); - int (*vop_write)(struct vnode *file, struct uio *uio); - int (*vop_ioctl)(struct vnode *object, int op, userptr_t data); - int (*vop_stat)(struct vnode *object, struct stat *statbuf); - int (*vop_gettype)(struct vnode *object, mode_t *result); - bool (*vop_isseekable)(struct vnode *object); - int (*vop_fsync)(struct vnode *object); - int (*vop_mmap)(struct vnode *file /* add stuff */); - int (*vop_truncate)(struct vnode *file, off_t len); - int (*vop_namefile)(struct vnode *file, struct uio *uio); + int (*vop_creat)(struct vnode *dir, const char *name, bool excl, mode_t mode, + struct vnode **result); + int (*vop_symlink)(struct vnode *dir, const char *contents, const char *name); + int (*vop_mkdir)(struct vnode *parentdir, const char *name, mode_t mode); + int (*vop_link)(struct vnode *dir, const char *name, struct vnode *file); + int (*vop_remove)(struct vnode *dir, const char *name); + int (*vop_rmdir)(struct vnode *dir, const char *name); + int (*vop_rename)(struct vnode *vn1, const char *name1, struct vnode *vn2, + const char *name2); - int (*vop_creat)(struct vnode *dir, - const char *name, bool excl, mode_t mode, - struct vnode **result); - int (*vop_symlink)(struct vnode *dir, - const char *contents, const char *name); - int (*vop_mkdir)(struct vnode *parentdir, - const char *name, mode_t mode); - int (*vop_link)(struct vnode *dir, - const char *name, struct vnode *file); - int (*vop_remove)(struct vnode *dir, - const char *name); - int (*vop_rmdir)(struct vnode *dir, - const char *name); - - int (*vop_rename)(struct vnode *vn1, const char *name1, - struct vnode *vn2, const char *name2); - - - int (*vop_lookup)(struct vnode *dir, - char *pathname, struct vnode **result); - int (*vop_lookparent)(struct vnode *dir, - char *pathname, struct vnode **result, - char *buf, size_t len); + int (*vop_lookup)(struct vnode *dir, char *pathname, struct vnode **result); + int (*vop_lookparent)(struct vnode *dir, char *pathname, + struct vnode **result, char *buf, size_t len); }; #define __VOP(vn, sym) (vnode_check(vn, #sym), (vn)->vn_ops->vop_##sym) -#define VOP_EACHOPEN(vn, flags) (__VOP(vn, eachopen)(vn, flags)) -#define VOP_RECLAIM(vn) (__VOP(vn, reclaim)(vn)) +#define VOP_EACHOPEN(vn, flags) (__VOP(vn, eachopen)(vn, flags)) +#define VOP_RECLAIM(vn) (__VOP(vn, reclaim)(vn)) -#define VOP_READ(vn, uio) (__VOP(vn, read)(vn, uio)) -#define VOP_READLINK(vn, uio) (__VOP(vn, readlink)(vn, uio)) -#define VOP_GETDIRENTRY(vn, uio) (__VOP(vn,getdirentry)(vn, uio)) -#define VOP_WRITE(vn, uio) (__VOP(vn, write)(vn, uio)) -#define VOP_IOCTL(vn, code, buf) (__VOP(vn, ioctl)(vn,code,buf)) -#define VOP_STAT(vn, ptr) (__VOP(vn, stat)(vn, ptr)) -#define VOP_GETTYPE(vn, result) (__VOP(vn, gettype)(vn, result)) -#define VOP_ISSEEKABLE(vn) (__VOP(vn, isseekable)(vn)) -#define VOP_FSYNC(vn) (__VOP(vn, fsync)(vn)) -#define VOP_MMAP(vn /*add stuff */) (__VOP(vn, mmap)(vn /*add stuff */)) -#define VOP_TRUNCATE(vn, pos) (__VOP(vn, truncate)(vn, pos)) -#define VOP_NAMEFILE(vn, uio) (__VOP(vn, namefile)(vn, uio)) +#define VOP_READ(vn, uio) (__VOP(vn, read)(vn, uio)) +#define VOP_READLINK(vn, uio) (__VOP(vn, readlink)(vn, uio)) +#define VOP_GETDIRENTRY(vn, uio) (__VOP(vn, getdirentry)(vn, uio)) +#define VOP_WRITE(vn, uio) (__VOP(vn, write)(vn, uio)) +#define VOP_IOCTL(vn, code, buf) (__VOP(vn, ioctl)(vn, code, buf)) +#define VOP_STAT(vn, ptr) (__VOP(vn, stat)(vn, ptr)) +#define VOP_GETTYPE(vn, result) (__VOP(vn, gettype)(vn, result)) +#define VOP_ISSEEKABLE(vn) (__VOP(vn, isseekable)(vn)) +#define VOP_FSYNC(vn) (__VOP(vn, fsync)(vn)) +#define VOP_MMAP(vn /*add stuff */) (__VOP(vn, mmap)(vn /*add stuff */)) +#define VOP_TRUNCATE(vn, pos) (__VOP(vn, truncate)(vn, pos)) +#define VOP_NAMEFILE(vn, uio) (__VOP(vn, namefile)(vn, uio)) -#define VOP_CREAT(vn,nm,excl,mode,res) (__VOP(vn, creat)(vn,nm,excl,mode,res)) -#define VOP_SYMLINK(vn, name, content) (__VOP(vn, symlink)(vn, name, content)) -#define VOP_MKDIR(vn, name, mode) (__VOP(vn, mkdir)(vn, name, mode)) -#define VOP_LINK(vn, name, vn2) (__VOP(vn, link)(vn, name, vn2)) -#define VOP_REMOVE(vn, name) (__VOP(vn, remove)(vn, name)) -#define VOP_RMDIR(vn, name) (__VOP(vn, rmdir)(vn, name)) -#define VOP_RENAME(vn1,name1,vn2,name2)(__VOP(vn1,rename)(vn1,name1,vn2,name2)) +#define VOP_CREAT(vn, nm, excl, mode, res) \ + (__VOP(vn, creat)(vn, nm, excl, mode, res)) +#define VOP_SYMLINK(vn, name, content) (__VOP(vn, symlink)(vn, name, content)) +#define VOP_MKDIR(vn, name, mode) (__VOP(vn, mkdir)(vn, name, mode)) +#define VOP_LINK(vn, name, vn2) (__VOP(vn, link)(vn, name, vn2)) +#define VOP_REMOVE(vn, name) (__VOP(vn, remove)(vn, name)) +#define VOP_RMDIR(vn, name) (__VOP(vn, rmdir)(vn, name)) +#define VOP_RENAME(vn1, name1, vn2, name2) \ + (__VOP(vn1, rename)(vn1, name1, vn2, name2)) -#define VOP_LOOKUP(vn, name, res) (__VOP(vn, lookup)(vn, name, res)) -#define VOP_LOOKPARENT(vn,nm,res,bf,ln) (__VOP(vn,lookparent)(vn,nm,res,bf,ln)) +#define VOP_LOOKUP(vn, name, res) (__VOP(vn, lookup)(vn, name, res)) +#define VOP_LOOKPARENT(vn, nm, res, bf, ln) \ + (__VOP(vn, lookparent)(vn, nm, res, bf, ln)) /* * Consistency check @@ -263,15 +254,15 @@ void vnode_check(struct vnode *, const char *op); void vnode_incref(struct vnode *); void vnode_decref(struct vnode *); -#define VOP_INCREF(vn) vnode_incref(vn) -#define VOP_DECREF(vn) vnode_decref(vn) +#define VOP_INCREF(vn) vnode_incref(vn) +#define VOP_DECREF(vn) vnode_decref(vn) /* * Vnode initialization (intended for use by filesystem code) * The reference count is initialized to 1. */ -int vnode_init(struct vnode *, const struct vnode_ops *ops, - struct fs *fs, void *fsdata); +int vnode_init(struct vnode *, const struct vnode_ops *ops, struct fs *fs, + void *fsdata); /* * Vnode final cleanup (intended for use by filesystem code) @@ -291,26 +282,24 @@ int vopfail_mmap_perm(struct vnode *vn /* add stuff */); int vopfail_mmap_nosys(struct vnode *vn /* add stuff */); int vopfail_truncate_isdir(struct vnode *vn, off_t pos); int vopfail_creat_notdir(struct vnode *vn, const char *name, bool excl, - mode_t mode, struct vnode **result); + mode_t mode, struct vnode **result); int vopfail_symlink_notdir(struct vnode *vn, const char *contents, - const char *name); + const char *name); int vopfail_symlink_nosys(struct vnode *vn, const char *contents, - const char *name); + const char *name); int vopfail_mkdir_notdir(struct vnode *vn, const char *name, mode_t mode); int vopfail_mkdir_nosys(struct vnode *vn, const char *name, mode_t mode); int vopfail_link_notdir(struct vnode *dir, const char *name, - struct vnode *file); -int vopfail_link_nosys(struct vnode *dir, const char *name, - struct vnode *file); + struct vnode *file); +int vopfail_link_nosys(struct vnode *dir, const char *name, struct vnode *file); int vopfail_string_notdir(struct vnode *vn, const char *name); int vopfail_string_nosys(struct vnode *vn, const char *name); int vopfail_rename_notdir(struct vnode *fromdir, const char *fromname, - struct vnode *todir, const char *toname); + struct vnode *todir, const char *toname); int vopfail_rename_nosys(struct vnode *fromdir, const char *fromname, - struct vnode *todir, const char *toname); + struct vnode *todir, const char *toname); int vopfail_lookup_notdir(struct vnode *vn, char *path, struct vnode **result); int vopfail_lookparent_notdir(struct vnode *vn, char *path, - struct vnode **result, char *buf, size_t len); - + struct vnode **result, char *buf, size_t len); #endif /* _VNODE_H_ */ diff --git a/kern/include/wchan.h b/kern/include/wchan.h index 8009598..7baf937 100644 --- a/kern/include/wchan.h +++ b/kern/include/wchan.h @@ -34,9 +34,8 @@ * Wait channel. */ - struct spinlock; /* in spinlock.h */ -struct wchan; /* Opaque */ +struct wchan; /* Opaque */ /* * Create a wait channel. Use NAME as a symbolic name for the channel. @@ -76,5 +75,4 @@ void wchan_sleep(struct wchan *wc, struct spinlock *lk); void wchan_wakeone(struct wchan *wc, struct spinlock *lk); void wchan_wakeall(struct wchan *wc, struct spinlock *lk); - #endif /* _WCHAN_H_ */ diff --git a/kern/lib/array.c b/kern/lib/array.c index 0efb362..a0ee50e 100644 --- a/kern/lib/array.c +++ b/kern/lib/array.c @@ -34,102 +34,88 @@ #include #include -struct array * -array_create(void) -{ - struct array *a; +struct array *array_create(void) { + struct array *a; - a = kmalloc(sizeof(*a)); - if (a != NULL) { - array_init(a); - } - return a; + a = kmalloc(sizeof(*a)); + if (a != NULL) { + array_init(a); + } + return a; } -void -array_destroy(struct array *a) -{ - array_cleanup(a); - kfree(a); +void array_destroy(struct array *a) { + array_cleanup(a); + kfree(a); } -void -array_init(struct array *a) -{ - a->num = a->max = 0; - a->v = NULL; +void array_init(struct array *a) { + a->num = a->max = 0; + a->v = NULL; } -void -array_cleanup(struct array *a) -{ - /* - * Require array to be empty - helps avoid memory leaks since - * we don't/can't free anything any contents may be pointing - * to. - */ - ARRAYASSERT(a->num == 0); - kfree(a->v); +void array_cleanup(struct array *a) { + /* + * Require array to be empty - helps avoid memory leaks since + * we don't/can't free anything any contents may be pointing + * to. + */ + ARRAYASSERT(a->num == 0); + kfree(a->v); #ifdef ARRAYS_CHECKED - a->v = NULL; + a->v = NULL; #endif } -int -array_preallocate(struct array *a, unsigned num) -{ - void **newptr; - unsigned newmax; +int array_preallocate(struct array *a, unsigned num) { + void **newptr; + unsigned newmax; - if (num > a->max) { - /* Don't touch A until the allocation succeeds. */ - newmax = a->max; - while (num > newmax) { - newmax = newmax ? newmax*2 : 4; - } + if (num > a->max) { + /* Don't touch A until the allocation succeeds. */ + newmax = a->max; + while (num > newmax) { + newmax = newmax ? newmax * 2 : 4; + } - /* - * We don't have krealloc, and it wouldn't be - * worthwhile to implement just for this. So just - * allocate a new block and copy. (Exercise: what - * about this and/or kmalloc makes it not worthwhile?) - */ + /* + * We don't have krealloc, and it wouldn't be + * worthwhile to implement just for this. So just + * allocate a new block and copy. (Exercise: what + * about this and/or kmalloc makes it not worthwhile?) + */ - newptr = kmalloc(newmax*sizeof(*a->v)); - if (newptr == NULL) { - return ENOMEM; - } - memcpy(newptr, a->v, a->num*sizeof(*a->v)); - kfree(a->v); - a->v = newptr; - a->max = newmax; - } - return 0; + newptr = kmalloc(newmax * sizeof(*a->v)); + if (newptr == NULL) { + return ENOMEM; + } + memcpy(newptr, a->v, a->num * sizeof(*a->v)); + kfree(a->v); + a->v = newptr; + a->max = newmax; + } + return 0; } -int -array_setsize(struct array *a, unsigned num) -{ - int result; +int array_setsize(struct array *a, unsigned num) { + int result; - result = array_preallocate(a, num); - if (result) { - return result; - } - a->num = num; + result = array_preallocate(a, num); + if (result) { + return result; + } + a->num = num; - return 0; + return 0; } -void -array_remove(struct array *a, unsigned index) -{ - unsigned num_to_move; +void array_remove(struct array *a, unsigned index) { + unsigned num_to_move; - ARRAYASSERT(a->num <= a->max); - ARRAYASSERT(index < a->num); + ARRAYASSERT(a->num <= a->max); + ARRAYASSERT(index < a->num); - num_to_move = a->num - (index + 1); - memmove(a->v + index, a->v + index+1, num_to_move*sizeof(void *)); - a->num--; + num_to_move = a->num - (index + 1); + memmove(a->v + index, a->v + index + 1, num_to_move * sizeof(void *)); + a->num--; } diff --git a/kern/lib/bitmap.c b/kern/lib/bitmap.c index 1e6ce01..27d3318 100644 --- a/kern/lib/bitmap.c +++ b/kern/lib/bitmap.c @@ -43,134 +43,113 @@ * bitmap data saved on disk becomes endian-dependent, which is a * severe nuisance. */ -#define BITS_PER_WORD (CHAR_BIT) -#define WORD_TYPE unsigned char -#define WORD_ALLBITS (0xff) +#define BITS_PER_WORD (CHAR_BIT) +#define WORD_TYPE unsigned char +#define WORD_ALLBITS (0xff) struct bitmap { - unsigned nbits; - WORD_TYPE *v; + unsigned nbits; + WORD_TYPE *v; }; +struct bitmap *bitmap_create(unsigned nbits) { + struct bitmap *b; + unsigned words; -struct bitmap * -bitmap_create(unsigned nbits) -{ - struct bitmap *b; - unsigned words; + words = DIVROUNDUP(nbits, BITS_PER_WORD); + b = kmalloc(sizeof(struct bitmap)); + if (b == NULL) { + return NULL; + } + b->v = kmalloc(words * sizeof(WORD_TYPE)); + if (b->v == NULL) { + kfree(b); + return NULL; + } - words = DIVROUNDUP(nbits, BITS_PER_WORD); - b = kmalloc(sizeof(struct bitmap)); - if (b == NULL) { - return NULL; + bzero(b->v, words * sizeof(WORD_TYPE)); + b->nbits = nbits; + + /* Mark any leftover bits at the end in use */ + if (words > nbits / BITS_PER_WORD) { + unsigned j, ix = words - 1; + unsigned overbits = nbits - ix * BITS_PER_WORD; + + KASSERT(nbits / BITS_PER_WORD == words - 1); + KASSERT(overbits > 0 && overbits < BITS_PER_WORD); + + for (j = overbits; j < BITS_PER_WORD; j++) { + b->v[ix] |= ((WORD_TYPE)1 << j); + } + } + + return b; +} + +void *bitmap_getdata(struct bitmap *b) { return b->v; } + +int bitmap_alloc(struct bitmap *b, unsigned *index) { + unsigned ix; + unsigned maxix = DIVROUNDUP(b->nbits, BITS_PER_WORD); + unsigned offset; + + for (ix = 0; ix < maxix; ix++) { + if (b->v[ix] != WORD_ALLBITS) { + for (offset = 0; offset < BITS_PER_WORD; offset++) { + WORD_TYPE mask = ((WORD_TYPE)1) << offset; + + if ((b->v[ix] & mask) == 0) { + b->v[ix] |= mask; + *index = (ix * BITS_PER_WORD) + offset; + KASSERT(*index < b->nbits); + return 0; } - b->v = kmalloc(words*sizeof(WORD_TYPE)); - if (b->v == NULL) { - kfree(b); - return NULL; - } - - bzero(b->v, words*sizeof(WORD_TYPE)); - b->nbits = nbits; - - /* Mark any leftover bits at the end in use */ - if (words > nbits / BITS_PER_WORD) { - unsigned j, ix = words-1; - unsigned overbits = nbits - ix*BITS_PER_WORD; - - KASSERT(nbits / BITS_PER_WORD == words-1); - KASSERT(overbits > 0 && overbits < BITS_PER_WORD); - - for (j=overbits; jv[ix] |= ((WORD_TYPE)1 << j); - } - } - - return b; + } + KASSERT(0); + } + } + return ENOSPC; } -void * -bitmap_getdata(struct bitmap *b) -{ - return b->v; +static inline void bitmap_translate(unsigned bitno, unsigned *ix, + WORD_TYPE *mask) { + unsigned offset; + *ix = bitno / BITS_PER_WORD; + offset = bitno % BITS_PER_WORD; + *mask = ((WORD_TYPE)1) << offset; } -int -bitmap_alloc(struct bitmap *b, unsigned *index) -{ - unsigned ix; - unsigned maxix = DIVROUNDUP(b->nbits, BITS_PER_WORD); - unsigned offset; +void bitmap_mark(struct bitmap *b, unsigned index) { + unsigned ix; + WORD_TYPE mask; - for (ix=0; ixv[ix]!=WORD_ALLBITS) { - for (offset = 0; offset < BITS_PER_WORD; offset++) { - WORD_TYPE mask = ((WORD_TYPE)1) << offset; + KASSERT(index < b->nbits); + bitmap_translate(index, &ix, &mask); - if ((b->v[ix] & mask)==0) { - b->v[ix] |= mask; - *index = (ix*BITS_PER_WORD)+offset; - KASSERT(*index < b->nbits); - return 0; - } - } - KASSERT(0); - } - } - return ENOSPC; + KASSERT((b->v[ix] & mask) == 0); + b->v[ix] |= mask; } -static -inline -void -bitmap_translate(unsigned bitno, unsigned *ix, WORD_TYPE *mask) -{ - unsigned offset; - *ix = bitno / BITS_PER_WORD; - offset = bitno % BITS_PER_WORD; - *mask = ((WORD_TYPE)1) << offset; +void bitmap_unmark(struct bitmap *b, unsigned index) { + unsigned ix; + WORD_TYPE mask; + + KASSERT(index < b->nbits); + bitmap_translate(index, &ix, &mask); + + KASSERT((b->v[ix] & mask) != 0); + b->v[ix] &= ~mask; } -void -bitmap_mark(struct bitmap *b, unsigned index) -{ - unsigned ix; - WORD_TYPE mask; +int bitmap_isset(struct bitmap *b, unsigned index) { + unsigned ix; + WORD_TYPE mask; - KASSERT(index < b->nbits); - bitmap_translate(index, &ix, &mask); - - KASSERT((b->v[ix] & mask)==0); - b->v[ix] |= mask; + bitmap_translate(index, &ix, &mask); + return (b->v[ix] & mask); } -void -bitmap_unmark(struct bitmap *b, unsigned index) -{ - unsigned ix; - WORD_TYPE mask; - - KASSERT(index < b->nbits); - bitmap_translate(index, &ix, &mask); - - KASSERT((b->v[ix] & mask)!=0); - b->v[ix] &= ~mask; -} - - -int -bitmap_isset(struct bitmap *b, unsigned index) -{ - unsigned ix; - WORD_TYPE mask; - - bitmap_translate(index, &ix, &mask); - return (b->v[ix] & mask); -} - -void -bitmap_destroy(struct bitmap *b) -{ - kfree(b->v); - kfree(b); +void bitmap_destroy(struct bitmap *b) { + kfree(b->v); + kfree(b); } diff --git a/kern/lib/bswap.c b/kern/lib/bswap.c index fb8adf2..471eee2 100644 --- a/kern/lib/bswap.c +++ b/kern/lib/bswap.c @@ -43,33 +43,23 @@ * loop-based. */ -uint16_t -bswap16(uint16_t val) -{ - return ((val & 0x00ff) << 8) - | ((val & 0xff00) >> 8); +uint16_t bswap16(uint16_t val) { + return ((val & 0x00ff) << 8) | ((val & 0xff00) >> 8); } -uint32_t -bswap32(uint32_t val) -{ - return ((val & 0x000000ff) << 24) - | ((val & 0x0000ff00) << 8) - | ((val & 0x00ff0000) >> 8) - | ((val & 0xff000000) >> 24); +uint32_t bswap32(uint32_t val) { + return ((val & 0x000000ff) << 24) | ((val & 0x0000ff00) << 8) | + ((val & 0x00ff0000) >> 8) | ((val & 0xff000000) >> 24); } -uint64_t -bswap64(uint64_t val) -{ - return ((val & 0x00000000000000ff) << 56) - | ((val & 0x000000000000ff00) << 40) - | ((val & 0x0000000000ff0000) << 24) - | ((val & 0x00000000ff000000) << 8) - | ((val & 0x000000ff00000000) << 8) - | ((val & 0x0000ff0000000000) << 24) - | ((val & 0x00ff000000000000) >> 40) - | ((val & 0xff00000000000000) >> 56); +uint64_t bswap64(uint64_t val) { + return ((val & 0x00000000000000ff) << 56) | + ((val & 0x000000000000ff00) << 40) | + ((val & 0x0000000000ff0000) << 24) | + ((val & 0x00000000ff000000) << 8) | ((val & 0x000000ff00000000) << 8) | + ((val & 0x0000ff0000000000) << 24) | + ((val & 0x00ff000000000000) >> 40) | + ((val & 0xff00000000000000) >> 56); } /* @@ -92,9 +82,9 @@ bswap64(uint64_t val) */ #if _BYTE_ORDER == _LITTLE_ENDIAN -#define TO(tag, bits, type) \ - type ntoh##tag(type val) { return bswap##bits(val); } \ - type hton##tag(type val) { return bswap##bits(val); } +#define TO(tag, bits, type) \ + type ntoh##tag(type val) { return bswap##bits(val); } \ + type hton##tag(type val) { return bswap##bits(val); } #endif /* @@ -103,9 +93,9 @@ bswap64(uint64_t val) * the wrong option. */ #if _BYTE_ORDER == _BIG_ENDIAN -#define TO(tag, bits, type) \ - type ntoh##tag(type val) { return val; } \ - type hton##tag(type val) { return val; } +#define TO(tag, bits, type) \ + type ntoh##tag(type val) { return val; } \ + type hton##tag(type val) { return val; } #endif #if _BYTE_ORDER == _PDP_ENDIAN @@ -116,11 +106,10 @@ bswap64(uint64_t val) #error "_BYTE_ORDER not set" #endif -TO(s, 16, uint16_t) -TO(l, 32, uint32_t) +TO(s, 16, uint16_t) +TO(l, 32, uint32_t) TO(ll, 64, uint64_t) - /* * Some utility functions for handling 64-bit values. * @@ -134,27 +123,23 @@ TO(ll, 64, uint64_t) * word. */ -void -join32to64(uint32_t x1, uint32_t x2, uint64_t *y2) -{ +void join32to64(uint32_t x1, uint32_t x2, uint64_t *y2) { #if _BYTE_ORDER == _BIG_ENDIAN - *y2 = ((uint64_t)x1 << 32) | (uint64_t)x2; + *y2 = ((uint64_t)x1 << 32) | (uint64_t)x2; #elif _BYTE_ORDER == _LITTLE_ENDIAN - *y2 = (uint64_t)x1 | ((uint64_t)x2 << 32); + *y2 = (uint64_t)x1 | ((uint64_t)x2 << 32); #else #error "Eh?" #endif } -void -split64to32(uint64_t x, uint32_t *y1, uint32_t *y2) -{ +void split64to32(uint64_t x, uint32_t *y1, uint32_t *y2) { #if _BYTE_ORDER == _BIG_ENDIAN - *y1 = x >> 32; - *y2 = x & 0xffffffff; + *y1 = x >> 32; + *y2 = x & 0xffffffff; #elif _BYTE_ORDER == _LITTLE_ENDIAN - *y1 = x & 0xffffffff; - *y2 = x >> 32; + *y1 = x & 0xffffffff; + *y2 = x >> 32; #else #error "Eh?" #endif diff --git a/kern/lib/kgets.c b/kern/lib/kgets.c index 18deafb..75b14e6 100644 --- a/kern/lib/kgets.c +++ b/kern/lib/kgets.c @@ -27,7 +27,6 @@ * SUCH DAMAGE. */ - #include #include @@ -36,13 +35,10 @@ * We overwrite the current character with a space in case we're on * a terminal where backspace is nondestructive. */ -static -void -backsp(void) -{ - putch('\b'); - putch(' '); - putch('\b'); +static void backsp(void) { + putch('\b'); + putch(' '); + putch('\b'); } /* @@ -50,64 +46,56 @@ backsp(void) * common control characters. Do not include the terminating newline * in the buffer passed back. */ -void -kgets(char *buf, size_t maxlen) -{ - size_t pos = 0; - int ch; +void kgets(char *buf, size_t maxlen) { + size_t pos = 0; + int ch; - while (1) { - ch = getch(); - if (ch=='\n' || ch=='\r') { - putch('\n'); - break; - } + while (1) { + ch = getch(); + if (ch == '\n' || ch == '\r') { + putch('\n'); + break; + } - /* Only allow the normal 7-bit ascii */ - if (ch>=32 && ch<127 && pos < maxlen-1) { - putch(ch); - buf[pos++] = ch; - } - else if ((ch=='\b' || ch==127) && pos>0) { - /* backspace */ - backsp(); - pos--; - } - else if (ch==3) { - /* ^C - return empty string */ - putch('^'); - putch('C'); - putch('\n'); - pos = 0; - break; - } - else if (ch==18) { - /* ^R - reprint input */ - buf[pos] = 0; - kprintf("^R\n%s", buf); - } - else if (ch==21) { - /* ^U - erase line */ - while (pos > 0) { - backsp(); - pos--; - } - } - else if (ch==23) { - /* ^W - erase word */ - while (pos > 0 && buf[pos-1]==' ') { - backsp(); - pos--; - } - while (pos > 0 && buf[pos-1]!=' ') { - backsp(); - pos--; - } - } - else { - beep(); - } - } + /* Only allow the normal 7-bit ascii */ + if (ch >= 32 && ch < 127 && pos < maxlen - 1) { + putch(ch); + buf[pos++] = ch; + } else if ((ch == '\b' || ch == 127) && pos > 0) { + /* backspace */ + backsp(); + pos--; + } else if (ch == 3) { + /* ^C - return empty string */ + putch('^'); + putch('C'); + putch('\n'); + pos = 0; + break; + } else if (ch == 18) { + /* ^R - reprint input */ + buf[pos] = 0; + kprintf("^R\n%s", buf); + } else if (ch == 21) { + /* ^U - erase line */ + while (pos > 0) { + backsp(); + pos--; + } + } else if (ch == 23) { + /* ^W - erase word */ + while (pos > 0 && buf[pos - 1] == ' ') { + backsp(); + pos--; + } + while (pos > 0 && buf[pos - 1] != ' ') { + backsp(); + pos--; + } + } else { + beep(); + } + } - buf[pos] = 0; + buf[pos] = 0; } diff --git a/kern/lib/kprintf.c b/kern/lib/kprintf.c index 3adc7a3..b2ae049 100644 --- a/kern/lib/kprintf.c +++ b/kern/lib/kprintf.c @@ -37,10 +37,9 @@ #include #include #include -#include // for vfs_sync() +#include // for vfs_sync() #include // for ltrace_stop() - /* Flags word for DEBUG() macro. */ uint32_t dbflags = 0; @@ -50,79 +49,66 @@ static struct lock *kprintf_lock; /* Lock for polled kprintfs */ static struct spinlock kprintf_spinlock; - /* * Warning: all this has to work from interrupt handlers and when * interrupts are disabled. */ - /* * Create the kprintf lock. Must be called before creating a second * thread or enabling a second CPU. */ -void -kprintf_bootstrap(void) -{ - KASSERT(kprintf_lock == NULL); +void kprintf_bootstrap(void) { + KASSERT(kprintf_lock == NULL); - kprintf_lock = lock_create("kprintf_lock"); - if (kprintf_lock == NULL) { - panic("Could not create kprintf_lock\n"); - } - spinlock_init(&kprintf_spinlock); + kprintf_lock = lock_create("kprintf_lock"); + if (kprintf_lock == NULL) { + panic("Could not create kprintf_lock\n"); + } + spinlock_init(&kprintf_spinlock); } /* * Send characters to the console. Backend for __printf. */ -static -void -console_send(void *junk, const char *data, size_t len) -{ - size_t i; +static void console_send(void *junk, const char *data, size_t len) { + size_t i; - (void)junk; + (void)junk; - for (i=0; it_in_interrupt == false - && curthread->t_curspl == 0 - && curcpu->c_spinlocks == 0; + dolock = kprintf_lock != NULL && curthread->t_in_interrupt == false && + curthread->t_curspl == 0 && curcpu->c_spinlocks == 0; - if (dolock) { - lock_acquire(kprintf_lock); - } - else { - spinlock_acquire(&kprintf_spinlock); - } + if (dolock) { + lock_acquire(kprintf_lock); + } else { + spinlock_acquire(&kprintf_spinlock); + } - va_start(ap, fmt); - chars = __vprintf(console_send, NULL, fmt, ap); - va_end(ap); + va_start(ap, fmt); + chars = __vprintf(console_send, NULL, fmt, ap); + va_end(ap); - if (dolock) { - lock_release(kprintf_lock); - } - else { - spinlock_release(&kprintf_spinlock); - } + if (dolock) { + lock_release(kprintf_lock); + } else { + spinlock_release(&kprintf_spinlock); + } - return chars; + return chars; } /* @@ -130,87 +116,83 @@ kprintf(const char *fmt, ...) * passed and then halts the system. */ -void -panic(const char *fmt, ...) -{ - va_list ap; +void panic(const char *fmt, ...) { + va_list ap; - /* - * When we reach panic, the system is usually fairly screwed up. - * It's not entirely uncommon for anything else we try to do - * here to trigger more panics. - * - * This variable makes sure that if we try to do something here, - * and it causes another panic, *that* panic doesn't try again; - * trying again almost inevitably causes infinite recursion. - * - * This is not excessively paranoid - these things DO happen! - */ - static volatile int evil; + /* + * When we reach panic, the system is usually fairly screwed up. + * It's not entirely uncommon for anything else we try to do + * here to trigger more panics. + * + * This variable makes sure that if we try to do something here, + * and it causes another panic, *that* panic doesn't try again; + * trying again almost inevitably causes infinite recursion. + * + * This is not excessively paranoid - these things DO happen! + */ + static volatile int evil; - if (evil == 0) { - evil = 1; + if (evil == 0) { + evil = 1; - /* - * Not only do we not want to be interrupted while - * panicking, but we also want the console to be - * printing in polling mode so as not to do context - * switches. So turn interrupts off on this CPU. - */ - splhigh(); - } + /* + * Not only do we not want to be interrupted while + * panicking, but we also want the console to be + * printing in polling mode so as not to do context + * switches. So turn interrupts off on this CPU. + */ + splhigh(); + } - if (evil == 1) { - evil = 2; + if (evil == 1) { + evil = 2; - /* Kill off other threads and halt other CPUs. */ - thread_panic(); - } + /* Kill off other threads and halt other CPUs. */ + thread_panic(); + } - if (evil == 2) { - evil = 3; + if (evil == 2) { + evil = 3; - /* Print the message. */ - kprintf("panic: "); - va_start(ap, fmt); - __vprintf(console_send, NULL, fmt, ap); - va_end(ap); - } + /* Print the message. */ + kprintf("panic: "); + va_start(ap, fmt); + __vprintf(console_send, NULL, fmt, ap); + va_end(ap); + } - if (evil == 3) { - evil = 4; + if (evil == 3) { + evil = 4; - /* Drop to the debugger. */ - ltrace_stop(0); - } + /* Drop to the debugger. */ + ltrace_stop(0); + } - if (evil == 4) { - evil = 5; + if (evil == 4) { + evil = 5; - /* Try to sync the disks. */ - vfs_sync(); - } + /* Try to sync the disks. */ + vfs_sync(); + } - if (evil == 5) { - evil = 6; + if (evil == 5) { + evil = 6; - /* Shut down or reboot the system. */ - mainbus_panic(); - } + /* Shut down or reboot the system. */ + mainbus_panic(); + } - /* - * Last resort, just in case. - */ + /* + * Last resort, just in case. + */ - for (;;); + for (;;) + ; } /* * Assertion failures go through this. */ -void -badassert(const char *expr, const char *file, int line, const char *func) -{ - panic("Assertion failed: %s, at %s:%d (%s)\n", - expr, file, line, func); +void badassert(const char *expr, const char *file, int line, const char *func) { + panic("Assertion failed: %s, at %s:%d (%s)\n", expr, file, line, func); } diff --git a/kern/lib/misc.c b/kern/lib/misc.c index 2388e1d..200de7d 100644 --- a/kern/lib/misc.c +++ b/kern/lib/misc.c @@ -34,29 +34,25 @@ /* * Like strdup, but calls kmalloc. */ -char * -kstrdup(const char *s) -{ - char *z; +char *kstrdup(const char *s) { + char *z; - z = kmalloc(strlen(s)+1); - if (z == NULL) { - return NULL; - } - strcpy(z, s); - return z; + z = kmalloc(strlen(s) + 1); + if (z == NULL) { + return NULL; + } + strcpy(z, s); + return z; } /* * Standard C function to return a string for a given errno. * Kernel version; panics if it hits an unknown error. */ -const char * -strerror(int errcode) -{ - if (errcode>=0 && errcode < sys_nerr) { - return sys_errlist[errcode]; - } - panic("Invalid error code %d\n", errcode); - return NULL; +const char *strerror(int errcode) { + if (errcode >= 0 && errcode < sys_nerr) { + return sys_errlist[errcode]; + } + panic("Invalid error code %d\n", errcode); + return NULL; } diff --git a/kern/lib/time.c b/kern/lib/time.c index 077e6da..8e1c45d 100644 --- a/kern/lib/time.c +++ b/kern/lib/time.c @@ -33,37 +33,31 @@ /* * ts1 + ts2 */ -void -timespec_add(const struct timespec *ts1, - const struct timespec *ts2, - struct timespec *ret) -{ - ret->tv_nsec = ts1->tv_nsec + ts2->tv_nsec; - ret->tv_sec = ts1->tv_sec + ts2->tv_sec; - if (ret->tv_nsec >= 1000000000) { - ret->tv_nsec -= 1000000000; - ret->tv_sec += 1; - } +void timespec_add(const struct timespec *ts1, const struct timespec *ts2, + struct timespec *ret) { + ret->tv_nsec = ts1->tv_nsec + ts2->tv_nsec; + ret->tv_sec = ts1->tv_sec + ts2->tv_sec; + if (ret->tv_nsec >= 1000000000) { + ret->tv_nsec -= 1000000000; + ret->tv_sec += 1; + } } /* * ts1 - ts2 */ -void -timespec_sub(const struct timespec *ts1, - const struct timespec *ts2, - struct timespec *ret) -{ - /* in case ret and ts1 or ts2 are the same */ - struct timespec r; +void timespec_sub(const struct timespec *ts1, const struct timespec *ts2, + struct timespec *ret) { + /* in case ret and ts1 or ts2 are the same */ + struct timespec r; - r = *ts1; - if (r.tv_nsec < ts2->tv_nsec) { - r.tv_nsec += 1000000000; - r.tv_sec--; - } + r = *ts1; + if (r.tv_nsec < ts2->tv_nsec) { + r.tv_nsec += 1000000000; + r.tv_sec--; + } - r.tv_nsec -= ts2->tv_nsec; - r.tv_sec -= ts2->tv_sec; - *ret = r; + r.tv_nsec -= ts2->tv_nsec; + r.tv_sec -= ts2->tv_sec; + *ret = r; } diff --git a/kern/lib/uio.c b/kern/lib/uio.c index 69f9a85..846f71e 100644 --- a/kern/lib/uio.c +++ b/kern/lib/uio.c @@ -38,127 +38,117 @@ * See uio.h for a description. */ -int -uiomove(void *ptr, size_t n, struct uio *uio) -{ - struct iovec *iov; - size_t size; - int result; +int uiomove(void *ptr, size_t n, struct uio *uio) { + struct iovec *iov; + size_t size; + int result; - if (uio->uio_rw != UIO_READ && uio->uio_rw != UIO_WRITE) { - panic("uiomove: Invalid uio_rw %d\n", (int) uio->uio_rw); - } - if (uio->uio_segflg==UIO_SYSSPACE) { - KASSERT(uio->uio_space == NULL); - } - else { - KASSERT(uio->uio_space == proc_getas()); - } + if (uio->uio_rw != UIO_READ && uio->uio_rw != UIO_WRITE) { + panic("uiomove: Invalid uio_rw %d\n", (int)uio->uio_rw); + } + if (uio->uio_segflg == UIO_SYSSPACE) { + KASSERT(uio->uio_space == NULL); + } else { + KASSERT(uio->uio_space == proc_getas()); + } - while (n > 0 && uio->uio_resid > 0) { - /* get the first iovec */ - iov = uio->uio_iov; - size = iov->iov_len; + while (n > 0 && uio->uio_resid > 0) { + /* get the first iovec */ + iov = uio->uio_iov; + size = iov->iov_len; - if (size > n) { - size = n; - } + if (size > n) { + size = n; + } - if (size == 0) { - /* move to the next iovec and try again */ - uio->uio_iov++; - uio->uio_iovcnt--; - if (uio->uio_iovcnt == 0) { - /* - * This should only happen if you set - * uio_resid incorrectly (to more than - * the total length of buffers the uio - * points to). - */ - panic("uiomove: ran out of buffers\n"); - } - continue; - } + if (size == 0) { + /* move to the next iovec and try again */ + uio->uio_iov++; + uio->uio_iovcnt--; + if (uio->uio_iovcnt == 0) { + /* + * This should only happen if you set + * uio_resid incorrectly (to more than + * the total length of buffers the uio + * points to). + */ + panic("uiomove: ran out of buffers\n"); + } + continue; + } - switch (uio->uio_segflg) { - case UIO_SYSSPACE: - if (uio->uio_rw == UIO_READ) { - memmove(iov->iov_kbase, ptr, size); - } - else { - memmove(ptr, iov->iov_kbase, size); - } - iov->iov_kbase = ((char *)iov->iov_kbase+size); - break; - case UIO_USERSPACE: - case UIO_USERISPACE: - if (uio->uio_rw == UIO_READ) { - result = copyout(ptr, iov->iov_ubase,size); - } - else { - result = copyin(iov->iov_ubase, ptr, size); - } - if (result) { - return result; - } - iov->iov_ubase += size; - break; - default: - panic("uiomove: Invalid uio_segflg %d\n", - (int)uio->uio_segflg); - } + switch (uio->uio_segflg) { + case UIO_SYSSPACE: + if (uio->uio_rw == UIO_READ) { + memmove(iov->iov_kbase, ptr, size); + } else { + memmove(ptr, iov->iov_kbase, size); + } + iov->iov_kbase = ((char *)iov->iov_kbase + size); + break; + case UIO_USERSPACE: + case UIO_USERISPACE: + if (uio->uio_rw == UIO_READ) { + result = copyout(ptr, iov->iov_ubase, size); + } else { + result = copyin(iov->iov_ubase, ptr, size); + } + if (result) { + return result; + } + iov->iov_ubase += size; + break; + default: + panic("uiomove: Invalid uio_segflg %d\n", (int)uio->uio_segflg); + } - iov->iov_len -= size; - uio->uio_resid -= size; - uio->uio_offset += size; - ptr = ((char *)ptr + size); - n -= size; - } + iov->iov_len -= size; + uio->uio_resid -= size; + uio->uio_offset += size; + ptr = ((char *)ptr + size); + n -= size; + } - return 0; + return 0; } -int -uiomovezeros(size_t n, struct uio *uio) -{ - /* static, so initialized as zero */ - static char zeros[16]; - size_t amt; - int result; +int uiomovezeros(size_t n, struct uio *uio) { + /* static, so initialized as zero */ + static char zeros[16]; + size_t amt; + int result; - /* This only makes sense when reading */ - KASSERT(uio->uio_rw == UIO_READ); + /* This only makes sense when reading */ + KASSERT(uio->uio_rw == UIO_READ); - while (n > 0) { - amt = sizeof(zeros); - if (amt > n) { - amt = n; - } - result = uiomove(zeros, amt, uio); - if (result) { - return result; - } - n -= amt; - } + while (n > 0) { + amt = sizeof(zeros); + if (amt > n) { + amt = n; + } + result = uiomove(zeros, amt, uio); + if (result) { + return result; + } + n -= amt; + } - return 0; + return 0; } /* * Convenience function to initialize an iovec and uio for kernel I/O. */ -void -uio_kinit(struct iovec *iov, struct uio *u, - void *kbuf, size_t len, off_t pos, enum uio_rw rw) -{ - iov->iov_kbase = kbuf; - iov->iov_len = len; - u->uio_iov = iov; - u->uio_iovcnt = 1; - u->uio_offset = pos; - u->uio_resid = len; - u->uio_segflg = UIO_SYSSPACE; - u->uio_rw = rw; - u->uio_space = NULL; +void uio_kinit(struct iovec *iov, struct uio *u, void *kbuf, size_t len, + off_t pos, enum uio_rw rw) { + iov->iov_kbase = kbuf; + iov->iov_len = len; + u->uio_iov = iov; + u->uio_iovcnt = 1; + u->uio_offset = pos; + u->uio_resid = len; + u->uio_segflg = UIO_SYSSPACE; + u->uio_rw = rw; + u->uio_space = NULL; } diff --git a/kern/main/main.c b/kern/main/main.c index d095480..4a75012 100644 --- a/kern/main/main.c +++ b/kern/main/main.c @@ -49,8 +49,7 @@ #include #include #include -#include "autoconf.h" // for pseudoconfig - +#include "autoconf.h" // for pseudoconfig /* * These two pieces of data are maintained by the makefiles and build system. @@ -71,92 +70,85 @@ static const char harvard_copyright[] = "Copyright (c) 2000, 2001-2005, 2008-2011, 2013, 2014\n" " President and Fellows of Harvard College. All rights reserved.\n"; - /* * Initial boot sequence. */ -static -void -boot(void) -{ - /* - * The order of these is important! - * Don't go changing it without thinking about the consequences. - * - * Among other things, be aware that console output gets - * buffered up at first and does not actually appear until - * mainbus_bootstrap() attaches the console device. This can - * be remarkably confusing if a bug occurs at this point. So - * don't put new code before mainbus_bootstrap if you don't - * absolutely have to. - * - * Also note that the buffer for this is only 1k. If you - * overflow it, the system will crash without printing - * anything at all. You can make it larger though (it's in - * dev/generic/console.c). - */ +static void boot(void) { + /* + * The order of these is important! + * Don't go changing it without thinking about the consequences. + * + * Among other things, be aware that console output gets + * buffered up at first and does not actually appear until + * mainbus_bootstrap() attaches the console device. This can + * be remarkably confusing if a bug occurs at this point. So + * don't put new code before mainbus_bootstrap if you don't + * absolutely have to. + * + * Also note that the buffer for this is only 1k. If you + * overflow it, the system will crash without printing + * anything at all. You can make it larger though (it's in + * dev/generic/console.c). + */ - kprintf("\n"); - kprintf("OS/161 base system version %s\n", BASE_VERSION); - kprintf("%s", harvard_copyright); - kprintf("\n"); + kprintf("\n"); + kprintf("OS/161 base system version %s\n", BASE_VERSION); + kprintf("%s", harvard_copyright); + kprintf("\n"); - kprintf("Put-your-group-name-here's system version %s (%s #%d)\n", - GROUP_VERSION, buildconfig, buildversion); - kprintf("\n"); + kprintf("Put-your-group-name-here's system version %s (%s #%d)\n", + GROUP_VERSION, buildconfig, buildversion); + kprintf("\n"); - /* Early initialization. */ - ram_bootstrap(); - proc_bootstrap(); - thread_bootstrap(); - hardclock_bootstrap(); - vfs_bootstrap(); - kheap_nextgeneration(); + /* Early initialization. */ + ram_bootstrap(); + proc_bootstrap(); + thread_bootstrap(); + hardclock_bootstrap(); + vfs_bootstrap(); + kheap_nextgeneration(); - /* Probe and initialize devices. Interrupts should come on. */ - kprintf("Device probe...\n"); - KASSERT(curthread->t_curspl > 0); - mainbus_bootstrap(); - KASSERT(curthread->t_curspl == 0); - /* Now do pseudo-devices. */ - pseudoconfig(); - kprintf("\n"); - kheap_nextgeneration(); + /* Probe and initialize devices. Interrupts should come on. */ + kprintf("Device probe...\n"); + KASSERT(curthread->t_curspl > 0); + mainbus_bootstrap(); + KASSERT(curthread->t_curspl == 0); + /* Now do pseudo-devices. */ + pseudoconfig(); + kprintf("\n"); + kheap_nextgeneration(); - /* Late phase of initialization. */ - vm_bootstrap(); - kprintf_bootstrap(); - thread_start_cpus(); + /* Late phase of initialization. */ + vm_bootstrap(); + kprintf_bootstrap(); + thread_start_cpus(); - /* Default bootfs - but ignore failure, in case emu0 doesn't exist */ - vfs_setbootfs("emu0"); + /* Default bootfs - but ignore failure, in case emu0 doesn't exist */ + vfs_setbootfs("emu0"); - kheap_nextgeneration(); + kheap_nextgeneration(); - /* - * Make sure various things aren't screwed up. - */ - COMPILE_ASSERT(sizeof(userptr_t) == sizeof(char *)); - COMPILE_ASSERT(sizeof(*(userptr_t)0) == sizeof(char)); + /* + * Make sure various things aren't screwed up. + */ + COMPILE_ASSERT(sizeof(userptr_t) == sizeof(char *)); + COMPILE_ASSERT(sizeof(*(userptr_t)0) == sizeof(char)); } /* * Shutdown sequence. Opposite to boot(). */ -static -void -shutdown(void) -{ +static void shutdown(void) { - kprintf("Shutting down.\n"); + kprintf("Shutting down.\n"); - vfs_clearbootfs(); - vfs_clearcurdir(); - vfs_unmountall(); + vfs_clearbootfs(); + vfs_clearcurdir(); + vfs_unmountall(); - thread_shutdown(); + thread_shutdown(); - splhigh(); + splhigh(); } /*****************************************/ @@ -168,49 +160,45 @@ shutdown(void) * not because this is where system call code should go. Other syscall * code should probably live in the "syscall" directory. */ -int -sys_reboot(int code) -{ - switch (code) { - case RB_REBOOT: - case RB_HALT: - case RB_POWEROFF: - break; - default: - return EINVAL; - } +int sys_reboot(int code) { + switch (code) { + case RB_REBOOT: + case RB_HALT: + case RB_POWEROFF: + break; + default: + return EINVAL; + } - shutdown(); + shutdown(); - switch (code) { - case RB_HALT: - kprintf("The system is halted.\n"); - mainbus_halt(); - break; - case RB_REBOOT: - kprintf("Rebooting...\n"); - mainbus_reboot(); - break; - case RB_POWEROFF: - kprintf("The system is halted.\n"); - mainbus_poweroff(); - break; - } + switch (code) { + case RB_HALT: + kprintf("The system is halted.\n"); + mainbus_halt(); + break; + case RB_REBOOT: + kprintf("Rebooting...\n"); + mainbus_reboot(); + break; + case RB_POWEROFF: + kprintf("The system is halted.\n"); + mainbus_poweroff(); + break; + } - panic("reboot operation failed\n"); - return 0; + panic("reboot operation failed\n"); + return 0; } /* * Kernel main. Boot up, then fork the menu thread; wait for a reboot * request, and then shut down. */ -void -kmain(char *arguments) -{ - boot(); +void kmain(char *arguments) { + boot(); - menu(arguments); + menu(arguments); - /* Should not get here */ + /* Should not get here */ } diff --git a/kern/main/menu.c b/kern/main/menu.c index 1f5723a..007d631 100644 --- a/kern/main/menu.c +++ b/kern/main/menu.c @@ -52,7 +52,7 @@ #define _PATH_SHELL "/bin/sh" -#define MAXMENUARGS 16 +#define MAXMENUARGS 16 //////////////////////////////////////////////////////////// // @@ -69,33 +69,29 @@ * It copies the program name because runprogram destroys the copy * it gets by passing it to vfs_open(). */ -static -void -cmd_progthread(void *ptr, unsigned long nargs) -{ - char **args = ptr; - char progname[128]; - int result; +static void cmd_progthread(void *ptr, unsigned long nargs) { + char **args = ptr; + char progname[128]; + int result; - KASSERT(nargs >= 1); + KASSERT(nargs >= 1); - if (nargs > 2) { - kprintf("Warning: argument passing from menu not supported\n"); - } + if (nargs > 2) { + kprintf("Warning: argument passing from menu not supported\n"); + } - /* Hope we fit. */ - KASSERT(strlen(args[0]) < sizeof(progname)); + /* Hope we fit. */ + KASSERT(strlen(args[0]) < sizeof(progname)); - strcpy(progname, args[0]); + strcpy(progname, args[0]); - result = runprogram(progname); - if (result) { - kprintf("Running program %s failed: %s\n", args[0], - strerror(result)); - return; - } + result = runprogram(progname); + if (result) { + kprintf("Running program %s failed: %s\n", args[0], strerror(result)); + return; + } - /* NOTREACHED: runprogram only returns on error. */ + /* NOTREACHED: runprogram only returns on error. */ } /* @@ -110,253 +106,218 @@ cmd_progthread(void *ptr, unsigned long nargs) * array and strings, until you do this a race condition exists * between that code and the menu input code. */ -static -int -common_prog(int nargs, char **args) -{ - struct proc *proc; - int result; +static int common_prog(int nargs, char **args) { + struct proc *proc; + int result; - /* Create a process for the new program to run in. */ - proc = proc_create_runprogram(args[0] /* name */); - if (proc == NULL) { - return ENOMEM; - } + /* Create a process for the new program to run in. */ + proc = proc_create_runprogram(args[0] /* name */); + if (proc == NULL) { + return ENOMEM; + } - result = thread_fork(args[0] /* thread name */, - proc /* new process */, - cmd_progthread /* thread function */, - args /* thread arg */, nargs /* thread arg */); - if (result) { - kprintf("thread_fork failed: %s\n", strerror(result)); - proc_destroy(proc); - return result; - } + result = thread_fork(args[0] /* thread name */, proc /* new process */, + cmd_progthread /* thread function */, + args /* thread arg */, nargs /* thread arg */); + if (result) { + kprintf("thread_fork failed: %s\n", strerror(result)); + proc_destroy(proc); + return result; + } - /* - * The new process will be destroyed when the program exits... - * once you write the code for handling that. - */ + /* + * The new process will be destroyed when the program exits... + * once you write the code for handling that. + */ - return 0; + return 0; } /* * Command for running an arbitrary userlevel program. */ -static -int -cmd_prog(int nargs, char **args) -{ - if (nargs < 2) { - kprintf("Usage: p program [arguments]\n"); - return EINVAL; - } +static int cmd_prog(int nargs, char **args) { + if (nargs < 2) { + kprintf("Usage: p program [arguments]\n"); + return EINVAL; + } - /* drop the leading "p" */ - args++; - nargs--; + /* drop the leading "p" */ + args++; + nargs--; - return common_prog(nargs, args); + return common_prog(nargs, args); } /* * Command for starting the system shell. */ -static -int -cmd_shell(int nargs, char **args) -{ - (void)args; - if (nargs != 1) { - kprintf("Usage: s\n"); - return EINVAL; - } +static int cmd_shell(int nargs, char **args) { + (void)args; + if (nargs != 1) { + kprintf("Usage: s\n"); + return EINVAL; + } - args[0] = (char *)_PATH_SHELL; + args[0] = (char *)_PATH_SHELL; - return common_prog(nargs, args); + return common_prog(nargs, args); } /* * Command for changing directory. */ -static -int -cmd_chdir(int nargs, char **args) -{ - if (nargs != 2) { - kprintf("Usage: cd directory\n"); - return EINVAL; - } +static int cmd_chdir(int nargs, char **args) { + if (nargs != 2) { + kprintf("Usage: cd directory\n"); + return EINVAL; + } - return vfs_chdir(args[1]); + return vfs_chdir(args[1]); } /* * Command for printing the current directory. */ -static -int -cmd_pwd(int nargs, char **args) -{ - char buf[PATH_MAX+1]; - int result; - struct iovec iov; - struct uio ku; +static int cmd_pwd(int nargs, char **args) { + char buf[PATH_MAX + 1]; + int result; + struct iovec iov; + struct uio ku; - (void)nargs; - (void)args; + (void)nargs; + (void)args; - uio_kinit(&iov, &ku, buf, sizeof(buf)-1, 0, UIO_READ); - result = vfs_getcwd(&ku); - if (result) { - kprintf("vfs_getcwd failed (%s)\n", strerror(result)); - return result; - } + uio_kinit(&iov, &ku, buf, sizeof(buf) - 1, 0, UIO_READ); + result = vfs_getcwd(&ku); + if (result) { + kprintf("vfs_getcwd failed (%s)\n", strerror(result)); + return result; + } - /* null terminate */ - buf[sizeof(buf)-1-ku.uio_resid] = 0; + /* null terminate */ + buf[sizeof(buf) - 1 - ku.uio_resid] = 0; - /* print it */ - kprintf("%s\n", buf); + /* print it */ + kprintf("%s\n", buf); - return 0; + return 0; } /* * Command for running sync. */ -static -int -cmd_sync(int nargs, char **args) -{ - (void)nargs; - (void)args; +static int cmd_sync(int nargs, char **args) { + (void)nargs; + (void)args; - vfs_sync(); + vfs_sync(); - return 0; + return 0; } /* * Command for dropping to the debugger. */ -static -int -cmd_debug(int nargs, char **args) -{ - (void)nargs; - (void)args; +static int cmd_debug(int nargs, char **args) { + (void)nargs; + (void)args; - mainbus_debugger(); + mainbus_debugger(); - return 0; + return 0; } /* * Command for doing an intentional panic. */ -static -int -cmd_panic(int nargs, char **args) -{ - (void)nargs; - (void)args; +static int cmd_panic(int nargs, char **args) { + (void)nargs; + (void)args; - panic("User requested panic\n"); - return 0; + panic("User requested panic\n"); + return 0; } /* * Subthread for intentially deadlocking. */ struct deadlock { - struct lock *lock1; - struct lock *lock2; + struct lock *lock1; + struct lock *lock2; }; -static -void -cmd_deadlockthread(void *ptr, unsigned long num) -{ - struct deadlock *dl = ptr; +static void cmd_deadlockthread(void *ptr, unsigned long num) { + struct deadlock *dl = ptr; - (void)num; + (void)num; - /* If it doesn't wedge right away, keep trying... */ - while (1) { - lock_acquire(dl->lock2); - lock_acquire(dl->lock1); - kprintf("+"); - lock_release(dl->lock1); - lock_release(dl->lock2); - } + /* If it doesn't wedge right away, keep trying... */ + while (1) { + lock_acquire(dl->lock2); + lock_acquire(dl->lock1); + kprintf("+"); + lock_release(dl->lock1); + lock_release(dl->lock2); + } } /* * Command for doing an intentional deadlock. */ -static -int -cmd_deadlock(int nargs, char **args) -{ - struct deadlock dl; - int result; +static int cmd_deadlock(int nargs, char **args) { + struct deadlock dl; + int result; - (void)nargs; - (void)args; + (void)nargs; + (void)args; - dl.lock1 = lock_create("deadlock1"); - if (dl.lock1 == NULL) { - kprintf("lock_create failed\n"); - return ENOMEM; - } - dl.lock2 = lock_create("deadlock2"); - if (dl.lock2 == NULL) { - lock_destroy(dl.lock1); - kprintf("lock_create failed\n"); - return ENOMEM; - } + dl.lock1 = lock_create("deadlock1"); + if (dl.lock1 == NULL) { + kprintf("lock_create failed\n"); + return ENOMEM; + } + dl.lock2 = lock_create("deadlock2"); + if (dl.lock2 == NULL) { + lock_destroy(dl.lock1); + kprintf("lock_create failed\n"); + return ENOMEM; + } - result = thread_fork(args[0] /* thread name */, - NULL /* kernel thread */, - cmd_deadlockthread /* thread function */, - &dl /* thread arg */, 0 /* thread arg */); - if (result) { - kprintf("thread_fork failed: %s\n", strerror(result)); - lock_release(dl.lock1); - lock_destroy(dl.lock2); - lock_destroy(dl.lock1); - return result; - } + result = thread_fork(args[0] /* thread name */, NULL /* kernel thread */, + cmd_deadlockthread /* thread function */, + &dl /* thread arg */, 0 /* thread arg */); + if (result) { + kprintf("thread_fork failed: %s\n", strerror(result)); + lock_release(dl.lock1); + lock_destroy(dl.lock2); + lock_destroy(dl.lock1); + return result; + } - /* If it doesn't wedge right away, keep trying... */ - while (1) { - lock_acquire(dl.lock1); - lock_acquire(dl.lock2); - kprintf("."); - lock_release(dl.lock2); - lock_release(dl.lock1); - } - /* NOTREACHED */ - return 0; + /* If it doesn't wedge right away, keep trying... */ + while (1) { + lock_acquire(dl.lock1); + lock_acquire(dl.lock2); + kprintf("."); + lock_release(dl.lock2); + lock_release(dl.lock1); + } + /* NOTREACHED */ + return 0; } /* * Command for shutting down. */ -static -int -cmd_quit(int nargs, char **args) -{ - (void)nargs; - (void)args; +static int cmd_quit(int nargs, char **args) { + (void)nargs; + (void)args; - vfs_sync(); - sys_reboot(RB_POWEROFF); - thread_exit(); - return 0; + vfs_sync(); + sys_reboot(RB_POWEROFF); + thread_exit(); + return 0; } /* @@ -365,63 +326,57 @@ cmd_quit(int nargs, char **args) /* Table of mountable filesystem types. */ static const struct { - const char *name; - int (*func)(const char *device); + const char *name; + int (*func)(const char *device); } mounttable[] = { #if OPT_SFS - { "sfs", sfs_mount }, + {"sfs", sfs_mount}, #endif }; -static -int -cmd_mount(int nargs, char **args) -{ - char *fstype; - char *device; - unsigned i; +static int cmd_mount(int nargs, char **args) { + char *fstype; + char *device; + unsigned i; - if (nargs != 3) { - kprintf("Usage: mount fstype device:\n"); - return EINVAL; - } + if (nargs != 3) { + kprintf("Usage: mount fstype device:\n"); + return EINVAL; + } - fstype = args[1]; - device = args[2]; + fstype = args[1]; + device = args[2]; - /* Allow (but do not require) colon after device name */ - if (device[strlen(device)-1]==':') { - device[strlen(device)-1] = 0; - } + /* Allow (but do not require) colon after device name */ + if (device[strlen(device) - 1] == ':') { + device[strlen(device) - 1] = 0; + } - for (i=0; i= MAXMENUARGS) { - kprintf("Command line has too many words\n"); - return E2BIG; - } - args[nargs++] = word; - } + if (nargs >= MAXMENUARGS) { + kprintf("Command line has too many words\n"); + return E2BIG; + } + args[nargs++] = word; + } - if (nargs==0) { - return 0; - } + if (nargs == 0) { + return 0; + } - for (i=0; cmdtable[i].name; i++) { - if (*cmdtable[i].name && !strcmp(args[0], cmdtable[i].name)) { - KASSERT(cmdtable[i].func!=NULL); + for (i = 0; cmdtable[i].name; i++) { + if (*cmdtable[i].name && !strcmp(args[0], cmdtable[i].name)) { + KASSERT(cmdtable[i].func != NULL); - gettime(&before); + gettime(&before); - result = cmdtable[i].func(nargs, args); + result = cmdtable[i].func(nargs, args); - gettime(&after); - timespec_sub(&after, &before, &duration); + gettime(&after); + timespec_sub(&after, &before, &duration); - kprintf("Operation took %llu.%09lu seconds\n", - (unsigned long long) duration.tv_sec, - (unsigned long) duration.tv_nsec); + kprintf("Operation took %llu.%09lu seconds\n", + (unsigned long long)duration.tv_sec, + (unsigned long)duration.tv_nsec); - return result; - } - } + return result; + } + } - kprintf("%s: Command not found\n", args[0]); - return EINVAL; + kprintf("%s: Command not found\n", args[0]); + return EINVAL; } /* @@ -769,30 +687,26 @@ cmd_dispatch(char *cmd) * If "isargs" is set, we're doing command-line processing; print the * comamnds as we execute them and panic if the command is invalid or fails. */ -static -void -menu_execute(char *line, int isargs) -{ - char *command; - char *context; - int result; +static void menu_execute(char *line, int isargs) { + char *command; + char *context; + int result; - for (command = strtok_r(line, ";", &context); - command != NULL; - command = strtok_r(NULL, ";", &context)) { + for (command = strtok_r(line, ";", &context); command != NULL; + command = strtok_r(NULL, ";", &context)) { - if (isargs) { - kprintf("OS/161 kernel: %s\n", command); - } + if (isargs) { + kprintf("OS/161 kernel: %s\n", command); + } - result = cmd_dispatch(command); - if (result) { - kprintf("Menu command failed: %s\n", strerror(result)); - if (isargs) { - panic("Failure processing kernel arguments\n"); - } - } - } + result = cmd_dispatch(command); + if (result) { + kprintf("Menu command failed: %s\n", strerror(result)); + if (isargs) { + panic("Failure processing kernel arguments\n"); + } + } + } } /* @@ -812,16 +726,14 @@ menu_execute(char *line, int isargs) * "mount sfs lhd0; bootfs lhd0; s" */ -void -menu(char *args) -{ - char buf[64]; +void menu(char *args) { + char buf[64]; - menu_execute(args, 1); + menu_execute(args, 1); - while (1) { - kprintf("OS/161 kernel [? for menu]: "); - kgets(buf, sizeof(buf)); - menu_execute(buf, 0); - } + while (1) { + kprintf("OS/161 kernel [? for menu]: "); + kgets(buf, sizeof(buf)); + menu_execute(buf, 0); + } } diff --git a/kern/proc/proc.c b/kern/proc/proc.c index 2db8ea2..007c0fb 100644 --- a/kern/proc/proc.c +++ b/kern/proc/proc.c @@ -57,32 +57,29 @@ struct proc *kproc; /* * Create a proc structure. */ -static -struct proc * -proc_create(const char *name) -{ - struct proc *proc; +static struct proc *proc_create(const char *name) { + struct proc *proc; - proc = kmalloc(sizeof(*proc)); - if (proc == NULL) { - return NULL; - } - proc->p_name = kstrdup(name); - if (proc->p_name == NULL) { - kfree(proc); - return NULL; - } + proc = kmalloc(sizeof(*proc)); + if (proc == NULL) { + return NULL; + } + proc->p_name = kstrdup(name); + if (proc->p_name == NULL) { + kfree(proc); + return NULL; + } - proc->p_numthreads = 0; - spinlock_init(&proc->p_lock); + proc->p_numthreads = 0; + spinlock_init(&proc->p_lock); - /* VM fields */ - proc->p_addrspace = NULL; + /* VM fields */ + proc->p_addrspace = NULL; - /* VFS fields */ - proc->p_cwd = NULL; + /* VFS fields */ + proc->p_cwd = NULL; - return proc; + return proc; } /* @@ -91,97 +88,92 @@ proc_create(const char *name) * Note: nothing currently calls this. Your wait/exit code will * probably want to do so. */ -void -proc_destroy(struct proc *proc) -{ - /* - * You probably want to destroy and null out much of the - * process (particularly the address space) at exit time if - * your wait/exit design calls for the process structure to - * hang around beyond process exit. Some wait/exit designs - * do, some don't. - */ +void proc_destroy(struct proc *proc) { + /* + * You probably want to destroy and null out much of the + * process (particularly the address space) at exit time if + * your wait/exit design calls for the process structure to + * hang around beyond process exit. Some wait/exit designs + * do, some don't. + */ - KASSERT(proc != NULL); - KASSERT(proc != kproc); + KASSERT(proc != NULL); + KASSERT(proc != kproc); - /* - * We don't take p_lock in here because we must have the only - * reference to this structure. (Otherwise it would be - * incorrect to destroy it.) - */ + /* + * We don't take p_lock in here because we must have the only + * reference to this structure. (Otherwise it would be + * incorrect to destroy it.) + */ - /* VFS fields */ - if (proc->p_cwd) { - VOP_DECREF(proc->p_cwd); - proc->p_cwd = NULL; - } + /* VFS fields */ + if (proc->p_cwd) { + VOP_DECREF(proc->p_cwd); + proc->p_cwd = NULL; + } - /* VM fields */ - if (proc->p_addrspace) { - /* - * If p is the current process, remove it safely from - * p_addrspace before destroying it. This makes sure - * we don't try to activate the address space while - * it's being destroyed. - * - * Also explicitly deactivate, because setting the - * address space to NULL won't necessarily do that. - * - * (When the address space is NULL, it means the - * process is kernel-only; in that case it is normally - * ok if the MMU and MMU- related data structures - * still refer to the address space of the last - * process that had one. Then you save work if that - * process is the next one to run, which isn't - * uncommon. However, here we're going to destroy the - * address space, so we need to make sure that nothing - * in the VM system still refers to it.) - * - * The call to as_deactivate() must come after we - * clear the address space, or a timer interrupt might - * reactivate the old address space again behind our - * back. - * - * If p is not the current process, still remove it - * from p_addrspace before destroying it as a - * precaution. Note that if p is not the current - * process, in order to be here p must either have - * never run (e.g. cleaning up after fork failed) or - * have finished running and exited. It is quite - * incorrect to destroy the proc structure of some - * random other process while it's still running... - */ - struct addrspace *as; + /* VM fields */ + if (proc->p_addrspace) { + /* + * If p is the current process, remove it safely from + * p_addrspace before destroying it. This makes sure + * we don't try to activate the address space while + * it's being destroyed. + * + * Also explicitly deactivate, because setting the + * address space to NULL won't necessarily do that. + * + * (When the address space is NULL, it means the + * process is kernel-only; in that case it is normally + * ok if the MMU and MMU- related data structures + * still refer to the address space of the last + * process that had one. Then you save work if that + * process is the next one to run, which isn't + * uncommon. However, here we're going to destroy the + * address space, so we need to make sure that nothing + * in the VM system still refers to it.) + * + * The call to as_deactivate() must come after we + * clear the address space, or a timer interrupt might + * reactivate the old address space again behind our + * back. + * + * If p is not the current process, still remove it + * from p_addrspace before destroying it as a + * precaution. Note that if p is not the current + * process, in order to be here p must either have + * never run (e.g. cleaning up after fork failed) or + * have finished running and exited. It is quite + * incorrect to destroy the proc structure of some + * random other process while it's still running... + */ + struct addrspace *as; - if (proc == curproc) { - as = proc_setas(NULL); - as_deactivate(); - } - else { - as = proc->p_addrspace; - proc->p_addrspace = NULL; - } - as_destroy(as); - } + if (proc == curproc) { + as = proc_setas(NULL); + as_deactivate(); + } else { + as = proc->p_addrspace; + proc->p_addrspace = NULL; + } + as_destroy(as); + } - KASSERT(proc->p_numthreads == 0); - spinlock_cleanup(&proc->p_lock); + KASSERT(proc->p_numthreads == 0); + spinlock_cleanup(&proc->p_lock); - kfree(proc->p_name); - kfree(proc); + kfree(proc->p_name); + kfree(proc); } /* * Create the process structure for the kernel. */ -void -proc_bootstrap(void) -{ - kproc = proc_create("[kernel]"); - if (kproc == NULL) { - panic("proc_create for kproc failed\n"); - } +void proc_bootstrap(void) { + kproc = proc_create("[kernel]"); + if (kproc == NULL) { + panic("proc_create for kproc failed\n"); + } } /* @@ -190,35 +182,33 @@ proc_bootstrap(void) * It will have no address space and will inherit the current * process's (that is, the kernel menu's) current directory. */ -struct proc * -proc_create_runprogram(const char *name) -{ - struct proc *newproc; +struct proc *proc_create_runprogram(const char *name) { + struct proc *newproc; - newproc = proc_create(name); - if (newproc == NULL) { - return NULL; - } + newproc = proc_create(name); + if (newproc == NULL) { + return NULL; + } - /* VM fields */ + /* VM fields */ - newproc->p_addrspace = NULL; + newproc->p_addrspace = NULL; - /* VFS fields */ + /* VFS fields */ - /* - * Lock the current process to copy its current directory. - * (We don't need to lock the new process, though, as we have - * the only reference to it.) - */ - spinlock_acquire(&curproc->p_lock); - if (curproc->p_cwd != NULL) { - VOP_INCREF(curproc->p_cwd); - newproc->p_cwd = curproc->p_cwd; - } - spinlock_release(&curproc->p_lock); + /* + * Lock the current process to copy its current directory. + * (We don't need to lock the new process, though, as we have + * the only reference to it.) + */ + spinlock_acquire(&curproc->p_lock); + if (curproc->p_cwd != NULL) { + VOP_INCREF(curproc->p_cwd); + newproc->p_cwd = curproc->p_cwd; + } + spinlock_release(&curproc->p_lock); - return newproc; + return newproc; } /* @@ -230,22 +220,20 @@ proc_create_runprogram(const char *name) * the timer interrupt context switch, and any other implicit uses * of "curproc". */ -int -proc_addthread(struct proc *proc, struct thread *t) -{ - int spl; +int proc_addthread(struct proc *proc, struct thread *t) { + int spl; - KASSERT(t->t_proc == NULL); + KASSERT(t->t_proc == NULL); - spinlock_acquire(&proc->p_lock); - proc->p_numthreads++; - spinlock_release(&proc->p_lock); + spinlock_acquire(&proc->p_lock); + proc->p_numthreads++; + spinlock_release(&proc->p_lock); - spl = splhigh(); - t->t_proc = proc; - splx(spl); + spl = splhigh(); + t->t_proc = proc; + splx(spl); - return 0; + return 0; } /* @@ -257,23 +245,21 @@ proc_addthread(struct proc *proc, struct thread *t) * the timer interrupt context switch, and any other implicit uses * of "curproc". */ -void -proc_remthread(struct thread *t) -{ - struct proc *proc; - int spl; +void proc_remthread(struct thread *t) { + struct proc *proc; + int spl; - proc = t->t_proc; - KASSERT(proc != NULL); + proc = t->t_proc; + KASSERT(proc != NULL); - spinlock_acquire(&proc->p_lock); - KASSERT(proc->p_numthreads > 0); - proc->p_numthreads--; - spinlock_release(&proc->p_lock); + spinlock_acquire(&proc->p_lock); + KASSERT(proc->p_numthreads > 0); + proc->p_numthreads--; + spinlock_release(&proc->p_lock); - spl = splhigh(); - t->t_proc = NULL; - splx(spl); + spl = splhigh(); + t->t_proc = NULL; + splx(spl); } /* @@ -284,37 +270,33 @@ proc_remthread(struct thread *t) * some other method to make this safe. Otherwise the returned address * space might disappear under you. */ -struct addrspace * -proc_getas(void) -{ - struct addrspace *as; - struct proc *proc = curproc; +struct addrspace *proc_getas(void) { + struct addrspace *as; + struct proc *proc = curproc; - if (proc == NULL) { - return NULL; - } + if (proc == NULL) { + return NULL; + } - spinlock_acquire(&proc->p_lock); - as = proc->p_addrspace; - spinlock_release(&proc->p_lock); - return as; + spinlock_acquire(&proc->p_lock); + as = proc->p_addrspace; + spinlock_release(&proc->p_lock); + return as; } /* * Change the address space of (the current) process. Return the old * one for later restoration or disposal. */ -struct addrspace * -proc_setas(struct addrspace *newas) -{ - struct addrspace *oldas; - struct proc *proc = curproc; +struct addrspace *proc_setas(struct addrspace *newas) { + struct addrspace *oldas; + struct proc *proc = curproc; - KASSERT(proc != NULL); + KASSERT(proc != NULL); - spinlock_acquire(&proc->p_lock); - oldas = proc->p_addrspace; - proc->p_addrspace = newas; - spinlock_release(&proc->p_lock); - return oldas; + spinlock_acquire(&proc->p_lock); + oldas = proc->p_addrspace; + proc->p_addrspace = newas; + spinlock_release(&proc->p_lock); + return oldas; } diff --git a/kern/syscall/loadelf.c b/kern/syscall/loadelf.c index ccfc5f9..f0d55c8 100644 --- a/kern/syscall/loadelf.c +++ b/kern/syscall/loadelf.c @@ -27,7 +27,6 @@ * SUCH DAMAGE. */ - /* * Code to load an ELF-format executable into the current address space. * @@ -74,60 +73,56 @@ * change this code to not use uiomove, be sure to check for this case * explicitly. */ -static -int -load_segment(struct addrspace *as, struct vnode *v, - off_t offset, vaddr_t vaddr, - size_t memsize, size_t filesize, - int is_executable) -{ - struct iovec iov; - struct uio u; - int result; +static int load_segment(struct addrspace *as, struct vnode *v, off_t offset, + vaddr_t vaddr, size_t memsize, size_t filesize, + int is_executable) { + struct iovec iov; + struct uio u; + int result; - if (filesize > memsize) { - kprintf("ELF: warning: segment filesize > segment memsize\n"); - filesize = memsize; - } + if (filesize > memsize) { + kprintf("ELF: warning: segment filesize > segment memsize\n"); + filesize = memsize; + } - DEBUG(DB_EXEC, "ELF: Loading %lu bytes to 0x%lx\n", - (unsigned long) filesize, (unsigned long) vaddr); + DEBUG(DB_EXEC, "ELF: Loading %lu bytes to 0x%lx\n", (unsigned long)filesize, + (unsigned long)vaddr); - iov.iov_ubase = (userptr_t)vaddr; - iov.iov_len = memsize; // length of the memory space - u.uio_iov = &iov; - u.uio_iovcnt = 1; - u.uio_resid = filesize; // amount to read from the file - u.uio_offset = offset; - u.uio_segflg = is_executable ? UIO_USERISPACE : UIO_USERSPACE; - u.uio_rw = UIO_READ; - u.uio_space = as; + iov.iov_ubase = (userptr_t)vaddr; + iov.iov_len = memsize; // length of the memory space + u.uio_iov = &iov; + u.uio_iovcnt = 1; + u.uio_resid = filesize; // amount to read from the file + u.uio_offset = offset; + u.uio_segflg = is_executable ? UIO_USERISPACE : UIO_USERSPACE; + u.uio_rw = UIO_READ; + u.uio_space = as; - result = VOP_READ(v, &u); - if (result) { - return result; - } + result = VOP_READ(v, &u); + if (result) { + return result; + } - if (u.uio_resid != 0) { - /* short read; problem with executable? */ - kprintf("ELF: short read on segment - file truncated?\n"); - return ENOEXEC; - } + if (u.uio_resid != 0) { + /* short read; problem with executable? */ + kprintf("ELF: short read on segment - file truncated?\n"); + return ENOEXEC; + } - /* - * If memsize > filesize, the remaining space should be - * zero-filled. There is no need to do this explicitly, - * because the VM system should provide pages that do not - * contain other processes' data, i.e., are already zeroed. - * - * During development of your VM system, it may have bugs that - * cause it to (maybe only sometimes) not provide zero-filled - * pages, which can cause user programs to fail in strange - * ways. Explicitly zeroing program BSS may help identify such - * bugs, so the following disabled code is provided as a - * diagnostic tool. Note that it must be disabled again before - * you submit your code for grading. - */ + /* + * If memsize > filesize, the remaining space should be + * zero-filled. There is no need to do this explicitly, + * because the VM system should provide pages that do not + * contain other processes' data, i.e., are already zeroed. + * + * During development of your VM system, it may have bugs that + * cause it to (maybe only sometimes) not provide zero-filled + * pages, which can cause user programs to fail in strange + * ways. Explicitly zeroing program BSS may help identify such + * bugs, so the following disabled code is provided as a + * diagnostic tool. Note that it must be disabled again before + * you submit your code for grading. + */ #if 0 { size_t fillamt; @@ -142,7 +137,7 @@ load_segment(struct addrspace *as, struct vnode *v, } #endif - return result; + return result; } /* @@ -150,158 +145,154 @@ load_segment(struct addrspace *as, struct vnode *v, * * Returns the entry point (initial PC) for the program in ENTRYPOINT. */ -int -load_elf(struct vnode *v, vaddr_t *entrypoint) -{ - Elf_Ehdr eh; /* Executable header */ - Elf_Phdr ph; /* "Program header" = segment header */ - int result, i; - struct iovec iov; - struct uio ku; - struct addrspace *as; +int load_elf(struct vnode *v, vaddr_t *entrypoint) { + Elf_Ehdr eh; /* Executable header */ + Elf_Phdr ph; /* "Program header" = segment header */ + int result, i; + struct iovec iov; + struct uio ku; + struct addrspace *as; - as = proc_getas(); + as = proc_getas(); - /* - * Read the executable header from offset 0 in the file. - */ + /* + * Read the executable header from offset 0 in the file. + */ - uio_kinit(&iov, &ku, &eh, sizeof(eh), 0, UIO_READ); - result = VOP_READ(v, &ku); - if (result) { - return result; - } + uio_kinit(&iov, &ku, &eh, sizeof(eh), 0, UIO_READ); + result = VOP_READ(v, &ku); + if (result) { + return result; + } - if (ku.uio_resid != 0) { - /* short read; problem with executable? */ - kprintf("ELF: short read on header - file truncated?\n"); - return ENOEXEC; - } + if (ku.uio_resid != 0) { + /* short read; problem with executable? */ + kprintf("ELF: short read on header - file truncated?\n"); + return ENOEXEC; + } - /* - * Check to make sure it's a 32-bit ELF-version-1 executable - * for our processor type. If it's not, we can't run it. - * - * Ignore EI_OSABI and EI_ABIVERSION - properly, we should - * define our own, but that would require tinkering with the - * linker to have it emit our magic numbers instead of the - * default ones. (If the linker even supports these fields, - * which were not in the original elf spec.) - */ + /* + * Check to make sure it's a 32-bit ELF-version-1 executable + * for our processor type. If it's not, we can't run it. + * + * Ignore EI_OSABI and EI_ABIVERSION - properly, we should + * define our own, but that would require tinkering with the + * linker to have it emit our magic numbers instead of the + * default ones. (If the linker even supports these fields, + * which were not in the original elf spec.) + */ - if (eh.e_ident[EI_MAG0] != ELFMAG0 || - eh.e_ident[EI_MAG1] != ELFMAG1 || - eh.e_ident[EI_MAG2] != ELFMAG2 || - eh.e_ident[EI_MAG3] != ELFMAG3 || - eh.e_ident[EI_CLASS] != ELFCLASS32 || - eh.e_ident[EI_DATA] != ELFDATA2MSB || - eh.e_ident[EI_VERSION] != EV_CURRENT || - eh.e_version != EV_CURRENT || - eh.e_type!=ET_EXEC || - eh.e_machine!=EM_MACHINE) { - return ENOEXEC; - } + if (eh.e_ident[EI_MAG0] != ELFMAG0 || eh.e_ident[EI_MAG1] != ELFMAG1 || + eh.e_ident[EI_MAG2] != ELFMAG2 || eh.e_ident[EI_MAG3] != ELFMAG3 || + eh.e_ident[EI_CLASS] != ELFCLASS32 || + eh.e_ident[EI_DATA] != ELFDATA2MSB || + eh.e_ident[EI_VERSION] != EV_CURRENT || eh.e_version != EV_CURRENT || + eh.e_type != ET_EXEC || eh.e_machine != EM_MACHINE) { + return ENOEXEC; + } - /* - * Go through the list of segments and set up the address space. - * - * Ordinarily there will be one code segment, one read-only - * data segment, and one data/bss segment, but there might - * conceivably be more. You don't need to support such files - * if it's unduly awkward to do so. - * - * Note that the expression eh.e_phoff + i*eh.e_phentsize is - * mandated by the ELF standard - we use sizeof(ph) to load, - * because that's the structure we know, but the file on disk - * might have a larger structure, so we must use e_phentsize - * to find where the phdr starts. - */ + /* + * Go through the list of segments and set up the address space. + * + * Ordinarily there will be one code segment, one read-only + * data segment, and one data/bss segment, but there might + * conceivably be more. You don't need to support such files + * if it's unduly awkward to do so. + * + * Note that the expression eh.e_phoff + i*eh.e_phentsize is + * mandated by the ELF standard - we use sizeof(ph) to load, + * because that's the structure we know, but the file on disk + * might have a larger structure, so we must use e_phentsize + * to find where the phdr starts. + */ - for (i=0; i #define TESTSIZE 73 -#define BIGTESTSIZE 3000 /* more than one page of pointers */ -#define NTH(i) ((void *)(0xb007 + 3*(i))) +#define BIGTESTSIZE 3000 /* more than one page of pointers */ +#define NTH(i) ((void *)(0xb007 + 3 * (i))) -static -void -testa(struct array *a) -{ - int testarray[TESTSIZE]; - int i, j, n, r, *p; +static void testa(struct array *a) { + int testarray[TESTSIZE]; + int i, j, n, r, *p; - for (i=0; i #include -#define SLOGAN "HODIE MIHI - CRAS TIBI\n" +#define SLOGAN "HODIE MIHI - CRAS TIBI\n" #define FILENAME "fstest.tmp" -#define NCHUNKS 720 +#define NCHUNKS 720 #define NTHREADS 12 -#define NLONG 32 -#define NCREATE 24 +#define NLONG 32 +#define NCREATE 24 static struct semaphore *threadsem = NULL; -static -void -init_threadsem(void) -{ - if (threadsem==NULL) { - threadsem = sem_create("fstestsem", 0); - if (threadsem == NULL) { - panic("fstest: sem_create failed\n"); - } - } +static void init_threadsem(void) { + if (threadsem == NULL) { + threadsem = sem_create("fstestsem", 0); + if (threadsem == NULL) { + panic("fstest: sem_create failed\n"); + } + } } /* * Vary each line of the test file in a way that's predictable but * unlikely to mask bugs in the filesystem. */ -static -void -rotate(char *str, int amt) -{ - int i, ch; +static void rotate(char *str, int amt) { + int i, ch; - amt = (amt+2600)%26; - KASSERT(amt>=0); + amt = (amt + 2600) % 26; + KASSERT(amt >= 0); - for (i=0; str[i]; i++) { - ch = str[i]; - if (ch>='A' && ch<='Z') { - ch = ch - 'A'; - ch += amt; - ch %= 26; - ch = ch + 'A'; - KASSERT(ch>='A' && ch<='Z'); - } - str[i] = ch; - } + for (i = 0; str[i]; i++) { + ch = str[i]; + if (ch >= 'A' && ch <= 'Z') { + ch = ch - 'A'; + ch += amt; + ch %= 26; + ch = ch + 'A'; + KASSERT(ch >= 'A' && ch <= 'Z'); + } + str[i] = ch; + } } //////////////////////////////////////////////////////////// -static -void -fstest_makename(char *buf, size_t buflen, - const char *fs, const char *namesuffix) -{ - snprintf(buf, buflen, "%s:%s%s", fs, FILENAME, namesuffix); - KASSERT(strlen(buf) < buflen); +static void fstest_makename(char *buf, size_t buflen, const char *fs, + const char *namesuffix) { + snprintf(buf, buflen, "%s:%s%s", fs, FILENAME, namesuffix); + KASSERT(strlen(buf) < buflen); } #define MAKENAME() fstest_makename(name, sizeof(name), fs, namesuffix) -static -int -fstest_remove(const char *fs, const char *namesuffix) -{ - char name[32]; - char buf[32]; - int err; +static int fstest_remove(const char *fs, const char *namesuffix) { + char name[32]; + char buf[32]; + int err; - MAKENAME(); + MAKENAME(); - strcpy(buf, name); - err = vfs_remove(buf); - if (err) { - kprintf("Could not remove %s: %s\n", name, strerror(err)); - return -1; - } + strcpy(buf, name); + err = vfs_remove(buf); + if (err) { + kprintf("Could not remove %s: %s\n", name, strerror(err)); + return -1; + } - return 0; + return 0; } -static -int -fstest_write(const char *fs, const char *namesuffix, - int stridesize, int stridepos) -{ - struct vnode *vn; - int err; - int i; - size_t shouldbytes=0; - size_t bytes=0; - off_t pos=0; - char name[32]; - char buf[32]; - struct iovec iov; - struct uio ku; - int flags; +static int fstest_write(const char *fs, const char *namesuffix, int stridesize, + int stridepos) { + struct vnode *vn; + int err; + int i; + size_t shouldbytes = 0; + size_t bytes = 0; + off_t pos = 0; + char name[32]; + char buf[32]; + struct iovec iov; + struct uio ku; + int flags; - KASSERT(sizeof(buf) > strlen(SLOGAN)); + KASSERT(sizeof(buf) > strlen(SLOGAN)); - MAKENAME(); + MAKENAME(); - flags = O_WRONLY|O_CREAT; - if (stridesize == 1) { - flags |= O_TRUNC; - } + flags = O_WRONLY | O_CREAT; + if (stridesize == 1) { + flags |= O_TRUNC; + } - /* vfs_open destroys the string it's passed */ - strcpy(buf, name); - err = vfs_open(buf, flags, 0664, &vn); - if (err) { - kprintf("Could not open %s for write: %s\n", - name, strerror(err)); - return -1; - } + /* vfs_open destroys the string it's passed */ + strcpy(buf, name); + err = vfs_open(buf, flags, 0664, &vn); + if (err) { + kprintf("Could not open %s for write: %s\n", name, strerror(err)); + return -1; + } - for (i=0; i 0) { - kprintf("%s: Short write: %lu bytes left over\n", - name, (unsigned long) ku.uio_resid); - vfs_close(vn); - vfs_remove(name); - return -1; - } + if (ku.uio_resid > 0) { + kprintf("%s: Short write: %lu bytes left over\n", name, + (unsigned long)ku.uio_resid); + vfs_close(vn); + vfs_remove(name); + return -1; + } - bytes += (ku.uio_offset - pos); - shouldbytes += strlen(SLOGAN); - pos = ku.uio_offset; - } + bytes += (ku.uio_offset - pos); + shouldbytes += strlen(SLOGAN); + pos = ku.uio_offset; + } - vfs_close(vn); + vfs_close(vn); - if (bytes != shouldbytes) { - kprintf("%s: %lu bytes written, should have been %lu!\n", - name, (unsigned long) bytes, - (unsigned long) (NCHUNKS*strlen(SLOGAN))); - vfs_remove(name); - return -1; - } - kprintf("%s: %lu bytes written\n", name, (unsigned long) bytes); + if (bytes != shouldbytes) { + kprintf("%s: %lu bytes written, should have been %lu!\n", name, + (unsigned long)bytes, (unsigned long)(NCHUNKS * strlen(SLOGAN))); + vfs_remove(name); + return -1; + } + kprintf("%s: %lu bytes written\n", name, (unsigned long)bytes); - return 0; + return 0; } -static -int -fstest_read(const char *fs, const char *namesuffix) -{ - struct vnode *vn; - int err; - int i; - size_t bytes=0; - char name[32]; - char buf[32]; - struct iovec iov; - struct uio ku; +static int fstest_read(const char *fs, const char *namesuffix) { + struct vnode *vn; + int err; + int i; + size_t bytes = 0; + char name[32]; + char buf[32]; + struct iovec iov; + struct uio ku; - MAKENAME(); + MAKENAME(); - /* vfs_open destroys the string it's passed */ - strcpy(buf, name); - err = vfs_open(buf, O_RDONLY, 0664, &vn); - if (err) { - kprintf("Could not open test file for read: %s\n", - strerror(err)); - return -1; - } + /* vfs_open destroys the string it's passed */ + strcpy(buf, name); + err = vfs_open(buf, O_RDONLY, 0664, &vn); + if (err) { + kprintf("Could not open test file for read: %s\n", strerror(err)); + return -1; + } - for (i=0; i 0) { - kprintf("%s: Short read: %lu bytes left over\n", name, - (unsigned long) ku.uio_resid); - vfs_close(vn); - return -1; - } - buf[strlen(SLOGAN)] = 0; - rotate(buf, -i); - if (strcmp(buf, SLOGAN)) { - kprintf("%s: Test failed: line %d mismatched: %s\n", - name, i+1, buf); - vfs_close(vn); - return -1; - } + if (ku.uio_resid > 0) { + kprintf("%s: Short read: %lu bytes left over\n", name, + (unsigned long)ku.uio_resid); + vfs_close(vn); + return -1; + } + buf[strlen(SLOGAN)] = 0; + rotate(buf, -i); + if (strcmp(buf, SLOGAN)) { + kprintf("%s: Test failed: line %d mismatched: %s\n", name, i + 1, buf); + vfs_close(vn); + return -1; + } - bytes = ku.uio_offset; - } + bytes = ku.uio_offset; + } - vfs_close(vn); + vfs_close(vn); - if (bytes != NCHUNKS*strlen(SLOGAN)) { - kprintf("%s: %lu bytes read, should have been %lu!\n", - name, (unsigned long) bytes, - (unsigned long) (NCHUNKS*strlen(SLOGAN))); - return -1; - } - kprintf("%s: %lu bytes read\n", name, (unsigned long) bytes); - return 0; + if (bytes != NCHUNKS * strlen(SLOGAN)) { + kprintf("%s: %lu bytes read, should have been %lu!\n", name, + (unsigned long)bytes, (unsigned long)(NCHUNKS * strlen(SLOGAN))); + return -1; + } + kprintf("%s: %lu bytes read\n", name, (unsigned long)bytes); + return 0; } //////////////////////////////////////////////////////////// -static -void -dofstest(const char *filesys) -{ - kprintf("*** Starting filesystem test on %s:\n", filesys); +static void dofstest(const char *filesys) { + kprintf("*** Starting filesystem test on %s:\n", filesys); - if (fstest_write(filesys, "", 1, 0)) { - kprintf("*** Test failed\n"); - return; - } + if (fstest_write(filesys, "", 1, 0)) { + kprintf("*** Test failed\n"); + return; + } - if (fstest_read(filesys, "")) { - kprintf("*** Test failed\n"); - return; - } + if (fstest_read(filesys, "")) { + kprintf("*** Test failed\n"); + return; + } - if (fstest_remove(filesys, "")) { - kprintf("*** Test failed\n"); - return; - } + if (fstest_remove(filesys, "")) { + kprintf("*** Test failed\n"); + return; + } - kprintf("*** Filesystem test done\n"); + kprintf("*** Filesystem test done\n"); } //////////////////////////////////////////////////////////// -static -void -readstress_thread(void *fs, unsigned long num) -{ - const char *filesys = fs; - if (fstest_read(filesys, "")) { - kprintf("*** Thread %lu: failed\n", num); - } - V(threadsem); +static void readstress_thread(void *fs, unsigned long num) { + const char *filesys = fs; + if (fstest_read(filesys, "")) { + kprintf("*** Thread %lu: failed\n", num); + } + V(threadsem); } -static -void -doreadstress(const char *filesys) -{ - int i, err; +static void doreadstress(const char *filesys) { + int i, err; - init_threadsem(); + init_threadsem(); - kprintf("*** Starting fs read stress test on %s:\n", filesys); + kprintf("*** Starting fs read stress test on %s:\n", filesys); - if (fstest_write(filesys, "", 1, 0)) { - kprintf("*** Test failed\n"); - return; - } + if (fstest_write(filesys, "", 1, 0)) { + kprintf("*** Test failed\n"); + return; + } - for (i=0; i 0) { - kprintf("%s: Short write: %lu bytes left over\n", - name, (unsigned long) ku.uio_resid); - continue; - } + uio_kinit(&iov, &ku, buf, strlen(SLOGAN), 0, UIO_WRITE); + err = VOP_WRITE(vn, &ku); + vfs_close(vn); + if (err) { + kprintf("%s: Write error: %s\n", name, strerror(err)); + continue; + } + if (ku.uio_resid > 0) { + kprintf("%s: Short write: %lu bytes left over\n", name, + (unsigned long)ku.uio_resid); + continue; + } - bytes = ku.uio_offset; - if (bytes != strlen(SLOGAN)) { - kprintf("%s: %lu bytes written, expected %lu!\n", - name, (unsigned long) bytes, - (unsigned long) strlen(SLOGAN)); - continue; - } - numwritten++; - } - kprintf("Thread %lu: %u files written\n", num, numwritten); + bytes = ku.uio_offset; + if (bytes != strlen(SLOGAN)) { + kprintf("%s: %lu bytes written, expected %lu!\n", name, + (unsigned long)bytes, (unsigned long)strlen(SLOGAN)); + continue; + } + numwritten++; + } + kprintf("Thread %lu: %u files written\n", num, numwritten); - for (i=0; i 0) { - kprintf("%s: Short read: %lu bytes left over\n", - name, (unsigned long) ku.uio_resid); - continue; - } + uio_kinit(&iov, &ku, buf, strlen(SLOGAN), 0, UIO_READ); + err = VOP_READ(vn, &ku); + vfs_close(vn); + if (err) { + kprintf("%s: Read error: %s\n", name, strerror(err)); + continue; + } + if (ku.uio_resid > 0) { + kprintf("%s: Short read: %lu bytes left over\n", name, + (unsigned long)ku.uio_resid); + continue; + } - buf[strlen(SLOGAN)] = 0; - rotate(buf, -i); + buf[strlen(SLOGAN)] = 0; + rotate(buf, -i); - if (strcmp(buf, SLOGAN)) { - kprintf("%s: Test failed: file mismatched: %s\n", - name, buf); - continue; - } + if (strcmp(buf, SLOGAN)) { + kprintf("%s: Test failed: file mismatched: %s\n", name, buf); + continue; + } - bytes = ku.uio_offset; - if (bytes != strlen(SLOGAN)) { - kprintf("%s: %lu bytes read, expected %lu!\n", - name, (unsigned long) bytes, - (unsigned long) strlen(SLOGAN)); - continue; - } + bytes = ku.uio_offset; + if (bytes != strlen(SLOGAN)) { + kprintf("%s: %lu bytes read, expected %lu!\n", name, (unsigned long)bytes, + (unsigned long)strlen(SLOGAN)); + continue; + } - numread++; - } - kprintf("Thread %lu: %u files read\n", num, numread); + numread++; + } + kprintf("Thread %lu: %u files read\n", num, numread); - for (i=0; i 0) { - done = 1; - } + if (ku.uio_resid > 0) { + done = 1; + } - uio_kinit(&iov, &ku, buf, sizeof(buf)-ku.uio_resid, wpos, - UIO_WRITE); - result = VOP_WRITE(wv, &ku); - if (result) { - kprintf("Write error: %s\n", strerror(result)); - break; - } - wpos = ku.uio_offset; + uio_kinit(&iov, &ku, buf, sizeof(buf) - ku.uio_resid, wpos, UIO_WRITE); + result = VOP_WRITE(wv, &ku); + if (result) { + kprintf("Write error: %s\n", strerror(result)); + break; + } + wpos = ku.uio_offset; - if (ku.uio_resid > 0) { - kprintf("Warning: short write\n"); - } - } + if (ku.uio_resid > 0) { + kprintf("Warning: short write\n"); + } + } - vfs_close(wv); - vfs_close(rv); + vfs_close(wv); + vfs_close(rv); - return 0; + return 0; } diff --git a/kern/test/kmalloctest.c b/kern/test/kmalloctest.c index 6abb39c..270b352 100644 --- a/kern/test/kmalloctest.c +++ b/kern/test/kmalloctest.c @@ -54,95 +54,85 @@ * threads at once. */ -#define NTRIES 1200 -#define ITEMSIZE 997 -#define NTHREADS 8 +#define NTRIES 1200 +#define ITEMSIZE 997 +#define NTHREADS 8 -static -void -kmallocthread(void *sm, unsigned long num) -{ - struct semaphore *sem = sm; - void *ptr; - void *oldptr=NULL; - void *oldptr2=NULL; - int i; +static void kmallocthread(void *sm, unsigned long num) { + struct semaphore *sem = sm; + void *ptr; + void *oldptr = NULL; + void *oldptr2 = NULL; + int i; - for (i=0; i= blocksize / sizeof(void *)) { - curblock++; - curpos = 0; - } - /* Update the running total, and rotate the size. */ - totalsize += cursize; - cursizeindex = (cursizeindex + 1) % NUM_KM3_SIZES; - } + /* Allocate the objects. */ + curblock = 0; + curpos = 0; + cursizeindex = 0; + totalsize = 0; + for (i = 0; i < numptrs; i++) { + cursize = sizes[cursizeindex]; + ptr = kmalloc(cursize); + if (ptr == NULL) { + kprintf("kmalloctest3: failed on object %u size %u\n", i, cursize); + kprintf("kmalloctest3: pos %u in pointer block %u\n", curpos, curblock); + kprintf("kmalloctest3: total so far %zu\n", totalsize); + panic("kmalloctest3: failed.\n"); + } + /* Fill the object with its number. */ + for (j = 0; j < cursize; j++) { + ptr[j] = (unsigned char)i; + } + /* Move to the next slot in the tree. */ + ptrblocks[curblock][curpos] = ptr; + curpos++; + if (curpos >= blocksize / sizeof(void *)) { + curblock++; + curpos = 0; + } + /* Update the running total, and rotate the size. */ + totalsize += cursize; + cursizeindex = (cursizeindex + 1) % NUM_KM3_SIZES; + } - kprintf("kmalloctest3: %zu bytes allocated\n", totalsize); + kprintf("kmalloctest3: %zu bytes allocated\n", totalsize); - /* Free the objects. */ - curblock = 0; - curpos = 0; - cursizeindex = 0; - for (i=0; i= blocksize / sizeof(void *)) { - curblock++; - curpos = 0; - } - KASSERT(totalsize > 0); - totalsize -= cursize; - cursizeindex = (cursizeindex + 1) % NUM_KM3_SIZES; - } - KASSERT(totalsize == 0); + /* Free the objects. */ + curblock = 0; + curpos = 0; + cursizeindex = 0; + for (i = 0; i < numptrs; i++) { + cursize = sizes[cursizeindex]; + ptr = ptrblocks[curblock][curpos]; + KASSERT(ptr != NULL); + for (j = 0; j < cursize; j++) { + if (ptr[j] == (unsigned char)i) { + continue; + } + kprintf("kmalloctest3: failed on object %u size %u\n", i, cursize); + kprintf("kmalloctest3: pos %u in pointer block %u\n", curpos, curblock); + kprintf("kmalloctest3: at object offset %u\n", j); + kprintf("kmalloctest3: expected 0x%x, found 0x%x\n", ptr[j], + (unsigned char)i); + panic("kmalloctest3: failed.\n"); + } + kfree(ptr); + curpos++; + if (curpos >= blocksize / sizeof(void *)) { + curblock++; + curpos = 0; + } + KASSERT(totalsize > 0); + totalsize -= cursize; + cursizeindex = (cursizeindex + 1) % NUM_KM3_SIZES; + } + KASSERT(totalsize == 0); - /* Free the lower tier. */ - for (i=0; i #include -int -nettest(int nargs, char **args) -{ - (void)nargs; - (void)args; - kprintf("No network support available\n"); - return 1; +int nettest(int nargs, char **args) { + (void)nargs; + (void)args; + kprintf("No network support available\n"); + return 1; } diff --git a/kern/test/semunit.c b/kern/test/semunit.c index bbe6a68..295898a 100644 --- a/kern/test/semunit.c +++ b/kern/test/semunit.c @@ -61,66 +61,52 @@ static unsigned waiters_running = 0; static struct spinlock waiters_lock = SPINLOCK_INITIALIZER; -static -void -ok(void) -{ - kprintf("Test passed; now cleaning up.\n"); -} +static void ok(void) { kprintf("Test passed; now cleaning up.\n"); } /* * Wrapper for sem_create when we aren't explicitly tweaking it. */ -static -struct semaphore * -makesem(unsigned count) -{ - struct semaphore *sem; +static struct semaphore *makesem(unsigned count) { + struct semaphore *sem; - sem = sem_create(NAMESTRING, count); - if (sem == NULL) { - panic("semunit: whoops: sem_create failed\n"); - } - return sem; + sem = sem_create(NAMESTRING, count); + if (sem == NULL) { + panic("semunit: whoops: sem_create failed\n"); + } + return sem; } /* * A thread that just waits on a semaphore. */ -static -void -waiter(void *vsem, unsigned long junk) -{ - struct semaphore *sem = vsem; - (void)junk; +static void waiter(void *vsem, unsigned long junk) { + struct semaphore *sem = vsem; + (void)junk; - P(sem); + P(sem); - spinlock_acquire(&waiters_lock); - KASSERT(waiters_running > 0); - waiters_running--; - spinlock_release(&waiters_lock); + spinlock_acquire(&waiters_lock); + KASSERT(waiters_running > 0); + waiters_running--; + spinlock_release(&waiters_lock); } /* * Set up a waiter. */ -static -void -makewaiter(struct semaphore *sem) -{ - int result; +static void makewaiter(struct semaphore *sem) { + int result; - spinlock_acquire(&waiters_lock); - waiters_running++; - spinlock_release(&waiters_lock); + spinlock_acquire(&waiters_lock); + waiters_running++; + spinlock_release(&waiters_lock); - result = thread_fork("semunit waiter", NULL, waiter, sem, 0); - if (result) { - panic("semunit: thread_fork failed\n"); - } - kprintf("Sleeping for waiter to run\n"); - clocksleep(1); + result = thread_fork("semunit waiter", NULL, waiter, sem, 0); + if (result) { + panic("semunit: thread_fork failed\n"); + } + kprintf("Sleeping for waiter to run\n"); + clocksleep(1); } /* @@ -133,11 +119,8 @@ makewaiter(struct semaphore *sem) * we're checking it, or the check wouldn't be reliable; and, provided * clocksleep works, nobody can. */ -static -bool -spinlock_not_held(struct spinlock *splk) -{ - return splk->splk_holder == NULL; +static bool spinlock_not_held(struct spinlock *splk) { + return splk->splk_holder == NULL; } //////////////////////////////////////////////////////////// @@ -151,159 +134,151 @@ spinlock_not_held(struct spinlock *splk) * - sem_lock is not held and has no owner * - sem_count is the passed-in count */ -int -semu1(int nargs, char **args) -{ - struct semaphore *sem; - const char *name = NAMESTRING; +int semu1(int nargs, char **args) { + struct semaphore *sem; + const char *name = NAMESTRING; - (void)nargs; (void)args; + (void)nargs; + (void)args; - sem = sem_create(name, 56); - if (sem == NULL) { - panic("semu1: whoops: sem_create failed\n"); - } - KASSERT(!strcmp(sem->sem_name, name)); - KASSERT(sem->sem_name != name); - KASSERT(sem->sem_wchan != NULL); - KASSERT(spinlock_not_held(&sem->sem_lock)); - KASSERT(sem->sem_count == 56); + sem = sem_create(name, 56); + if (sem == NULL) { + panic("semu1: whoops: sem_create failed\n"); + } + KASSERT(!strcmp(sem->sem_name, name)); + KASSERT(sem->sem_name != name); + KASSERT(sem->sem_wchan != NULL); + KASSERT(spinlock_not_held(&sem->sem_lock)); + KASSERT(sem->sem_count == 56); - ok(); - /* clean up */ - sem_destroy(sem); - return 0; + ok(); + /* clean up */ + sem_destroy(sem); + return 0; } /* * 2. Passing a null name to sem_create asserts or crashes. */ -int -semu2(int nargs, char **args) -{ - struct semaphore *sem; +int semu2(int nargs, char **args) { + struct semaphore *sem; - (void)nargs; (void)args; + (void)nargs; + (void)args; - kprintf("This should crash with a kernel null dereference\n"); - sem = sem_create(NULL, 44); - (void)sem; - panic("semu2: sem_create accepted a null name\n"); - return 0; + kprintf("This should crash with a kernel null dereference\n"); + sem = sem_create(NULL, 44); + (void)sem; + panic("semu2: sem_create accepted a null name\n"); + return 0; } /* * 3. Passing a null semaphore to sem_destroy asserts or crashes. */ -int -semu3(int nargs, char **args) -{ - (void)nargs; (void)args; +int semu3(int nargs, char **args) { + (void)nargs; + (void)args; - kprintf("This should assert that sem != NULL\n"); - sem_destroy(NULL); - panic("semu3: sem_destroy accepted a null semaphore\n"); + kprintf("This should assert that sem != NULL\n"); + sem_destroy(NULL); + panic("semu3: sem_destroy accepted a null semaphore\n"); } - /* * 4. sem_count is an unsigned type. */ -int -semu4(int nargs, char **args) -{ - struct semaphore *sem; +int semu4(int nargs, char **args) { + struct semaphore *sem; - (void)nargs; (void)args; + (void)nargs; + (void)args; - /* Create a semaphore with count 0. */ - sem = makesem(0); - /* Decrement the count. */ - sem->sem_count--; - /* This value should be positive. */ - KASSERT(sem->sem_count > 0); + /* Create a semaphore with count 0. */ + sem = makesem(0); + /* Decrement the count. */ + sem->sem_count--; + /* This value should be positive. */ + KASSERT(sem->sem_count > 0); - /* Clean up. */ - ok(); - sem_destroy(sem); - return 0; + /* Clean up. */ + ok(); + sem_destroy(sem); + return 0; } /* * 5. A semaphore can be successfully initialized with a count of at * least 0xf0000000. */ -int -semu5(int nargs, char **args) -{ - struct semaphore *sem; +int semu5(int nargs, char **args) { + struct semaphore *sem; - (void)nargs; (void)args; + (void)nargs; + (void)args; - sem = sem_create(NAMESTRING, 0xf0000000U); - if (sem == NULL) { - /* This might not be an innocuous malloc shortage. */ - panic("semu5: sem_create failed\n"); - } - KASSERT(sem->sem_count == 0xf0000000U); + sem = sem_create(NAMESTRING, 0xf0000000U); + if (sem == NULL) { + /* This might not be an innocuous malloc shortage. */ + panic("semu5: sem_create failed\n"); + } + KASSERT(sem->sem_count == 0xf0000000U); - /* Clean up. */ - ok(); - sem_destroy(sem); - return 0; + /* Clean up. */ + ok(); + sem_destroy(sem); + return 0; } /* * 6. Passing a semaphore with a waiting thread to sem_destroy asserts * (in the wchan code). */ -int -semu6(int nargs, char **args) -{ - struct semaphore *sem; +int semu6(int nargs, char **args) { + struct semaphore *sem; - (void)nargs; (void)args; + (void)nargs; + (void)args; - sem = makesem(0); - makewaiter(sem); - kprintf("This should assert that the wchan's threadlist is empty\n"); - sem_destroy(sem); - panic("semu6: wchan_destroy with waiters succeeded\n"); - return 0; + sem = makesem(0); + makewaiter(sem); + kprintf("This should assert that the wchan's threadlist is empty\n"); + sem_destroy(sem); + panic("semu6: wchan_destroy with waiters succeeded\n"); + return 0; } /* * 7. Calling V on a semaphore does not block the caller, regardless * of the semaphore count. */ -int -semu7(int nargs, char **args) -{ - struct semaphore *sem; - struct spinlock lk; +int semu7(int nargs, char **args) { + struct semaphore *sem; + struct spinlock lk; - (void)nargs; (void)args; + (void)nargs; + (void)args; - sem = makesem(0); + sem = makesem(0); - /* - * Check for blocking by taking a spinlock; if we block while - * holding a spinlock, wchan_sleep will assert. - */ - spinlock_init(&lk); - spinlock_acquire(&lk); + /* + * Check for blocking by taking a spinlock; if we block while + * holding a spinlock, wchan_sleep will assert. + */ + spinlock_init(&lk); + spinlock_acquire(&lk); - /* try with count 0, count 1, and count 2, just for completeness */ - V(sem); - V(sem); - V(sem); + /* try with count 0, count 1, and count 2, just for completeness */ + V(sem); + V(sem); + V(sem); - /* Clean up. */ - ok(); - spinlock_release(&lk); - spinlock_cleanup(&lk); - sem_destroy(sem); - return 0; + /* Clean up. */ + ok(); + spinlock_release(&lk); + spinlock_cleanup(&lk); + sem_destroy(sem); + return 0; } /* @@ -315,70 +290,65 @@ semu7(int nargs, char **args) * * This is true even if we are in an interrupt handler. */ -static -void -do_semu89(bool interrupthandler) -{ - struct semaphore *sem; - struct wchan *wchan; - const char *name; +static void do_semu89(bool interrupthandler) { + struct semaphore *sem; + struct wchan *wchan; + const char *name; - sem = makesem(0); + sem = makesem(0); - /* check preconditions */ - name = sem->sem_name; - wchan = sem->sem_wchan; - KASSERT(!strcmp(name, NAMESTRING)); - KASSERT(spinlock_not_held(&sem->sem_lock)); + /* check preconditions */ + name = sem->sem_name; + wchan = sem->sem_wchan; + KASSERT(!strcmp(name, NAMESTRING)); + KASSERT(spinlock_not_held(&sem->sem_lock)); - /* - * The right way to this is to set up an actual interrupt, - * e.g. an interprocessor interrupt, and hook onto it to run - * the V() in the actual interrupt handler. However, that - * requires a good bit of infrastructure that we don't - * have. Instead we'll fake it by explicitly setting - * curthread->t_in_interrupt. - */ - if (interrupthandler) { - KASSERT(curthread->t_in_interrupt == false); - curthread->t_in_interrupt = true; - } + /* + * The right way to this is to set up an actual interrupt, + * e.g. an interprocessor interrupt, and hook onto it to run + * the V() in the actual interrupt handler. However, that + * requires a good bit of infrastructure that we don't + * have. Instead we'll fake it by explicitly setting + * curthread->t_in_interrupt. + */ + if (interrupthandler) { + KASSERT(curthread->t_in_interrupt == false); + curthread->t_in_interrupt = true; + } - V(sem); + V(sem); - if (interrupthandler) { - KASSERT(curthread->t_in_interrupt == true); - curthread->t_in_interrupt = false; - } + if (interrupthandler) { + KASSERT(curthread->t_in_interrupt == true); + curthread->t_in_interrupt = false; + } - /* check postconditions */ - KASSERT(name == sem->sem_name); - KASSERT(!strcmp(name, NAMESTRING)); - KASSERT(wchan == sem->sem_wchan); - KASSERT(spinlock_not_held(&sem->sem_lock)); - KASSERT(sem->sem_count == 1); + /* check postconditions */ + KASSERT(name == sem->sem_name); + KASSERT(!strcmp(name, NAMESTRING)); + KASSERT(wchan == sem->sem_wchan); + KASSERT(spinlock_not_held(&sem->sem_lock)); + KASSERT(sem->sem_count == 1); - /* clean up */ - ok(); - sem_destroy(sem); + /* clean up */ + ok(); + sem_destroy(sem); } -int -semu8(int nargs, char **args) -{ - (void)nargs; (void)args; +int semu8(int nargs, char **args) { + (void)nargs; + (void)args; - do_semu89(false /*interrupthandler*/); - return 0; + do_semu89(false /*interrupthandler*/); + return 0; } -int -semu9(int nargs, char **args) -{ - (void)nargs; (void)args; +int semu9(int nargs, char **args) { + (void)nargs; + (void)args; - do_semu89(true /*interrupthandler*/); - return 0; + do_semu89(true /*interrupthandler*/); + return 0; } /* @@ -392,78 +362,71 @@ semu9(int nargs, char **args) * * This is true even if we are in an interrupt handler. */ -static -int -do_semu1011(bool interrupthandler) -{ - struct semaphore *sem; - struct wchan *wchan; - const char *name; +static int do_semu1011(bool interrupthandler) { + struct semaphore *sem; + struct wchan *wchan; + const char *name; - sem = makesem(0); - makewaiter(sem); + sem = makesem(0); + makewaiter(sem); - /* check preconditions */ - name = sem->sem_name; - wchan = sem->sem_wchan; - KASSERT(!strcmp(name, NAMESTRING)); - KASSERT(spinlock_not_held(&sem->sem_lock)); - spinlock_acquire(&waiters_lock); - KASSERT(waiters_running == 1); - spinlock_release(&waiters_lock); + /* check preconditions */ + name = sem->sem_name; + wchan = sem->sem_wchan; + KASSERT(!strcmp(name, NAMESTRING)); + KASSERT(spinlock_not_held(&sem->sem_lock)); + spinlock_acquire(&waiters_lock); + KASSERT(waiters_running == 1); + spinlock_release(&waiters_lock); - /* see above */ - if (interrupthandler) { - KASSERT(curthread->t_in_interrupt == false); - curthread->t_in_interrupt = true; - } + /* see above */ + if (interrupthandler) { + KASSERT(curthread->t_in_interrupt == false); + curthread->t_in_interrupt = true; + } - V(sem); + V(sem); - if (interrupthandler) { - KASSERT(curthread->t_in_interrupt == true); - curthread->t_in_interrupt = false; - } + if (interrupthandler) { + KASSERT(curthread->t_in_interrupt == true); + curthread->t_in_interrupt = false; + } - /* give the waiter time to exit */ - clocksleep(1); + /* give the waiter time to exit */ + clocksleep(1); - /* check postconditions */ - KASSERT(name == sem->sem_name); - KASSERT(!strcmp(name, NAMESTRING)); - KASSERT(wchan == sem->sem_wchan); - KASSERT(spinlock_not_held(&sem->sem_lock)); - KASSERT(sem->sem_count == 0); - spinlock_acquire(&waiters_lock); - KASSERT(waiters_running == 0); - spinlock_release(&waiters_lock); - - /* clean up */ - ok(); - sem_destroy(sem); - return 0; + /* check postconditions */ + KASSERT(name == sem->sem_name); + KASSERT(!strcmp(name, NAMESTRING)); + KASSERT(wchan == sem->sem_wchan); + KASSERT(spinlock_not_held(&sem->sem_lock)); + KASSERT(sem->sem_count == 0); + spinlock_acquire(&waiters_lock); + KASSERT(waiters_running == 0); + spinlock_release(&waiters_lock); + /* clean up */ + ok(); + sem_destroy(sem); + return 0; } -int -semu10(int nargs, char **args) -{ - (void)nargs; (void)args; +int semu10(int nargs, char **args) { + (void)nargs; + (void)args; - do_semu1011(false /*interrupthandler*/); - return 0; + do_semu1011(false /*interrupthandler*/); + return 0; } -int -semu11(int nargs, char **args) -{ - (void)nargs; (void)args; +int semu11(int nargs, char **args) { + (void)nargs; + (void)args; - do_semu1011(true /*interrupthandler*/); - return 0; + do_semu1011(true /*interrupthandler*/); + return 0; } - /* * 12/13. After calling V on a semaphore with two threads waiting, and * giving it time to run: @@ -474,145 +437,137 @@ semu11(int nargs, char **args) * - one of the other threads does in fact run * - the other one does not */ -static -void -semu1213(bool interrupthandler) -{ - struct semaphore *sem; - struct wchan *wchan; - const char *name; +static void semu1213(bool interrupthandler) { + struct semaphore *sem; + struct wchan *wchan; + const char *name; - sem = makesem(0); - makewaiter(sem); - makewaiter(sem); + sem = makesem(0); + makewaiter(sem); + makewaiter(sem); - /* check preconditions */ - name = sem->sem_name; - wchan = sem->sem_wchan; - KASSERT(!strcmp(name, NAMESTRING)); - wchan = sem->sem_wchan; - KASSERT(spinlock_not_held(&sem->sem_lock)); - spinlock_acquire(&waiters_lock); - KASSERT(waiters_running == 2); - spinlock_release(&waiters_lock); + /* check preconditions */ + name = sem->sem_name; + wchan = sem->sem_wchan; + KASSERT(!strcmp(name, NAMESTRING)); + wchan = sem->sem_wchan; + KASSERT(spinlock_not_held(&sem->sem_lock)); + spinlock_acquire(&waiters_lock); + KASSERT(waiters_running == 2); + spinlock_release(&waiters_lock); - /* see above */ - if (interrupthandler) { - KASSERT(curthread->t_in_interrupt == false); - curthread->t_in_interrupt = true; - } + /* see above */ + if (interrupthandler) { + KASSERT(curthread->t_in_interrupt == false); + curthread->t_in_interrupt = true; + } - V(sem); + V(sem); - if (interrupthandler) { - KASSERT(curthread->t_in_interrupt == true); - curthread->t_in_interrupt = false; - } + if (interrupthandler) { + KASSERT(curthread->t_in_interrupt == true); + curthread->t_in_interrupt = false; + } - /* give the waiter time to exit */ - clocksleep(1); + /* give the waiter time to exit */ + clocksleep(1); - /* check postconditions */ - KASSERT(name == sem->sem_name); - KASSERT(!strcmp(name, NAMESTRING)); - KASSERT(wchan == sem->sem_wchan); - KASSERT(spinlock_not_held(&sem->sem_lock)); - KASSERT(sem->sem_count == 0); - spinlock_acquire(&waiters_lock); - KASSERT(waiters_running == 1); - spinlock_release(&waiters_lock); + /* check postconditions */ + KASSERT(name == sem->sem_name); + KASSERT(!strcmp(name, NAMESTRING)); + KASSERT(wchan == sem->sem_wchan); + KASSERT(spinlock_not_held(&sem->sem_lock)); + KASSERT(sem->sem_count == 0); + spinlock_acquire(&waiters_lock); + KASSERT(waiters_running == 1); + spinlock_release(&waiters_lock); - /* clean up */ - ok(); - V(sem); - clocksleep(1); - spinlock_acquire(&waiters_lock); - KASSERT(waiters_running == 0); - spinlock_release(&waiters_lock); - sem_destroy(sem); + /* clean up */ + ok(); + V(sem); + clocksleep(1); + spinlock_acquire(&waiters_lock); + KASSERT(waiters_running == 0); + spinlock_release(&waiters_lock); + sem_destroy(sem); } -int -semu12(int nargs, char **args) -{ - (void)nargs; (void)args; +int semu12(int nargs, char **args) { + (void)nargs; + (void)args; - semu1213(false /*interrupthandler*/); - return 0; + semu1213(false /*interrupthandler*/); + return 0; } -int -semu13(int nargs, char **args) -{ - (void)nargs; (void)args; +int semu13(int nargs, char **args) { + (void)nargs; + (void)args; - semu1213(true /*interrupthandler*/); - return 0; + semu1213(true /*interrupthandler*/); + return 0; } /* * 14. Calling V on a semaphore whose count is the maximum allowed value * asserts. */ -int -semu14(int nargs, char **args) -{ - struct semaphore *sem; +int semu14(int nargs, char **args) { + struct semaphore *sem; - (void)nargs; (void)args; + (void)nargs; + (void)args; - kprintf("This should assert that sem_count is > 0.\n"); - sem = makesem(0); + kprintf("This should assert that sem_count is > 0.\n"); + sem = makesem(0); - /* - * The maximum value is (unsigned)-1. Get this by decrementing - * from 0. - */ - sem->sem_count--; - V(sem); - KASSERT(sem->sem_count == 0); - panic("semu14: V tolerated count wraparound\n"); - return 0; + /* + * The maximum value is (unsigned)-1. Get this by decrementing + * from 0. + */ + sem->sem_count--; + V(sem); + KASSERT(sem->sem_count == 0); + panic("semu14: V tolerated count wraparound\n"); + return 0; } /* * 15. Calling V on a null semaphore asserts. */ -int -semu15(int nargs, char **args) -{ - (void)nargs; (void)args; +int semu15(int nargs, char **args) { + (void)nargs; + (void)args; - kprintf("This should assert that the semaphore isn't null.\n"); - V(NULL); - panic("semu15: V tolerated null semaphore\n"); - return 0; + kprintf("This should assert that the semaphore isn't null.\n"); + V(NULL); + panic("semu15: V tolerated null semaphore\n"); + return 0; } /* * 16. Calling P on a semaphore with count > 0 does not block the caller. */ -int -semu16(int nargs, char **args) -{ - struct semaphore *sem; - struct spinlock lk; +int semu16(int nargs, char **args) { + struct semaphore *sem; + struct spinlock lk; - (void)nargs; (void)args; + (void)nargs; + (void)args; - sem = makesem(1); + sem = makesem(1); - /* As above, check for improper blocking by taking a spinlock. */ - spinlock_init(&lk); - spinlock_acquire(&lk); + /* As above, check for improper blocking by taking a spinlock. */ + spinlock_init(&lk); + spinlock_acquire(&lk); - P(sem); + P(sem); - ok(); - spinlock_release(&lk); - spinlock_cleanup(&lk); - sem_destroy(sem); - return 0; + ok(); + spinlock_release(&lk); + spinlock_cleanup(&lk); + sem_destroy(sem); + return 0; } /* @@ -621,51 +576,47 @@ semu16(int nargs, char **args) static struct thread *semu17_thread; -static -void -semu17_sub(void *semv, unsigned long junk) -{ - struct semaphore *sem = semv; +static void semu17_sub(void *semv, unsigned long junk) { + struct semaphore *sem = semv; - (void)junk; + (void)junk; - semu17_thread = curthread; + semu17_thread = curthread; - /* precondition */ - KASSERT(sem->sem_count == 0); + /* precondition */ + KASSERT(sem->sem_count == 0); - P(sem); + P(sem); } -int -semu17(int nargs, char **args) -{ - struct semaphore *sem; - int result; +int semu17(int nargs, char **args) { + struct semaphore *sem; + int result; - (void)nargs; (void)args; + (void)nargs; + (void)args; - semu17_thread = NULL; + semu17_thread = NULL; - sem = makesem(0); - result = thread_fork("semu17_sub", NULL, semu17_sub, sem, 0); - if (result) { - panic("semu17: whoops: thread_fork failed\n"); - } - kprintf("Waiting for subthread...\n"); - clocksleep(1); + sem = makesem(0); + result = thread_fork("semu17_sub", NULL, semu17_sub, sem, 0); + if (result) { + panic("semu17: whoops: thread_fork failed\n"); + } + kprintf("Waiting for subthread...\n"); + clocksleep(1); - /* The subthread should be blocked. */ - KASSERT(semu17_thread != NULL); - KASSERT(semu17_thread->t_state == S_SLEEP); + /* The subthread should be blocked. */ + KASSERT(semu17_thread != NULL); + KASSERT(semu17_thread->t_state == S_SLEEP); - /* Clean up. */ - ok(); - V(sem); - clocksleep(1); - sem_destroy(sem); - semu17_thread = NULL; - return 0; + /* Clean up. */ + ok(); + V(sem); + clocksleep(1); + sem_destroy(sem); + semu17_thread = NULL; + return 0; } /* @@ -675,34 +626,33 @@ semu17(int nargs, char **args) * - sem_lock is unheld and has no owner * - sem_count is one less */ -int -semu18(int nargs, char **args) -{ - struct semaphore *sem; - struct wchan *wchan; - const char *name; +int semu18(int nargs, char **args) { + struct semaphore *sem; + struct wchan *wchan; + const char *name; - (void)nargs; (void)args; + (void)nargs; + (void)args; - sem = makesem(1); + sem = makesem(1); - /* preconditions */ - name = sem->sem_name; - KASSERT(!strcmp(name, NAMESTRING)); - wchan = sem->sem_wchan; - KASSERT(spinlock_not_held(&sem->sem_lock)); - KASSERT(sem->sem_count == 1); + /* preconditions */ + name = sem->sem_name; + KASSERT(!strcmp(name, NAMESTRING)); + wchan = sem->sem_wchan; + KASSERT(spinlock_not_held(&sem->sem_lock)); + KASSERT(sem->sem_count == 1); - P(sem); - - /* postconditions */ - KASSERT(name == sem->sem_name); - KASSERT(!strcmp(name, NAMESTRING)); - KASSERT(wchan == sem->sem_wchan); - KASSERT(spinlock_not_held(&sem->sem_lock)); - KASSERT(sem->sem_count == 0); + P(sem); - return 0; + /* postconditions */ + KASSERT(name == sem->sem_name); + KASSERT(!strcmp(name, NAMESTRING)); + KASSERT(wchan == sem->sem_wchan); + KASSERT(spinlock_not_held(&sem->sem_lock)); + KASSERT(sem->sem_count == 0); + + return 0; } /* @@ -714,107 +664,100 @@ semu18(int nargs, char **args) * - sem_count is still 0 */ -static -void -semu19_sub(void *semv, unsigned long junk) -{ - struct semaphore *sem = semv; +static void semu19_sub(void *semv, unsigned long junk) { + struct semaphore *sem = semv; - (void)junk; + (void)junk; - kprintf("semu19: waiting for parent to sleep\n"); - clocksleep(1); - /* - * We could assert here that the parent *is* sleeping; but for - * that we'd need its thread pointer and it's not worth the - * trouble. - */ - V(sem); + kprintf("semu19: waiting for parent to sleep\n"); + clocksleep(1); + /* + * We could assert here that the parent *is* sleeping; but for + * that we'd need its thread pointer and it's not worth the + * trouble. + */ + V(sem); } -int -semu19(int nargs, char **args) -{ - struct semaphore *sem; - struct wchan *wchan; - const char *name; - int result; +int semu19(int nargs, char **args) { + struct semaphore *sem; + struct wchan *wchan; + const char *name; + int result; - (void)nargs; (void)args; + (void)nargs; + (void)args; - sem = makesem(0); - result = thread_fork("semu19_sub", NULL, semu19_sub, sem, 0); - if (result) { - panic("semu19: whoops: thread_fork failed\n"); - } + sem = makesem(0); + result = thread_fork("semu19_sub", NULL, semu19_sub, sem, 0); + if (result) { + panic("semu19: whoops: thread_fork failed\n"); + } - /* preconditions */ - name = sem->sem_name; - KASSERT(!strcmp(name, NAMESTRING)); - wchan = sem->sem_wchan; - KASSERT(spinlock_not_held(&sem->sem_lock)); - KASSERT(sem->sem_count == 0); + /* preconditions */ + name = sem->sem_name; + KASSERT(!strcmp(name, NAMESTRING)); + wchan = sem->sem_wchan; + KASSERT(spinlock_not_held(&sem->sem_lock)); + KASSERT(sem->sem_count == 0); - P(sem); + P(sem); - /* postconditions */ - KASSERT(name == sem->sem_name); - KASSERT(!strcmp(name, NAMESTRING)); - KASSERT(wchan == sem->sem_wchan); - KASSERT(spinlock_not_held(&sem->sem_lock)); - KASSERT(sem->sem_count == 0); + /* postconditions */ + KASSERT(name == sem->sem_name); + KASSERT(!strcmp(name, NAMESTRING)); + KASSERT(wchan == sem->sem_wchan); + KASSERT(spinlock_not_held(&sem->sem_lock)); + KASSERT(sem->sem_count == 0); - return 0; + return 0; } /* * 20/21. Calling P in an interrupt handler asserts, regardless of the * count. */ -int -semu20(int nargs, char **args) -{ - struct semaphore *sem; +int semu20(int nargs, char **args) { + struct semaphore *sem; - (void)nargs; (void)args; + (void)nargs; + (void)args; - kprintf("This should assert that we aren't in an interrupt\n"); + kprintf("This should assert that we aren't in an interrupt\n"); - sem = makesem(0); - /* as above */ - curthread->t_in_interrupt = true; - P(sem); - panic("semu20: P tolerated being in an interrupt handler\n"); - return 0; + sem = makesem(0); + /* as above */ + curthread->t_in_interrupt = true; + P(sem); + panic("semu20: P tolerated being in an interrupt handler\n"); + return 0; } -int -semu21(int nargs, char **args) -{ - struct semaphore *sem; +int semu21(int nargs, char **args) { + struct semaphore *sem; - (void)nargs; (void)args; + (void)nargs; + (void)args; - kprintf("This should assert that we aren't in an interrupt\n"); + kprintf("This should assert that we aren't in an interrupt\n"); - sem = makesem(1); - /* as above */ - curthread->t_in_interrupt = true; - P(sem); - panic("semu21: P tolerated being in an interrupt handler\n"); - return 0; + sem = makesem(1); + /* as above */ + curthread->t_in_interrupt = true; + P(sem); + panic("semu21: P tolerated being in an interrupt handler\n"); + return 0; } /* * 22. Calling P on a null semaphore asserts. */ -int -semu22(int nargs, char **args) -{ - (void)nargs; (void)args; +int semu22(int nargs, char **args) { + (void)nargs; + (void)args; - kprintf("This should assert that the semaphore isn't null.\n"); - P(NULL); - panic("semu22: P tolerated null semaphore\n"); - return 0; + kprintf("This should assert that the semaphore isn't null.\n"); + P(NULL); + panic("semu22: P tolerated null semaphore\n"); + return 0; } diff --git a/kern/test/synchtest.c b/kern/test/synchtest.c index c5582e2..3797b19 100644 --- a/kern/test/synchtest.c +++ b/kern/test/synchtest.c @@ -38,10 +38,10 @@ #include #include -#define NSEMLOOPS 63 -#define NLOCKLOOPS 120 -#define NCVLOOPS 5 -#define NTHREADS 32 +#define NSEMLOOPS 63 +#define NLOCKLOOPS 120 +#define NCVLOOPS 5 +#define NTHREADS 32 static volatile unsigned long testval1; static volatile unsigned long testval2; @@ -51,250 +51,223 @@ static struct lock *testlock; static struct cv *testcv; static struct semaphore *donesem; -static -void -inititems(void) -{ - if (testsem==NULL) { - testsem = sem_create("testsem", 2); - if (testsem == NULL) { - panic("synchtest: sem_create failed\n"); - } - } - if (testlock==NULL) { - testlock = lock_create("testlock"); - if (testlock == NULL) { - panic("synchtest: lock_create failed\n"); - } - } - if (testcv==NULL) { - testcv = cv_create("testlock"); - if (testcv == NULL) { - panic("synchtest: cv_create failed\n"); - } - } - if (donesem==NULL) { - donesem = sem_create("donesem", 0); - if (donesem == NULL) { - panic("synchtest: sem_create failed\n"); - } - } +static void inititems(void) { + if (testsem == NULL) { + testsem = sem_create("testsem", 2); + if (testsem == NULL) { + panic("synchtest: sem_create failed\n"); + } + } + if (testlock == NULL) { + testlock = lock_create("testlock"); + if (testlock == NULL) { + panic("synchtest: lock_create failed\n"); + } + } + if (testcv == NULL) { + testcv = cv_create("testlock"); + if (testcv == NULL) { + panic("synchtest: cv_create failed\n"); + } + } + if (donesem == NULL) { + donesem = sem_create("donesem", 0); + if (donesem == NULL) { + panic("synchtest: sem_create failed\n"); + } + } } -static -void -semtestthread(void *junk, unsigned long num) -{ - int i; - (void)junk; +static void semtestthread(void *junk, unsigned long num) { + int i; + (void)junk; - /* - * Only one of these should print at a time. - */ - P(testsem); - kprintf("Thread %2lu: ", num); - for (i=0; it_name = kstrdup(name); - if (t->t_name == NULL) { - panic("threadlisttest: Out of memory\n"); - } - t->t_stack = FAKE_MAGIC; - threadlistnode_init(&t->t_listnode, t); - return t; + t = kmalloc(sizeof(*t)); + if (t == NULL) { + panic("threadlisttest: Out of memory\n"); + } + /* ignore most of the fields, zero everything for tidiness */ + bzero(t, sizeof(*t)); + t->t_name = kstrdup(name); + if (t->t_name == NULL) { + panic("threadlisttest: Out of memory\n"); + } + t->t_stack = FAKE_MAGIC; + threadlistnode_init(&t->t_listnode, t); + return t; } /* * Destroy a fake thread. */ -static -void -fakethread_destroy(struct thread *t) -{ - KASSERT(t->t_stack == FAKE_MAGIC); - threadlistnode_cleanup(&t->t_listnode); - kfree(t->t_name); - kfree(t); +static void fakethread_destroy(struct thread *t) { + KASSERT(t->t_stack == FAKE_MAGIC); + threadlistnode_cleanup(&t->t_listnode); + kfree(t->t_name); + kfree(t); } //////////////////////////////////////////////////////////// // support stuff -static -void -check_order(struct threadlist *tl, bool rev) -{ - const char string0[] = "..."; - const char stringN[] = "~~~"; +static void check_order(struct threadlist *tl, bool rev) { + const char string0[] = "..."; + const char stringN[] = "~~~"; - struct thread *t; - const char *first = rev ? stringN : string0; - const char *last = rev ? string0 : stringN; - const char *prev; - int cmp; + struct thread *t; + const char *first = rev ? stringN : string0; + const char *last = rev ? string0 : stringN; + const char *prev; + int cmp; - prev = first; - THREADLIST_FORALL(t, *tl) { - cmp = strcmp(prev, t->t_name); - KASSERT(rev ? (cmp > 0) : (cmp < 0)); - prev = t->t_name; - } - cmp = strcmp(prev, last); - KASSERT(rev ? (cmp > 0) : (cmp < 0)); + prev = first; + THREADLIST_FORALL(t, *tl) { + cmp = strcmp(prev, t->t_name); + KASSERT(rev ? (cmp > 0) : (cmp < 0)); + prev = t->t_name; + } + cmp = strcmp(prev, last); + KASSERT(rev ? (cmp > 0) : (cmp < 0)); } //////////////////////////////////////////////////////////// // tests -static -void -threadlisttest_a(void) -{ - struct threadlist tl; +static void threadlisttest_a(void) { + struct threadlist tl; - threadlist_init(&tl); - KASSERT(threadlist_isempty(&tl)); - threadlist_cleanup(&tl); + threadlist_init(&tl); + KASSERT(threadlist_isempty(&tl)); + threadlist_cleanup(&tl); } -static -void -threadlisttest_b(void) -{ - struct threadlist tl; - struct thread *t; +static void threadlisttest_b(void) { + struct threadlist tl; + struct thread *t; - threadlist_init(&tl); + threadlist_init(&tl); - threadlist_addhead(&tl, fakethreads[0]); - check_order(&tl, false); - check_order(&tl, true); - KASSERT(tl.tl_count == 1); - t = threadlist_remhead(&tl); - KASSERT(tl.tl_count == 0); - KASSERT(t == fakethreads[0]); + threadlist_addhead(&tl, fakethreads[0]); + check_order(&tl, false); + check_order(&tl, true); + KASSERT(tl.tl_count == 1); + t = threadlist_remhead(&tl); + KASSERT(tl.tl_count == 0); + KASSERT(t == fakethreads[0]); - threadlist_addtail(&tl, fakethreads[0]); - check_order(&tl, false); - check_order(&tl, true); - KASSERT(tl.tl_count == 1); - t = threadlist_remtail(&tl); - KASSERT(tl.tl_count == 0); - KASSERT(t == fakethreads[0]); + threadlist_addtail(&tl, fakethreads[0]); + check_order(&tl, false); + check_order(&tl, true); + KASSERT(tl.tl_count == 1); + t = threadlist_remtail(&tl); + KASSERT(tl.tl_count == 0); + KASSERT(t == fakethreads[0]); - threadlist_cleanup(&tl); + threadlist_cleanup(&tl); } -static -void -threadlisttest_c(void) -{ - struct threadlist tl; - struct thread *t; +static void threadlisttest_c(void) { + struct threadlist tl; + struct thread *t; - threadlist_init(&tl); + threadlist_init(&tl); - threadlist_addhead(&tl, fakethreads[0]); - threadlist_addhead(&tl, fakethreads[1]); - KASSERT(tl.tl_count == 2); + threadlist_addhead(&tl, fakethreads[0]); + threadlist_addhead(&tl, fakethreads[1]); + KASSERT(tl.tl_count == 2); - check_order(&tl, true); + check_order(&tl, true); - t = threadlist_remhead(&tl); - KASSERT(t == fakethreads[1]); - t = threadlist_remhead(&tl); - KASSERT(t == fakethreads[0]); - KASSERT(tl.tl_count == 0); + t = threadlist_remhead(&tl); + KASSERT(t == fakethreads[1]); + t = threadlist_remhead(&tl); + KASSERT(t == fakethreads[0]); + KASSERT(tl.tl_count == 0); - threadlist_addtail(&tl, fakethreads[0]); - threadlist_addtail(&tl, fakethreads[1]); - KASSERT(tl.tl_count == 2); + threadlist_addtail(&tl, fakethreads[0]); + threadlist_addtail(&tl, fakethreads[1]); + KASSERT(tl.tl_count == 2); - check_order(&tl, false); + check_order(&tl, false); - t = threadlist_remtail(&tl); - KASSERT(t == fakethreads[1]); - t = threadlist_remtail(&tl); - KASSERT(t == fakethreads[0]); - KASSERT(tl.tl_count == 0); + t = threadlist_remtail(&tl); + KASSERT(t == fakethreads[1]); + t = threadlist_remtail(&tl); + KASSERT(t == fakethreads[0]); + KASSERT(tl.tl_count == 0); - threadlist_cleanup(&tl); + threadlist_cleanup(&tl); } -static -void -threadlisttest_d(void) -{ - struct threadlist tl; - struct thread *t; +static void threadlisttest_d(void) { + struct threadlist tl; + struct thread *t; - threadlist_init(&tl); + threadlist_init(&tl); - threadlist_addhead(&tl, fakethreads[0]); - threadlist_addtail(&tl, fakethreads[1]); - KASSERT(tl.tl_count == 2); + threadlist_addhead(&tl, fakethreads[0]); + threadlist_addtail(&tl, fakethreads[1]); + KASSERT(tl.tl_count == 2); - check_order(&tl, false); + check_order(&tl, false); - t = threadlist_remhead(&tl); - KASSERT(t == fakethreads[0]); - t = threadlist_remtail(&tl); - KASSERT(t == fakethreads[1]); - KASSERT(tl.tl_count == 0); + t = threadlist_remhead(&tl); + KASSERT(t == fakethreads[0]); + t = threadlist_remtail(&tl); + KASSERT(t == fakethreads[1]); + KASSERT(tl.tl_count == 0); - threadlist_addhead(&tl, fakethreads[0]); - threadlist_addtail(&tl, fakethreads[1]); - KASSERT(tl.tl_count == 2); + threadlist_addhead(&tl, fakethreads[0]); + threadlist_addtail(&tl, fakethreads[1]); + KASSERT(tl.tl_count == 2); - check_order(&tl, false); + check_order(&tl, false); - t = threadlist_remtail(&tl); - KASSERT(t == fakethreads[1]); - t = threadlist_remtail(&tl); - KASSERT(t == fakethreads[0]); - KASSERT(tl.tl_count == 0); + t = threadlist_remtail(&tl); + KASSERT(t == fakethreads[1]); + t = threadlist_remtail(&tl); + KASSERT(t == fakethreads[0]); + KASSERT(tl.tl_count == 0); - threadlist_cleanup(&tl); + threadlist_cleanup(&tl); } -static -void -threadlisttest_e(void) -{ - struct threadlist tl; - struct thread *t; - unsigned i; +static void threadlisttest_e(void) { + struct threadlist tl; + struct thread *t; + unsigned i; - threadlist_init(&tl); + threadlist_init(&tl); - threadlist_addhead(&tl, fakethreads[1]); - threadlist_addtail(&tl, fakethreads[3]); - KASSERT(tl.tl_count == 2); - check_order(&tl, false); + threadlist_addhead(&tl, fakethreads[1]); + threadlist_addtail(&tl, fakethreads[3]); + KASSERT(tl.tl_count == 2); + check_order(&tl, false); - threadlist_insertafter(&tl, fakethreads[3], fakethreads[4]); - KASSERT(tl.tl_count == 3); - check_order(&tl, false); + threadlist_insertafter(&tl, fakethreads[3], fakethreads[4]); + KASSERT(tl.tl_count == 3); + check_order(&tl, false); - threadlist_insertbefore(&tl, fakethreads[0], fakethreads[1]); - KASSERT(tl.tl_count == 4); - check_order(&tl, false); + threadlist_insertbefore(&tl, fakethreads[0], fakethreads[1]); + KASSERT(tl.tl_count == 4); + check_order(&tl, false); - threadlist_insertafter(&tl, fakethreads[1], fakethreads[2]); - KASSERT(tl.tl_count == 5); - check_order(&tl, false); + threadlist_insertafter(&tl, fakethreads[1], fakethreads[2]); + KASSERT(tl.tl_count == 5); + check_order(&tl, false); - KASSERT(fakethreads[4]->t_listnode.tln_prev->tln_self == - fakethreads[3]); - KASSERT(fakethreads[3]->t_listnode.tln_prev->tln_self == - fakethreads[2]); - KASSERT(fakethreads[2]->t_listnode.tln_prev->tln_self == - fakethreads[1]); - KASSERT(fakethreads[1]->t_listnode.tln_prev->tln_self == - fakethreads[0]); + KASSERT(fakethreads[4]->t_listnode.tln_prev->tln_self == fakethreads[3]); + KASSERT(fakethreads[3]->t_listnode.tln_prev->tln_self == fakethreads[2]); + KASSERT(fakethreads[2]->t_listnode.tln_prev->tln_self == fakethreads[1]); + KASSERT(fakethreads[1]->t_listnode.tln_prev->tln_self == fakethreads[0]); - for (i=0; i<5; i++) { - t = threadlist_remhead(&tl); - KASSERT(t == fakethreads[i]); - } - KASSERT(tl.tl_count == 0); + for (i = 0; i < 5; i++) { + t = threadlist_remhead(&tl); + KASSERT(t == fakethreads[i]); + } + KASSERT(tl.tl_count == 0); - threadlist_cleanup(&tl); + threadlist_cleanup(&tl); } -static -void -threadlisttest_f(void) -{ - struct threadlist tl; - struct thread *t; - unsigned i; +static void threadlisttest_f(void) { + struct threadlist tl; + struct thread *t; + unsigned i; - threadlist_init(&tl); + threadlist_init(&tl); - for (i=0; i #include -#define NTHREADS 8 +#define NTHREADS 8 static struct semaphore *tsem = NULL; -static -void -init_sem(void) -{ - if (tsem==NULL) { - tsem = sem_create("tsem", 0); - if (tsem == NULL) { - panic("threadtest: sem_create failed\n"); - } - } +static void init_sem(void) { + if (tsem == NULL) { + tsem = sem_create("tsem", 0); + if (tsem == NULL) { + panic("threadtest: sem_create failed\n"); + } + } } -static -void -loudthread(void *junk, unsigned long num) -{ - int ch = '0' + num; - int i; +static void loudthread(void *junk, unsigned long num) { + int ch = '0' + num; + int i; - (void)junk; + (void)junk; - for (i=0; i<120; i++) { - putch(ch); - } - V(tsem); + for (i = 0; i < 120; i++) { + putch(ch); + } + V(tsem); } /* @@ -77,70 +71,58 @@ loudthread(void *junk, unsigned long num) * The delay loop is supposed to be long enough that it should be clear * if either timeslicing or the scheduler is not working right. */ -static -void -quietthread(void *junk, unsigned long num) -{ - int ch = '0' + num; - volatile int i; +static void quietthread(void *junk, unsigned long num) { + int ch = '0' + num; + volatile int i; - (void)junk; + (void)junk; - putch(ch); - for (i=0; i<200000; i++); - putch(ch); + putch(ch); + for (i = 0; i < 200000; i++) + ; + putch(ch); - V(tsem); + V(tsem); } -static -void -runthreads(int doloud) -{ - char name[16]; - int i, result; +static void runthreads(int doloud) { + char name[16]; + int i, result; - for (i=0; im[i][j] = rand >> 16; - m2->m[i][j] = rand & 0xffff; - } - } + for (i = 0; i < DIM; i++) { + for (j = 0; j < DIM; j++) { + rand = random(); + m1->m[i][j] = rand >> 16; + m2->m[i][j] = rand & 0xffff; + } + } - for (i=0; im[i][k] * m2->m[k][j]; - } - m3->m[i][j] = tot; - } - } + for (i = 0; i < DIM; i++) { + for (j = 0; j < DIM; j++) { + tot = 0; + for (k = 0; k < DIM; k++) { + tot += m1->m[i][k] * m2->m[k][j]; + } + m3->m[i][j] = tot; + } + } - tot = 0; - for (i=0; im[i][i]; - } + tot = 0; + for (i = 0; i < DIM; i++) { + tot += m3->m[i][i]; + } - kprintf("{%lu: %u}", num, (unsigned) tot); - thread_yield(); - } + kprintf("{%lu: %u}", num, (unsigned)tot); + thread_yield(); + } - kfree(m1); - kfree(m2); - kfree(m3); + kfree(m1); + kfree(m2); + kfree(m3); - V(donesem); + V(donesem); } -static -void -make_computes(int howmany) -{ - char name[16]; - int i, result; +static void make_computes(int howmany) { + char name[16]; + int i, result; - for (i=0; ic_hardclocks++; - if ((curcpu->c_hardclocks % MIGRATE_HARDCLOCKS) == 0) { - thread_consider_migration(); - } - if ((curcpu->c_hardclocks % SCHEDULE_HARDCLOCKS) == 0) { - schedule(); - } - thread_yield(); + curcpu->c_hardclocks++; + if ((curcpu->c_hardclocks % MIGRATE_HARDCLOCKS) == 0) { + thread_consider_migration(); + } + if ((curcpu->c_hardclocks % SCHEDULE_HARDCLOCKS) == 0) { + schedule(); + } + thread_yield(); } /* * Suspend execution for n seconds. */ -void -clocksleep(int num_secs) -{ - spinlock_acquire(&lbolt_lock); - while (num_secs > 0) { - wchan_sleep(lbolt, &lbolt_lock); - num_secs--; - } - spinlock_release(&lbolt_lock); +void clocksleep(int num_secs) { + spinlock_acquire(&lbolt_lock); + while (num_secs > 0) { + wchan_sleep(lbolt, &lbolt_lock); + num_secs--; + } + spinlock_release(&lbolt_lock); } diff --git a/kern/thread/hangman.c b/kern/thread/hangman.c index 127167a..7635be5 100644 --- a/kern/thread/hangman.c +++ b/kern/thread/hangman.c @@ -47,50 +47,47 @@ static struct spinlock hangman_lock = SPINLOCK_INITIALIZER; * only be waiting for one thing at a time, this turns out to be * quite simple. */ -static -void -hangman_check(const struct hangman_lockable *start, - const struct hangman_actor *target) -{ - const struct hangman_actor *cur; +static void hangman_check(const struct hangman_lockable *start, + const struct hangman_actor *target) { + const struct hangman_actor *cur; - cur = start->l_holding; - while (cur != NULL) { - if (cur == target) { - goto found; - } - if (cur->a_waiting == NULL) { - break; - } - cur = cur->a_waiting->l_holding; - } - return; + cur = start->l_holding; + while (cur != NULL) { + if (cur == target) { + goto found; + } + if (cur->a_waiting == NULL) { + break; + } + cur = cur->a_waiting->l_holding; + } + return; - found: - /* - * None of this can change while we print it (that's the point - * of it being a deadlock) so drop hangman_lock while - * printing; otherwise we can come back via kprintf_spinlock - * and that makes a mess. But force splhigh() explicitly so - * the console prints in polled mode and to discourage other - * things from running in the middle of the printout. - */ - splhigh(); - spinlock_release(&hangman_lock); +found: + /* + * None of this can change while we print it (that's the point + * of it being a deadlock) so drop hangman_lock while + * printing; otherwise we can come back via kprintf_spinlock + * and that makes a mess. But force splhigh() explicitly so + * the console prints in polled mode and to discourage other + * things from running in the middle of the printout. + */ + splhigh(); + spinlock_release(&hangman_lock); - kprintf("hangman: Detected lock cycle!\n"); - kprintf("hangman: in %s (%p);\n", target->a_name, target); - kprintf("hangman: waiting for %s (%p), but:\n", start->l_name, start); - kprintf(" lockable %s (%p)\n", start->l_name, start); - cur = start->l_holding; - while (cur != target) { - kprintf(" held by actor %s (%p)\n", cur->a_name, cur); - kprintf(" waiting for lockable %s (%p)\n", - cur->a_waiting->l_name, cur->a_waiting); - cur = cur->a_waiting->l_holding; - } - kprintf(" held by actor %s (%p)\n", cur->a_name, cur); - panic("Deadlock.\n"); + kprintf("hangman: Detected lock cycle!\n"); + kprintf("hangman: in %s (%p);\n", target->a_name, target); + kprintf("hangman: waiting for %s (%p), but:\n", start->l_name, start); + kprintf(" lockable %s (%p)\n", start->l_name, start); + cur = start->l_holding; + while (cur != target) { + kprintf(" held by actor %s (%p)\n", cur->a_name, cur); + kprintf(" waiting for lockable %s (%p)\n", cur->a_waiting->l_name, + cur->a_waiting); + cur = cur->a_waiting->l_holding; + } + kprintf(" held by actor %s (%p)\n", cur->a_name, cur); + panic("Deadlock.\n"); } /* @@ -106,77 +103,67 @@ hangman_check(const struct hangman_lockable *start, * tricky and problematic. For now we'll settle for just detecting and * reporting deadlocks that do happen. */ -void -hangman_wait(struct hangman_actor *a, - struct hangman_lockable *l) -{ - if (l == &hangman_lock.splk_hangman) { - /* don't recurse */ - return; - } +void hangman_wait(struct hangman_actor *a, struct hangman_lockable *l) { + if (l == &hangman_lock.splk_hangman) { + /* don't recurse */ + return; + } - spinlock_acquire(&hangman_lock); + spinlock_acquire(&hangman_lock); - if (a->a_waiting != NULL) { - spinlock_release(&hangman_lock); - panic("hangman_wait: already waiting for something?\n"); - } + if (a->a_waiting != NULL) { + spinlock_release(&hangman_lock); + panic("hangman_wait: already waiting for something?\n"); + } - hangman_check(l, a); - a->a_waiting = l; + hangman_check(l, a); + a->a_waiting = l; - spinlock_release(&hangman_lock); + spinlock_release(&hangman_lock); } -void -hangman_acquire(struct hangman_actor *a, - struct hangman_lockable *l) -{ - if (l == &hangman_lock.splk_hangman) { - /* don't recurse */ - return; - } +void hangman_acquire(struct hangman_actor *a, struct hangman_lockable *l) { + if (l == &hangman_lock.splk_hangman) { + /* don't recurse */ + return; + } - spinlock_acquire(&hangman_lock); + spinlock_acquire(&hangman_lock); - if (a->a_waiting != l) { - spinlock_release(&hangman_lock); - panic("hangman_acquire: not waiting for lock %s (%p)\n", - l->l_name, l); - } - if (l->l_holding != NULL) { - spinlock_release(&hangman_lock); - panic("hangman_acquire: lock %s (%p) still held by %s (%p)\n", - l->l_name, l, a->a_name, a); - } + if (a->a_waiting != l) { + spinlock_release(&hangman_lock); + panic("hangman_acquire: not waiting for lock %s (%p)\n", l->l_name, l); + } + if (l->l_holding != NULL) { + spinlock_release(&hangman_lock); + panic("hangman_acquire: lock %s (%p) still held by %s (%p)\n", l->l_name, l, + a->a_name, a); + } - l->l_holding = a; - a->a_waiting = NULL; + l->l_holding = a; + a->a_waiting = NULL; - spinlock_release(&hangman_lock); + spinlock_release(&hangman_lock); } -void -hangman_release(struct hangman_actor *a, - struct hangman_lockable *l) -{ - if (l == &hangman_lock.splk_hangman) { - /* don't recurse */ - return; - } +void hangman_release(struct hangman_actor *a, struct hangman_lockable *l) { + if (l == &hangman_lock.splk_hangman) { + /* don't recurse */ + return; + } - spinlock_acquire(&hangman_lock); + spinlock_acquire(&hangman_lock); - if (a->a_waiting != NULL) { - spinlock_release(&hangman_lock); - panic("hangman_release: waiting for something?\n"); - } - if (l->l_holding != a) { - spinlock_release(&hangman_lock); - panic("hangman_release: not the holder\n"); - } + if (a->a_waiting != NULL) { + spinlock_release(&hangman_lock); + panic("hangman_release: waiting for something?\n"); + } + if (l->l_holding != a) { + spinlock_release(&hangman_lock); + panic("hangman_release: not the holder\n"); + } - l->l_holding = NULL; + l->l_holding = NULL; - spinlock_release(&hangman_lock); + spinlock_release(&hangman_lock); } diff --git a/kern/thread/spinlock.c b/kern/thread/spinlock.c index 0cdf9aa..364e078 100644 --- a/kern/thread/spinlock.c +++ b/kern/thread/spinlock.c @@ -28,8 +28,8 @@ */ /* Make sure to build out-of-line versions of inline functions */ -#define SPINLOCK_INLINE /* empty */ -#define MEMBAR_INLINE /* empty */ +#define SPINLOCK_INLINE /* empty */ +#define MEMBAR_INLINE /* empty */ #include #include @@ -37,32 +37,27 @@ #include #include #include -#include /* for curcpu */ +#include /* for curcpu */ /* * Spinlocks. */ - /* * Initialize spinlock. */ -void -spinlock_init(struct spinlock *splk) -{ - spinlock_data_set(&splk->splk_lock, 0); - splk->splk_holder = NULL; - HANGMAN_LOCKABLEINIT(&splk->splk_hangman, "spinlock"); +void spinlock_init(struct spinlock *splk) { + spinlock_data_set(&splk->splk_lock, 0); + splk->splk_holder = NULL; + HANGMAN_LOCKABLEINIT(&splk->splk_hangman, "spinlock"); } /* * Clean up spinlock. */ -void -spinlock_cleanup(struct spinlock *splk) -{ - KASSERT(splk->splk_holder == NULL); - KASSERT(spinlock_data_get(&splk->splk_lock) == 0); +void spinlock_cleanup(struct spinlock *splk) { + KASSERT(splk->splk_holder == NULL); + KASSERT(spinlock_data_get(&splk->splk_lock) == 0); } /* @@ -72,85 +67,78 @@ spinlock_cleanup(struct spinlock *splk) * might come back to this lock and deadlock), then use a machine-level * atomic operation to wait for the lock to be free. */ -void -spinlock_acquire(struct spinlock *splk) -{ - struct cpu *mycpu; +void spinlock_acquire(struct spinlock *splk) { + struct cpu *mycpu; - splraise(IPL_NONE, IPL_HIGH); + splraise(IPL_NONE, IPL_HIGH); - /* this must work before curcpu initialization */ - if (CURCPU_EXISTS()) { - mycpu = curcpu->c_self; - if (splk->splk_holder == mycpu) { - panic("Deadlock on spinlock %p\n", splk); - } - mycpu->c_spinlocks++; + /* this must work before curcpu initialization */ + if (CURCPU_EXISTS()) { + mycpu = curcpu->c_self; + if (splk->splk_holder == mycpu) { + panic("Deadlock on spinlock %p\n", splk); + } + mycpu->c_spinlocks++; - HANGMAN_WAIT(&curcpu->c_hangman, &splk->splk_hangman); - } - else { - mycpu = NULL; - } + HANGMAN_WAIT(&curcpu->c_hangman, &splk->splk_hangman); + } else { + mycpu = NULL; + } - while (1) { - /* - * Do test-test-and-set, that is, read first before - * doing test-and-set, to reduce bus contention. - * - * Test-and-set is a machine-level atomic operation - * that writes 1 into the lock word and returns the - * previous value. If that value was 0, the lock was - * previously unheld and we now own it. If it was 1, - * we don't. - */ - if (spinlock_data_get(&splk->splk_lock) != 0) { - continue; - } - if (spinlock_data_testandset(&splk->splk_lock) != 0) { - continue; - } - break; - } + while (1) { + /* + * Do test-test-and-set, that is, read first before + * doing test-and-set, to reduce bus contention. + * + * Test-and-set is a machine-level atomic operation + * that writes 1 into the lock word and returns the + * previous value. If that value was 0, the lock was + * previously unheld and we now own it. If it was 1, + * we don't. + */ + if (spinlock_data_get(&splk->splk_lock) != 0) { + continue; + } + if (spinlock_data_testandset(&splk->splk_lock) != 0) { + continue; + } + break; + } - membar_store_any(); - splk->splk_holder = mycpu; + membar_store_any(); + splk->splk_holder = mycpu; - if (CURCPU_EXISTS()) { - HANGMAN_ACQUIRE(&curcpu->c_hangman, &splk->splk_hangman); - } + if (CURCPU_EXISTS()) { + HANGMAN_ACQUIRE(&curcpu->c_hangman, &splk->splk_hangman); + } } /* * Release the lock. */ -void -spinlock_release(struct spinlock *splk) -{ - /* this must work before curcpu initialization */ - if (CURCPU_EXISTS()) { - KASSERT(splk->splk_holder == curcpu->c_self); - KASSERT(curcpu->c_spinlocks > 0); - curcpu->c_spinlocks--; - HANGMAN_RELEASE(&curcpu->c_hangman, &splk->splk_hangman); - } +void spinlock_release(struct spinlock *splk) { + /* this must work before curcpu initialization */ + if (CURCPU_EXISTS()) { + KASSERT(splk->splk_holder == curcpu->c_self); + KASSERT(curcpu->c_spinlocks > 0); + curcpu->c_spinlocks--; + HANGMAN_RELEASE(&curcpu->c_hangman, &splk->splk_hangman); + } - splk->splk_holder = NULL; - membar_any_store(); - spinlock_data_set(&splk->splk_lock, 0); - spllower(IPL_HIGH, IPL_NONE); + splk->splk_holder = NULL; + membar_any_store(); + spinlock_data_set(&splk->splk_lock, 0); + spllower(IPL_HIGH, IPL_NONE); } /* * Check if the current cpu holds the lock. */ -bool -spinlock_do_i_hold(struct spinlock *splk) -{ - if (!CURCPU_EXISTS()) { - return true; - } +bool spinlock_do_i_hold(struct spinlock *splk) { + if (!CURCPU_EXISTS()) { + return true; + } - /* Assume we can read splk_holder atomically enough for this to work */ - return (splk->splk_holder == curcpu->c_self); + /* Assume we can read splk_holder atomically enough for this to work */ + return (splk->splk_holder == curcpu->c_self); } diff --git a/kern/thread/spl.c b/kern/thread/spl.c index cbdfef9..8d327d6 100644 --- a/kern/thread/spl.c +++ b/kern/thread/spl.c @@ -28,7 +28,7 @@ */ /* Make sure to build out-of-line versions of spl inline functions */ -#define SPL_INLINE /* empty */ +#define SPL_INLINE /* empty */ #include #include @@ -54,7 +54,6 @@ * complicated -- but nearly all of this code could remain MI. */ - /* * Raise and lower the interrupt priority level. * @@ -83,78 +82,69 @@ * * curthread->t_iplhigh_count is used to track this. */ -void -splraise(int oldspl, int newspl) -{ - struct thread *cur = curthread; +void splraise(int oldspl, int newspl) { + struct thread *cur = curthread; - /* only one priority level, only one valid args configuration */ - KASSERT(oldspl == IPL_NONE); - KASSERT(newspl == IPL_HIGH); + /* only one priority level, only one valid args configuration */ + KASSERT(oldspl == IPL_NONE); + KASSERT(newspl == IPL_HIGH); - if (!CURCPU_EXISTS()) { - /* before curcpu initialization; interrupts are off anyway */ - return; - } + if (!CURCPU_EXISTS()) { + /* before curcpu initialization; interrupts are off anyway */ + return; + } - if (cur->t_iplhigh_count == 0) { - cpu_irqoff(); - } - cur->t_iplhigh_count++; + if (cur->t_iplhigh_count == 0) { + cpu_irqoff(); + } + cur->t_iplhigh_count++; } -void -spllower(int oldspl, int newspl) -{ - struct thread *cur = curthread; +void spllower(int oldspl, int newspl) { + struct thread *cur = curthread; - /* only one priority level, only one valid args configuration */ - KASSERT(oldspl == IPL_HIGH); - KASSERT(newspl == IPL_NONE); + /* only one priority level, only one valid args configuration */ + KASSERT(oldspl == IPL_HIGH); + KASSERT(newspl == IPL_NONE); - if (!CURCPU_EXISTS()) { - /* before curcpu initialization; interrupts are off anyway */ - return; - } + if (!CURCPU_EXISTS()) { + /* before curcpu initialization; interrupts are off anyway */ + return; + } - cur->t_iplhigh_count--; - if (cur->t_iplhigh_count == 0) { - cpu_irqon(); - } + cur->t_iplhigh_count--; + if (cur->t_iplhigh_count == 0) { + cpu_irqon(); + } } - /* * Disable or enable interrupts and adjust curspl setting. Return old * spl level. */ -int -splx(int spl) -{ - struct thread *cur = curthread; - int ret; +int splx(int spl) { + struct thread *cur = curthread; + int ret; - if (!CURCPU_EXISTS()) { - /* before curcpu initialization; interrupts are off anyway */ - return spl; - } + if (!CURCPU_EXISTS()) { + /* before curcpu initialization; interrupts are off anyway */ + return spl; + } - if (cur->t_curspl < spl) { - /* turning interrupts off */ - splraise(cur->t_curspl, spl); - ret = cur->t_curspl; - cur->t_curspl = spl; - } - else if (cur->t_curspl > spl) { - /* turning interrupts on */ - ret = cur->t_curspl; - cur->t_curspl = spl; - spllower(ret, spl); - } - else { - /* do nothing */ - ret = spl; - } + if (cur->t_curspl < spl) { + /* turning interrupts off */ + splraise(cur->t_curspl, spl); + ret = cur->t_curspl; + cur->t_curspl = spl; + } else if (cur->t_curspl > spl) { + /* turning interrupts on */ + ret = cur->t_curspl; + cur->t_curspl = spl; + spllower(ret, spl); + } else { + /* do nothing */ + ret = spl; + } - return ret; + return ret; } diff --git a/kern/thread/synch.c b/kern/thread/synch.c index ad58934..d7cf202 100644 --- a/kern/thread/synch.c +++ b/kern/thread/synch.c @@ -44,226 +44,197 @@ // // Semaphore. -struct semaphore * -sem_create(const char *name, unsigned initial_count) -{ - struct semaphore *sem; +struct semaphore *sem_create(const char *name, unsigned initial_count) { + struct semaphore *sem; - sem = kmalloc(sizeof(*sem)); - if (sem == NULL) { - return NULL; - } + sem = kmalloc(sizeof(*sem)); + if (sem == NULL) { + return NULL; + } - sem->sem_name = kstrdup(name); - if (sem->sem_name == NULL) { - kfree(sem); - return NULL; - } + sem->sem_name = kstrdup(name); + if (sem->sem_name == NULL) { + kfree(sem); + return NULL; + } - sem->sem_wchan = wchan_create(sem->sem_name); - if (sem->sem_wchan == NULL) { - kfree(sem->sem_name); - kfree(sem); - return NULL; - } + sem->sem_wchan = wchan_create(sem->sem_name); + if (sem->sem_wchan == NULL) { + kfree(sem->sem_name); + kfree(sem); + return NULL; + } - spinlock_init(&sem->sem_lock); - sem->sem_count = initial_count; + spinlock_init(&sem->sem_lock); + sem->sem_count = initial_count; - return sem; + return sem; } -void -sem_destroy(struct semaphore *sem) -{ - KASSERT(sem != NULL); +void sem_destroy(struct semaphore *sem) { + KASSERT(sem != NULL); - /* wchan_cleanup will assert if anyone's waiting on it */ - spinlock_cleanup(&sem->sem_lock); - wchan_destroy(sem->sem_wchan); - kfree(sem->sem_name); - kfree(sem); + /* wchan_cleanup will assert if anyone's waiting on it */ + spinlock_cleanup(&sem->sem_lock); + wchan_destroy(sem->sem_wchan); + kfree(sem->sem_name); + kfree(sem); } -void -P(struct semaphore *sem) -{ - KASSERT(sem != NULL); +void P(struct semaphore *sem) { + KASSERT(sem != NULL); - /* - * May not block in an interrupt handler. - * - * For robustness, always check, even if we can actually - * complete the P without blocking. - */ - KASSERT(curthread->t_in_interrupt == false); + /* + * May not block in an interrupt handler. + * + * For robustness, always check, even if we can actually + * complete the P without blocking. + */ + KASSERT(curthread->t_in_interrupt == false); - /* Use the semaphore spinlock to protect the wchan as well. */ - spinlock_acquire(&sem->sem_lock); - while (sem->sem_count == 0) { - /* - * - * Note that we don't maintain strict FIFO ordering of - * threads going through the semaphore; that is, we - * might "get" it on the first try even if other - * threads are waiting. Apparently according to some - * textbooks semaphores must for some reason have - * strict ordering. Too bad. :-) - * - * Exercise: how would you implement strict FIFO - * ordering? - */ - wchan_sleep(sem->sem_wchan, &sem->sem_lock); - } - KASSERT(sem->sem_count > 0); - sem->sem_count--; - spinlock_release(&sem->sem_lock); + /* Use the semaphore spinlock to protect the wchan as well. */ + spinlock_acquire(&sem->sem_lock); + while (sem->sem_count == 0) { + /* + * + * Note that we don't maintain strict FIFO ordering of + * threads going through the semaphore; that is, we + * might "get" it on the first try even if other + * threads are waiting. Apparently according to some + * textbooks semaphores must for some reason have + * strict ordering. Too bad. :-) + * + * Exercise: how would you implement strict FIFO + * ordering? + */ + wchan_sleep(sem->sem_wchan, &sem->sem_lock); + } + KASSERT(sem->sem_count > 0); + sem->sem_count--; + spinlock_release(&sem->sem_lock); } -void -V(struct semaphore *sem) -{ - KASSERT(sem != NULL); +void V(struct semaphore *sem) { + KASSERT(sem != NULL); - spinlock_acquire(&sem->sem_lock); + spinlock_acquire(&sem->sem_lock); - sem->sem_count++; - KASSERT(sem->sem_count > 0); - wchan_wakeone(sem->sem_wchan, &sem->sem_lock); + sem->sem_count++; + KASSERT(sem->sem_count > 0); + wchan_wakeone(sem->sem_wchan, &sem->sem_lock); - spinlock_release(&sem->sem_lock); + spinlock_release(&sem->sem_lock); } //////////////////////////////////////////////////////////// // // Lock. -struct lock * -lock_create(const char *name) -{ - struct lock *lock; +struct lock *lock_create(const char *name) { + struct lock *lock; - lock = kmalloc(sizeof(*lock)); - if (lock == NULL) { - return NULL; - } + lock = kmalloc(sizeof(*lock)); + if (lock == NULL) { + return NULL; + } - lock->lk_name = kstrdup(name); - if (lock->lk_name == NULL) { - kfree(lock); - return NULL; - } + lock->lk_name = kstrdup(name); + if (lock->lk_name == NULL) { + kfree(lock); + return NULL; + } - HANGMAN_LOCKABLEINIT(&lock->lk_hangman, lock->lk_name); + HANGMAN_LOCKABLEINIT(&lock->lk_hangman, lock->lk_name); - // add stuff here as needed + // add stuff here as needed - return lock; + return lock; } -void -lock_destroy(struct lock *lock) -{ - KASSERT(lock != NULL); +void lock_destroy(struct lock *lock) { + KASSERT(lock != NULL); - // add stuff here as needed + // add stuff here as needed - kfree(lock->lk_name); - kfree(lock); + kfree(lock->lk_name); + kfree(lock); } -void -lock_acquire(struct lock *lock) -{ - /* Call this (atomically) before waiting for a lock */ - //HANGMAN_WAIT(&curthread->t_hangman, &lock->lk_hangman); +void lock_acquire(struct lock *lock) { + /* Call this (atomically) before waiting for a lock */ + // HANGMAN_WAIT(&curthread->t_hangman, &lock->lk_hangman); - // Write this + // Write this - (void)lock; // suppress warning until code gets written + (void)lock; // suppress warning until code gets written - /* Call this (atomically) once the lock is acquired */ - //HANGMAN_ACQUIRE(&curthread->t_hangman, &lock->lk_hangman); + /* Call this (atomically) once the lock is acquired */ + // HANGMAN_ACQUIRE(&curthread->t_hangman, &lock->lk_hangman); } -void -lock_release(struct lock *lock) -{ - /* Call this (atomically) when the lock is released */ - //HANGMAN_RELEASE(&curthread->t_hangman, &lock->lk_hangman); +void lock_release(struct lock *lock) { + /* Call this (atomically) when the lock is released */ + // HANGMAN_RELEASE(&curthread->t_hangman, &lock->lk_hangman); - // Write this + // Write this - (void)lock; // suppress warning until code gets written + (void)lock; // suppress warning until code gets written } -bool -lock_do_i_hold(struct lock *lock) -{ - // Write this +bool lock_do_i_hold(struct lock *lock) { + // Write this - (void)lock; // suppress warning until code gets written + (void)lock; // suppress warning until code gets written - return true; // dummy until code gets written + return true; // dummy until code gets written } //////////////////////////////////////////////////////////// // // CV +struct cv *cv_create(const char *name) { + struct cv *cv; -struct cv * -cv_create(const char *name) -{ - struct cv *cv; + cv = kmalloc(sizeof(*cv)); + if (cv == NULL) { + return NULL; + } - cv = kmalloc(sizeof(*cv)); - if (cv == NULL) { - return NULL; - } + cv->cv_name = kstrdup(name); + if (cv->cv_name == NULL) { + kfree(cv); + return NULL; + } - cv->cv_name = kstrdup(name); - if (cv->cv_name==NULL) { - kfree(cv); - return NULL; - } + // add stuff here as needed - // add stuff here as needed - - return cv; + return cv; } -void -cv_destroy(struct cv *cv) -{ - KASSERT(cv != NULL); +void cv_destroy(struct cv *cv) { + KASSERT(cv != NULL); - // add stuff here as needed + // add stuff here as needed - kfree(cv->cv_name); - kfree(cv); + kfree(cv->cv_name); + kfree(cv); } -void -cv_wait(struct cv *cv, struct lock *lock) -{ - // Write this - (void)cv; // suppress warning until code gets written - (void)lock; // suppress warning until code gets written +void cv_wait(struct cv *cv, struct lock *lock) { + // Write this + (void)cv; // suppress warning until code gets written + (void)lock; // suppress warning until code gets written } -void -cv_signal(struct cv *cv, struct lock *lock) -{ - // Write this - (void)cv; // suppress warning until code gets written - (void)lock; // suppress warning until code gets written +void cv_signal(struct cv *cv, struct lock *lock) { + // Write this + (void)cv; // suppress warning until code gets written + (void)lock; // suppress warning until code gets written } -void -cv_broadcast(struct cv *cv, struct lock *lock) -{ - // Write this - (void)cv; // suppress warning until code gets written - (void)lock; // suppress warning until code gets written +void cv_broadcast(struct cv *cv, struct lock *lock) { + // Write this + (void)cv; // suppress warning until code gets written + (void)lock; // suppress warning until code gets written } diff --git a/kern/thread/thread.c b/kern/thread/thread.c index e6fe983..647a412 100644 --- a/kern/thread/thread.c +++ b/kern/thread/thread.c @@ -51,14 +51,13 @@ #include #include - /* Magic number used as a guard value on kernel thread stacks. */ #define THREAD_STACK_MAGIC 0xbaadf00d /* Wait channel. A wchan is protected by an associated, passed-in spinlock. */ struct wchan { - const char *wc_name; /* name for this channel */ - struct threadlist wc_threads; /* list of waiting threads */ + const char *wc_name; /* name for this channel */ + struct threadlist wc_threads; /* list of waiting threads */ }; /* Master array of CPUs. */ @@ -76,14 +75,11 @@ static struct semaphore *cpu_startup_sem; * (sometimes) catch kernel stack overflows. Use thread_checkstack() * to test this. */ -static -void -thread_checkstack_init(struct thread *thread) -{ - ((uint32_t *)thread->t_stack)[0] = THREAD_STACK_MAGIC; - ((uint32_t *)thread->t_stack)[1] = THREAD_STACK_MAGIC; - ((uint32_t *)thread->t_stack)[2] = THREAD_STACK_MAGIC; - ((uint32_t *)thread->t_stack)[3] = THREAD_STACK_MAGIC; +static void thread_checkstack_init(struct thread *thread) { + ((uint32_t *)thread->t_stack)[0] = THREAD_STACK_MAGIC; + ((uint32_t *)thread->t_stack)[1] = THREAD_STACK_MAGIC; + ((uint32_t *)thread->t_stack)[2] = THREAD_STACK_MAGIC; + ((uint32_t *)thread->t_stack)[3] = THREAD_STACK_MAGIC; } /* @@ -96,60 +92,54 @@ thread_checkstack_init(struct thread *thread) * cannot be freed (which in turn is the case if the stack is the boot * stack, and the thread is the boot thread) this doesn't do anything. */ -static -void -thread_checkstack(struct thread *thread) -{ - if (thread->t_stack != NULL) { - KASSERT(((uint32_t*)thread->t_stack)[0] == THREAD_STACK_MAGIC); - KASSERT(((uint32_t*)thread->t_stack)[1] == THREAD_STACK_MAGIC); - KASSERT(((uint32_t*)thread->t_stack)[2] == THREAD_STACK_MAGIC); - KASSERT(((uint32_t*)thread->t_stack)[3] == THREAD_STACK_MAGIC); - } +static void thread_checkstack(struct thread *thread) { + if (thread->t_stack != NULL) { + KASSERT(((uint32_t *)thread->t_stack)[0] == THREAD_STACK_MAGIC); + KASSERT(((uint32_t *)thread->t_stack)[1] == THREAD_STACK_MAGIC); + KASSERT(((uint32_t *)thread->t_stack)[2] == THREAD_STACK_MAGIC); + KASSERT(((uint32_t *)thread->t_stack)[3] == THREAD_STACK_MAGIC); + } } /* * Create a thread. This is used both to create a first thread * for each CPU and to create subsequent forked threads. */ -static -struct thread * -thread_create(const char *name) -{ - struct thread *thread; +static struct thread *thread_create(const char *name) { + struct thread *thread; - DEBUGASSERT(name != NULL); + DEBUGASSERT(name != NULL); - thread = kmalloc(sizeof(*thread)); - if (thread == NULL) { - return NULL; - } + thread = kmalloc(sizeof(*thread)); + if (thread == NULL) { + return NULL; + } - thread->t_name = kstrdup(name); - if (thread->t_name == NULL) { - kfree(thread); - return NULL; - } - thread->t_wchan_name = "NEW"; - thread->t_state = S_READY; + thread->t_name = kstrdup(name); + if (thread->t_name == NULL) { + kfree(thread); + return NULL; + } + thread->t_wchan_name = "NEW"; + thread->t_state = S_READY; - /* Thread subsystem fields */ - thread_machdep_init(&thread->t_machdep); - threadlistnode_init(&thread->t_listnode, thread); - thread->t_stack = NULL; - thread->t_context = NULL; - thread->t_cpu = NULL; - thread->t_proc = NULL; - HANGMAN_ACTORINIT(&thread->t_hangman, thread->t_name); + /* Thread subsystem fields */ + thread_machdep_init(&thread->t_machdep); + threadlistnode_init(&thread->t_listnode, thread); + thread->t_stack = NULL; + thread->t_context = NULL; + thread->t_cpu = NULL; + thread->t_proc = NULL; + HANGMAN_ACTORINIT(&thread->t_hangman, thread->t_name); - /* Interrupt state fields */ - thread->t_in_interrupt = false; - thread->t_curspl = IPL_HIGH; - thread->t_iplhigh_count = 1; /* corresponding to t_curspl */ + /* Interrupt state fields */ + thread->t_in_interrupt = false; + thread->t_curspl = IPL_HIGH; + thread->t_iplhigh_count = 1; /* corresponding to t_curspl */ - /* If you add to struct thread, be sure to initialize here */ + /* If you add to struct thread, be sure to initialize here */ - return thread; + return thread; } /* @@ -160,96 +150,93 @@ thread_create(const char *name) * board config or whatnot) is tracked separately because it is not * necessarily anything sane or meaningful. */ -struct cpu * -cpu_create(unsigned hardware_number) -{ - struct cpu *c; - int result; - char namebuf[16]; +struct cpu *cpu_create(unsigned hardware_number) { + struct cpu *c; + int result; + char namebuf[16]; - c = kmalloc(sizeof(*c)); - if (c == NULL) { - panic("cpu_create: Out of memory\n"); - } + c = kmalloc(sizeof(*c)); + if (c == NULL) { + panic("cpu_create: Out of memory\n"); + } - c->c_self = c; - c->c_hardware_number = hardware_number; + c->c_self = c; + c->c_hardware_number = hardware_number; - c->c_curthread = NULL; - threadlist_init(&c->c_zombies); - c->c_hardclocks = 0; - c->c_spinlocks = 0; + c->c_curthread = NULL; + threadlist_init(&c->c_zombies); + c->c_hardclocks = 0; + c->c_spinlocks = 0; - c->c_isidle = false; - threadlist_init(&c->c_runqueue); - spinlock_init(&c->c_runqueue_lock); + c->c_isidle = false; + threadlist_init(&c->c_runqueue); + spinlock_init(&c->c_runqueue_lock); - c->c_ipi_pending = 0; - c->c_numshootdown = 0; - spinlock_init(&c->c_ipi_lock); + c->c_ipi_pending = 0; + c->c_numshootdown = 0; + spinlock_init(&c->c_ipi_lock); - result = cpuarray_add(&allcpus, c, &c->c_number); - if (result != 0) { - panic("cpu_create: array_add: %s\n", strerror(result)); - } + result = cpuarray_add(&allcpus, c, &c->c_number); + if (result != 0) { + panic("cpu_create: array_add: %s\n", strerror(result)); + } - snprintf(namebuf, sizeof(namebuf), "", c->c_number); - c->c_curthread = thread_create(namebuf); - if (c->c_curthread == NULL) { - panic("cpu_create: thread_create failed\n"); - } - c->c_curthread->t_cpu = c; + snprintf(namebuf, sizeof(namebuf), "", c->c_number); + c->c_curthread = thread_create(namebuf); + if (c->c_curthread == NULL) { + panic("cpu_create: thread_create failed\n"); + } + c->c_curthread->t_cpu = c; - if (c->c_number == 0) { - /* - * Leave c->c_curthread->t_stack NULL for the boot - * cpu. This means we're using the boot stack, which - * can't be freed. (Exercise: what would it take to - * make it possible to free the boot stack?) - */ - /*c->c_curthread->t_stack = ... */ - } - else { - c->c_curthread->t_stack = kmalloc(STACK_SIZE); - if (c->c_curthread->t_stack == NULL) { - panic("cpu_create: couldn't allocate stack"); - } - thread_checkstack_init(c->c_curthread); - } + if (c->c_number == 0) { + /* + * Leave c->c_curthread->t_stack NULL for the boot + * cpu. This means we're using the boot stack, which + * can't be freed. (Exercise: what would it take to + * make it possible to free the boot stack?) + */ + /*c->c_curthread->t_stack = ... */ + } else { + c->c_curthread->t_stack = kmalloc(STACK_SIZE); + if (c->c_curthread->t_stack == NULL) { + panic("cpu_create: couldn't allocate stack"); + } + thread_checkstack_init(c->c_curthread); + } - /* - * If there is no curcpu (or curthread) yet, we are creating - * the first (boot) cpu. Initialize curcpu and curthread as - * early as possible so that other code can take locks without - * exploding. - */ - if (!CURCPU_EXISTS()) { - /* - * Initializing curcpu and curthread is - * machine-dependent because either of curcpu and - * curthread might be defined in terms of the other. - */ - INIT_CURCPU(c, c->c_curthread); + /* + * If there is no curcpu (or curthread) yet, we are creating + * the first (boot) cpu. Initialize curcpu and curthread as + * early as possible so that other code can take locks without + * exploding. + */ + if (!CURCPU_EXISTS()) { + /* + * Initializing curcpu and curthread is + * machine-dependent because either of curcpu and + * curthread might be defined in terms of the other. + */ + INIT_CURCPU(c, c->c_curthread); - /* - * Now make sure both t_cpu and c_curthread are - * set. This might be partially redundant with - * INIT_CURCPU depending on how things are defined. - */ - curthread->t_cpu = curcpu; - curcpu->c_curthread = curthread; - } + /* + * Now make sure both t_cpu and c_curthread are + * set. This might be partially redundant with + * INIT_CURCPU depending on how things are defined. + */ + curthread->t_cpu = curcpu; + curcpu->c_curthread = curthread; + } - HANGMAN_ACTORINIT(&c->c_hangman, "cpu"); + HANGMAN_ACTORINIT(&c->c_hangman, "cpu"); - result = proc_addthread(kproc, c->c_curthread); - if (result) { - panic("cpu_create: proc_addthread:: %s\n", strerror(result)); - } + result = proc_addthread(kproc, c->c_curthread); + if (result) { + panic("cpu_create: proc_addthread:: %s\n", strerror(result)); + } - cpu_machdep_init(c); + cpu_machdep_init(c); - return c; + return c; } /* @@ -260,31 +247,28 @@ cpu_create(unsigned hardware_number) * * (Freeing the stack you're actually using to run is ... inadvisable.) */ -static -void -thread_destroy(struct thread *thread) -{ - KASSERT(thread != curthread); - KASSERT(thread->t_state != S_RUN); +static void thread_destroy(struct thread *thread) { + KASSERT(thread != curthread); + KASSERT(thread->t_state != S_RUN); - /* - * If you add things to struct thread, be sure to clean them up - * either here or in thread_exit(). (And not both...) - */ + /* + * If you add things to struct thread, be sure to clean them up + * either here or in thread_exit(). (And not both...) + */ - /* Thread subsystem fields */ - KASSERT(thread->t_proc == NULL); - if (thread->t_stack != NULL) { - kfree(thread->t_stack); - } - threadlistnode_cleanup(&thread->t_listnode); - thread_machdep_cleanup(&thread->t_machdep); + /* Thread subsystem fields */ + KASSERT(thread->t_proc == NULL); + if (thread->t_stack != NULL) { + kfree(thread->t_stack); + } + threadlistnode_cleanup(&thread->t_listnode); + thread_machdep_cleanup(&thread->t_machdep); - /* sheer paranoia */ - thread->t_wchan_name = "DESTROYED"; + /* sheer paranoia */ + thread->t_wchan_name = "DESTROYED"; - kfree(thread->t_name); - kfree(thread); + kfree(thread->t_name); + kfree(thread); } /* @@ -293,17 +277,14 @@ thread_destroy(struct thread *thread) * * The list of zombies is per-cpu. */ -static -void -exorcise(void) -{ - struct thread *z; +static void exorcise(void) { + struct thread *z; - while ((z = threadlist_remhead(&curcpu->c_zombies)) != NULL) { - KASSERT(z != curthread); - KASSERT(z->t_state == S_ZOMBIE); - thread_destroy(z); - } + while ((z = threadlist_remhead(&curcpu->c_zombies)) != NULL) { + KASSERT(z != curthread); + KASSERT(z->t_state == S_ZOMBIE); + thread_destroy(z); + } } /* @@ -311,87 +292,81 @@ exorcise(void) * possible) to make sure we don't end up letting any other threads * run. */ -void -thread_panic(void) -{ - /* - * Kill off other CPUs. - * - * We could wait for them to stop, except that they might not. - */ - ipi_broadcast(IPI_PANIC); +void thread_panic(void) { + /* + * Kill off other CPUs. + * + * We could wait for them to stop, except that they might not. + */ + ipi_broadcast(IPI_PANIC); - /* - * Drop runnable threads on the floor. - * - * Don't try to get the run queue lock; we might not be able - * to. Instead, blat the list structure by hand, and take the - * risk that it might not be quite atomic. - */ - curcpu->c_runqueue.tl_count = 0; - curcpu->c_runqueue.tl_head.tln_next = &curcpu->c_runqueue.tl_tail; - curcpu->c_runqueue.tl_tail.tln_prev = &curcpu->c_runqueue.tl_head; + /* + * Drop runnable threads on the floor. + * + * Don't try to get the run queue lock; we might not be able + * to. Instead, blat the list structure by hand, and take the + * risk that it might not be quite atomic. + */ + curcpu->c_runqueue.tl_count = 0; + curcpu->c_runqueue.tl_head.tln_next = &curcpu->c_runqueue.tl_tail; + curcpu->c_runqueue.tl_tail.tln_prev = &curcpu->c_runqueue.tl_head; - /* - * Ideally, we want to make sure sleeping threads don't wake - * up and start running. However, there's no good way to track - * down all the wchans floating around the system. Another - * alternative would be to set a global flag to make the wchan - * wakeup operations do nothing; but that would mean we - * ourselves couldn't sleep to wait for an I/O completion - * interrupt, and we'd like to be able to do that if the - * system isn't that badly hosed. - * - * So, do nothing else here. - * - * This may prove inadequate in practice and further steps - * might be needed. It may also be necessary to go through and - * forcibly unlock all locks or the like... - */ + /* + * Ideally, we want to make sure sleeping threads don't wake + * up and start running. However, there's no good way to track + * down all the wchans floating around the system. Another + * alternative would be to set a global flag to make the wchan + * wakeup operations do nothing; but that would mean we + * ourselves couldn't sleep to wait for an I/O completion + * interrupt, and we'd like to be able to do that if the + * system isn't that badly hosed. + * + * So, do nothing else here. + * + * This may prove inadequate in practice and further steps + * might be needed. It may also be necessary to go through and + * forcibly unlock all locks or the like... + */ } /* * At system shutdown, ask the other CPUs to switch off. */ -void -thread_shutdown(void) -{ - /* - * Stop the other CPUs. - * - * We should probably wait for them to stop and shut them off - * on the system board. - */ - ipi_broadcast(IPI_OFFLINE); +void thread_shutdown(void) { + /* + * Stop the other CPUs. + * + * We should probably wait for them to stop and shut them off + * on the system board. + */ + ipi_broadcast(IPI_OFFLINE); } /* * Thread system initialization. */ -void -thread_bootstrap(void) -{ - cpuarray_init(&allcpus); +void thread_bootstrap(void) { + cpuarray_init(&allcpus); - /* - * Create the cpu structure for the bootup CPU, the one we're - * currently running on. Assume the hardware number is 0; that - * might be updated later by mainbus-type code. This also - * creates a thread structure for the first thread, the one - * that's already implicitly running when the kernel is - * started from the bootloader. - */ - KASSERT(CURCPU_EXISTS() == false); - (void)cpu_create(0); - KASSERT(CURCPU_EXISTS() == true); + /* + * Create the cpu structure for the bootup CPU, the one we're + * currently running on. Assume the hardware number is 0; that + * might be updated later by mainbus-type code. This also + * creates a thread structure for the first thread, the one + * that's already implicitly running when the kernel is + * started from the bootloader. + */ + KASSERT(CURCPU_EXISTS() == false); + (void)cpu_create(0); + KASSERT(CURCPU_EXISTS() == true); - /* cpu_create() should also have set t_proc. */ - KASSERT(curcpu != NULL); - KASSERT(curthread != NULL); - KASSERT(curthread->t_proc != NULL); - KASSERT(curthread->t_proc == kproc); + /* cpu_create() should also have set t_proc. */ + KASSERT(curcpu != NULL); + KASSERT(curthread != NULL); + KASSERT(curthread->t_proc != NULL); + KASSERT(curthread->t_proc == kproc); - /* Done */ + /* Done */ } /* @@ -402,44 +377,40 @@ thread_bootstrap(void) * to do anything. The startup thread can just exit; we only need it * to be able to get into thread_switch() properly. */ -void -cpu_hatch(unsigned software_number) -{ - char buf[64]; +void cpu_hatch(unsigned software_number) { + char buf[64]; - KASSERT(curcpu != NULL); - KASSERT(curthread != NULL); - KASSERT(curcpu->c_number == software_number); + KASSERT(curcpu != NULL); + KASSERT(curthread != NULL); + KASSERT(curcpu->c_number == software_number); - spl0(); - cpu_identify(buf, sizeof(buf)); + spl0(); + cpu_identify(buf, sizeof(buf)); - kprintf("cpu%u: %s\n", software_number, buf); + kprintf("cpu%u: %s\n", software_number, buf); - V(cpu_startup_sem); - thread_exit(); + V(cpu_startup_sem); + thread_exit(); } /* * Start up secondary cpus. Called from boot(). */ -void -thread_start_cpus(void) -{ - char buf[64]; - unsigned i; +void thread_start_cpus(void) { + char buf[64]; + unsigned i; - cpu_identify(buf, sizeof(buf)); - kprintf("cpu0: %s\n", buf); + cpu_identify(buf, sizeof(buf)); + kprintf("cpu0: %s\n", buf); - cpu_startup_sem = sem_create("cpu_hatch", 0); - mainbus_start_cpus(); + cpu_startup_sem = sem_create("cpu_hatch", 0); + mainbus_start_cpus(); - for (i=0; it_cpu; + /* Lock the run queue of the target thread's cpu. */ + targetcpu = target->t_cpu; - if (already_have_lock) { - /* The target thread's cpu should be already locked. */ - KASSERT(spinlock_do_i_hold(&targetcpu->c_runqueue_lock)); - } - else { - spinlock_acquire(&targetcpu->c_runqueue_lock); - } + if (already_have_lock) { + /* The target thread's cpu should be already locked. */ + KASSERT(spinlock_do_i_hold(&targetcpu->c_runqueue_lock)); + } else { + spinlock_acquire(&targetcpu->c_runqueue_lock); + } - /* Target thread is now ready to run; put it on the run queue. */ - target->t_state = S_READY; - threadlist_addtail(&targetcpu->c_runqueue, target); + /* Target thread is now ready to run; put it on the run queue. */ + target->t_state = S_READY; + threadlist_addtail(&targetcpu->c_runqueue, target); - if (targetcpu->c_isidle && targetcpu != curcpu->c_self) { - /* - * Other processor is idle; send interrupt to make - * sure it unidles. - */ - ipi_send(targetcpu, IPI_UNIDLE); - } + if (targetcpu->c_isidle && targetcpu != curcpu->c_self) { + /* + * Other processor is idle; send interrupt to make + * sure it unidles. + */ + ipi_send(targetcpu, IPI_UNIDLE); + } - if (!already_have_lock) { - spinlock_release(&targetcpu->c_runqueue_lock); - } + if (!already_have_lock) { + spinlock_release(&targetcpu->c_runqueue_lock); + } } /* @@ -491,60 +459,57 @@ thread_make_runnable(struct thread *target, bool already_have_lock) * process is inherited from the caller. It will start on the same CPU * as the caller, unless the scheduler intervenes first. */ -int -thread_fork(const char *name, - struct proc *proc, - void (*entrypoint)(void *data1, unsigned long data2), - void *data1, unsigned long data2) -{ - struct thread *newthread; - int result; +int thread_fork(const char *name, struct proc *proc, + void (*entrypoint)(void *data1, unsigned long data2), + void *data1, unsigned long data2) { + struct thread *newthread; + int result; - newthread = thread_create(name); - if (newthread == NULL) { - return ENOMEM; - } + newthread = thread_create(name); + if (newthread == NULL) { + return ENOMEM; + } - /* Allocate a stack */ - newthread->t_stack = kmalloc(STACK_SIZE); - if (newthread->t_stack == NULL) { - thread_destroy(newthread); - return ENOMEM; - } - thread_checkstack_init(newthread); + /* Allocate a stack */ + newthread->t_stack = kmalloc(STACK_SIZE); + if (newthread->t_stack == NULL) { + thread_destroy(newthread); + return ENOMEM; + } + thread_checkstack_init(newthread); - /* - * Now we clone various fields from the parent thread. - */ + /* + * Now we clone various fields from the parent thread. + */ - /* Thread subsystem fields */ - newthread->t_cpu = curthread->t_cpu; + /* Thread subsystem fields */ + newthread->t_cpu = curthread->t_cpu; - /* Attach the new thread to its process */ - if (proc == NULL) { - proc = curthread->t_proc; - } - result = proc_addthread(proc, newthread); - if (result) { - /* thread_destroy will clean up the stack */ - thread_destroy(newthread); - return result; - } + /* Attach the new thread to its process */ + if (proc == NULL) { + proc = curthread->t_proc; + } + result = proc_addthread(proc, newthread); + if (result) { + /* thread_destroy will clean up the stack */ + thread_destroy(newthread); + return result; + } - /* - * Because new threads come out holding the cpu runqueue lock - * (see notes at bottom of thread_switch), we need to account - * for the spllower() that will be done releasing it. - */ - newthread->t_iplhigh_count++; + /* + * Because new threads come out holding the cpu runqueue lock + * (see notes at bottom of thread_switch), we need to account + * for the spllower() that will be done releasing it. + */ + newthread->t_iplhigh_count++; - /* Set up the switchframe so entrypoint() gets called */ - switchframe_init(newthread, entrypoint, data1, data2); + /* Set up the switchframe so entrypoint() gets called */ + switchframe_init(newthread, entrypoint, data1, data2); - /* Lock the current cpu's run queue and make the new thread runnable */ - thread_make_runnable(newthread, false); + /* Lock the current cpu's run queue and make the new thread runnable */ + thread_make_runnable(newthread, false); - return 0; + return 0; } /* @@ -557,174 +522,171 @@ thread_fork(const char *name, * WC, protected by the spinlock LK. Otherwise WC and Lk should be * NULL. */ -static -void -thread_switch(threadstate_t newstate, struct wchan *wc, struct spinlock *lk) -{ - struct thread *cur, *next; - int spl; +static void thread_switch(threadstate_t newstate, struct wchan *wc, + struct spinlock *lk) { + struct thread *cur, *next; + int spl; - DEBUGASSERT(curcpu->c_curthread == curthread); - DEBUGASSERT(curthread->t_cpu == curcpu->c_self); + DEBUGASSERT(curcpu->c_curthread == curthread); + DEBUGASSERT(curthread->t_cpu == curcpu->c_self); - /* Explicitly disable interrupts on this processor */ - spl = splhigh(); + /* Explicitly disable interrupts on this processor */ + spl = splhigh(); - cur = curthread; + cur = curthread; - /* - * If we're idle, return without doing anything. This happens - * when the timer interrupt interrupts the idle loop. - */ - if (curcpu->c_isidle) { - splx(spl); - return; - } + /* + * If we're idle, return without doing anything. This happens + * when the timer interrupt interrupts the idle loop. + */ + if (curcpu->c_isidle) { + splx(spl); + return; + } - /* Check the stack guard band. */ - thread_checkstack(cur); + /* Check the stack guard band. */ + thread_checkstack(cur); - /* Lock the run queue. */ - spinlock_acquire(&curcpu->c_runqueue_lock); + /* Lock the run queue. */ + spinlock_acquire(&curcpu->c_runqueue_lock); - /* Micro-optimization: if nothing to do, just return */ - if (newstate == S_READY && threadlist_isempty(&curcpu->c_runqueue)) { - spinlock_release(&curcpu->c_runqueue_lock); - splx(spl); - return; - } + /* Micro-optimization: if nothing to do, just return */ + if (newstate == S_READY && threadlist_isempty(&curcpu->c_runqueue)) { + spinlock_release(&curcpu->c_runqueue_lock); + splx(spl); + return; + } - /* Put the thread in the right place. */ - switch (newstate) { - case S_RUN: - panic("Illegal S_RUN in thread_switch\n"); - case S_READY: - thread_make_runnable(cur, true /*have lock*/); - break; - case S_SLEEP: - cur->t_wchan_name = wc->wc_name; - /* - * Add the thread to the list in the wait channel, and - * unlock same. To avoid a race with someone else - * calling wchan_wake*, we must keep the wchan's - * associated spinlock locked from the point the - * caller of wchan_sleep locked it until the thread is - * on the list. - */ - threadlist_addtail(&wc->wc_threads, cur); - spinlock_release(lk); - break; - case S_ZOMBIE: - cur->t_wchan_name = "ZOMBIE"; - threadlist_addtail(&curcpu->c_zombies, cur); - break; - } - cur->t_state = newstate; + /* Put the thread in the right place. */ + switch (newstate) { + case S_RUN: + panic("Illegal S_RUN in thread_switch\n"); + case S_READY: + thread_make_runnable(cur, true /*have lock*/); + break; + case S_SLEEP: + cur->t_wchan_name = wc->wc_name; + /* + * Add the thread to the list in the wait channel, and + * unlock same. To avoid a race with someone else + * calling wchan_wake*, we must keep the wchan's + * associated spinlock locked from the point the + * caller of wchan_sleep locked it until the thread is + * on the list. + */ + threadlist_addtail(&wc->wc_threads, cur); + spinlock_release(lk); + break; + case S_ZOMBIE: + cur->t_wchan_name = "ZOMBIE"; + threadlist_addtail(&curcpu->c_zombies, cur); + break; + } + cur->t_state = newstate; - /* - * Get the next thread. While there isn't one, call cpu_idle(). - * curcpu->c_isidle must be true when cpu_idle is - * called. Unlock the runqueue while idling too, to make sure - * things can be added to it. - * - * Note that we don't need to unlock the runqueue atomically - * with idling; becoming unidle requires receiving an - * interrupt (either a hardware interrupt or an interprocessor - * interrupt from another cpu posting a wakeup) and idling - * *is* atomic with respect to re-enabling interrupts. - * - * Note that c_isidle becomes true briefly even if we don't go - * idle. However, because one is supposed to hold the runqueue - * lock to look at it, this should not be visible or matter. - */ + /* + * Get the next thread. While there isn't one, call cpu_idle(). + * curcpu->c_isidle must be true when cpu_idle is + * called. Unlock the runqueue while idling too, to make sure + * things can be added to it. + * + * Note that we don't need to unlock the runqueue atomically + * with idling; becoming unidle requires receiving an + * interrupt (either a hardware interrupt or an interprocessor + * interrupt from another cpu posting a wakeup) and idling + * *is* atomic with respect to re-enabling interrupts. + * + * Note that c_isidle becomes true briefly even if we don't go + * idle. However, because one is supposed to hold the runqueue + * lock to look at it, this should not be visible or matter. + */ - /* The current cpu is now idle. */ - curcpu->c_isidle = true; - do { - next = threadlist_remhead(&curcpu->c_runqueue); - if (next == NULL) { - spinlock_release(&curcpu->c_runqueue_lock); - cpu_idle(); - spinlock_acquire(&curcpu->c_runqueue_lock); - } - } while (next == NULL); - curcpu->c_isidle = false; + /* The current cpu is now idle. */ + curcpu->c_isidle = true; + do { + next = threadlist_remhead(&curcpu->c_runqueue); + if (next == NULL) { + spinlock_release(&curcpu->c_runqueue_lock); + cpu_idle(); + spinlock_acquire(&curcpu->c_runqueue_lock); + } + } while (next == NULL); + curcpu->c_isidle = false; - /* - * Note that curcpu->c_curthread may be the same variable as - * curthread and it may not be, depending on how curthread and - * curcpu are defined by the MD code. We'll assign both and - * assume the compiler will optimize one away if they're the - * same. - */ - curcpu->c_curthread = next; - curthread = next; + /* + * Note that curcpu->c_curthread may be the same variable as + * curthread and it may not be, depending on how curthread and + * curcpu are defined by the MD code. We'll assign both and + * assume the compiler will optimize one away if they're the + * same. + */ + curcpu->c_curthread = next; + curthread = next; - /* do the switch (in assembler in switch.S) */ - switchframe_switch(&cur->t_context, &next->t_context); + /* do the switch (in assembler in switch.S) */ + switchframe_switch(&cur->t_context, &next->t_context); - /* - * When we get to this point we are either running in the next - * thread, or have come back to the same thread again, - * depending on how you look at it. That is, - * switchframe_switch returns immediately in another thread - * context, which in general will be executing here with a - * different stack and different values in the local - * variables. (Although new threads go to thread_startup - * instead.) But, later on when the processor, or some - * processor, comes back to the previous thread, it's also - * executing here with the *same* value in the local - * variables. - * - * The upshot, however, is as follows: - * - * - The thread now currently running is "cur", not "next", - * because when we return from switchrame_switch on the - * same stack, we're back to the thread that - * switchframe_switch call switched away from, which is - * "cur". - * - * - "cur" is _not_ the thread that just *called* - * switchframe_switch. - * - * - If newstate is S_ZOMB we never get back here in that - * context at all. - * - * - If the thread just chosen to run ("next") was a new - * thread, we don't get to this code again until - * *another* context switch happens, because when new - * threads return from switchframe_switch they teleport - * to thread_startup. - * - * - At this point the thread whose stack we're now on may - * have been migrated to another cpu since it last ran. - * - * The above is inherently confusing and will probably take a - * while to get used to. - * - * However, the important part is that code placed here, after - * the call to switchframe_switch, does not necessarily run on - * every context switch. Thus any such code must be either - * skippable on some switches or also called from - * thread_startup. - */ + /* + * When we get to this point we are either running in the next + * thread, or have come back to the same thread again, + * depending on how you look at it. That is, + * switchframe_switch returns immediately in another thread + * context, which in general will be executing here with a + * different stack and different values in the local + * variables. (Although new threads go to thread_startup + * instead.) But, later on when the processor, or some + * processor, comes back to the previous thread, it's also + * executing here with the *same* value in the local + * variables. + * + * The upshot, however, is as follows: + * + * - The thread now currently running is "cur", not "next", + * because when we return from switchrame_switch on the + * same stack, we're back to the thread that + * switchframe_switch call switched away from, which is + * "cur". + * + * - "cur" is _not_ the thread that just *called* + * switchframe_switch. + * + * - If newstate is S_ZOMB we never get back here in that + * context at all. + * + * - If the thread just chosen to run ("next") was a new + * thread, we don't get to this code again until + * *another* context switch happens, because when new + * threads return from switchframe_switch they teleport + * to thread_startup. + * + * - At this point the thread whose stack we're now on may + * have been migrated to another cpu since it last ran. + * + * The above is inherently confusing and will probably take a + * while to get used to. + * + * However, the important part is that code placed here, after + * the call to switchframe_switch, does not necessarily run on + * every context switch. Thus any such code must be either + * skippable on some switches or also called from + * thread_startup. + */ + /* Clear the wait channel and set the thread state. */ + cur->t_wchan_name = NULL; + cur->t_state = S_RUN; - /* Clear the wait channel and set the thread state. */ - cur->t_wchan_name = NULL; - cur->t_state = S_RUN; + /* Unlock the run queue. */ + spinlock_release(&curcpu->c_runqueue_lock); - /* Unlock the run queue. */ - spinlock_release(&curcpu->c_runqueue_lock); + /* Activate our address space in the MMU. */ + as_activate(); - /* Activate our address space in the MMU. */ - as_activate(); + /* Clean up dead threads. */ + exorcise(); - /* Clean up dead threads. */ - exorcise(); - - /* Turn interrupts back on. */ - splx(spl); + /* Turn interrupts back on. */ + splx(spl); } /* @@ -735,35 +697,33 @@ thread_switch(threadstate_t newstate, struct wchan *wc, struct spinlock *lk) * thread_switch, the beginning part of this function must match the * tail of thread_switch. */ -void -thread_startup(void (*entrypoint)(void *data1, unsigned long data2), - void *data1, unsigned long data2) -{ - struct thread *cur; +void thread_startup(void (*entrypoint)(void *data1, unsigned long data2), + void *data1, unsigned long data2) { + struct thread *cur; - cur = curthread; + cur = curthread; - /* Clear the wait channel and set the thread state. */ - cur->t_wchan_name = NULL; - cur->t_state = S_RUN; + /* Clear the wait channel and set the thread state. */ + cur->t_wchan_name = NULL; + cur->t_state = S_RUN; - /* Release the runqueue lock acquired in thread_switch. */ - spinlock_release(&curcpu->c_runqueue_lock); + /* Release the runqueue lock acquired in thread_switch. */ + spinlock_release(&curcpu->c_runqueue_lock); - /* Activate our address space in the MMU. */ - as_activate(); + /* Activate our address space in the MMU. */ + as_activate(); - /* Clean up dead threads. */ - exorcise(); + /* Clean up dead threads. */ + exorcise(); - /* Enable interrupts. */ - spl0(); + /* Enable interrupts. */ + spl0(); - /* Call the function. */ - entrypoint(data1, data2); + /* Call the function. */ + entrypoint(data1, data2); - /* Done. */ - thread_exit(); + /* Done. */ + thread_exit(); } /* @@ -775,39 +735,33 @@ thread_startup(void (*entrypoint)(void *data1, unsigned long data2), * * Does not return. */ -void -thread_exit(void) -{ - struct thread *cur; +void thread_exit(void) { + struct thread *cur; - cur = curthread; + cur = curthread; - /* - * Detach from our process. You might need to move this action - * around, depending on how your wait/exit works. - */ - proc_remthread(cur); + /* + * Detach from our process. You might need to move this action + * around, depending on how your wait/exit works. + */ + proc_remthread(cur); - /* Make sure we *are* detached (move this only if you're sure!) */ - KASSERT(cur->t_proc == NULL); + /* Make sure we *are* detached (move this only if you're sure!) */ + KASSERT(cur->t_proc == NULL); - /* Check the stack guard band. */ - thread_checkstack(cur); + /* Check the stack guard band. */ + thread_checkstack(cur); - /* Interrupts off on this processor */ - splhigh(); - thread_switch(S_ZOMBIE, NULL, NULL); - panic("braaaaaaaiiiiiiiiiiinssssss\n"); + /* Interrupts off on this processor */ + splhigh(); + thread_switch(S_ZOMBIE, NULL, NULL); + panic("braaaaaaaiiiiiiiiiiinssssss\n"); } /* * Yield the cpu to another process, but stay runnable. */ -void -thread_yield(void) -{ - thread_switch(S_READY, NULL, NULL); -} +void thread_yield(void) { thread_switch(S_READY, NULL, NULL); } //////////////////////////////////////////////////////////// @@ -818,13 +772,11 @@ thread_yield(void) * the current CPU's run queue by job priority. */ -void -schedule(void) -{ - /* - * You can write this. If we do nothing, threads will run in - * round-robin fashion. - */ +void schedule(void) { + /* + * You can write this. If we do nothing, threads will run in + * round-robin fashion. + */ } /* @@ -844,109 +796,106 @@ schedule(void) * System/161 does not (yet) model such cache effects, we'll be very * aggressive. */ -void -thread_consider_migration(void) -{ - unsigned my_count, total_count, one_share, to_send; - unsigned i, numcpus; - struct cpu *c; - struct threadlist victims; - struct thread *t; +void thread_consider_migration(void) { + unsigned my_count, total_count, one_share, to_send; + unsigned i, numcpus; + struct cpu *c; + struct threadlist victims; + struct thread *t; - my_count = total_count = 0; - numcpus = cpuarray_num(&allcpus); - for (i=0; ic_runqueue_lock); - total_count += c->c_runqueue.tl_count; - if (c == curcpu->c_self) { - my_count = c->c_runqueue.tl_count; - } - spinlock_release(&c->c_runqueue_lock); - } + my_count = total_count = 0; + numcpus = cpuarray_num(&allcpus); + for (i = 0; i < numcpus; i++) { + c = cpuarray_get(&allcpus, i); + spinlock_acquire(&c->c_runqueue_lock); + total_count += c->c_runqueue.tl_count; + if (c == curcpu->c_self) { + my_count = c->c_runqueue.tl_count; + } + spinlock_release(&c->c_runqueue_lock); + } - one_share = DIVROUNDUP(total_count, numcpus); - if (my_count < one_share) { - return; - } + one_share = DIVROUNDUP(total_count, numcpus); + if (my_count < one_share) { + return; + } - to_send = my_count - one_share; - threadlist_init(&victims); - spinlock_acquire(&curcpu->c_runqueue_lock); - for (i=0; ic_runqueue); - threadlist_addhead(&victims, t); - } - spinlock_release(&curcpu->c_runqueue_lock); + to_send = my_count - one_share; + threadlist_init(&victims); + spinlock_acquire(&curcpu->c_runqueue_lock); + for (i = 0; i < to_send; i++) { + t = threadlist_remtail(&curcpu->c_runqueue); + threadlist_addhead(&victims, t); + } + spinlock_release(&curcpu->c_runqueue_lock); - for (i=0; i < numcpus && to_send > 0; i++) { - c = cpuarray_get(&allcpus, i); - if (c == curcpu->c_self) { - continue; - } - spinlock_acquire(&c->c_runqueue_lock); - while (c->c_runqueue.tl_count < one_share && to_send > 0) { - t = threadlist_remhead(&victims); - /* - * Ordinarily, curthread will not appear on - * the run queue. However, it can under the - * following circumstances: - * - it went to sleep; - * - the processor became idle, so it - * remained curthread; - * - it was reawakened, so it was put on the - * run queue; - * - and the processor hasn't fully unidled - * yet, so all these things are still true. - * - * If the timer interrupt happens at (almost) - * exactly the proper moment, we can come here - * while things are in this state and see - * curthread. However, *migrating* curthread - * can cause bad things to happen (Exercise: - * Why? And what?) so shuffle it to the end of - * the list and decrement to_send in order to - * skip it. Then it goes back on our own run - * queue below. - */ - if (t == curthread) { - threadlist_addtail(&victims, t); - to_send--; - continue; - } + for (i = 0; i < numcpus && to_send > 0; i++) { + c = cpuarray_get(&allcpus, i); + if (c == curcpu->c_self) { + continue; + } + spinlock_acquire(&c->c_runqueue_lock); + while (c->c_runqueue.tl_count < one_share && to_send > 0) { + t = threadlist_remhead(&victims); + /* + * Ordinarily, curthread will not appear on + * the run queue. However, it can under the + * following circumstances: + * - it went to sleep; + * - the processor became idle, so it + * remained curthread; + * - it was reawakened, so it was put on the + * run queue; + * - and the processor hasn't fully unidled + * yet, so all these things are still true. + * + * If the timer interrupt happens at (almost) + * exactly the proper moment, we can come here + * while things are in this state and see + * curthread. However, *migrating* curthread + * can cause bad things to happen (Exercise: + * Why? And what?) so shuffle it to the end of + * the list and decrement to_send in order to + * skip it. Then it goes back on our own run + * queue below. + */ + if (t == curthread) { + threadlist_addtail(&victims, t); + to_send--; + continue; + } - t->t_cpu = c; - threadlist_addtail(&c->c_runqueue, t); - DEBUG(DB_THREADS, - "Migrated thread %s: cpu %u -> %u", - t->t_name, curcpu->c_number, c->c_number); - to_send--; - if (c->c_isidle) { - /* - * Other processor is idle; send - * interrupt to make sure it unidles. - */ - ipi_send(c, IPI_UNIDLE); - } - } - spinlock_release(&c->c_runqueue_lock); - } + t->t_cpu = c; + threadlist_addtail(&c->c_runqueue, t); + DEBUG(DB_THREADS, "Migrated thread %s: cpu %u -> %u", t->t_name, + curcpu->c_number, c->c_number); + to_send--; + if (c->c_isidle) { + /* + * Other processor is idle; send + * interrupt to make sure it unidles. + */ + ipi_send(c, IPI_UNIDLE); + } + } + spinlock_release(&c->c_runqueue_lock); + } - /* - * Because the code above isn't atomic, the thread counts may have - * changed while we were working and we may end up with leftovers. - * Don't panic; just put them back on our own run queue. - */ - if (!threadlist_isempty(&victims)) { - spinlock_acquire(&curcpu->c_runqueue_lock); - while ((t = threadlist_remhead(&victims)) != NULL) { - threadlist_addtail(&curcpu->c_runqueue, t); - } - spinlock_release(&curcpu->c_runqueue_lock); - } + /* + * Because the code above isn't atomic, the thread counts may have + * changed while we were working and we may end up with leftovers. + * Don't panic; just put them back on our own run queue. + */ + if (!threadlist_isempty(&victims)) { + spinlock_acquire(&curcpu->c_runqueue_lock); + while ((t = threadlist_remhead(&victims)) != NULL) { + threadlist_addtail(&curcpu->c_runqueue, t); + } + spinlock_release(&curcpu->c_runqueue_lock); + } - KASSERT(threadlist_isempty(&victims)); - threadlist_cleanup(&victims); + KASSERT(threadlist_isempty(&victims)); + threadlist_cleanup(&victims); } //////////////////////////////////////////////////////////// @@ -963,30 +912,26 @@ thread_consider_migration(void) * arrangements should be made to free it after the wait channel is * destroyed. */ -struct wchan * -wchan_create(const char *name) -{ - struct wchan *wc; +struct wchan *wchan_create(const char *name) { + struct wchan *wc; - wc = kmalloc(sizeof(*wc)); - if (wc == NULL) { - return NULL; - } - threadlist_init(&wc->wc_threads); - wc->wc_name = name; + wc = kmalloc(sizeof(*wc)); + if (wc == NULL) { + return NULL; + } + threadlist_init(&wc->wc_threads); + wc->wc_name = name; - return wc; + return wc; } /* * Destroy a wait channel. Must be empty and unlocked. * (The corresponding cleanup functions require this.) */ -void -wchan_destroy(struct wchan *wc) -{ - threadlist_cleanup(&wc->wc_threads); - kfree(wc); +void wchan_destroy(struct wchan *wc) { + threadlist_cleanup(&wc->wc_threads); + kfree(wc); } /* @@ -996,97 +941,89 @@ wchan_destroy(struct wchan *wc) * be locked. The call to thread_switch unlocks it; we relock it * before returning. */ -void -wchan_sleep(struct wchan *wc, struct spinlock *lk) -{ - /* may not sleep in an interrupt handler */ - KASSERT(!curthread->t_in_interrupt); +void wchan_sleep(struct wchan *wc, struct spinlock *lk) { + /* may not sleep in an interrupt handler */ + KASSERT(!curthread->t_in_interrupt); - /* must hold the spinlock */ - KASSERT(spinlock_do_i_hold(lk)); + /* must hold the spinlock */ + KASSERT(spinlock_do_i_hold(lk)); - /* must not hold other spinlocks */ - KASSERT(curcpu->c_spinlocks == 1); + /* must not hold other spinlocks */ + KASSERT(curcpu->c_spinlocks == 1); - thread_switch(S_SLEEP, wc, lk); - spinlock_acquire(lk); + thread_switch(S_SLEEP, wc, lk); + spinlock_acquire(lk); } /* * Wake up one thread sleeping on a wait channel. */ -void -wchan_wakeone(struct wchan *wc, struct spinlock *lk) -{ - struct thread *target; +void wchan_wakeone(struct wchan *wc, struct spinlock *lk) { + struct thread *target; - KASSERT(spinlock_do_i_hold(lk)); + KASSERT(spinlock_do_i_hold(lk)); - /* Grab a thread from the channel */ - target = threadlist_remhead(&wc->wc_threads); + /* Grab a thread from the channel */ + target = threadlist_remhead(&wc->wc_threads); - if (target == NULL) { - /* Nobody was sleeping. */ - return; - } + if (target == NULL) { + /* Nobody was sleeping. */ + return; + } - /* - * Note that thread_make_runnable acquires a runqueue lock - * while we're holding LK. This is ok; all spinlocks - * associated with wchans must come before the runqueue locks, - * as we also bridge from the wchan lock to the runqueue lock - * in thread_switch. - */ + /* + * Note that thread_make_runnable acquires a runqueue lock + * while we're holding LK. This is ok; all spinlocks + * associated with wchans must come before the runqueue locks, + * as we also bridge from the wchan lock to the runqueue lock + * in thread_switch. + */ - thread_make_runnable(target, false); + thread_make_runnable(target, false); } /* * Wake up all threads sleeping on a wait channel. */ -void -wchan_wakeall(struct wchan *wc, struct spinlock *lk) -{ - struct thread *target; - struct threadlist list; +void wchan_wakeall(struct wchan *wc, struct spinlock *lk) { + struct thread *target; + struct threadlist list; - KASSERT(spinlock_do_i_hold(lk)); + KASSERT(spinlock_do_i_hold(lk)); - threadlist_init(&list); + threadlist_init(&list); - /* - * Grab all the threads from the channel, moving them to a - * private list. - */ - while ((target = threadlist_remhead(&wc->wc_threads)) != NULL) { - threadlist_addtail(&list, target); - } + /* + * Grab all the threads from the channel, moving them to a + * private list. + */ + while ((target = threadlist_remhead(&wc->wc_threads)) != NULL) { + threadlist_addtail(&list, target); + } - /* - * We could conceivably sort by cpu first to cause fewer lock - * ops and fewer IPIs, but for now at least don't bother. Just - * make each thread runnable. - */ - while ((target = threadlist_remhead(&list)) != NULL) { - thread_make_runnable(target, false); - } + /* + * We could conceivably sort by cpu first to cause fewer lock + * ops and fewer IPIs, but for now at least don't bother. Just + * make each thread runnable. + */ + while ((target = threadlist_remhead(&list)) != NULL) { + thread_make_runnable(target, false); + } - threadlist_cleanup(&list); + threadlist_cleanup(&list); } /* * Return nonzero if there are no threads sleeping on the channel. * This is meant to be used only for diagnostic purposes. */ -bool -wchan_isempty(struct wchan *wc, struct spinlock *lk) -{ - bool ret; +bool wchan_isempty(struct wchan *wc, struct spinlock *lk) { + bool ret; - KASSERT(spinlock_do_i_hold(lk)); - ret = threadlist_isempty(&wc->wc_threads); + KASSERT(spinlock_do_i_hold(lk)); + ret = threadlist_isempty(&wc->wc_threads); - return ret; + return ret; } //////////////////////////////////////////////////////////// @@ -1098,115 +1035,105 @@ wchan_isempty(struct wchan *wc, struct spinlock *lk) /* * Send an IPI (inter-processor interrupt) to the specified CPU. */ -void -ipi_send(struct cpu *target, int code) -{ - KASSERT(code >= 0 && code < 32); +void ipi_send(struct cpu *target, int code) { + KASSERT(code >= 0 && code < 32); - spinlock_acquire(&target->c_ipi_lock); - target->c_ipi_pending |= (uint32_t)1 << code; - mainbus_send_ipi(target); - spinlock_release(&target->c_ipi_lock); + spinlock_acquire(&target->c_ipi_lock); + target->c_ipi_pending |= (uint32_t)1 << code; + mainbus_send_ipi(target); + spinlock_release(&target->c_ipi_lock); } /* * Send an IPI to all CPUs. */ -void -ipi_broadcast(int code) -{ - unsigned i; - struct cpu *c; +void ipi_broadcast(int code) { + unsigned i; + struct cpu *c; - for (i=0; i < cpuarray_num(&allcpus); i++) { - c = cpuarray_get(&allcpus, i); - if (c != curcpu->c_self) { - ipi_send(c, code); - } - } + for (i = 0; i < cpuarray_num(&allcpus); i++) { + c = cpuarray_get(&allcpus, i); + if (c != curcpu->c_self) { + ipi_send(c, code); + } + } } /* * Send a TLB shootdown IPI to the specified CPU. */ -void -ipi_tlbshootdown(struct cpu *target, const struct tlbshootdown *mapping) -{ - unsigned n; +void ipi_tlbshootdown(struct cpu *target, const struct tlbshootdown *mapping) { + unsigned n; - spinlock_acquire(&target->c_ipi_lock); + spinlock_acquire(&target->c_ipi_lock); - n = target->c_numshootdown; - if (n == TLBSHOOTDOWN_MAX) { - /* - * If you have problems with this panic going off, - * consider: (1) increasing the maximum, (2) putting - * logic here to sleep until space appears (may - * interact awkwardly with VM system locking), (3) - * putting logic here to coalesce requests together, - * and/or (4) improving VM system state tracking to - * reduce the number of unnecessary shootdowns. - */ - panic("ipi_tlbshootdown: Too many shootdowns queued\n"); - } - else { - target->c_shootdown[n] = *mapping; - target->c_numshootdown = n+1; - } + n = target->c_numshootdown; + if (n == TLBSHOOTDOWN_MAX) { + /* + * If you have problems with this panic going off, + * consider: (1) increasing the maximum, (2) putting + * logic here to sleep until space appears (may + * interact awkwardly with VM system locking), (3) + * putting logic here to coalesce requests together, + * and/or (4) improving VM system state tracking to + * reduce the number of unnecessary shootdowns. + */ + panic("ipi_tlbshootdown: Too many shootdowns queued\n"); + } else { + target->c_shootdown[n] = *mapping; + target->c_numshootdown = n + 1; + } - target->c_ipi_pending |= (uint32_t)1 << IPI_TLBSHOOTDOWN; - mainbus_send_ipi(target); + target->c_ipi_pending |= (uint32_t)1 << IPI_TLBSHOOTDOWN; + mainbus_send_ipi(target); - spinlock_release(&target->c_ipi_lock); + spinlock_release(&target->c_ipi_lock); } /* * Handle an incoming interprocessor interrupt. */ -void -interprocessor_interrupt(void) -{ - uint32_t bits; - unsigned i; +void interprocessor_interrupt(void) { + uint32_t bits; + unsigned i; - spinlock_acquire(&curcpu->c_ipi_lock); - bits = curcpu->c_ipi_pending; + spinlock_acquire(&curcpu->c_ipi_lock); + bits = curcpu->c_ipi_pending; - if (bits & (1U << IPI_PANIC)) { - /* panic on another cpu - just stop dead */ - spinlock_release(&curcpu->c_ipi_lock); - cpu_halt(); - } - if (bits & (1U << IPI_OFFLINE)) { - /* offline request */ - spinlock_release(&curcpu->c_ipi_lock); - spinlock_acquire(&curcpu->c_runqueue_lock); - if (!curcpu->c_isidle) { - kprintf("cpu%d: offline: warning: not idle\n", - curcpu->c_number); - } - spinlock_release(&curcpu->c_runqueue_lock); - kprintf("cpu%d: offline.\n", curcpu->c_number); - cpu_halt(); - } - if (bits & (1U << IPI_UNIDLE)) { - /* - * The cpu has already unidled itself to take the - * interrupt; don't need to do anything else. - */ - } - if (bits & (1U << IPI_TLBSHOOTDOWN)) { - /* - * Note: depending on your VM system locking you might - * need to release the ipi lock while calling - * vm_tlbshootdown. - */ - for (i=0; ic_numshootdown; i++) { - vm_tlbshootdown(&curcpu->c_shootdown[i]); - } - curcpu->c_numshootdown = 0; - } + if (bits & (1U << IPI_PANIC)) { + /* panic on another cpu - just stop dead */ + spinlock_release(&curcpu->c_ipi_lock); + cpu_halt(); + } + if (bits & (1U << IPI_OFFLINE)) { + /* offline request */ + spinlock_release(&curcpu->c_ipi_lock); + spinlock_acquire(&curcpu->c_runqueue_lock); + if (!curcpu->c_isidle) { + kprintf("cpu%d: offline: warning: not idle\n", curcpu->c_number); + } + spinlock_release(&curcpu->c_runqueue_lock); + kprintf("cpu%d: offline.\n", curcpu->c_number); + cpu_halt(); + } + if (bits & (1U << IPI_UNIDLE)) { + /* + * The cpu has already unidled itself to take the + * interrupt; don't need to do anything else. + */ + } + if (bits & (1U << IPI_TLBSHOOTDOWN)) { + /* + * Note: depending on your VM system locking you might + * need to release the ipi lock while calling + * vm_tlbshootdown. + */ + for (i = 0; i < curcpu->c_numshootdown; i++) { + vm_tlbshootdown(&curcpu->c_shootdown[i]); + } + curcpu->c_numshootdown = 0; + } - curcpu->c_ipi_pending = 0; - spinlock_release(&curcpu->c_ipi_lock); + curcpu->c_ipi_pending = 0; + spinlock_release(&curcpu->c_ipi_lock); } diff --git a/kern/thread/threadlist.c b/kern/thread/threadlist.c index 7ae0595..3d5e3f5 100644 --- a/kern/thread/threadlist.c +++ b/kern/thread/threadlist.c @@ -36,64 +36,54 @@ #include #include -void -threadlistnode_init(struct threadlistnode *tln, struct thread *t) -{ - DEBUGASSERT(tln != NULL); - KASSERT(t != NULL); +void threadlistnode_init(struct threadlistnode *tln, struct thread *t) { + DEBUGASSERT(tln != NULL); + KASSERT(t != NULL); - tln->tln_next = NULL; - tln->tln_prev = NULL; - tln->tln_self = t; + tln->tln_next = NULL; + tln->tln_prev = NULL; + tln->tln_self = t; } -void -threadlistnode_cleanup(struct threadlistnode *tln) -{ - DEBUGASSERT(tln != NULL); +void threadlistnode_cleanup(struct threadlistnode *tln) { + DEBUGASSERT(tln != NULL); - KASSERT(tln->tln_next == NULL); - KASSERT(tln->tln_prev == NULL); - KASSERT(tln->tln_self != NULL); + KASSERT(tln->tln_next == NULL); + KASSERT(tln->tln_prev == NULL); + KASSERT(tln->tln_self != NULL); } -void -threadlist_init(struct threadlist *tl) -{ - DEBUGASSERT(tl != NULL); +void threadlist_init(struct threadlist *tl) { + DEBUGASSERT(tl != NULL); - tl->tl_head.tln_next = &tl->tl_tail; - tl->tl_head.tln_prev = NULL; - tl->tl_tail.tln_next = NULL; - tl->tl_tail.tln_prev = &tl->tl_head; - tl->tl_head.tln_self = NULL; - tl->tl_tail.tln_self = NULL; - tl->tl_count = 0; + tl->tl_head.tln_next = &tl->tl_tail; + tl->tl_head.tln_prev = NULL; + tl->tl_tail.tln_next = NULL; + tl->tl_tail.tln_prev = &tl->tl_head; + tl->tl_head.tln_self = NULL; + tl->tl_tail.tln_self = NULL; + tl->tl_count = 0; } -void -threadlist_cleanup(struct threadlist *tl) -{ - DEBUGASSERT(tl != NULL); - DEBUGASSERT(tl->tl_head.tln_next == &tl->tl_tail); - DEBUGASSERT(tl->tl_head.tln_prev == NULL); - DEBUGASSERT(tl->tl_tail.tln_next == NULL); - DEBUGASSERT(tl->tl_tail.tln_prev == &tl->tl_head); - DEBUGASSERT(tl->tl_head.tln_self == NULL); - DEBUGASSERT(tl->tl_tail.tln_self == NULL); +void threadlist_cleanup(struct threadlist *tl) { + DEBUGASSERT(tl != NULL); + DEBUGASSERT(tl->tl_head.tln_next == &tl->tl_tail); + DEBUGASSERT(tl->tl_head.tln_prev == NULL); + DEBUGASSERT(tl->tl_tail.tln_next == NULL); + DEBUGASSERT(tl->tl_tail.tln_prev == &tl->tl_head); + DEBUGASSERT(tl->tl_head.tln_self == NULL); + DEBUGASSERT(tl->tl_tail.tln_self == NULL); - KASSERT(threadlist_isempty(tl)); - KASSERT(tl->tl_count == 0); + KASSERT(threadlist_isempty(tl)); + KASSERT(tl->tl_count == 0); - /* nothing (else) to do */ + /* nothing (else) to do */ } -bool -threadlist_isempty(struct threadlist *tl) -{ - DEBUGASSERT(tl != NULL); +bool threadlist_isempty(struct threadlist *tl) { + DEBUGASSERT(tl != NULL); - return (tl->tl_count == 0); + return (tl->tl_count == 0); } //////////////////////////////////////////////////////////// @@ -102,139 +92,118 @@ threadlist_isempty(struct threadlist *tl) /* * Do insertion. Doesn't update tl_count. */ -static -void -threadlist_insertafternode(struct threadlistnode *onlist, struct thread *t) -{ - struct threadlistnode *addee; +static void threadlist_insertafternode(struct threadlistnode *onlist, + struct thread *t) { + struct threadlistnode *addee; - addee = &t->t_listnode; + addee = &t->t_listnode; - DEBUGASSERT(addee->tln_prev == NULL); - DEBUGASSERT(addee->tln_next == NULL); + DEBUGASSERT(addee->tln_prev == NULL); + DEBUGASSERT(addee->tln_next == NULL); - addee->tln_prev = onlist; - addee->tln_next = onlist->tln_next; - addee->tln_prev->tln_next = addee; - addee->tln_next->tln_prev = addee; + addee->tln_prev = onlist; + addee->tln_next = onlist->tln_next; + addee->tln_prev->tln_next = addee; + addee->tln_next->tln_prev = addee; } /* * Do insertion. Doesn't update tl_count. */ -static -void -threadlist_insertbeforenode(struct thread *t, struct threadlistnode *onlist) -{ - struct threadlistnode *addee; +static void threadlist_insertbeforenode(struct thread *t, + struct threadlistnode *onlist) { + struct threadlistnode *addee; - addee = &t->t_listnode; + addee = &t->t_listnode; - DEBUGASSERT(addee->tln_prev == NULL); - DEBUGASSERT(addee->tln_next == NULL); + DEBUGASSERT(addee->tln_prev == NULL); + DEBUGASSERT(addee->tln_next == NULL); - addee->tln_prev = onlist->tln_prev; - addee->tln_next = onlist; - addee->tln_prev->tln_next = addee; - addee->tln_next->tln_prev = addee; + addee->tln_prev = onlist->tln_prev; + addee->tln_next = onlist; + addee->tln_prev->tln_next = addee; + addee->tln_next->tln_prev = addee; } /* * Do removal. Doesn't update tl_count. */ -static -void -threadlist_removenode(struct threadlistnode *tln) -{ - DEBUGASSERT(tln != NULL); - DEBUGASSERT(tln->tln_prev != NULL); - DEBUGASSERT(tln->tln_next != NULL); +static void threadlist_removenode(struct threadlistnode *tln) { + DEBUGASSERT(tln != NULL); + DEBUGASSERT(tln->tln_prev != NULL); + DEBUGASSERT(tln->tln_next != NULL); - tln->tln_prev->tln_next = tln->tln_next; - tln->tln_next->tln_prev = tln->tln_prev; - tln->tln_prev = NULL; - tln->tln_next = NULL; + tln->tln_prev->tln_next = tln->tln_next; + tln->tln_next->tln_prev = tln->tln_prev; + tln->tln_prev = NULL; + tln->tln_next = NULL; } //////////////////////////////////////////////////////////// // public -void -threadlist_addhead(struct threadlist *tl, struct thread *t) -{ - DEBUGASSERT(tl != NULL); - DEBUGASSERT(t != NULL); +void threadlist_addhead(struct threadlist *tl, struct thread *t) { + DEBUGASSERT(tl != NULL); + DEBUGASSERT(t != NULL); - threadlist_insertafternode(&tl->tl_head, t); - tl->tl_count++; + threadlist_insertafternode(&tl->tl_head, t); + tl->tl_count++; } -void -threadlist_addtail(struct threadlist *tl, struct thread *t) -{ - DEBUGASSERT(tl != NULL); - DEBUGASSERT(t != NULL); +void threadlist_addtail(struct threadlist *tl, struct thread *t) { + DEBUGASSERT(tl != NULL); + DEBUGASSERT(t != NULL); - threadlist_insertbeforenode(t, &tl->tl_tail); - tl->tl_count++; + threadlist_insertbeforenode(t, &tl->tl_tail); + tl->tl_count++; } -struct thread * -threadlist_remhead(struct threadlist *tl) -{ - struct threadlistnode *tln; +struct thread *threadlist_remhead(struct threadlist *tl) { + struct threadlistnode *tln; - DEBUGASSERT(tl != NULL); + DEBUGASSERT(tl != NULL); - tln = tl->tl_head.tln_next; - if (tln->tln_next == NULL) { - /* list was empty */ - return NULL; - } - threadlist_removenode(tln); - DEBUGASSERT(tl->tl_count > 0); - tl->tl_count--; - return tln->tln_self; + tln = tl->tl_head.tln_next; + if (tln->tln_next == NULL) { + /* list was empty */ + return NULL; + } + threadlist_removenode(tln); + DEBUGASSERT(tl->tl_count > 0); + tl->tl_count--; + return tln->tln_self; } -struct thread * -threadlist_remtail(struct threadlist *tl) -{ - struct threadlistnode *tln; +struct thread *threadlist_remtail(struct threadlist *tl) { + struct threadlistnode *tln; - DEBUGASSERT(tl != NULL); + DEBUGASSERT(tl != NULL); - tln = tl->tl_tail.tln_prev; - if (tln->tln_prev == NULL) { - /* list was empty */ - return NULL; - } - threadlist_removenode(tln); - DEBUGASSERT(tl->tl_count > 0); - tl->tl_count--; - return tln->tln_self; + tln = tl->tl_tail.tln_prev; + if (tln->tln_prev == NULL) { + /* list was empty */ + return NULL; + } + threadlist_removenode(tln); + DEBUGASSERT(tl->tl_count > 0); + tl->tl_count--; + return tln->tln_self; } -void -threadlist_insertafter(struct threadlist *tl, - struct thread *onlist, struct thread *addee) -{ - threadlist_insertafternode(&onlist->t_listnode, addee); - tl->tl_count++; +void threadlist_insertafter(struct threadlist *tl, struct thread *onlist, + struct thread *addee) { + threadlist_insertafternode(&onlist->t_listnode, addee); + tl->tl_count++; } -void -threadlist_insertbefore(struct threadlist *tl, - struct thread *addee, struct thread *onlist) -{ - threadlist_insertbeforenode(addee, &onlist->t_listnode); - tl->tl_count++; +void threadlist_insertbefore(struct threadlist *tl, struct thread *addee, + struct thread *onlist) { + threadlist_insertbeforenode(addee, &onlist->t_listnode); + tl->tl_count++; } -void -threadlist_remove(struct threadlist *tl, struct thread *t) -{ - threadlist_removenode(&t->t_listnode); - DEBUGASSERT(tl->tl_count > 0); - tl->tl_count--; +void threadlist_remove(struct threadlist *tl, struct thread *t) { + threadlist_removenode(&t->t_listnode); + DEBUGASSERT(tl->tl_count > 0); + tl->tl_count--; } diff --git a/kern/vfs/device.c b/kern/vfs/device.c index a591749..5e67f0b 100644 --- a/kern/vfs/device.c +++ b/kern/vfs/device.c @@ -48,30 +48,24 @@ * * We reject O_APPEND. */ -static -int -dev_eachopen(struct vnode *v, int flags) -{ - struct device *d = v->vn_data; +static int dev_eachopen(struct vnode *v, int flags) { + struct device *d = v->vn_data; - if (flags & (O_CREAT | O_TRUNC | O_EXCL | O_APPEND)) { - return EINVAL; - } + if (flags & (O_CREAT | O_TRUNC | O_EXCL | O_APPEND)) { + return EINVAL; + } - return DEVOP_EACHOPEN(d, flags); + return DEVOP_EACHOPEN(d, flags); } /* * Called when the vnode refcount reaches zero. * Do nothing; devices are permanent. */ -static -int -dev_reclaim(struct vnode *v) -{ - (void)v; - /* nothing - device continues to exist even when not in use */ - return 0; +static int dev_reclaim(struct vnode *v) { + (void)v; + /* nothing - device continues to exist even when not in use */ + return 0; } /* @@ -81,73 +75,60 @@ dev_reclaim(struct vnode *v) * For character devices, we should prohibit seeking entirely, but * for the moment we need to accept any position. (XXX) */ -static -int -dev_tryseek(struct device *d, off_t pos) -{ - if (d->d_blocks > 0) { - if ((pos % d->d_blocksize)!=0) { - /* not block-aligned */ - return EINVAL; - } - if (pos / d->d_blocksize >= d->d_blocks) { - /* off the end */ - return EINVAL; - } - } - else { - //return ESPIPE; - } - return 0; +static int dev_tryseek(struct device *d, off_t pos) { + if (d->d_blocks > 0) { + if ((pos % d->d_blocksize) != 0) { + /* not block-aligned */ + return EINVAL; + } + if (pos / d->d_blocksize >= d->d_blocks) { + /* off the end */ + return EINVAL; + } + } else { + // return ESPIPE; + } + return 0; } /* * Called for read. Hand off to DEVOP_IO. */ -static -int -dev_read(struct vnode *v, struct uio *uio) -{ - struct device *d = v->vn_data; - int result; +static int dev_read(struct vnode *v, struct uio *uio) { + struct device *d = v->vn_data; + int result; - result = dev_tryseek(d, uio->uio_offset); - if (result) { - return result; - } + result = dev_tryseek(d, uio->uio_offset); + if (result) { + return result; + } - KASSERT(uio->uio_rw == UIO_READ); - return DEVOP_IO(d, uio); + KASSERT(uio->uio_rw == UIO_READ); + return DEVOP_IO(d, uio); } /* * Called for write. Hand off to DEVOP_IO. */ -static -int -dev_write(struct vnode *v, struct uio *uio) -{ - struct device *d = v->vn_data; - int result; +static int dev_write(struct vnode *v, struct uio *uio) { + struct device *d = v->vn_data; + int result; - result = dev_tryseek(d, uio->uio_offset); - if (result) { - return result; - } + result = dev_tryseek(d, uio->uio_offset); + if (result) { + return result; + } - KASSERT(uio->uio_rw == UIO_WRITE); - return DEVOP_IO(d, uio); + KASSERT(uio->uio_rw == UIO_WRITE); + return DEVOP_IO(d, uio); } /* * Called for ioctl(). Just pass through. */ -static -int -dev_ioctl(struct vnode *v, int op, userptr_t data) -{ - struct device *d = v->vn_data; - return DEVOP_IOCTL(d, op, data); +static int dev_ioctl(struct vnode *v, int op, userptr_t data) { + struct device *d = v->vn_data; + return DEVOP_IOCTL(d, op, data); } /* @@ -155,40 +136,36 @@ dev_ioctl(struct vnode *v, int op, userptr_t data) * Set the type and the size (block devices only). * The link count for a device is always 1. */ -static -int -dev_stat(struct vnode *v, struct stat *statbuf) -{ - struct device *d = v->vn_data; - int result; +static int dev_stat(struct vnode *v, struct stat *statbuf) { + struct device *d = v->vn_data; + int result; - bzero(statbuf, sizeof(struct stat)); + bzero(statbuf, sizeof(struct stat)); - if (d->d_blocks > 0) { - statbuf->st_size = d->d_blocks * d->d_blocksize; - statbuf->st_blksize = d->d_blocksize; - } - else { - statbuf->st_size = 0; - } + if (d->d_blocks > 0) { + statbuf->st_size = d->d_blocks * d->d_blocksize; + statbuf->st_blksize = d->d_blocksize; + } else { + statbuf->st_size = 0; + } - result = VOP_GETTYPE(v, &statbuf->st_mode); - if (result) { - return result; - } - /* Make up some plausible default permissions. */ - statbuf->st_mode |= 0600; + result = VOP_GETTYPE(v, &statbuf->st_mode); + if (result) { + return result; + } + /* Make up some plausible default permissions. */ + statbuf->st_mode |= 0600; - statbuf->st_nlink = 1; - statbuf->st_blocks = d->d_blocks; + statbuf->st_nlink = 1; + statbuf->st_blocks = d->d_blocks; - /* The device number this device sits on (in OS/161, it doesn't) */ - statbuf->st_dev = 0; + /* The device number this device sits on (in OS/161, it doesn't) */ + statbuf->st_dev = 0; - /* The device number this device *is* */ - statbuf->st_rdev = d->d_devnumber; + /* The device number this device *is* */ + statbuf->st_rdev = d->d_devnumber; - return 0; + return 0; } /* @@ -196,75 +173,59 @@ dev_stat(struct vnode *v, struct stat *statbuf) * length. A device that generates data in a stream is a "character * device". */ -static -int -dev_gettype(struct vnode *v, mode_t *ret) -{ - struct device *d = v->vn_data; - if (d->d_blocks > 0) { - *ret = S_IFBLK; - } - else { - *ret = S_IFCHR; - } - return 0; +static int dev_gettype(struct vnode *v, mode_t *ret) { + struct device *d = v->vn_data; + if (d->d_blocks > 0) { + *ret = S_IFBLK; + } else { + *ret = S_IFCHR; + } + return 0; } /* * Check if seeking is allowed. */ -static -bool -dev_isseekable(struct vnode *v) -{ - struct device *d = v->vn_data; +static bool dev_isseekable(struct vnode *v) { + struct device *d = v->vn_data; - if (d->d_blocks == 0) { - return false; - } - return true; + if (d->d_blocks == 0) { + return false; + } + return true; } /* * For fsync() - meaningless, do nothing. */ -static -int -null_fsync(struct vnode *v) -{ - (void)v; - return 0; +static int null_fsync(struct vnode *v) { + (void)v; + return 0; } /* * For mmap. If you want this to do anything, you have to write it * yourself. Some devices may not make sense to map. Others do. */ -static -int -dev_mmap(struct vnode *v /* add stuff as needed */) -{ - (void)v; - return ENOSYS; +static int dev_mmap(struct vnode *v /* add stuff as needed */) { + (void)v; + return ENOSYS; } /* * For ftruncate(). */ -static -int -dev_truncate(struct vnode *v, off_t len) -{ - struct device *d = v->vn_data; +static int dev_truncate(struct vnode *v, off_t len) { + struct device *d = v->vn_data; - /* - * Allow truncating to the object's own size, if it has one. - */ - if (d->d_blocks > 0 && (off_t)(d->d_blocks*d->d_blocksize) == len) { - return 0; - } + /* + * Allow truncating to the object's own size, if it has one. + */ + if (d->d_blocks > 0 && (off_t)(d->d_blocks * d->d_blocksize) == len) { + return 0; + } - return EINVAL; + return EINVAL; } /* @@ -273,20 +234,17 @@ dev_truncate(struct vnode *v, off_t len) * This should never be reached, as it's not possible to chdir to a * device vnode. */ -static -int -dev_namefile(struct vnode *v, struct uio *uio) -{ - /* - * The name of a device is always just "device:". The VFS - * layer puts in the device name for us, so we don't need to - * do anything further. - */ +static int dev_namefile(struct vnode *v, struct uio *uio) { + /* + * The name of a device is always just "device:". The VFS + * layer puts in the device name for us, so we don't need to + * do anything further. + */ - (void)v; - (void)uio; + (void)v; + (void)uio; - return 0; + return 0; } /* @@ -301,76 +259,71 @@ dev_namefile(struct vnode *v, struct uio *uio) * * However, we have no support for this in the base system. */ -static -int -dev_lookup(struct vnode *dir, - char *pathname, struct vnode **result) -{ - /* - * If the path was "device:", we get "". For that, return self. - * Anything else is an error. - * Increment the ref count of the vnode before returning it. - */ - if (strlen(pathname)>0) { - return ENOENT; - } - VOP_INCREF(dir); - *result = dir; - return 0; +static int dev_lookup(struct vnode *dir, char *pathname, + struct vnode **result) { + /* + * If the path was "device:", we get "". For that, return self. + * Anything else is an error. + * Increment the ref count of the vnode before returning it. + */ + if (strlen(pathname) > 0) { + return ENOENT; + } + VOP_INCREF(dir); + *result = dir; + return 0; } /* * Function table for device vnodes. */ static const struct vnode_ops dev_vnode_ops = { - .vop_magic = VOP_MAGIC, + .vop_magic = VOP_MAGIC, - .vop_eachopen = dev_eachopen, - .vop_reclaim = dev_reclaim, - .vop_read = dev_read, - .vop_readlink = vopfail_uio_inval, - .vop_getdirentry = vopfail_uio_notdir, - .vop_write = dev_write, - .vop_ioctl = dev_ioctl, - .vop_stat = dev_stat, - .vop_gettype = dev_gettype, - .vop_isseekable = dev_isseekable, - .vop_fsync = null_fsync, - .vop_mmap = dev_mmap, - .vop_truncate = dev_truncate, - .vop_namefile = dev_namefile, - .vop_creat = vopfail_creat_notdir, - .vop_symlink = vopfail_symlink_notdir, - .vop_mkdir = vopfail_mkdir_notdir, - .vop_link = vopfail_link_notdir, - .vop_remove = vopfail_string_notdir, - .vop_rmdir = vopfail_string_notdir, - .vop_rename = vopfail_rename_notdir, - .vop_lookup = dev_lookup, - .vop_lookparent = vopfail_lookparent_notdir, + .vop_eachopen = dev_eachopen, + .vop_reclaim = dev_reclaim, + .vop_read = dev_read, + .vop_readlink = vopfail_uio_inval, + .vop_getdirentry = vopfail_uio_notdir, + .vop_write = dev_write, + .vop_ioctl = dev_ioctl, + .vop_stat = dev_stat, + .vop_gettype = dev_gettype, + .vop_isseekable = dev_isseekable, + .vop_fsync = null_fsync, + .vop_mmap = dev_mmap, + .vop_truncate = dev_truncate, + .vop_namefile = dev_namefile, + .vop_creat = vopfail_creat_notdir, + .vop_symlink = vopfail_symlink_notdir, + .vop_mkdir = vopfail_mkdir_notdir, + .vop_link = vopfail_link_notdir, + .vop_remove = vopfail_string_notdir, + .vop_rmdir = vopfail_string_notdir, + .vop_rename = vopfail_rename_notdir, + .vop_lookup = dev_lookup, + .vop_lookparent = vopfail_lookparent_notdir, }; /* * Function to create a vnode for a VFS device. */ -struct vnode * -dev_create_vnode(struct device *dev) -{ - int result; - struct vnode *v; +struct vnode *dev_create_vnode(struct device *dev) { + int result; + struct vnode *v; - v = kmalloc(sizeof(struct vnode)); - if (v==NULL) { - return NULL; - } + v = kmalloc(sizeof(struct vnode)); + if (v == NULL) { + return NULL; + } - result = vnode_init(v, &dev_vnode_ops, NULL, dev); - if (result != 0) { - panic("While creating vnode for device: vnode_init: %s\n", - strerror(result)); - } + result = vnode_init(v, &dev_vnode_ops, NULL, dev); + if (result != 0) { + panic("While creating vnode for device: vnode_init: %s\n", + strerror(result)); + } - return v; + return v; } /* @@ -379,10 +332,8 @@ dev_create_vnode(struct device *dev) * Note: this is only used in failure paths; we don't support * hotpluggable devices, so once a device is attached it's permanent. */ -void -dev_uncreate_vnode(struct vnode *vn) -{ - KASSERT(vn->vn_ops == &dev_vnode_ops); - vnode_cleanup(vn); - kfree(vn); +void dev_uncreate_vnode(struct vnode *vn) { + KASSERT(vn->vn_ops == &dev_vnode_ops); + vnode_cleanup(vn); + kfree(vn); } diff --git a/kern/vfs/devnull.c b/kern/vfs/devnull.c index 35f3e2e..7a9213a 100644 --- a/kern/vfs/devnull.c +++ b/kern/vfs/devnull.c @@ -39,86 +39,75 @@ #include /* For open() */ -static -int -nullopen(struct device *dev, int openflags) -{ - (void)dev; - (void)openflags; +static int nullopen(struct device *dev, int openflags) { + (void)dev; + (void)openflags; - return 0; + return 0; } /* For d_io() */ -static -int -nullio(struct device *dev, struct uio *uio) -{ - /* - * On write, discard everything without looking at it. - * (Notice that you can write to the null device from invalid - * buffer pointers and it will still succeed. This behavior is - * traditional.) - * - * On read, do nothing, generating an immediate EOF. - */ +static int nullio(struct device *dev, struct uio *uio) { + /* + * On write, discard everything without looking at it. + * (Notice that you can write to the null device from invalid + * buffer pointers and it will still succeed. This behavior is + * traditional.) + * + * On read, do nothing, generating an immediate EOF. + */ - (void)dev; // unused + (void)dev; // unused - if (uio->uio_rw == UIO_WRITE) { - uio->uio_resid = 0; - } + if (uio->uio_rw == UIO_WRITE) { + uio->uio_resid = 0; + } - return 0; + return 0; } /* For ioctl() */ -static -int -nullioctl(struct device *dev, int op, userptr_t data) -{ - /* - * No ioctls. - */ +static int nullioctl(struct device *dev, int op, userptr_t data) { + /* + * No ioctls. + */ - (void)dev; - (void)op; - (void)data; + (void)dev; + (void)op; + (void)data; - return EINVAL; + return EINVAL; } static const struct device_ops null_devops = { - .devop_eachopen = nullopen, - .devop_io = nullio, - .devop_ioctl = nullioctl, + .devop_eachopen = nullopen, + .devop_io = nullio, + .devop_ioctl = nullioctl, }; /* * Function to create and attach null: */ -void -devnull_create(void) -{ - int result; - struct device *dev; +void devnull_create(void) { + int result; + struct device *dev; - dev = kmalloc(sizeof(*dev)); - if (dev==NULL) { - panic("Could not add null device: out of memory\n"); - } + dev = kmalloc(sizeof(*dev)); + if (dev == NULL) { + panic("Could not add null device: out of memory\n"); + } - dev->d_ops = &null_devops; + dev->d_ops = &null_devops; - dev->d_blocks = 0; - dev->d_blocksize = 1; + dev->d_blocks = 0; + dev->d_blocksize = 1; - dev->d_devnumber = 0; /* assigned by vfs_adddev */ + dev->d_devnumber = 0; /* assigned by vfs_adddev */ - dev->d_data = NULL; + dev->d_data = NULL; - result = vfs_adddev("null", dev, 0); - if (result) { - panic("Could not add null device: %s\n", strerror(result)); - } + result = vfs_adddev("null", dev, 0); + if (result) { + panic("Could not add null device: %s\n", strerror(result)); + } } diff --git a/kern/vfs/vfscwd.c b/kern/vfs/vfscwd.c index dac5fb7..8ef365f 100644 --- a/kern/vfs/vfscwd.c +++ b/kern/vfs/vfscwd.c @@ -45,94 +45,85 @@ /* * Get current directory as a vnode. */ -int -vfs_getcurdir(struct vnode **ret) -{ - int rv = 0; +int vfs_getcurdir(struct vnode **ret) { + int rv = 0; - spinlock_acquire(&curproc->p_lock); - if (curproc->p_cwd!=NULL) { - VOP_INCREF(curproc->p_cwd); - *ret = curproc->p_cwd; - } - else { - rv = ENOENT; - } - spinlock_release(&curproc->p_lock); + spinlock_acquire(&curproc->p_lock); + if (curproc->p_cwd != NULL) { + VOP_INCREF(curproc->p_cwd); + *ret = curproc->p_cwd; + } else { + rv = ENOENT; + } + spinlock_release(&curproc->p_lock); - return rv; + return rv; } /* * Set current directory as a vnode. * The passed vnode must in fact be a directory. */ -int -vfs_setcurdir(struct vnode *dir) -{ - struct vnode *old; - mode_t vtype; - int result; +int vfs_setcurdir(struct vnode *dir) { + struct vnode *old; + mode_t vtype; + int result; - result = VOP_GETTYPE(dir, &vtype); - if (result) { - return result; - } - if (vtype != S_IFDIR) { - return ENOTDIR; - } + result = VOP_GETTYPE(dir, &vtype); + if (result) { + return result; + } + if (vtype != S_IFDIR) { + return ENOTDIR; + } - VOP_INCREF(dir); + VOP_INCREF(dir); - spinlock_acquire(&curproc->p_lock); - old = curproc->p_cwd; - curproc->p_cwd = dir; - spinlock_release(&curproc->p_lock); + spinlock_acquire(&curproc->p_lock); + old = curproc->p_cwd; + curproc->p_cwd = dir; + spinlock_release(&curproc->p_lock); - if (old!=NULL) { - VOP_DECREF(old); - } + if (old != NULL) { + VOP_DECREF(old); + } - return 0; + return 0; } /* * Set current directory to "none". */ -int -vfs_clearcurdir(void) -{ - struct vnode *old; +int vfs_clearcurdir(void) { + struct vnode *old; - spinlock_acquire(&curproc->p_lock); - old = curproc->p_cwd; - curproc->p_cwd = NULL; - spinlock_release(&curproc->p_lock); + spinlock_acquire(&curproc->p_lock); + old = curproc->p_cwd; + curproc->p_cwd = NULL; + spinlock_release(&curproc->p_lock); - if (old!=NULL) { - VOP_DECREF(old); - } + if (old != NULL) { + VOP_DECREF(old); + } - return 0; + return 0; } /* * Set current directory, as a pathname. Use vfs_lookup to translate * it to a vnode. */ -int -vfs_chdir(char *path) -{ - struct vnode *vn; - int result; +int vfs_chdir(char *path) { + struct vnode *vn; + int result; - result = vfs_lookup(path, &vn); - if (result) { - return result; - } - result = vfs_setcurdir(vn); - VOP_DECREF(vn); - return result; + result = vfs_lookup(path, &vn); + if (result) { + return result; + } + result = vfs_setcurdir(vn); + VOP_DECREF(vn); + return result; } /* @@ -140,45 +131,43 @@ vfs_chdir(char *path) * Use VOP_NAMEFILE to get the pathname and FSOP_GETVOLNAME to get the * volume name. */ -int -vfs_getcwd(struct uio *uio) -{ - struct vnode *cwd; - int result; - const char *name; - char colon=':'; +int vfs_getcwd(struct uio *uio) { + struct vnode *cwd; + int result; + const char *name; + char colon = ':'; - KASSERT(uio->uio_rw==UIO_READ); + KASSERT(uio->uio_rw == UIO_READ); - result = vfs_getcurdir(&cwd); - if (result) { - return result; - } + result = vfs_getcurdir(&cwd); + if (result) { + return result; + } - /* The current dir must be a directory, and thus it is not a device. */ - KASSERT(cwd->vn_fs != NULL); + /* The current dir must be a directory, and thus it is not a device. */ + KASSERT(cwd->vn_fs != NULL); - name = FSOP_GETVOLNAME(cwd->vn_fs); - if (name==NULL) { - vfs_biglock_acquire(); - name = vfs_getdevname(cwd->vn_fs); - vfs_biglock_release(); - } - KASSERT(name != NULL); + name = FSOP_GETVOLNAME(cwd->vn_fs); + if (name == NULL) { + vfs_biglock_acquire(); + name = vfs_getdevname(cwd->vn_fs); + vfs_biglock_release(); + } + KASSERT(name != NULL); - result = uiomove((char *)name, strlen(name), uio); - if (result) { - goto out; - } - result = uiomove(&colon, 1, uio); - if (result) { - goto out; - } + result = uiomove((char *)name, strlen(name), uio); + if (result) { + goto out; + } + result = uiomove(&colon, 1, uio); + if (result) { + goto out; + } - result = VOP_NAMEFILE(cwd, uio); + result = VOP_NAMEFILE(cwd, uio); - out: +out: - VOP_DECREF(cwd); - return result; + VOP_DECREF(cwd); + return result; } diff --git a/kern/vfs/vfsfail.c b/kern/vfs/vfsfail.c index 6aaf360..ab47238 100644 --- a/kern/vfs/vfsfail.c +++ b/kern/vfs/vfsfail.c @@ -47,218 +47,177 @@ //////////////////////////////////////////////////////////// // uio ops (read, readlink, getdirentry, write, namefile) -int -vopfail_uio_notdir(struct vnode *vn, struct uio *uio) -{ - (void)vn; - (void)uio; - return ENOTDIR; +int vopfail_uio_notdir(struct vnode *vn, struct uio *uio) { + (void)vn; + (void)uio; + return ENOTDIR; } -int -vopfail_uio_isdir(struct vnode *vn, struct uio *uio) -{ - (void)vn; - (void)uio; - return EISDIR; +int vopfail_uio_isdir(struct vnode *vn, struct uio *uio) { + (void)vn; + (void)uio; + return EISDIR; } -int -vopfail_uio_inval(struct vnode *vn, struct uio *uio) -{ - (void)vn; - (void)uio; - return EINVAL; +int vopfail_uio_inval(struct vnode *vn, struct uio *uio) { + (void)vn; + (void)uio; + return EINVAL; } -int -vopfail_uio_nosys(struct vnode *vn, struct uio *uio) -{ - (void)vn; - (void)uio; - return ENOSYS; +int vopfail_uio_nosys(struct vnode *vn, struct uio *uio) { + (void)vn; + (void)uio; + return ENOSYS; } //////////////////////////////////////////////////////////// // mmap -int -vopfail_mmap_isdir(struct vnode *vn /*add stuff */) -{ - (void)vn; - return EISDIR; +int vopfail_mmap_isdir(struct vnode *vn /*add stuff */) { + (void)vn; + return EISDIR; } -int -vopfail_mmap_perm(struct vnode *vn /*add stuff */) -{ - (void)vn; - return EPERM; +int vopfail_mmap_perm(struct vnode *vn /*add stuff */) { + (void)vn; + return EPERM; } -int -vopfail_mmap_nosys(struct vnode *vn /*add stuff */) -{ - (void)vn; - return ENOSYS; +int vopfail_mmap_nosys(struct vnode *vn /*add stuff */) { + (void)vn; + return ENOSYS; } //////////////////////////////////////////////////////////// // truncate -int -vopfail_truncate_isdir(struct vnode *vn, off_t pos) -{ - (void)vn; - (void)pos; - return EISDIR; +int vopfail_truncate_isdir(struct vnode *vn, off_t pos) { + (void)vn; + (void)pos; + return EISDIR; } //////////////////////////////////////////////////////////// // creat -int -vopfail_creat_notdir(struct vnode *vn, const char *name, bool excl, - mode_t mode, struct vnode **result) -{ - (void)vn; - (void)name; - (void)excl; - (void)mode; - (void)result; - return ENOTDIR; +int vopfail_creat_notdir(struct vnode *vn, const char *name, bool excl, + mode_t mode, struct vnode **result) { + (void)vn; + (void)name; + (void)excl; + (void)mode; + (void)result; + return ENOTDIR; } //////////////////////////////////////////////////////////// // symlink -int -vopfail_symlink_notdir(struct vnode *vn, const char *contents, - const char *name) -{ - (void)vn; - (void)contents; - (void)name; - return ENOTDIR; +int vopfail_symlink_notdir(struct vnode *vn, const char *contents, + const char *name) { + (void)vn; + (void)contents; + (void)name; + return ENOTDIR; } -int -vopfail_symlink_nosys(struct vnode *vn, const char *contents, - const char *name) -{ - (void)vn; - (void)contents; - (void)name; - return ENOSYS; +int vopfail_symlink_nosys(struct vnode *vn, const char *contents, + const char *name) { + (void)vn; + (void)contents; + (void)name; + return ENOSYS; } //////////////////////////////////////////////////////////// // mkdir -int -vopfail_mkdir_notdir(struct vnode *vn, const char *name, mode_t mode) -{ - (void)vn; - (void)name; - (void)mode; - return ENOTDIR; +int vopfail_mkdir_notdir(struct vnode *vn, const char *name, mode_t mode) { + (void)vn; + (void)name; + (void)mode; + return ENOTDIR; } -int -vopfail_mkdir_nosys(struct vnode *vn, const char *name, mode_t mode) -{ - (void)vn; - (void)name; - (void)mode; - return ENOSYS; +int vopfail_mkdir_nosys(struct vnode *vn, const char *name, mode_t mode) { + (void)vn; + (void)name; + (void)mode; + return ENOSYS; } //////////////////////////////////////////////////////////// // link -int -vopfail_link_notdir(struct vnode *dir, const char *name, struct vnode *file) -{ - (void)dir; - (void)name; - (void)file; - return ENOTDIR; +int vopfail_link_notdir(struct vnode *dir, const char *name, + struct vnode *file) { + (void)dir; + (void)name; + (void)file; + return ENOTDIR; } -int -vopfail_link_nosys(struct vnode *dir, const char *name, struct vnode *file) -{ - (void)dir; - (void)name; - (void)file; - return ENOSYS; +int vopfail_link_nosys(struct vnode *dir, const char *name, + struct vnode *file) { + (void)dir; + (void)name; + (void)file; + return ENOSYS; } //////////////////////////////////////////////////////////// // string ops (remove and rmdir) -int -vopfail_string_notdir(struct vnode *vn, const char *name) -{ - (void)vn; - (void)name; - return ENOTDIR; +int vopfail_string_notdir(struct vnode *vn, const char *name) { + (void)vn; + (void)name; + return ENOTDIR; } -int -vopfail_string_nosys(struct vnode *vn, const char *name) -{ - (void)vn; - (void)name; - return ENOSYS; +int vopfail_string_nosys(struct vnode *vn, const char *name) { + (void)vn; + (void)name; + return ENOSYS; } //////////////////////////////////////////////////////////// // rename -int -vopfail_rename_notdir(struct vnode *fromdir, const char *fromname, - struct vnode *todir, const char *toname) -{ - (void)fromdir; - (void)fromname; - (void)todir; - (void)toname; - return ENOTDIR; +int vopfail_rename_notdir(struct vnode *fromdir, const char *fromname, + struct vnode *todir, const char *toname) { + (void)fromdir; + (void)fromname; + (void)todir; + (void)toname; + return ENOTDIR; } -int -vopfail_rename_nosys(struct vnode *fromdir, const char *fromname, - struct vnode *todir, const char *toname) -{ - (void)fromdir; - (void)fromname; - (void)todir; - (void)toname; - return ENOSYS; +int vopfail_rename_nosys(struct vnode *fromdir, const char *fromname, + struct vnode *todir, const char *toname) { + (void)fromdir; + (void)fromname; + (void)todir; + (void)toname; + return ENOSYS; } //////////////////////////////////////////////////////////// // lookup -int -vopfail_lookup_notdir(struct vnode *vn, char *path, struct vnode **result) -{ - (void)vn; - (void)path; - (void)result; - return ENOTDIR; +int vopfail_lookup_notdir(struct vnode *vn, char *path, struct vnode **result) { + (void)vn; + (void)path; + (void)result; + return ENOTDIR; } -int -vopfail_lookparent_notdir(struct vnode *vn, char *path, struct vnode **result, - char *buf, size_t len) -{ - (void)vn; - (void)path; - (void)result; - (void)buf; - (void)len; - return ENOTDIR; +int vopfail_lookparent_notdir(struct vnode *vn, char *path, + struct vnode **result, char *buf, size_t len) { + (void)vn; + (void)path; + (void)result; + (void)buf; + (void)len; + return ENOTDIR; } - diff --git a/kern/vfs/vfslist.c b/kern/vfs/vfslist.c index 64f6a9d..fdcf733 100644 --- a/kern/vfs/vfslist.c +++ b/kern/vfs/vfslist.c @@ -75,15 +75,15 @@ */ struct knowndev { - char *kd_name; - char *kd_rawname; - struct device *kd_device; - struct vnode *kd_vnode; - struct fs *kd_fs; + char *kd_name; + char *kd_rawname; + struct device *kd_device; + struct vnode *kd_vnode; + struct fs *kd_fs; }; /* A placeholder for kd_fs for devices used as swap */ -#define SWAP_FS ((struct fs *)-1) +#define SWAP_FS ((struct fs *)-1) DECLARRAY(knowndev, static __UNUSED inline); DEFARRAY(knowndev, static __UNUSED inline); @@ -94,26 +94,23 @@ static struct knowndevarray *knowndevs; static struct lock *vfs_biglock; static unsigned vfs_biglock_depth; - /* * Setup function */ -void -vfs_bootstrap(void) -{ - knowndevs = knowndevarray_create(); - if (knowndevs==NULL) { - panic("vfs: Could not create knowndevs array\n"); - } +void vfs_bootstrap(void) { + knowndevs = knowndevarray_create(); + if (knowndevs == NULL) { + panic("vfs: Could not create knowndevs array\n"); + } - vfs_biglock = lock_create("vfs_biglock"); - if (vfs_biglock==NULL) { - panic("vfs: Could not create vfs big lock\n"); - } - vfs_biglock_depth = 0; + vfs_biglock = lock_create("vfs_biglock"); + if (vfs_biglock == NULL) { + panic("vfs: Could not create vfs big lock\n"); + } + vfs_biglock_depth = 0; - devnull_create(); - semfs_bootstrap(); + devnull_create(); + semfs_bootstrap(); } /* @@ -123,226 +120,198 @@ vfs_bootstrap(void) * much material. Your solution scheme for FS and VFS locking should * not require recursive locks. */ -void -vfs_biglock_acquire(void) -{ - if (!lock_do_i_hold(vfs_biglock)) { - lock_acquire(vfs_biglock); - } - else if (vfs_biglock_depth == 0) { - /* - * Supposedly we hold it, but the depth is 0. This may - * mean: (1) the count is messed up, or (2) - * lock_do_i_hold is lying. Since OS/161 ships out of - * the box with unimplemented locks (students - * implement them) that always return true, assume - * situation (2). In this case acquire the lock - * anyway. - * - * Once you have working locks, this won't be the - * case, and if you get here it should be situation - * (1), in which case the count is messed up and one - * can panic. - */ - lock_acquire(vfs_biglock); - } - vfs_biglock_depth++; +void vfs_biglock_acquire(void) { + if (!lock_do_i_hold(vfs_biglock)) { + lock_acquire(vfs_biglock); + } else if (vfs_biglock_depth == 0) { + /* + * Supposedly we hold it, but the depth is 0. This may + * mean: (1) the count is messed up, or (2) + * lock_do_i_hold is lying. Since OS/161 ships out of + * the box with unimplemented locks (students + * implement them) that always return true, assume + * situation (2). In this case acquire the lock + * anyway. + * + * Once you have working locks, this won't be the + * case, and if you get here it should be situation + * (1), in which case the count is messed up and one + * can panic. + */ + lock_acquire(vfs_biglock); + } + vfs_biglock_depth++; } -void -vfs_biglock_release(void) -{ - KASSERT(lock_do_i_hold(vfs_biglock)); - KASSERT(vfs_biglock_depth > 0); - vfs_biglock_depth--; - if (vfs_biglock_depth == 0) { - lock_release(vfs_biglock); - } +void vfs_biglock_release(void) { + KASSERT(lock_do_i_hold(vfs_biglock)); + KASSERT(vfs_biglock_depth > 0); + vfs_biglock_depth--; + if (vfs_biglock_depth == 0) { + lock_release(vfs_biglock); + } } -bool -vfs_biglock_do_i_hold(void) -{ - return lock_do_i_hold(vfs_biglock); -} +bool vfs_biglock_do_i_hold(void) { return lock_do_i_hold(vfs_biglock); } /* * Global sync function - call FSOP_SYNC on all devices. */ -int -vfs_sync(void) -{ - struct knowndev *dev; - unsigned i, num; +int vfs_sync(void) { + struct knowndev *dev; + unsigned i, num; - vfs_biglock_acquire(); + vfs_biglock_acquire(); - num = knowndevarray_num(knowndevs); - for (i=0; ikd_fs != NULL && dev->kd_fs != SWAP_FS) { - /*result =*/ FSOP_SYNC(dev->kd_fs); - } - } + num = knowndevarray_num(knowndevs); + for (i = 0; i < num; i++) { + dev = knowndevarray_get(knowndevs, i); + if (dev->kd_fs != NULL && dev->kd_fs != SWAP_FS) { + /*result =*/FSOP_SYNC(dev->kd_fs); + } + } - vfs_biglock_release(); + vfs_biglock_release(); - return 0; + return 0; } /* * Given a device name (lhd0, emu0, somevolname, null, etc.), hand * back an appropriate vnode. */ -int -vfs_getroot(const char *devname, struct vnode **ret) -{ - struct knowndev *kd; - unsigned i, num; +int vfs_getroot(const char *devname, struct vnode **ret) { + struct knowndev *kd; + unsigned i, num; - KASSERT(vfs_biglock_do_i_hold()); + KASSERT(vfs_biglock_do_i_hold()); - num = knowndevarray_num(knowndevs); - for (i=0; ikd_fs != NULL && kd->kd_fs != SWAP_FS) { - const char *volname; - volname = FSOP_GETVOLNAME(kd->kd_fs); + if (kd->kd_fs != NULL && kd->kd_fs != SWAP_FS) { + const char *volname; + volname = FSOP_GETVOLNAME(kd->kd_fs); - if (!strcmp(kd->kd_name, devname) || - (volname!=NULL && !strcmp(volname, devname))) { - return FSOP_GETROOT(kd->kd_fs, ret); - } - } - else { - if (kd->kd_rawname!=NULL && - !strcmp(kd->kd_name, devname)) { - return ENXIO; - } - } + if (!strcmp(kd->kd_name, devname) || + (volname != NULL && !strcmp(volname, devname))) { + return FSOP_GETROOT(kd->kd_fs, ret); + } + } else { + if (kd->kd_rawname != NULL && !strcmp(kd->kd_name, devname)) { + return ENXIO; + } + } - /* - * If DEVNAME names the device, and we get here, it - * must have no fs and not be mountable. In this case, - * we return the device itself. - */ - if (!strcmp(kd->kd_name, devname)) { - KASSERT(kd->kd_fs==NULL); - KASSERT(kd->kd_rawname==NULL); - KASSERT(kd->kd_device != NULL); - VOP_INCREF(kd->kd_vnode); - *ret = kd->kd_vnode; - return 0; - } + /* + * If DEVNAME names the device, and we get here, it + * must have no fs and not be mountable. In this case, + * we return the device itself. + */ + if (!strcmp(kd->kd_name, devname)) { + KASSERT(kd->kd_fs == NULL); + KASSERT(kd->kd_rawname == NULL); + KASSERT(kd->kd_device != NULL); + VOP_INCREF(kd->kd_vnode); + *ret = kd->kd_vnode; + return 0; + } - /* - * If the device has a rawname and DEVNAME names that, - * return the device itself. - */ - if (kd->kd_rawname!=NULL && !strcmp(kd->kd_rawname, devname)) { - KASSERT(kd->kd_device != NULL); - VOP_INCREF(kd->kd_vnode); - *ret = kd->kd_vnode; - return 0; - } + /* + * If the device has a rawname and DEVNAME names that, + * return the device itself. + */ + if (kd->kd_rawname != NULL && !strcmp(kd->kd_rawname, devname)) { + KASSERT(kd->kd_device != NULL); + VOP_INCREF(kd->kd_vnode); + *ret = kd->kd_vnode; + return 0; + } - /* - * If none of the above tests matched, we didn't name - * any of the names of this device, so go on to the - * next one. - */ - } + /* + * If none of the above tests matched, we didn't name + * any of the names of this device, so go on to the + * next one. + */ + } - /* - * If we got here, the device specified by devname doesn't exist. - */ + /* + * If we got here, the device specified by devname doesn't exist. + */ - return ENODEV; + return ENODEV; } /* * Given a filesystem, hand back the name of the device it's mounted on. */ -const char * -vfs_getdevname(struct fs *fs) -{ - struct knowndev *kd; - unsigned i, num; +const char *vfs_getdevname(struct fs *fs) { + struct knowndev *kd; + unsigned i, num; - KASSERT(fs != NULL); + KASSERT(fs != NULL); - KASSERT(vfs_biglock_do_i_hold()); + KASSERT(vfs_biglock_do_i_hold()); - num = knowndevarray_num(knowndevs); - for (i=0; ikd_fs == fs) { - /* - * This is not a race condition: as long as the - * guy calling us holds a reference to the fs, - * the fs cannot go away, and the device can't - * go away until the fs goes away. - */ - return kd->kd_name; - } - } + if (kd->kd_fs == fs) { + /* + * This is not a race condition: as long as the + * guy calling us holds a reference to the fs, + * the fs cannot go away, and the device can't + * go away until the fs goes away. + */ + return kd->kd_name; + } + } - return NULL; + return NULL; } /* * Assemble the name for a raw device from the name for the regular device. */ -static -char * -mkrawname(const char *name) -{ - char *s = kmalloc(strlen(name)+3+1); - if (!s) { - return NULL; - } - strcpy(s, name); - strcat(s, "raw"); - return s; +static char *mkrawname(const char *name) { + char *s = kmalloc(strlen(name) + 3 + 1); + if (!s) { + return NULL; + } + strcpy(s, name); + strcat(s, "raw"); + return s; } - /* * Check if the two strings passed in are the same, if they're both * not NULL (the latter part being significant). */ -static -inline -int -samestring(const char *a, const char *b) -{ - if (a==NULL || b==NULL) { - return 0; - } - return !strcmp(a, b); +static inline int samestring(const char *a, const char *b) { + if (a == NULL || b == NULL) { + return 0; + } + return !strcmp(a, b); } /* * Check if the first string passed is the same as any of the three others, * if they're not NULL. */ -static -inline -int -samestring3(const char *a, const char *b, const char *c, const char *d) -{ - return samestring(a,b) || samestring(a,c) || samestring(a,d); +static inline int samestring3(const char *a, const char *b, const char *c, + const char *d) { + return samestring(a, b) || samestring(a, c) || samestring(a, d); } /* @@ -350,34 +319,31 @@ samestring3(const char *a, const char *b, const char *c, const char *d) * name. */ -static -int -badnames(const char *n1, const char *n2, const char *n3) -{ - const char *volname; - unsigned i, num; - struct knowndev *kd; +static int badnames(const char *n1, const char *n2, const char *n3) { + const char *volname; + unsigned i, num; + struct knowndev *kd; - KASSERT(vfs_biglock_do_i_hold()); + KASSERT(vfs_biglock_do_i_hold()); - num = knowndevarray_num(knowndevs); - for (i=0; ikd_fs != NULL && kd->kd_fs != SWAP_FS) { - volname = FSOP_GETVOLNAME(kd->kd_fs); - if (samestring3(volname, n1, n2, n3)) { - return 1; - } - } + if (kd->kd_fs != NULL && kd->kd_fs != SWAP_FS) { + volname = FSOP_GETVOLNAME(kd->kd_fs); + if (samestring3(volname, n1, n2, n3)) { + return 1; + } + } - if (samestring3(kd->kd_rawname, n1, n2, n3) || - samestring3(kd->kd_name, n1, n2, n3)) { - return 1; - } - } + if (samestring3(kd->kd_rawname, n1, n2, n3) || + samestring3(kd->kd_name, n1, n2, n3)) { + return 1; + } + } - return 0; + return 0; } /* @@ -387,101 +353,97 @@ badnames(const char *n1, const char *n2, const char *n3) * to have a filesystem mounted on it, and a raw device will be created * for direct access. */ -static -int -vfs_doadd(const char *dname, int mountable, struct device *dev, struct fs *fs) -{ - char *name=NULL, *rawname=NULL; - struct knowndev *kd=NULL; - struct vnode *vnode=NULL; - const char *volname=NULL; - unsigned index; - int result; +static int vfs_doadd(const char *dname, int mountable, struct device *dev, + struct fs *fs) { + char *name = NULL, *rawname = NULL; + struct knowndev *kd = NULL; + struct vnode *vnode = NULL; + const char *volname = NULL; + unsigned index; + int result; - /* Silence warning with gcc 4.8 -Og (but not -O2) */ - index = 0; + /* Silence warning with gcc 4.8 -Og (but not -O2) */ + index = 0; - vfs_biglock_acquire(); + vfs_biglock_acquire(); - name = kstrdup(dname); - if (name==NULL) { - result = ENOMEM; - goto fail; - } - if (mountable) { - rawname = mkrawname(name); - if (rawname==NULL) { - result = ENOMEM; - goto fail; - } - } + name = kstrdup(dname); + if (name == NULL) { + result = ENOMEM; + goto fail; + } + if (mountable) { + rawname = mkrawname(name); + if (rawname == NULL) { + result = ENOMEM; + goto fail; + } + } - vnode = dev_create_vnode(dev); - if (vnode==NULL) { - result = ENOMEM; - goto fail; - } + vnode = dev_create_vnode(dev); + if (vnode == NULL) { + result = ENOMEM; + goto fail; + } - kd = kmalloc(sizeof(struct knowndev)); - if (kd==NULL) { - result = ENOMEM; - goto fail; - } + kd = kmalloc(sizeof(struct knowndev)); + if (kd == NULL) { + result = ENOMEM; + goto fail; + } - kd->kd_name = name; - kd->kd_rawname = rawname; - kd->kd_device = dev; - kd->kd_vnode = vnode; - kd->kd_fs = fs; + kd->kd_name = name; + kd->kd_rawname = rawname; + kd->kd_device = dev; + kd->kd_vnode = vnode; + kd->kd_fs = fs; - if (fs!=NULL) { - volname = FSOP_GETVOLNAME(fs); - } + if (fs != NULL) { + volname = FSOP_GETVOLNAME(fs); + } - if (badnames(name, rawname, volname)) { - result = EEXIST; - goto fail; - } + if (badnames(name, rawname, volname)) { + result = EEXIST; + goto fail; + } - result = knowndevarray_add(knowndevs, kd, &index); - if (result) { - goto fail; - } + result = knowndevarray_add(knowndevs, kd, &index); + if (result) { + goto fail; + } - if (dev != NULL) { - /* use index+1 as the device number, so 0 is reserved */ - dev->d_devnumber = index+1; - } + if (dev != NULL) { + /* use index+1 as the device number, so 0 is reserved */ + dev->d_devnumber = index + 1; + } - vfs_biglock_release(); - return 0; + vfs_biglock_release(); + return 0; - fail: - if (name) { - kfree(name); - } - if (rawname) { - kfree(rawname); - } - if (vnode) { - dev_uncreate_vnode(vnode); - } - if (kd) { - kfree(kd); - } +fail: + if (name) { + kfree(name); + } + if (rawname) { + kfree(rawname); + } + if (vnode) { + dev_uncreate_vnode(vnode); + } + if (kd) { + kfree(kd); + } - vfs_biglock_release(); - return result; + vfs_biglock_release(); + return result; } /* * Add a new device, by name. See above for the description of * mountable. */ -int -vfs_adddev(const char *devname, struct device *dev, int mountable) -{ - return vfs_doadd(devname, mountable, dev, NULL); +int vfs_adddev(const char *devname, struct device *dev, int mountable) { + return vfs_doadd(devname, mountable, dev, NULL); } /* @@ -489,10 +451,8 @@ vfs_adddev(const char *devname, struct device *dev, int mountable) * This is used for emufs, but might also be used for network * filesystems and the like. */ -int -vfs_addfs(const char *devname, struct fs *fs) -{ - return vfs_doadd(devname, 0, NULL, fs); +int vfs_addfs(const char *devname, struct fs *fs) { + return vfs_doadd(devname, 0, NULL, fs); } ////////////////////////////////////////////////// @@ -501,31 +461,28 @@ vfs_addfs(const char *devname, struct fs *fs) * Look for a mountable device named DEVNAME. * Should already hold knowndevs_lock. */ -static -int -findmount(const char *devname, struct knowndev **result) -{ - struct knowndev *dev; - unsigned i, num; - bool found = false; +static int findmount(const char *devname, struct knowndev **result) { + struct knowndev *dev; + unsigned i, num; + bool found = false; - KASSERT(vfs_biglock_do_i_hold()); + KASSERT(vfs_biglock_do_i_hold()); - num = knowndevarray_num(knowndevs); - for (i=0; !found && ikd_rawname==NULL) { - /* not mountable/unmountable */ - continue; - } + num = knowndevarray_num(knowndevs); + for (i = 0; !found && i < num; i++) { + dev = knowndevarray_get(knowndevs, i); + if (dev->kd_rawname == NULL) { + /* not mountable/unmountable */ + continue; + } - if (!strcmp(devname, dev->kd_name)) { - *result = dev; - found = true; - } - } + if (!strcmp(devname, dev->kd_name)) { + *result = dev; + found = true; + } + } - return found ? 0 : ENODEV; + return found ? 0 : ENODEV; } /* @@ -534,47 +491,45 @@ findmount(const char *devname, struct knowndev **result) * * The DATA argument is passed through unchanged to MOUNTFUNC. */ -int -vfs_mount(const char *devname, void *data, - int (*mountfunc)(void *data, struct device *, struct fs **ret)) -{ - const char *volname; - struct knowndev *kd; - struct fs *fs; - int result; +int vfs_mount(const char *devname, void *data, + int (*mountfunc)(void *data, struct device *, struct fs **ret)) { + const char *volname; + struct knowndev *kd; + struct fs *fs; + int result; - vfs_biglock_acquire(); + vfs_biglock_acquire(); - result = findmount(devname, &kd); - if (result) { - vfs_biglock_release(); - return result; - } + result = findmount(devname, &kd); + if (result) { + vfs_biglock_release(); + return result; + } - if (kd->kd_fs != NULL) { - vfs_biglock_release(); - return EBUSY; - } - KASSERT(kd->kd_rawname != NULL); - KASSERT(kd->kd_device != NULL); + if (kd->kd_fs != NULL) { + vfs_biglock_release(); + return EBUSY; + } + KASSERT(kd->kd_rawname != NULL); + KASSERT(kd->kd_device != NULL); - result = mountfunc(data, kd->kd_device, &fs); - if (result) { - vfs_biglock_release(); - return result; - } + result = mountfunc(data, kd->kd_device, &fs); + if (result) { + vfs_biglock_release(); + return result; + } - KASSERT(fs != NULL); - KASSERT(fs != SWAP_FS); + KASSERT(fs != NULL); + KASSERT(fs != SWAP_FS); - kd->kd_fs = fs; + kd->kd_fs = fs; - volname = FSOP_GETVOLNAME(fs); - kprintf("vfs: Mounted %s: on %s\n", - volname ? volname : kd->kd_name, kd->kd_name); + volname = FSOP_GETVOLNAME(fs); + kprintf("vfs: Mounted %s: on %s\n", volname ? volname : kd->kd_name, + kd->kd_name); - vfs_biglock_release(); - return 0; + vfs_biglock_release(); + return 0; } /* @@ -582,99 +537,95 @@ vfs_mount(const char *devname, void *data, * vnode. Unlike mount tolerates a trailing colon on the device name, * to avoid student-facing confusion. */ -int -vfs_swapon(const char *devname, struct vnode **ret) -{ - char *myname = NULL; - size_t len; - struct knowndev *kd; - int result; +int vfs_swapon(const char *devname, struct vnode **ret) { + char *myname = NULL; + size_t len; + struct knowndev *kd; + int result; - len = strlen(devname); - if (len > 0 && devname[len - 1] == ':') { - /* tolerate trailing :, e.g. lhd0: rather than lhd0 */ - myname = kstrdup(devname); - if (myname == NULL) { - return ENOMEM; - } - myname[len - 1] = 0; - devname = myname; - } + len = strlen(devname); + if (len > 0 && devname[len - 1] == ':') { + /* tolerate trailing :, e.g. lhd0: rather than lhd0 */ + myname = kstrdup(devname); + if (myname == NULL) { + return ENOMEM; + } + myname[len - 1] = 0; + devname = myname; + } - vfs_biglock_acquire(); + vfs_biglock_acquire(); - result = findmount(devname, &kd); - if (result) { - goto out; - } + result = findmount(devname, &kd); + if (result) { + goto out; + } - if (kd->kd_fs != NULL) { - result = EBUSY; - goto out; - } - KASSERT(kd->kd_rawname != NULL); - KASSERT(kd->kd_device != NULL); + if (kd->kd_fs != NULL) { + result = EBUSY; + goto out; + } + KASSERT(kd->kd_rawname != NULL); + KASSERT(kd->kd_device != NULL); - kprintf("vfs: Swap attached to %s\n", kd->kd_name); + kprintf("vfs: Swap attached to %s\n", kd->kd_name); - kd->kd_fs = SWAP_FS; - VOP_INCREF(kd->kd_vnode); - *ret = kd->kd_vnode; + kd->kd_fs = SWAP_FS; + VOP_INCREF(kd->kd_vnode); + *ret = kd->kd_vnode; - out: - vfs_biglock_release(); - if (myname != NULL) { - kfree(myname); - } +out: + vfs_biglock_release(); + if (myname != NULL) { + kfree(myname); + } - return result; + return result; } /* * Unmount a filesystem/device by name. * First calls FSOP_SYNC on the filesystem; then calls FSOP_UNMOUNT. */ -int -vfs_unmount(const char *devname) -{ - struct knowndev *kd; - int result; +int vfs_unmount(const char *devname) { + struct knowndev *kd; + int result; - vfs_biglock_acquire(); + vfs_biglock_acquire(); - result = findmount(devname, &kd); - if (result) { - goto fail; - } + result = findmount(devname, &kd); + if (result) { + goto fail; + } - if (kd->kd_fs == NULL || kd->kd_fs == SWAP_FS) { - result = EINVAL; - goto fail; - } - KASSERT(kd->kd_rawname != NULL); - KASSERT(kd->kd_device != NULL); + if (kd->kd_fs == NULL || kd->kd_fs == SWAP_FS) { + result = EINVAL; + goto fail; + } + KASSERT(kd->kd_rawname != NULL); + KASSERT(kd->kd_device != NULL); - /* sync the fs */ - result = FSOP_SYNC(kd->kd_fs); - if (result) { - goto fail; - } + /* sync the fs */ + result = FSOP_SYNC(kd->kd_fs); + if (result) { + goto fail; + } - result = FSOP_UNMOUNT(kd->kd_fs); - if (result) { - goto fail; - } + result = FSOP_UNMOUNT(kd->kd_fs); + if (result) { + goto fail; + } - kprintf("vfs: Unmounted %s:\n", kd->kd_name); + kprintf("vfs: Unmounted %s:\n", kd->kd_name); - /* now drop the filesystem */ - kd->kd_fs = NULL; + /* now drop the filesystem */ + kd->kd_fs = NULL; - KASSERT(result==0); + KASSERT(result == 0); - fail: - vfs_biglock_release(); - return result; +fail: + vfs_biglock_release(); + return result; } /* @@ -684,103 +635,99 @@ vfs_unmount(const char *devname) * explicitly prior to shutting down, except perhaps when swapping to * things that themselves want a clean shutdown, like RAIDs.) */ -int -vfs_swapoff(const char *devname) -{ - struct knowndev *kd; - int result; +int vfs_swapoff(const char *devname) { + struct knowndev *kd; + int result; - vfs_biglock_acquire(); + vfs_biglock_acquire(); - result = findmount(devname, &kd); - if (result) { - goto fail; - } + result = findmount(devname, &kd); + if (result) { + goto fail; + } - if (kd->kd_fs != SWAP_FS) { - result = EINVAL; - goto fail; - } + if (kd->kd_fs != SWAP_FS) { + result = EINVAL; + goto fail; + } - kprintf("vfs: Swap detached from %s:\n", kd->kd_name); + kprintf("vfs: Swap detached from %s:\n", kd->kd_name); - /* drop it */ - kd->kd_fs = NULL; + /* drop it */ + kd->kd_fs = NULL; - KASSERT(result==0); + KASSERT(result == 0); - fail: - vfs_biglock_release(); - return result; +fail: + vfs_biglock_release(); + return result; } /* * Global unmount function. */ -int -vfs_unmountall(void) -{ - struct knowndev *dev; - unsigned i, num; - int result; +int vfs_unmountall(void) { + struct knowndev *dev; + unsigned i, num; + int result; - vfs_biglock_acquire(); + vfs_biglock_acquire(); - num = knowndevarray_num(knowndevs); - for (i=0; ikd_rawname == NULL) { - /* not mountable/unmountable */ - continue; - } - if (dev->kd_fs == NULL) { - /* not mounted */ - continue; - } - if (dev->kd_fs == SWAP_FS) { - /* just drop it */ - dev->kd_fs = NULL; - continue; - } + num = knowndevarray_num(knowndevs); + for (i = 0; i < num; i++) { + dev = knowndevarray_get(knowndevs, i); + if (dev->kd_rawname == NULL) { + /* not mountable/unmountable */ + continue; + } + if (dev->kd_fs == NULL) { + /* not mounted */ + continue; + } + if (dev->kd_fs == SWAP_FS) { + /* just drop it */ + dev->kd_fs = NULL; + continue; + } - kprintf("vfs: Unmounting %s:\n", dev->kd_name); + kprintf("vfs: Unmounting %s:\n", dev->kd_name); - result = FSOP_SYNC(dev->kd_fs); - if (result) { - kprintf("vfs: Warning: sync failed for %s: %s, trying " - "again\n", dev->kd_name, strerror(result)); + result = FSOP_SYNC(dev->kd_fs); + if (result) { + kprintf("vfs: Warning: sync failed for %s: %s, trying " + "again\n", + dev->kd_name, strerror(result)); - result = FSOP_SYNC(dev->kd_fs); - if (result) { - kprintf("vfs: Warning: sync failed second time" - " for %s: %s, giving up...\n", - dev->kd_name, strerror(result)); - /* - * Do not attempt to complete the - * unmount as it will likely explode. - */ - continue; - } - } + result = FSOP_SYNC(dev->kd_fs); + if (result) { + kprintf("vfs: Warning: sync failed second time" + " for %s: %s, giving up...\n", + dev->kd_name, strerror(result)); + /* + * Do not attempt to complete the + * unmount as it will likely explode. + */ + continue; + } + } - result = FSOP_UNMOUNT(dev->kd_fs); - if (result == EBUSY) { - kprintf("vfs: Cannot unmount %s: (busy)\n", - dev->kd_name); - continue; - } - if (result) { - kprintf("vfs: Warning: unmount failed for %s:" - " %s, already synced, dropping...\n", - dev->kd_name, strerror(result)); - continue; - } + result = FSOP_UNMOUNT(dev->kd_fs); + if (result == EBUSY) { + kprintf("vfs: Cannot unmount %s: (busy)\n", dev->kd_name); + continue; + } + if (result) { + kprintf("vfs: Warning: unmount failed for %s:" + " %s, already synced, dropping...\n", + dev->kd_name, strerror(result)); + continue; + } - /* now drop the filesystem */ - dev->kd_fs = NULL; - } + /* now drop the filesystem */ + dev->kd_fs = NULL; + } - vfs_biglock_release(); + vfs_biglock_release(); - return 0; + return 0; } diff --git a/kern/vfs/vfslookup.c b/kern/vfs/vfslookup.c index afeacea..36a57e0 100644 --- a/kern/vfs/vfslookup.c +++ b/kern/vfs/vfslookup.c @@ -45,18 +45,15 @@ static struct vnode *bootfs_vnode = NULL; /* * Helper function for actually changing bootfs_vnode. */ -static -void -change_bootfs(struct vnode *newvn) -{ - struct vnode *oldvn; +static void change_bootfs(struct vnode *newvn) { + struct vnode *oldvn; - oldvn = bootfs_vnode; - bootfs_vnode = newvn; + oldvn = bootfs_vnode; + bootfs_vnode = newvn; - if (oldvn != NULL) { - VOP_DECREF(oldvn); - } + if (oldvn != NULL) { + VOP_DECREF(oldvn); + } } /* @@ -67,171 +64,161 @@ change_bootfs(struct vnode *newvn) * * It is also incidentally the system's first current directory. */ -int -vfs_setbootfs(const char *fsname) -{ - char tmp[NAME_MAX+1]; - char *s; - int result; - struct vnode *newguy; +int vfs_setbootfs(const char *fsname) { + char tmp[NAME_MAX + 1]; + char *s; + int result; + struct vnode *newguy; - vfs_biglock_acquire(); + vfs_biglock_acquire(); - snprintf(tmp, sizeof(tmp)-1, "%s", fsname); - s = strchr(tmp, ':'); - if (s) { - /* If there's a colon, it must be at the end */ - if (strlen(s)>0) { - vfs_biglock_release(); - return EINVAL; - } - } - else { - strcat(tmp, ":"); - } + snprintf(tmp, sizeof(tmp) - 1, "%s", fsname); + s = strchr(tmp, ':'); + if (s) { + /* If there's a colon, it must be at the end */ + if (strlen(s) > 0) { + vfs_biglock_release(); + return EINVAL; + } + } else { + strcat(tmp, ":"); + } - result = vfs_chdir(tmp); - if (result) { - vfs_biglock_release(); - return result; - } + result = vfs_chdir(tmp); + if (result) { + vfs_biglock_release(); + return result; + } - result = vfs_getcurdir(&newguy); - if (result) { - vfs_biglock_release(); - return result; - } + result = vfs_getcurdir(&newguy); + if (result) { + vfs_biglock_release(); + return result; + } - change_bootfs(newguy); + change_bootfs(newguy); - vfs_biglock_release(); - return 0; + vfs_biglock_release(); + return 0; } /* * Clear the bootfs vnode (preparatory to system shutdown). */ -void -vfs_clearbootfs(void) -{ - vfs_biglock_acquire(); - change_bootfs(NULL); - vfs_biglock_release(); +void vfs_clearbootfs(void) { + vfs_biglock_acquire(); + change_bootfs(NULL); + vfs_biglock_release(); } - /* * Common code to pull the device name, if any, off the front of a * path and choose the vnode to begin the name lookup relative to. */ -static -int -getdevice(char *path, char **subpath, struct vnode **startvn) -{ - int slash=-1, colon=-1, i; - struct vnode *vn; - int result; +static int getdevice(char *path, char **subpath, struct vnode **startvn) { + int slash = -1, colon = -1, i; + struct vnode *vn; + int result; - KASSERT(vfs_biglock_do_i_hold()); + KASSERT(vfs_biglock_do_i_hold()); - /* - * Entirely empty filenames aren't legal. - */ - if (path[0] == 0) { - return EINVAL; - } + /* + * Entirely empty filenames aren't legal. + */ + if (path[0] == 0) { + return EINVAL; + } - /* - * Locate the first colon or slash. - */ + /* + * Locate the first colon or slash. + */ - for (i=0; path[i]; i++) { - if (path[i]==':') { - colon = i; - break; - } - if (path[i]=='/') { - slash = i; - break; - } - } + for (i = 0; path[i]; i++) { + if (path[i] == ':') { + colon = i; + break; + } + if (path[i] == '/') { + slash = i; + break; + } + } - if (colon < 0 && slash != 0) { - /* - * No colon before a slash, so no device name - * specified, and the slash isn't leading or is also - * absent, so this is a relative path or just a bare - * filename. Start from the current directory, and - * use the whole thing as the subpath. - */ - *subpath = path; - return vfs_getcurdir(startvn); - } + if (colon < 0 && slash != 0) { + /* + * No colon before a slash, so no device name + * specified, and the slash isn't leading or is also + * absent, so this is a relative path or just a bare + * filename. Start from the current directory, and + * use the whole thing as the subpath. + */ + *subpath = path; + return vfs_getcurdir(startvn); + } - if (colon>0) { - /* device:path - get root of device's filesystem */ - path[colon]=0; - while (path[colon+1]=='/') { - /* device:/path - skip slash, treat as device:path */ - colon++; - } - *subpath = &path[colon+1]; + if (colon > 0) { + /* device:path - get root of device's filesystem */ + path[colon] = 0; + while (path[colon + 1] == '/') { + /* device:/path - skip slash, treat as device:path */ + colon++; + } + *subpath = &path[colon + 1]; - result = vfs_getroot(path, startvn); - if (result) { - return result; - } + result = vfs_getroot(path, startvn); + if (result) { + return result; + } - return 0; - } + return 0; + } - /* - * We have either /path or :path. - * - * /path is a path relative to the root of the "boot filesystem". - * :path is a path relative to the root of the current filesystem. - */ - KASSERT(colon==0 || slash==0); + /* + * We have either /path or :path. + * + * /path is a path relative to the root of the "boot filesystem". + * :path is a path relative to the root of the current filesystem. + */ + KASSERT(colon == 0 || slash == 0); - if (path[0]=='/') { - if (bootfs_vnode==NULL) { - return ENOENT; - } - VOP_INCREF(bootfs_vnode); - *startvn = bootfs_vnode; - } - else { - KASSERT(path[0]==':'); + if (path[0] == '/') { + if (bootfs_vnode == NULL) { + return ENOENT; + } + VOP_INCREF(bootfs_vnode); + *startvn = bootfs_vnode; + } else { + KASSERT(path[0] == ':'); - result = vfs_getcurdir(&vn); - if (result) { - return result; - } + result = vfs_getcurdir(&vn); + if (result) { + return result; + } - /* - * The current directory may not be a device, so it - * must have a fs. - */ - KASSERT(vn->vn_fs!=NULL); + /* + * The current directory may not be a device, so it + * must have a fs. + */ + KASSERT(vn->vn_fs != NULL); - result = FSOP_GETROOT(vn->vn_fs, startvn); + result = FSOP_GETROOT(vn->vn_fs, startvn); - VOP_DECREF(vn); + VOP_DECREF(vn); - if (result) { - return result; - } - } + if (result) { + return result; + } + } - while (path[1]=='/') { - /* ///... or :/... */ - path++; - } + while (path[1] == '/') { + /* ///... or :/... */ + path++; + } - *subpath = path+1; + *subpath = path + 1; - return 0; + return 0; } /* @@ -239,62 +226,57 @@ getdevice(char *path, char **subpath, struct vnode **startvn) * (In BSD, both of these are subsumed by namei().) */ -int -vfs_lookparent(char *path, struct vnode **retval, - char *buf, size_t buflen) -{ - struct vnode *startvn; - int result; +int vfs_lookparent(char *path, struct vnode **retval, char *buf, + size_t buflen) { + struct vnode *startvn; + int result; - vfs_biglock_acquire(); + vfs_biglock_acquire(); - result = getdevice(path, &path, &startvn); - if (result) { - vfs_biglock_release(); - return result; - } + result = getdevice(path, &path, &startvn); + if (result) { + vfs_biglock_release(); + return result; + } - if (strlen(path)==0) { - /* - * It does not make sense to use just a device name in - * a context where "lookparent" is the desired - * operation. - */ - result = EINVAL; - } - else { - result = VOP_LOOKPARENT(startvn, path, retval, buf, buflen); - } + if (strlen(path) == 0) { + /* + * It does not make sense to use just a device name in + * a context where "lookparent" is the desired + * operation. + */ + result = EINVAL; + } else { + result = VOP_LOOKPARENT(startvn, path, retval, buf, buflen); + } - VOP_DECREF(startvn); + VOP_DECREF(startvn); - vfs_biglock_release(); - return result; + vfs_biglock_release(); + return result; } -int -vfs_lookup(char *path, struct vnode **retval) -{ - struct vnode *startvn; - int result; +int vfs_lookup(char *path, struct vnode **retval) { + struct vnode *startvn; + int result; - vfs_biglock_acquire(); + vfs_biglock_acquire(); - result = getdevice(path, &path, &startvn); - if (result) { - vfs_biglock_release(); - return result; - } + result = getdevice(path, &path, &startvn); + if (result) { + vfs_biglock_release(); + return result; + } - if (strlen(path)==0) { - *retval = startvn; - vfs_biglock_release(); - return 0; - } + if (strlen(path) == 0) { + *retval = startvn; + vfs_biglock_release(); + return 0; + } - result = VOP_LOOKUP(startvn, path, retval); + result = VOP_LOOKUP(startvn, path, retval); - VOP_DECREF(startvn); - vfs_biglock_release(); - return result; + VOP_DECREF(startvn); + vfs_biglock_release(); + return result; } diff --git a/kern/vfs/vfspath.c b/kern/vfs/vfspath.c index a7198a4..a0059e4 100644 --- a/kern/vfs/vfspath.c +++ b/kern/vfs/vfspath.c @@ -39,185 +39,172 @@ #include #include - /* Does most of the work for open(). */ -int -vfs_open(char *path, int openflags, mode_t mode, struct vnode **ret) -{ - int how; - int result; - int canwrite; - struct vnode *vn = NULL; +int vfs_open(char *path, int openflags, mode_t mode, struct vnode **ret) { + int how; + int result; + int canwrite; + struct vnode *vn = NULL; - how = openflags & O_ACCMODE; + how = openflags & O_ACCMODE; - switch (how) { - case O_RDONLY: - canwrite=0; - break; - case O_WRONLY: - case O_RDWR: - canwrite=1; - break; - default: - return EINVAL; - } + switch (how) { + case O_RDONLY: + canwrite = 0; + break; + case O_WRONLY: + case O_RDWR: + canwrite = 1; + break; + default: + return EINVAL; + } - if (openflags & O_CREAT) { - char name[NAME_MAX+1]; - struct vnode *dir; - int excl = (openflags & O_EXCL)!=0; + if (openflags & O_CREAT) { + char name[NAME_MAX + 1]; + struct vnode *dir; + int excl = (openflags & O_EXCL) != 0; - result = vfs_lookparent(path, &dir, name, sizeof(name)); - if (result) { - return result; - } + result = vfs_lookparent(path, &dir, name, sizeof(name)); + if (result) { + return result; + } - result = VOP_CREAT(dir, name, excl, mode, &vn); + result = VOP_CREAT(dir, name, excl, mode, &vn); - VOP_DECREF(dir); - } - else { - result = vfs_lookup(path, &vn); - } + VOP_DECREF(dir); + } else { + result = vfs_lookup(path, &vn); + } - if (result) { - return result; - } + if (result) { + return result; + } - KASSERT(vn != NULL); + KASSERT(vn != NULL); - result = VOP_EACHOPEN(vn, openflags); - if (result) { - VOP_DECREF(vn); - return result; - } + result = VOP_EACHOPEN(vn, openflags); + if (result) { + VOP_DECREF(vn); + return result; + } - if (openflags & O_TRUNC) { - if (canwrite==0) { - result = EINVAL; - } - else { - result = VOP_TRUNCATE(vn, 0); - } - if (result) { - VOP_DECREF(vn); - return result; - } - } + if (openflags & O_TRUNC) { + if (canwrite == 0) { + result = EINVAL; + } else { + result = VOP_TRUNCATE(vn, 0); + } + if (result) { + VOP_DECREF(vn); + return result; + } + } - *ret = vn; + *ret = vn; - return 0; + return 0; } /* Does most of the work for close(). */ -void -vfs_close(struct vnode *vn) -{ - /* - * VOP_DECREF doesn't return an error. - * - * We assume that the file system makes every reasonable - * effort to not fail. If it does fail - such as on a hard I/O - * error or something - vnode.c prints a warning. The reason - * we don't report errors up to or above this level is that - * (1) most application software does not check for close - * failing, and more importantly - * (2) we're often called from places like process exit - * where reporting the error is impossible and - * meaningful recovery is entirely impractical. - */ +void vfs_close(struct vnode *vn) { + /* + * VOP_DECREF doesn't return an error. + * + * We assume that the file system makes every reasonable + * effort to not fail. If it does fail - such as on a hard I/O + * error or something - vnode.c prints a warning. The reason + * we don't report errors up to or above this level is that + * (1) most application software does not check for close + * failing, and more importantly + * (2) we're often called from places like process exit + * where reporting the error is impossible and + * meaningful recovery is entirely impractical. + */ - VOP_DECREF(vn); + VOP_DECREF(vn); } /* Does most of the work for remove(). */ -int -vfs_remove(char *path) -{ - struct vnode *dir; - char name[NAME_MAX+1]; - int result; +int vfs_remove(char *path) { + struct vnode *dir; + char name[NAME_MAX + 1]; + int result; - result = vfs_lookparent(path, &dir, name, sizeof(name)); - if (result) { - return result; - } + result = vfs_lookparent(path, &dir, name, sizeof(name)); + if (result) { + return result; + } - result = VOP_REMOVE(dir, name); - VOP_DECREF(dir); + result = VOP_REMOVE(dir, name); + VOP_DECREF(dir); - return result; + return result; } /* Does most of the work for rename(). */ -int -vfs_rename(char *oldpath, char *newpath) -{ - struct vnode *olddir; - char oldname[NAME_MAX+1]; - struct vnode *newdir; - char newname[NAME_MAX+1]; - int result; +int vfs_rename(char *oldpath, char *newpath) { + struct vnode *olddir; + char oldname[NAME_MAX + 1]; + struct vnode *newdir; + char newname[NAME_MAX + 1]; + int result; - result = vfs_lookparent(oldpath, &olddir, oldname, sizeof(oldname)); - if (result) { - return result; - } - result = vfs_lookparent(newpath, &newdir, newname, sizeof(newname)); - if (result) { - VOP_DECREF(olddir); - return result; - } + result = vfs_lookparent(oldpath, &olddir, oldname, sizeof(oldname)); + if (result) { + return result; + } + result = vfs_lookparent(newpath, &newdir, newname, sizeof(newname)); + if (result) { + VOP_DECREF(olddir); + return result; + } - if (olddir->vn_fs==NULL || newdir->vn_fs==NULL || - olddir->vn_fs != newdir->vn_fs) { - VOP_DECREF(newdir); - VOP_DECREF(olddir); - return EXDEV; - } + if (olddir->vn_fs == NULL || newdir->vn_fs == NULL || + olddir->vn_fs != newdir->vn_fs) { + VOP_DECREF(newdir); + VOP_DECREF(olddir); + return EXDEV; + } - result = VOP_RENAME(olddir, oldname, newdir, newname); + result = VOP_RENAME(olddir, oldname, newdir, newname); - VOP_DECREF(newdir); - VOP_DECREF(olddir); + VOP_DECREF(newdir); + VOP_DECREF(olddir); - return result; + return result; } /* Does most of the work for link(). */ -int -vfs_link(char *oldpath, char *newpath) -{ - struct vnode *oldfile; - struct vnode *newdir; - char newname[NAME_MAX+1]; - int result; +int vfs_link(char *oldpath, char *newpath) { + struct vnode *oldfile; + struct vnode *newdir; + char newname[NAME_MAX + 1]; + int result; - result = vfs_lookup(oldpath, &oldfile); - if (result) { - return result; - } - result = vfs_lookparent(newpath, &newdir, newname, sizeof(newname)); - if (result) { - VOP_DECREF(oldfile); - return result; - } + result = vfs_lookup(oldpath, &oldfile); + if (result) { + return result; + } + result = vfs_lookparent(newpath, &newdir, newname, sizeof(newname)); + if (result) { + VOP_DECREF(oldfile); + return result; + } - if (oldfile->vn_fs==NULL || newdir->vn_fs==NULL || - oldfile->vn_fs != newdir->vn_fs) { - VOP_DECREF(newdir); - VOP_DECREF(oldfile); - return EXDEV; - } + if (oldfile->vn_fs == NULL || newdir->vn_fs == NULL || + oldfile->vn_fs != newdir->vn_fs) { + VOP_DECREF(newdir); + VOP_DECREF(oldfile); + return EXDEV; + } - result = VOP_LINK(newdir, newname, oldfile); + result = VOP_LINK(newdir, newname, oldfile); - VOP_DECREF(newdir); - VOP_DECREF(oldfile); + VOP_DECREF(newdir); + VOP_DECREF(oldfile); - return result; + return result; } /* @@ -227,22 +214,20 @@ vfs_link(char *oldpath, char *newpath) * other parts of the VFS layer are missing crucial elements of * support for symlinks. */ -int -vfs_symlink(const char *contents, char *path) -{ - struct vnode *newdir; - char newname[NAME_MAX+1]; - int result; +int vfs_symlink(const char *contents, char *path) { + struct vnode *newdir; + char newname[NAME_MAX + 1]; + int result; - result = vfs_lookparent(path, &newdir, newname, sizeof(newname)); - if (result) { - return result; - } + result = vfs_lookparent(path, &newdir, newname, sizeof(newname)); + if (result) { + return result; + } - result = VOP_SYMLINK(newdir, newname, contents); - VOP_DECREF(newdir); + result = VOP_SYMLINK(newdir, newname, contents); + VOP_DECREF(newdir); - return result; + return result; } /* @@ -252,65 +237,58 @@ vfs_symlink(const char *contents, char *path) * other parts of the VFS layer are missing crucial elements of * support for symlinks. */ -int -vfs_readlink(char *path, struct uio *uio) -{ - struct vnode *vn; - int result; +int vfs_readlink(char *path, struct uio *uio) { + struct vnode *vn; + int result; - result = vfs_lookup(path, &vn); - if (result) { - return result; - } + result = vfs_lookup(path, &vn); + if (result) { + return result; + } - result = VOP_READLINK(vn, uio); + result = VOP_READLINK(vn, uio); - VOP_DECREF(vn); + VOP_DECREF(vn); - return result; + return result; } /* * Does most of the work for mkdir. */ -int -vfs_mkdir(char *path, mode_t mode) -{ - struct vnode *parent; - char name[NAME_MAX+1]; - int result; +int vfs_mkdir(char *path, mode_t mode) { + struct vnode *parent; + char name[NAME_MAX + 1]; + int result; - result = vfs_lookparent(path, &parent, name, sizeof(name)); - if (result) { - return result; - } + result = vfs_lookparent(path, &parent, name, sizeof(name)); + if (result) { + return result; + } - result = VOP_MKDIR(parent, name, mode); + result = VOP_MKDIR(parent, name, mode); - VOP_DECREF(parent); + VOP_DECREF(parent); - return result; + return result; } /* * Does most of the work for rmdir. */ -int -vfs_rmdir(char *path) -{ - struct vnode *parent; - char name[NAME_MAX+1]; - int result; +int vfs_rmdir(char *path) { + struct vnode *parent; + char name[NAME_MAX + 1]; + int result; - result = vfs_lookparent(path, &parent, name, sizeof(name)); - if (result) { - return result; - } + result = vfs_lookparent(path, &parent, name, sizeof(name)); + if (result) { + return result; + } - result = VOP_RMDIR(parent, name); + result = VOP_RMDIR(parent, name); - VOP_DECREF(parent); + VOP_DECREF(parent); - return result; + return result; } - diff --git a/kern/vfs/vnode.c b/kern/vfs/vnode.c index 7322707..5a2bf2c 100644 --- a/kern/vfs/vnode.c +++ b/kern/vfs/vnode.c @@ -40,50 +40,43 @@ /* * Initialize an abstract vnode. */ -int -vnode_init(struct vnode *vn, const struct vnode_ops *ops, - struct fs *fs, void *fsdata) -{ - KASSERT(vn != NULL); - KASSERT(ops != NULL); +int vnode_init(struct vnode *vn, const struct vnode_ops *ops, struct fs *fs, + void *fsdata) { + KASSERT(vn != NULL); + KASSERT(ops != NULL); - vn->vn_ops = ops; - vn->vn_refcount = 1; - spinlock_init(&vn->vn_countlock); - vn->vn_fs = fs; - vn->vn_data = fsdata; - return 0; + vn->vn_ops = ops; + vn->vn_refcount = 1; + spinlock_init(&vn->vn_countlock); + vn->vn_fs = fs; + vn->vn_data = fsdata; + return 0; } /* * Destroy an abstract vnode. */ -void -vnode_cleanup(struct vnode *vn) -{ - KASSERT(vn->vn_refcount == 1); +void vnode_cleanup(struct vnode *vn) { + KASSERT(vn->vn_refcount == 1); - spinlock_cleanup(&vn->vn_countlock); + spinlock_cleanup(&vn->vn_countlock); - vn->vn_ops = NULL; - vn->vn_refcount = 0; - vn->vn_fs = NULL; - vn->vn_data = NULL; + vn->vn_ops = NULL; + vn->vn_refcount = 0; + vn->vn_fs = NULL; + vn->vn_data = NULL; } - /* * Increment refcount. * Called by VOP_INCREF. */ -void -vnode_incref(struct vnode *vn) -{ - KASSERT(vn != NULL); +void vnode_incref(struct vnode *vn) { + KASSERT(vn != NULL); - spinlock_acquire(&vn->vn_countlock); - vn->vn_refcount++; - spinlock_release(&vn->vn_countlock); + spinlock_acquire(&vn->vn_countlock); + vn->vn_refcount++; + spinlock_release(&vn->vn_countlock); } /* @@ -91,88 +84,79 @@ vnode_incref(struct vnode *vn) * Called by VOP_DECREF. * Calls VOP_RECLAIM if the refcount hits zero. */ -void -vnode_decref(struct vnode *vn) -{ - bool destroy; - int result; +void vnode_decref(struct vnode *vn) { + bool destroy; + int result; - KASSERT(vn != NULL); + KASSERT(vn != NULL); - spinlock_acquire(&vn->vn_countlock); + spinlock_acquire(&vn->vn_countlock); - KASSERT(vn->vn_refcount > 0); - if (vn->vn_refcount > 1) { - vn->vn_refcount--; - destroy = false; - } - else { - /* Don't decrement; pass the reference to VOP_RECLAIM. */ - destroy = true; - } - spinlock_release(&vn->vn_countlock); + KASSERT(vn->vn_refcount > 0); + if (vn->vn_refcount > 1) { + vn->vn_refcount--; + destroy = false; + } else { + /* Don't decrement; pass the reference to VOP_RECLAIM. */ + destroy = true; + } + spinlock_release(&vn->vn_countlock); - if (destroy) { - result = VOP_RECLAIM(vn); - if (result != 0 && result != EBUSY) { - // XXX: lame. - kprintf("vfs: Warning: VOP_RECLAIM: %s\n", - strerror(result)); - } - } + if (destroy) { + result = VOP_RECLAIM(vn); + if (result != 0 && result != EBUSY) { + // XXX: lame. + kprintf("vfs: Warning: VOP_RECLAIM: %s\n", strerror(result)); + } + } } /* * Check for various things being valid. * Called before all VOP_* calls. */ -void -vnode_check(struct vnode *v, const char *opstr) -{ - /* not safe, and not really needed to check constant fields */ - /*vfs_biglock_acquire();*/ +void vnode_check(struct vnode *v, const char *opstr) { + /* not safe, and not really needed to check constant fields */ + /*vfs_biglock_acquire();*/ - if (v == NULL) { - panic("vnode_check: vop_%s: null vnode\n", opstr); - } - if (v == (void *)0xdeadbeef) { - panic("vnode_check: vop_%s: deadbeef vnode\n", opstr); - } + if (v == NULL) { + panic("vnode_check: vop_%s: null vnode\n", opstr); + } + if (v == (void *)0xdeadbeef) { + panic("vnode_check: vop_%s: deadbeef vnode\n", opstr); + } - if (v->vn_ops == NULL) { - panic("vnode_check: vop_%s: null ops pointer\n", opstr); - } - if (v->vn_ops == (void *)0xdeadbeef) { - panic("vnode_check: vop_%s: deadbeef ops pointer\n", opstr); - } + if (v->vn_ops == NULL) { + panic("vnode_check: vop_%s: null ops pointer\n", opstr); + } + if (v->vn_ops == (void *)0xdeadbeef) { + panic("vnode_check: vop_%s: deadbeef ops pointer\n", opstr); + } - if (v->vn_ops->vop_magic != VOP_MAGIC) { - panic("vnode_check: vop_%s: ops with bad magic number %lx\n", - opstr, v->vn_ops->vop_magic); - } + if (v->vn_ops->vop_magic != VOP_MAGIC) { + panic("vnode_check: vop_%s: ops with bad magic number %lx\n", opstr, + v->vn_ops->vop_magic); + } - // Device vnodes have null fs pointers. - //if (v->vn_fs == NULL) { - // panic("vnode_check: vop_%s: null fs pointer\n", opstr); - //} - if (v->vn_fs == (void *)0xdeadbeef) { - panic("vnode_check: vop_%s: deadbeef fs pointer\n", opstr); - } + // Device vnodes have null fs pointers. + // if (v->vn_fs == NULL) { + // panic("vnode_check: vop_%s: null fs pointer\n", opstr); + //} + if (v->vn_fs == (void *)0xdeadbeef) { + panic("vnode_check: vop_%s: deadbeef fs pointer\n", opstr); + } - spinlock_acquire(&v->vn_countlock); + spinlock_acquire(&v->vn_countlock); - if (v->vn_refcount < 0) { - panic("vnode_check: vop_%s: negative refcount %d\n", opstr, - v->vn_refcount); - } - else if (v->vn_refcount == 0) { - panic("vnode_check: vop_%s: zero refcount\n", opstr); - } - else if (v->vn_refcount > 0x100000) { - kprintf("vnode_check: vop_%s: warning: large refcount %d\n", - opstr, v->vn_refcount); - } + if (v->vn_refcount < 0) { + panic("vnode_check: vop_%s: negative refcount %d\n", opstr, v->vn_refcount); + } else if (v->vn_refcount == 0) { + panic("vnode_check: vop_%s: zero refcount\n", opstr); + } else if (v->vn_refcount > 0x100000) { + kprintf("vnode_check: vop_%s: warning: large refcount %d\n", opstr, + v->vn_refcount); + } - spinlock_release(&v->vn_countlock); - /*vfs_biglock_release();*/ + spinlock_release(&v->vn_countlock); + /*vfs_biglock_release();*/ } diff --git a/kern/vm/addrspace.c b/kern/vm/addrspace.c index 7da1c95..e8c3aa7 100644 --- a/kern/vm/addrspace.c +++ b/kern/vm/addrspace.c @@ -40,80 +40,70 @@ * used. The cheesy hack versions in dumbvm.c are used instead. */ -struct addrspace * -as_create(void) -{ - struct addrspace *as; +struct addrspace *as_create(void) { + struct addrspace *as; - as = kmalloc(sizeof(struct addrspace)); - if (as == NULL) { - return NULL; - } + as = kmalloc(sizeof(struct addrspace)); + if (as == NULL) { + return NULL; + } - /* - * Initialize as needed. - */ + /* + * Initialize as needed. + */ - return as; + return as; } -int -as_copy(struct addrspace *old, struct addrspace **ret) -{ - struct addrspace *newas; +int as_copy(struct addrspace *old, struct addrspace **ret) { + struct addrspace *newas; - newas = as_create(); - if (newas==NULL) { - return ENOMEM; - } + newas = as_create(); + if (newas == NULL) { + return ENOMEM; + } - /* - * Write this. - */ + /* + * Write this. + */ - (void)old; + (void)old; - *ret = newas; - return 0; + *ret = newas; + return 0; } -void -as_destroy(struct addrspace *as) -{ - /* - * Clean up as needed. - */ +void as_destroy(struct addrspace *as) { + /* + * Clean up as needed. + */ - kfree(as); + kfree(as); } -void -as_activate(void) -{ - struct addrspace *as; +void as_activate(void) { + struct addrspace *as; - as = proc_getas(); - if (as == NULL) { - /* - * Kernel thread without an address space; leave the - * prior address space in place. - */ - return; - } + as = proc_getas(); + if (as == NULL) { + /* + * Kernel thread without an address space; leave the + * prior address space in place. + */ + return; + } - /* - * Write this. - */ + /* + * Write this. + */ } -void -as_deactivate(void) -{ - /* - * Write this. For many designs it won't need to actually do - * anything. See proc.c for an explanation of why it (might) - * be needed. - */ +void as_deactivate(void) { + /* + * Write this. For many designs it won't need to actually do + * anything. See proc.c for an explanation of why it (might) + * be needed. + */ } /* @@ -126,57 +116,48 @@ as_deactivate(void) * moment, these are ignored. When you write the VM system, you may * want to implement them. */ -int -as_define_region(struct addrspace *as, vaddr_t vaddr, size_t memsize, - int readable, int writeable, int executable) -{ - /* - * Write this. - */ +int as_define_region(struct addrspace *as, vaddr_t vaddr, size_t memsize, + int readable, int writeable, int executable) { + /* + * Write this. + */ - (void)as; - (void)vaddr; - (void)memsize; - (void)readable; - (void)writeable; - (void)executable; - return ENOSYS; + (void)as; + (void)vaddr; + (void)memsize; + (void)readable; + (void)writeable; + (void)executable; + return ENOSYS; } -int -as_prepare_load(struct addrspace *as) -{ - /* - * Write this. - */ +int as_prepare_load(struct addrspace *as) { + /* + * Write this. + */ - (void)as; - return 0; + (void)as; + return 0; } -int -as_complete_load(struct addrspace *as) -{ - /* - * Write this. - */ +int as_complete_load(struct addrspace *as) { + /* + * Write this. + */ - (void)as; - return 0; + (void)as; + return 0; } -int -as_define_stack(struct addrspace *as, vaddr_t *stackptr) -{ - /* - * Write this. - */ +int as_define_stack(struct addrspace *as, vaddr_t *stackptr) { + /* + * Write this. + */ - (void)as; + (void)as; - /* Initial user-level stack pointer */ - *stackptr = USERSTACK; + /* Initial user-level stack pointer */ + *stackptr = USERSTACK; - return 0; + return 0; } - diff --git a/kern/vm/copyinout.c b/kern/vm/copyinout.c index 5ca1aa1..df0cd3a 100644 --- a/kern/vm/copyinout.c +++ b/kern/vm/copyinout.c @@ -95,12 +95,7 @@ * We use the C standard function longjmp() to teleport up the call * stack to where setjmp() was called. At that point we return EFAULT. */ -static -void -copyfail(void) -{ - longjmp(curthread->t_machdep.tm_copyjmp, 1); -} +static void copyfail(void) { longjmp(curthread->t_machdep.tm_copyjmp, 1); } /* * Memory region check function. This checks to make sure the block of @@ -113,33 +108,30 @@ copyfail(void) * * Assumes userspace runs from 0 through USERSPACETOP-1. */ -static -int -copycheck(const_userptr_t userptr, size_t len, size_t *stoplen) -{ - vaddr_t bot, top; +static int copycheck(const_userptr_t userptr, size_t len, size_t *stoplen) { + vaddr_t bot, top; - *stoplen = len; + *stoplen = len; - bot = (vaddr_t) userptr; - top = bot+len-1; + bot = (vaddr_t)userptr; + top = bot + len - 1; - if (top < bot) { - /* addresses wrapped around */ - return EFAULT; - } + if (top < bot) { + /* addresses wrapped around */ + return EFAULT; + } - if (bot >= USERSPACETOP) { - /* region is within the kernel */ - return EFAULT; - } + if (bot >= USERSPACETOP) { + /* region is within the kernel */ + return EFAULT; + } - if (top >= USERSPACETOP) { - /* region overlaps the kernel. adjust the max length. */ - *stoplen = USERSPACETOP - bot; - } + if (top >= USERSPACETOP) { + /* region overlaps the kernel. adjust the max length. */ + *stoplen = USERSPACETOP - bot; + } - return 0; + return 0; } /* @@ -149,33 +141,31 @@ copycheck(const_userptr_t userptr, size_t len, size_t *stoplen) * to kernel address DEST. We can use memcpy because it's protected by * the tm_badfaultfunc/copyfail logic. */ -int -copyin(const_userptr_t usersrc, void *dest, size_t len) -{ - int result; - size_t stoplen; +int copyin(const_userptr_t usersrc, void *dest, size_t len) { + int result; + size_t stoplen; - result = copycheck(usersrc, len, &stoplen); - if (result) { - return result; - } - if (stoplen != len) { - /* Single block, can't legally truncate it. */ - return EFAULT; - } + result = copycheck(usersrc, len, &stoplen); + if (result) { + return result; + } + if (stoplen != len) { + /* Single block, can't legally truncate it. */ + return EFAULT; + } - curthread->t_machdep.tm_badfaultfunc = copyfail; + curthread->t_machdep.tm_badfaultfunc = copyfail; - result = setjmp(curthread->t_machdep.tm_copyjmp); - if (result) { - curthread->t_machdep.tm_badfaultfunc = NULL; - return EFAULT; - } + result = setjmp(curthread->t_machdep.tm_copyjmp); + if (result) { + curthread->t_machdep.tm_badfaultfunc = NULL; + return EFAULT; + } - memcpy(dest, (const void *)usersrc, len); + memcpy(dest, (const void *)usersrc, len); - curthread->t_machdep.tm_badfaultfunc = NULL; - return 0; + curthread->t_machdep.tm_badfaultfunc = NULL; + return 0; } /* @@ -185,33 +175,31 @@ copyin(const_userptr_t usersrc, void *dest, size_t len) * user-level address USERDEST. We can use memcpy because it's * protected by the tm_badfaultfunc/copyfail logic. */ -int -copyout(const void *src, userptr_t userdest, size_t len) -{ - int result; - size_t stoplen; +int copyout(const void *src, userptr_t userdest, size_t len) { + int result; + size_t stoplen; - result = copycheck(userdest, len, &stoplen); - if (result) { - return result; - } - if (stoplen != len) { - /* Single block, can't legally truncate it. */ - return EFAULT; - } + result = copycheck(userdest, len, &stoplen); + if (result) { + return result; + } + if (stoplen != len) { + /* Single block, can't legally truncate it. */ + return EFAULT; + } - curthread->t_machdep.tm_badfaultfunc = copyfail; + curthread->t_machdep.tm_badfaultfunc = copyfail; - result = setjmp(curthread->t_machdep.tm_copyjmp); - if (result) { - curthread->t_machdep.tm_badfaultfunc = NULL; - return EFAULT; - } + result = setjmp(curthread->t_machdep.tm_copyjmp); + if (result) { + curthread->t_machdep.tm_badfaultfunc = NULL; + return EFAULT; + } - memcpy((void *)userdest, src, len); + memcpy((void *)userdest, src, len); - curthread->t_machdep.tm_badfaultfunc = NULL; - return 0; + curthread->t_machdep.tm_badfaultfunc = NULL; + return 0; } /* @@ -230,28 +218,25 @@ copyout(const void *src, userptr_t userdest, size_t len) * userspace. Thus in the latter case we return EFAULT, not * ENAMETOOLONG. */ -static -int -copystr(char *dest, const char *src, size_t maxlen, size_t stoplen, - size_t *gotlen) -{ - size_t i; +static int copystr(char *dest, const char *src, size_t maxlen, size_t stoplen, + size_t *gotlen) { + size_t i; - for (i=0; it_machdep.tm_badfaultfunc = copyfail; + curthread->t_machdep.tm_badfaultfunc = copyfail; - result = setjmp(curthread->t_machdep.tm_copyjmp); - if (result) { - curthread->t_machdep.tm_badfaultfunc = NULL; - return EFAULT; - } + result = setjmp(curthread->t_machdep.tm_copyjmp); + if (result) { + curthread->t_machdep.tm_badfaultfunc = NULL; + return EFAULT; + } - result = copystr(dest, (const char *)usersrc, len, stoplen, actual); + result = copystr(dest, (const char *)usersrc, len, stoplen, actual); - curthread->t_machdep.tm_badfaultfunc = NULL; - return result; + curthread->t_machdep.tm_badfaultfunc = NULL; + return result; } /* @@ -295,27 +278,26 @@ copyinstr(const_userptr_t usersrc, char *dest, size_t len, size_t *actual) * logic to protect against invalid addresses supplied by a user * process. */ -int -copyoutstr(const char *src, userptr_t userdest, size_t len, size_t *actual) -{ - int result; - size_t stoplen; +int copyoutstr(const char *src, userptr_t userdest, size_t len, + size_t *actual) { + int result; + size_t stoplen; - result = copycheck(userdest, len, &stoplen); - if (result) { - return result; - } + result = copycheck(userdest, len, &stoplen); + if (result) { + return result; + } - curthread->t_machdep.tm_badfaultfunc = copyfail; + curthread->t_machdep.tm_badfaultfunc = copyfail; - result = setjmp(curthread->t_machdep.tm_copyjmp); - if (result) { - curthread->t_machdep.tm_badfaultfunc = NULL; - return EFAULT; - } + result = setjmp(curthread->t_machdep.tm_copyjmp); + if (result) { + curthread->t_machdep.tm_badfaultfunc = NULL; + return EFAULT; + } - result = copystr((char *)userdest, src, len, stoplen, actual); + result = copystr((char *)userdest, src, len, stoplen, actual); - curthread->t_machdep.tm_badfaultfunc = NULL; - return result; + curthread->t_machdep.tm_badfaultfunc = NULL; + return result; } diff --git a/kern/vm/kmalloc.c b/kern/vm/kmalloc.c index b8a1204..0aad387 100644 --- a/kern/vm/kmalloc.c +++ b/kern/vm/kmalloc.c @@ -36,20 +36,16 @@ * Kernel malloc. */ - /* * Fill a block with 0xdeadbeef. */ -static -void -fill_deadbeef(void *vptr, size_t len) -{ - uint32_t *ptr = vptr; - size_t i; +static void fill_deadbeef(void *vptr, size_t len) { + uint32_t *ptr = vptr; + size_t i; - for (i=0; ipageaddr_and_blocktype & PAGE_FRAME) +#define PR_PAGEADDR(pr) ((pr)->pageaddr_and_blocktype & PAGE_FRAME) #define PR_BLOCKTYPE(pr) ((pr)->pageaddr_and_blocktype & ~PAGE_FRAME) -#define MKPAB(pa, blk) (((pa)&PAGE_FRAME) | ((blk) & ~PAGE_FRAME)) +#define MKPAB(pa, blk) (((pa) & PAGE_FRAME) | ((blk) & ~PAGE_FRAME)) //////////////////////////////////////// @@ -181,7 +177,7 @@ static struct spinlock kmalloc_spinlock = SPINLOCK_INITIALIZER; #define NPAGEREFS_PER_PAGE (PAGE_SIZE / sizeof(struct pageref)) struct pagerefpage { - struct pageref refs[NPAGEREFS_PER_PAGE]; + struct pageref refs[NPAGEREFS_PER_PAGE]; }; /* @@ -192,9 +188,9 @@ struct pagerefpage { #define INUSE_WORDS (NPAGEREFS_PER_PAGE / 32) struct kheap_root { - struct pagerefpage *page; - uint32_t pagerefs_inuse[INUSE_WORDS]; - unsigned numinuse; + struct pagerefpage *page; + uint32_t pagerefs_inuse[INUSE_WORDS]; + unsigned numinuse; }; /* @@ -215,125 +211,116 @@ static struct kheap_root kheaproots[NUM_PAGEREFPAGES]; /* * Allocate a page to hold pagerefs. */ -static -void -allocpagerefpage(struct kheap_root *root) -{ - vaddr_t va; +static void allocpagerefpage(struct kheap_root *root) { + vaddr_t va; - KASSERT(root->page == NULL); + KASSERT(root->page == NULL); - /* - * We release the spinlock while calling alloc_kpages. This - * avoids deadlock if alloc_kpages needs to come back here. - * Note that this means things can change behind our back... - */ - spinlock_release(&kmalloc_spinlock); - va = alloc_kpages(1); - spinlock_acquire(&kmalloc_spinlock); - if (va == 0) { - kprintf("kmalloc: Couldn't get a pageref page\n"); - return; - } - KASSERT(va % PAGE_SIZE == 0); + /* + * We release the spinlock while calling alloc_kpages. This + * avoids deadlock if alloc_kpages needs to come back here. + * Note that this means things can change behind our back... + */ + spinlock_release(&kmalloc_spinlock); + va = alloc_kpages(1); + spinlock_acquire(&kmalloc_spinlock); + if (va == 0) { + kprintf("kmalloc: Couldn't get a pageref page\n"); + return; + } + KASSERT(va % PAGE_SIZE == 0); - if (root->page != NULL) { - /* Oops, somebody else allocated it. */ - spinlock_release(&kmalloc_spinlock); - free_kpages(va); - spinlock_acquire(&kmalloc_spinlock); - /* Once allocated it isn't ever freed. */ - KASSERT(root->page != NULL); - return; - } + if (root->page != NULL) { + /* Oops, somebody else allocated it. */ + spinlock_release(&kmalloc_spinlock); + free_kpages(va); + spinlock_acquire(&kmalloc_spinlock); + /* Once allocated it isn't ever freed. */ + KASSERT(root->page != NULL); + return; + } - root->page = (struct pagerefpage *)va; + root->page = (struct pagerefpage *)va; } /* * Allocate a pageref structure. */ -static -struct pageref * -allocpageref(void) -{ - unsigned i,j; - uint32_t k; - unsigned whichroot; - struct kheap_root *root; +static struct pageref *allocpageref(void) { + unsigned i, j; + uint32_t k; + unsigned whichroot; + struct kheap_root *root; - for (whichroot=0; whichroot < NUM_PAGEREFPAGES; whichroot++) { - root = &kheaproots[whichroot]; - if (root->numinuse >= NPAGEREFS_PER_PAGE) { - continue; - } + for (whichroot = 0; whichroot < NUM_PAGEREFPAGES; whichroot++) { + root = &kheaproots[whichroot]; + if (root->numinuse >= NPAGEREFS_PER_PAGE) { + continue; + } - /* - * This should probably not be a linear search. - */ - for (i=0; ipagerefs_inuse[i]==0xffffffff) { - /* full */ - continue; - } - for (k=1,j=0; k!=0; k<<=1,j++) { - if ((root->pagerefs_inuse[i] & k)==0) { - root->pagerefs_inuse[i] |= k; - root->numinuse++; - if (root->page == NULL) { - allocpagerefpage(root); - } - if (root->page == NULL) { - return NULL; - } - return &root->page->refs[i*32 + j]; - } - } - KASSERT(0); - } - } + /* + * This should probably not be a linear search. + */ + for (i = 0; i < INUSE_WORDS; i++) { + if (root->pagerefs_inuse[i] == 0xffffffff) { + /* full */ + continue; + } + for (k = 1, j = 0; k != 0; k <<= 1, j++) { + if ((root->pagerefs_inuse[i] & k) == 0) { + root->pagerefs_inuse[i] |= k; + root->numinuse++; + if (root->page == NULL) { + allocpagerefpage(root); + } + if (root->page == NULL) { + return NULL; + } + return &root->page->refs[i * 32 + j]; + } + } + KASSERT(0); + } + } - /* ran out */ - return NULL; + /* ran out */ + return NULL; } /* * Release a pageref structure. */ -static -void -freepageref(struct pageref *p) -{ - size_t i, j; - uint32_t k; - unsigned whichroot; - struct kheap_root *root; - struct pagerefpage *page; +static void freepageref(struct pageref *p) { + size_t i, j; + uint32_t k; + unsigned whichroot; + struct kheap_root *root; + struct pagerefpage *page; - for (whichroot=0; whichroot < NUM_PAGEREFPAGES; whichroot++) { - root = &kheaproots[whichroot]; + for (whichroot = 0; whichroot < NUM_PAGEREFPAGES; whichroot++) { + root = &kheaproots[whichroot]; - page = root->page; - if (page == NULL) { - KASSERT(root->numinuse == 0); - continue; - } + page = root->page; + if (page == NULL) { + KASSERT(root->numinuse == 0); + continue; + } - j = p-page->refs; - /* note: j is unsigned, don't test < 0 */ - if (j < NPAGEREFS_PER_PAGE) { - /* on this page */ - i = j/32; - k = ((uint32_t)1) << (j%32); - KASSERT((root->pagerefs_inuse[i] & k) != 0); - root->pagerefs_inuse[i] &= ~k; - KASSERT(root->numinuse > 0); - root->numinuse--; - return; - } - } - /* pageref wasn't on any of the pages */ - KASSERT(0); + j = p - page->refs; + /* note: j is unsigned, don't test < 0 */ + if (j < NPAGEREFS_PER_PAGE) { + /* on this page */ + i = j / 32; + k = ((uint32_t)1) << (j % 32); + KASSERT((root->pagerefs_inuse[i] & k) != 0); + root->pagerefs_inuse[i] &= ~k; + KASSERT(root->numinuse > 0); + root->numinuse--; + return; + } + } + /* pageref wasn't on any of the pages */ + KASSERT(0); } //////////////////////////////////////// @@ -365,74 +352,70 @@ static struct pageref *allbase; /* * Set up the guard values in a block we're about to return. */ -static -void * -establishguardband(void *block, size_t clientsize, size_t blocksize) -{ - vaddr_t lowguard, lowsize, data, enddata, highguard, highsize, i; +static void *establishguardband(void *block, size_t clientsize, + size_t blocksize) { + vaddr_t lowguard, lowsize, data, enddata, highguard, highsize, i; - KASSERT(clientsize + GUARD_OVERHEAD <= blocksize); - KASSERT(clientsize < 65536U); + KASSERT(clientsize + GUARD_OVERHEAD <= blocksize); + KASSERT(clientsize < 65536U); - lowguard = (vaddr_t)block; - lowsize = lowguard + 2; - data = lowsize + 2; - enddata = data + clientsize; - highguard = lowguard + blocksize - 4; - highsize = highguard + 2; + lowguard = (vaddr_t)block; + lowsize = lowguard + 2; + data = lowsize + 2; + enddata = data + clientsize; + highguard = lowguard + blocksize - 4; + highsize = highguard + 2; - *(uint16_t *)lowguard = GUARD_HALFWORD; - *(uint16_t *)lowsize = clientsize; - for (i=data; i smallerblocksize); - KASSERT(clientsize + GUARD_OVERHEAD <= blocksize); - enddata = data + clientsize; - for (i=enddata; i smallerblocksize); + KASSERT(clientsize + GUARD_OVERHEAD <= blocksize); + enddata = data + clientsize; + for (i = enddata; i < highguard; i++) { + KASSERT(*(uint8_t *)i == GUARD_FILLBYTE); + } } #else /* not GUARDS */ @@ -457,16 +440,13 @@ checkguardband(vaddr_t blockaddr, size_t smallerblocksize, size_t blocksize) * The first word of the block is a freelist pointer and should not be * deadbeef; the rest of the block should be only deadbeef. */ -static -void -checkdeadbeef(void *block, size_t blocksize) -{ - uint32_t *ptr = block; - size_t i; +static void checkdeadbeef(void *block, size_t blocksize) { + uint32_t *ptr = block; + size_t i; - for (i=1; i < blocksize/sizeof(uint32_t); i++) { - KASSERT(ptr[i] == 0xdeadbeef); - } + for (i = 1; i < blocksize / sizeof(uint32_t); i++) { + KASSERT(ptr[i] == 0xdeadbeef); + } } #endif /* CHECKBEEF */ @@ -490,80 +470,76 @@ checkdeadbeef(void *block, size_t blocksize) * assertion as a bit in isfree is set twice; if not, a circular * freelist will cause an infinite loop. */ -static -void -checksubpage(struct pageref *pr) -{ - vaddr_t prpage, fla; - struct freelist *fl; - int blktype; - int nfree=0; - size_t blocksize; +static void checksubpage(struct pageref *pr) { + vaddr_t prpage, fla; + struct freelist *fl; + int blktype; + int nfree = 0; + size_t blocksize; #ifdef CHECKGUARDS - const unsigned maxblocks = PAGE_SIZE / SMALLEST_SUBPAGE_SIZE; - const unsigned numfreewords = DIVROUNDUP(maxblocks, 32); - uint32_t isfree[numfreewords], mask; - unsigned numblocks, blocknum, i; - size_t smallerblocksize; + const unsigned maxblocks = PAGE_SIZE / SMALLEST_SUBPAGE_SIZE; + const unsigned numfreewords = DIVROUNDUP(maxblocks, 32); + uint32_t isfree[numfreewords], mask; + unsigned numblocks, blocknum, i; + size_t smallerblocksize; #endif - KASSERT(spinlock_do_i_hold(&kmalloc_spinlock)); + KASSERT(spinlock_do_i_hold(&kmalloc_spinlock)); - if (pr->freelist_offset == INVALID_OFFSET) { - KASSERT(pr->nfree==0); - return; - } + if (pr->freelist_offset == INVALID_OFFSET) { + KASSERT(pr->nfree == 0); + return; + } - prpage = PR_PAGEADDR(pr); - blktype = PR_BLOCKTYPE(pr); - KASSERT(blktype >= 0 && blktype < NSIZES); - blocksize = sizes[blktype]; + prpage = PR_PAGEADDR(pr); + blktype = PR_BLOCKTYPE(pr); + KASSERT(blktype >= 0 && blktype < NSIZES); + blocksize = sizes[blktype]; #ifdef CHECKGUARDS - smallerblocksize = blktype > 0 ? sizes[blktype - 1] : 0; - for (i=0; i 0 ? sizes[blktype - 1] : 0; + for (i = 0; i < numfreewords; i++) { + isfree[i] = 0; + } #endif #ifdef __mips__ - KASSERT(prpage >= MIPS_KSEG0); - KASSERT(prpage < MIPS_KSEG1); + KASSERT(prpage >= MIPS_KSEG0); + KASSERT(prpage < MIPS_KSEG1); #endif - KASSERT(pr->freelist_offset < PAGE_SIZE); - KASSERT(pr->freelist_offset % blocksize == 0); + KASSERT(pr->freelist_offset < PAGE_SIZE); + KASSERT(pr->freelist_offset % blocksize == 0); - fla = prpage + pr->freelist_offset; - fl = (struct freelist *)fla; + fla = prpage + pr->freelist_offset; + fl = (struct freelist *)fla; - for (; fl != NULL; fl = fl->next) { - fla = (vaddr_t)fl; - KASSERT(fla >= prpage && fla < prpage + PAGE_SIZE); - KASSERT((fla-prpage) % blocksize == 0); + for (; fl != NULL; fl = fl->next) { + fla = (vaddr_t)fl; + KASSERT(fla >= prpage && fla < prpage + PAGE_SIZE); + KASSERT((fla - prpage) % blocksize == 0); #ifdef CHECKBEEF - checkdeadbeef(fl, blocksize); + checkdeadbeef(fl, blocksize); #endif #ifdef CHECKGUARDS - blocknum = (fla-prpage) / blocksize; - mask = 1U << (blocknum % 32); - KASSERT((isfree[blocknum / 32] & mask) == 0); - isfree[blocknum / 32] |= mask; + blocknum = (fla - prpage) / blocksize; + mask = 1U << (blocknum % 32); + KASSERT((isfree[blocknum / 32] & mask) == 0); + isfree[blocknum / 32] |= mask; #endif - KASSERT(fl->next != fl); - nfree++; - } - KASSERT(nfree==pr->nfree); + KASSERT(fl->next != fl); + nfree++; + } + KASSERT(nfree == pr->nfree); #ifdef CHECKGUARDS - numblocks = PAGE_SIZE / blocksize; - for (i=0; inext_samesize) { - checksubpage(pr); - KASSERT(sc < TOTAL_PAGEREFS); - sc++; - } - } + for (i = 0; i < NSIZES; i++) { + for (pr = sizebases[i]; pr != NULL; pr = pr->next_samesize) { + checksubpage(pr); + KASSERT(sc < TOTAL_PAGEREFS); + sc++; + } + } - for (pr = allbase; pr != NULL; pr = pr->next_all) { - checksubpage(pr); - KASSERT(ac < TOTAL_PAGEREFS); - ac++; - } + for (pr = allbase; pr != NULL; pr = pr->next_all) { + checksubpage(pr); + KASSERT(ac < TOTAL_PAGEREFS); + ac++; + } - KASSERT(sc==ac); + KASSERT(sc == ac); } #else #define checksubpages() @@ -613,8 +586,8 @@ checksubpages(void) #define LABEL_OVERHEAD LABEL_PTROFFSET struct malloclabel { - vaddr_t label; - unsigned generation; + vaddr_t label; + unsigned generation; }; static unsigned mallocgeneration; @@ -622,73 +595,64 @@ static unsigned mallocgeneration; /* * Label a block of memory. */ -static -void * -establishlabel(void *block, vaddr_t label) -{ - struct malloclabel *ml; +static void *establishlabel(void *block, vaddr_t label) { + struct malloclabel *ml; - ml = block; - ml->label = label; - ml->generation = mallocgeneration; - ml++; - return ml; + ml = block; + ml->label = label; + ml->generation = mallocgeneration; + ml++; + return ml; } -static -void -dump_subpage(struct pageref *pr, unsigned generation) -{ - unsigned blocksize = sizes[PR_BLOCKTYPE(pr)]; - unsigned numblocks = PAGE_SIZE / blocksize; - unsigned numfreewords = DIVROUNDUP(numblocks, 32); - uint32_t isfree[numfreewords], mask; - vaddr_t prpage; - struct freelist *fl; - vaddr_t blockaddr; - struct malloclabel *ml; - unsigned i; +static void dump_subpage(struct pageref *pr, unsigned generation) { + unsigned blocksize = sizes[PR_BLOCKTYPE(pr)]; + unsigned numblocks = PAGE_SIZE / blocksize; + unsigned numfreewords = DIVROUNDUP(numblocks, 32); + uint32_t isfree[numfreewords], mask; + vaddr_t prpage; + struct freelist *fl; + vaddr_t blockaddr; + struct malloclabel *ml; + unsigned i; - for (i=0; ifreelist_offset); - for (; fl != NULL; fl = fl->next) { - i = ((vaddr_t)fl - prpage) / blocksize; - mask = 1U << (i % 32); - isfree[i / 32] |= mask; - } + prpage = PR_PAGEADDR(pr); + fl = (struct freelist *)(prpage + pr->freelist_offset); + for (; fl != NULL; fl = fl->next) { + i = ((vaddr_t)fl - prpage) / blocksize; + mask = 1U << (i % 32); + isfree[i / 32] |= mask; + } - for (i=0; igeneration != generation) { - continue; - } - kprintf("%5zu bytes at %p, allocated at %p\n", - blocksize, (void *)blockaddr, (void *)ml->label); - } + for (i = 0; i < numblocks; i++) { + mask = 1U << (i % 32); + if (isfree[i / 32] & mask) { + continue; + } + blockaddr = prpage + i * blocksize; + ml = (struct malloclabel *)blockaddr; + if (ml->generation != generation) { + continue; + } + kprintf("%5zu bytes at %p, allocated at %p\n", blocksize, (void *)blockaddr, + (void *)ml->label); + } } -static -void -dump_subpages(unsigned generation) -{ - struct pageref *pr; - int i; +static void dump_subpages(unsigned generation) { + struct pageref *pr; + int i; - kprintf("Remaining allocations from generation %u:\n", generation); - for (i=0; inext_samesize) { - dump_subpage(pr, generation); - } - } + kprintf("Remaining allocations from generation %u:\n", generation); + for (i = 0; i < NSIZES; i++) { + for (pr = sizebases[i]; pr != NULL; pr = pr->next_samesize) { + dump_subpage(pr, generation); + } + } } #else @@ -697,43 +661,37 @@ dump_subpages(unsigned generation) #endif /* LABELS */ -void -kheap_nextgeneration(void) -{ +void kheap_nextgeneration(void) { #ifdef LABELS - spinlock_acquire(&kmalloc_spinlock); - mallocgeneration++; - spinlock_release(&kmalloc_spinlock); + spinlock_acquire(&kmalloc_spinlock); + mallocgeneration++; + spinlock_release(&kmalloc_spinlock); #endif } -void -kheap_dump(void) -{ +void kheap_dump(void) { #ifdef LABELS - /* print the whole thing with interrupts off */ - spinlock_acquire(&kmalloc_spinlock); - dump_subpages(mallocgeneration); - spinlock_release(&kmalloc_spinlock); + /* print the whole thing with interrupts off */ + spinlock_acquire(&kmalloc_spinlock); + dump_subpages(mallocgeneration); + spinlock_release(&kmalloc_spinlock); #else - kprintf("Enable LABELS in kmalloc.c to use this functionality.\n"); + kprintf("Enable LABELS in kmalloc.c to use this functionality.\n"); #endif } -void -kheap_dumpall(void) -{ +void kheap_dumpall(void) { #ifdef LABELS - unsigned i; + unsigned i; - /* print the whole thing with interrupts off */ - spinlock_acquire(&kmalloc_spinlock); - for (i=0; i<=mallocgeneration; i++) { - dump_subpages(i); - } - spinlock_release(&kmalloc_spinlock); + /* print the whole thing with interrupts off */ + spinlock_acquire(&kmalloc_spinlock); + for (i = 0; i <= mallocgeneration; i++) { + dump_subpages(i); + } + spinlock_release(&kmalloc_spinlock); #else - kprintf("Enable LABELS in kmalloc.c to use this functionality.\n"); + kprintf("Enable LABELS in kmalloc.c to use this functionality.\n"); #endif } @@ -742,76 +700,70 @@ kheap_dumpall(void) /* * Print the allocated/freed map of a single kernel heap page. */ -static -void -subpage_stats(struct pageref *pr) -{ - vaddr_t prpage, fla; - struct freelist *fl; - int blktype; - unsigned i, n, index; - uint32_t freemap[PAGE_SIZE / (SMALLEST_SUBPAGE_SIZE*32)]; +static void subpage_stats(struct pageref *pr) { + vaddr_t prpage, fla; + struct freelist *fl; + int blktype; + unsigned i, n, index; + uint32_t freemap[PAGE_SIZE / (SMALLEST_SUBPAGE_SIZE * 32)]; - checksubpage(pr); - KASSERT(spinlock_do_i_hold(&kmalloc_spinlock)); + checksubpage(pr); + KASSERT(spinlock_do_i_hold(&kmalloc_spinlock)); - /* clear freemap[] */ - for (i=0; i= 0 && blktype < NSIZES); + prpage = PR_PAGEADDR(pr); + blktype = PR_BLOCKTYPE(pr); + KASSERT(blktype >= 0 && blktype < NSIZES); - /* compute how many bits we need in freemap and assert we fit */ - n = PAGE_SIZE / sizes[blktype]; - KASSERT(n <= 32 * ARRAYCOUNT(freemap)); + /* compute how many bits we need in freemap and assert we fit */ + n = PAGE_SIZE / sizes[blktype]; + KASSERT(n <= 32 * ARRAYCOUNT(freemap)); - if (pr->freelist_offset != INVALID_OFFSET) { - fla = prpage + pr->freelist_offset; - fl = (struct freelist *)fla; + if (pr->freelist_offset != INVALID_OFFSET) { + fla = prpage + pr->freelist_offset; + fl = (struct freelist *)fla; - for (; fl != NULL; fl = fl->next) { - fla = (vaddr_t)fl; - index = (fla-prpage) / sizes[blktype]; - KASSERT(indexnext) { + fla = (vaddr_t)fl; + index = (fla - prpage) / sizes[blktype]; + KASSERT(index < n); + freemap[index / 32] |= (1 << (index % 32)); + } + } - kprintf("at 0x%08lx: size %-4lu %u/%u free\n", - (unsigned long)prpage, (unsigned long) sizes[blktype], - (unsigned) pr->nfree, n); - kprintf(" "); - for (i=0; infree, n); + kprintf(" "); + for (i = 0; i < n; i++) { + int val = (freemap[i / 32] & (1 << (i % 32))) != 0; + kprintf("%c", val ? '.' : '*'); + if (i % 64 == 63 && i < n - 1) { + kprintf("\n "); + } + } + kprintf("\n"); } /* * Print the whole heap. */ -void -kheap_printstats(void) -{ - struct pageref *pr; +void kheap_printstats(void) { + struct pageref *pr; - /* print the whole thing with interrupts off */ - spinlock_acquire(&kmalloc_spinlock); + /* print the whole thing with interrupts off */ + spinlock_acquire(&kmalloc_spinlock); - kprintf("Subpage allocator status:\n"); + kprintf("Subpage allocator status:\n"); - for (pr = allbase; pr != NULL; pr = pr->next_all) { - subpage_stats(pr); - } + for (pr = allbase; pr != NULL; pr = pr->next_all) { + subpage_stats(pr); + } - spinlock_release(&kmalloc_spinlock); + spinlock_release(&kmalloc_spinlock); } //////////////////////////////////////// @@ -819,344 +771,330 @@ kheap_printstats(void) /* * Remove a pageref from both lists that it's on. */ -static -void -remove_lists(struct pageref *pr, int blktype) -{ - struct pageref **guy; +static void remove_lists(struct pageref *pr, int blktype) { + struct pageref **guy; - KASSERT(blktype>=0 && blktype= 0 && blktype < NSIZES); - for (guy = &sizebases[blktype]; *guy; guy = &(*guy)->next_samesize) { - checksubpage(*guy); - if (*guy == pr) { - *guy = pr->next_samesize; - break; - } - } + for (guy = &sizebases[blktype]; *guy; guy = &(*guy)->next_samesize) { + checksubpage(*guy); + if (*guy == pr) { + *guy = pr->next_samesize; + break; + } + } - for (guy = &allbase; *guy; guy = &(*guy)->next_all) { - checksubpage(*guy); - if (*guy == pr) { - *guy = pr->next_all; - break; - } - } + for (guy = &allbase; *guy; guy = &(*guy)->next_all) { + checksubpage(*guy); + if (*guy == pr) { + *guy = pr->next_all; + break; + } + } } /* * Given a requested client size, return the block type, that is, the * index into the sizes[] array for the block size to use. */ -static -inline -int blocktype(size_t clientsz) -{ - unsigned i; - for (i=0; inext_samesize) { + for (pr = sizebases[blktype]; pr != NULL; pr = pr->next_samesize) { - /* check for corruption */ - KASSERT(PR_BLOCKTYPE(pr) == blktype); - checksubpage(pr); + /* check for corruption */ + KASSERT(PR_BLOCKTYPE(pr) == blktype); + checksubpage(pr); - if (pr->nfree > 0) { + if (pr->nfree > 0) { - doalloc: /* comes here after getting a whole fresh page */ + doalloc: /* comes here after getting a whole fresh page */ - KASSERT(pr->freelist_offset < PAGE_SIZE); - prpage = PR_PAGEADDR(pr); - fla = prpage + pr->freelist_offset; - fl = (struct freelist *)fla; + KASSERT(pr->freelist_offset < PAGE_SIZE); + prpage = PR_PAGEADDR(pr); + fla = prpage + pr->freelist_offset; + fl = (struct freelist *)fla; - retptr = fl; - fl = fl->next; - pr->nfree--; + retptr = fl; + fl = fl->next; + pr->nfree--; - if (fl != NULL) { - KASSERT(pr->nfree > 0); - fla = (vaddr_t)fl; - KASSERT(fla - prpage < PAGE_SIZE); - pr->freelist_offset = fla - prpage; - } - else { - KASSERT(pr->nfree == 0); - pr->freelist_offset = INVALID_OFFSET; - } + if (fl != NULL) { + KASSERT(pr->nfree > 0); + fla = (vaddr_t)fl; + KASSERT(fla - prpage < PAGE_SIZE); + pr->freelist_offset = fla - prpage; + } else { + KASSERT(pr->nfree == 0); + pr->freelist_offset = INVALID_OFFSET; + } #ifdef GUARDS - retptr = establishguardband(retptr, clientsz, sz); + retptr = establishguardband(retptr, clientsz, sz); #endif #ifdef LABELS - retptr = establishlabel(retptr, label); + retptr = establishlabel(retptr, label); #endif - checksubpages(); + checksubpages(); - spinlock_release(&kmalloc_spinlock); - return retptr; - } - } + spinlock_release(&kmalloc_spinlock); + return retptr; + } + } - /* - * No page of the right size available. - * Make a new one. - * - * We release the spinlock while calling alloc_kpages. This - * avoids deadlock if alloc_kpages needs to come back here. - * Note that this means things can change behind our back... - */ + /* + * No page of the right size available. + * Make a new one. + * + * We release the spinlock while calling alloc_kpages. This + * avoids deadlock if alloc_kpages needs to come back here. + * Note that this means things can change behind our back... + */ - spinlock_release(&kmalloc_spinlock); - prpage = alloc_kpages(1); - if (prpage==0) { - /* Out of memory. */ - kprintf("kmalloc: Subpage allocator couldn't get a page\n"); - return NULL; - } - KASSERT(prpage % PAGE_SIZE == 0); + spinlock_release(&kmalloc_spinlock); + prpage = alloc_kpages(1); + if (prpage == 0) { + /* Out of memory. */ + kprintf("kmalloc: Subpage allocator couldn't get a page\n"); + return NULL; + } + KASSERT(prpage % PAGE_SIZE == 0); #ifdef CHECKBEEF - /* deadbeef the whole page, as it probably starts zeroed */ - fill_deadbeef((void *)prpage, PAGE_SIZE); + /* deadbeef the whole page, as it probably starts zeroed */ + fill_deadbeef((void *)prpage, PAGE_SIZE); #endif - spinlock_acquire(&kmalloc_spinlock); + spinlock_acquire(&kmalloc_spinlock); - pr = allocpageref(); - if (pr==NULL) { - /* Couldn't allocate accounting space for the new page. */ - spinlock_release(&kmalloc_spinlock); - free_kpages(prpage); - kprintf("kmalloc: Subpage allocator couldn't get pageref\n"); - return NULL; - } + pr = allocpageref(); + if (pr == NULL) { + /* Couldn't allocate accounting space for the new page. */ + spinlock_release(&kmalloc_spinlock); + free_kpages(prpage); + kprintf("kmalloc: Subpage allocator couldn't get pageref\n"); + return NULL; + } - pr->pageaddr_and_blocktype = MKPAB(prpage, blktype); - pr->nfree = PAGE_SIZE / sizes[blktype]; + pr->pageaddr_and_blocktype = MKPAB(prpage, blktype); + pr->nfree = PAGE_SIZE / sizes[blktype]; - /* - * Note: fl is volatile because the MIPS toolchain we were - * using in spring 2001 attempted to optimize this loop and - * blew it. Making fl volatile inhibits the optimization. - */ + /* + * Note: fl is volatile because the MIPS toolchain we were + * using in spring 2001 attempted to optimize this loop and + * blew it. Making fl volatile inhibits the optimization. + */ - fla = prpage; - fl = (struct freelist *)fla; - fl->next = NULL; - for (i=1; infree; i++) { - fl = (struct freelist *)(fla + i*sizes[blktype]); - fl->next = (struct freelist *)(fla + (i-1)*sizes[blktype]); - KASSERT(fl != fl->next); - } - fla = (vaddr_t) fl; - pr->freelist_offset = fla - prpage; - KASSERT(pr->freelist_offset == (pr->nfree-1)*sizes[blktype]); + fla = prpage; + fl = (struct freelist *)fla; + fl->next = NULL; + for (i = 1; i < pr->nfree; i++) { + fl = (struct freelist *)(fla + i * sizes[blktype]); + fl->next = (struct freelist *)(fla + (i - 1) * sizes[blktype]); + KASSERT(fl != fl->next); + } + fla = (vaddr_t)fl; + pr->freelist_offset = fla - prpage; + KASSERT(pr->freelist_offset == (pr->nfree - 1) * sizes[blktype]); - pr->next_samesize = sizebases[blktype]; - sizebases[blktype] = pr; + pr->next_samesize = sizebases[blktype]; + sizebases[blktype] = pr; - pr->next_all = allbase; - allbase = pr; + pr->next_all = allbase; + allbase = pr; - /* This is kind of cheesy, but avoids duplicating the alloc code. */ - goto doalloc; + /* This is kind of cheesy, but avoids duplicating the alloc code. */ + goto doalloc; } /* * Free a pointer previously returned from subpage_kmalloc. If the * pointer is not on any heap page we recognize, return -1. */ -static -int -subpage_kfree(void *ptr) -{ - int blktype; // index into sizes[] that we're using - vaddr_t ptraddr; // same as ptr - struct pageref *pr; // pageref for page we're freeing in - vaddr_t prpage; // PR_PAGEADDR(pr) - vaddr_t fla; // free list entry address - struct freelist *fl; // free list entry - vaddr_t offset; // offset into page +static int subpage_kfree(void *ptr) { + int blktype; // index into sizes[] that we're using + vaddr_t ptraddr; // same as ptr + struct pageref *pr; // pageref for page we're freeing in + vaddr_t prpage; // PR_PAGEADDR(pr) + vaddr_t fla; // free list entry address + struct freelist *fl; // free list entry + vaddr_t offset; // offset into page #ifdef GUARDS - size_t blocksize, smallerblocksize; + size_t blocksize, smallerblocksize; #endif - ptraddr = (vaddr_t)ptr; + ptraddr = (vaddr_t)ptr; #ifdef GUARDS - if (ptraddr % PAGE_SIZE == 0) { - /* - * With guard bands, all client-facing subpage - * pointers are offset by GUARD_PTROFFSET (which is 4) - * from the underlying blocks and are therefore not - * page-aligned. So a page-aligned pointer is not one - * of ours. Catch this up front, as otherwise - * subtracting GUARD_PTROFFSET could give a pointer on - * a page we *do* own, and then we'll panic because - * it's not a valid one. - */ - return -1; - } - ptraddr -= GUARD_PTROFFSET; + if (ptraddr % PAGE_SIZE == 0) { + /* + * With guard bands, all client-facing subpage + * pointers are offset by GUARD_PTROFFSET (which is 4) + * from the underlying blocks and are therefore not + * page-aligned. So a page-aligned pointer is not one + * of ours. Catch this up front, as otherwise + * subtracting GUARD_PTROFFSET could give a pointer on + * a page we *do* own, and then we'll panic because + * it's not a valid one. + */ + return -1; + } + ptraddr -= GUARD_PTROFFSET; #endif #ifdef LABELS - if (ptraddr % PAGE_SIZE == 0) { - /* ditto */ - return -1; - } - ptraddr -= LABEL_PTROFFSET; + if (ptraddr % PAGE_SIZE == 0) { + /* ditto */ + return -1; + } + ptraddr -= LABEL_PTROFFSET; #endif - spinlock_acquire(&kmalloc_spinlock); + spinlock_acquire(&kmalloc_spinlock); - checksubpages(); + checksubpages(); - /* Silence warnings with gcc 4.8 -Og (but not -O2) */ - prpage = 0; - blktype = 0; + /* Silence warnings with gcc 4.8 -Og (but not -O2) */ + prpage = 0; + blktype = 0; - for (pr = allbase; pr; pr = pr->next_all) { - prpage = PR_PAGEADDR(pr); - blktype = PR_BLOCKTYPE(pr); - KASSERT(blktype >= 0 && blktype < NSIZES); + for (pr = allbase; pr; pr = pr->next_all) { + prpage = PR_PAGEADDR(pr); + blktype = PR_BLOCKTYPE(pr); + KASSERT(blktype >= 0 && blktype < NSIZES); - /* check for corruption */ - KASSERT(blktype>=0 && blktype= 0 && blktype < NSIZES); + checksubpage(pr); - if (ptraddr >= prpage && ptraddr < prpage + PAGE_SIZE) { - break; - } - } + if (ptraddr >= prpage && ptraddr < prpage + PAGE_SIZE) { + break; + } + } - if (pr==NULL) { - /* Not on any of our pages - not a subpage allocation */ - spinlock_release(&kmalloc_spinlock); - return -1; - } + if (pr == NULL) { + /* Not on any of our pages - not a subpage allocation */ + spinlock_release(&kmalloc_spinlock); + return -1; + } - offset = ptraddr - prpage; + offset = ptraddr - prpage; - /* Check for proper positioning and alignment */ - if (offset >= PAGE_SIZE || offset % sizes[blktype] != 0) { - panic("kfree: subpage free of invalid addr %p\n", ptr); - } + /* Check for proper positioning and alignment */ + if (offset >= PAGE_SIZE || offset % sizes[blktype] != 0) { + panic("kfree: subpage free of invalid addr %p\n", ptr); + } #ifdef GUARDS - blocksize = sizes[blktype]; - smallerblocksize = blktype > 0 ? sizes[blktype - 1] : 0; - checkguardband(ptraddr, smallerblocksize, blocksize); + blocksize = sizes[blktype]; + smallerblocksize = blktype > 0 ? sizes[blktype - 1] : 0; + checkguardband(ptraddr, smallerblocksize, blocksize); #endif - /* - * Clear the block to 0xdeadbeef to make it easier to detect - * uses of dangling pointers. - */ - fill_deadbeef((void *)ptraddr, sizes[blktype]); + /* + * Clear the block to 0xdeadbeef to make it easier to detect + * uses of dangling pointers. + */ + fill_deadbeef((void *)ptraddr, sizes[blktype]); - /* - * We probably ought to check for free twice by seeing if the block - * is already on the free list. But that's expensive, so we don't. - */ + /* + * We probably ought to check for free twice by seeing if the block + * is already on the free list. But that's expensive, so we don't. + */ - fla = prpage + offset; - fl = (struct freelist *)fla; - if (pr->freelist_offset == INVALID_OFFSET) { - fl->next = NULL; - } else { - fl->next = (struct freelist *)(prpage + pr->freelist_offset); + fla = prpage + offset; + fl = (struct freelist *)fla; + if (pr->freelist_offset == INVALID_OFFSET) { + fl->next = NULL; + } else { + fl->next = (struct freelist *)(prpage + pr->freelist_offset); - /* this block should not already be on the free list! */ + /* this block should not already be on the free list! */ #ifdef SLOW - { - struct freelist *fl2; + { + struct freelist *fl2; - for (fl2 = fl->next; fl2 != NULL; fl2 = fl2->next) { - KASSERT(fl2 != fl); - } - } + for (fl2 = fl->next; fl2 != NULL; fl2 = fl2->next) { + KASSERT(fl2 != fl); + } + } #else - /* check just the head */ - KASSERT(fl != fl->next); + /* check just the head */ + KASSERT(fl != fl->next); #endif - } - pr->freelist_offset = offset; - pr->nfree++; + } + pr->freelist_offset = offset; + pr->nfree++; - KASSERT(pr->nfree <= PAGE_SIZE / sizes[blktype]); - if (pr->nfree == PAGE_SIZE / sizes[blktype]) { - /* Whole page is free. */ - remove_lists(pr, blktype); - freepageref(pr); - /* Call free_kpages without kmalloc_spinlock. */ - spinlock_release(&kmalloc_spinlock); - free_kpages(prpage); - } - else { - spinlock_release(&kmalloc_spinlock); - } + KASSERT(pr->nfree <= PAGE_SIZE / sizes[blktype]); + if (pr->nfree == PAGE_SIZE / sizes[blktype]) { + /* Whole page is free. */ + remove_lists(pr, blktype); + freepageref(pr); + /* Call free_kpages without kmalloc_spinlock. */ + spinlock_release(&kmalloc_spinlock); + free_kpages(prpage); + } else { + spinlock_release(&kmalloc_spinlock); + } #ifdef SLOWER /* Don't get the lock unless checksubpages does something. */ - spinlock_acquire(&kmalloc_spinlock); - checksubpages(); - spinlock_release(&kmalloc_spinlock); + spinlock_acquire(&kmalloc_spinlock); + checksubpages(); + spinlock_release(&kmalloc_spinlock); #endif - return 0; + return 0; } // @@ -1166,59 +1104,54 @@ subpage_kfree(void *ptr) * Allocate a block of size SZ. Redirect either to subpage_kmalloc or * alloc_kpages depending on how big SZ is. */ -void * -kmalloc(size_t sz) -{ - size_t checksz; +void *kmalloc(size_t sz) { + size_t checksz; #ifdef LABELS - vaddr_t label; + vaddr_t label; #endif #ifdef LABELS #ifdef __GNUC__ - label = (vaddr_t)__builtin_return_address(0); + label = (vaddr_t)__builtin_return_address(0); #else #error "Don't know how to get return address with this compiler" #endif /* __GNUC__ */ #endif /* LABELS */ - checksz = sz + GUARD_OVERHEAD + LABEL_OVERHEAD; - if (checksz >= LARGEST_SUBPAGE_SIZE) { - unsigned long npages; - vaddr_t address; + checksz = sz + GUARD_OVERHEAD + LABEL_OVERHEAD; + if (checksz >= LARGEST_SUBPAGE_SIZE) { + unsigned long npages; + vaddr_t address; - /* Round up to a whole number of pages. */ - npages = (sz + PAGE_SIZE - 1)/PAGE_SIZE; - address = alloc_kpages(npages); - if (address==0) { - return NULL; - } - KASSERT(address % PAGE_SIZE == 0); + /* Round up to a whole number of pages. */ + npages = (sz + PAGE_SIZE - 1) / PAGE_SIZE; + address = alloc_kpages(npages); + if (address == 0) { + return NULL; + } + KASSERT(address % PAGE_SIZE == 0); - return (void *)address; - } + return (void *)address; + } #ifdef LABELS - return subpage_kmalloc(sz, label); + return subpage_kmalloc(sz, label); #else - return subpage_kmalloc(sz); + return subpage_kmalloc(sz); #endif } /* * Free a block previously returned from kmalloc. */ -void -kfree(void *ptr) -{ - /* - * Try subpage first; if that fails, assume it's a big allocation. - */ - if (ptr == NULL) { - return; - } else if (subpage_kfree(ptr)) { - KASSERT((vaddr_t)ptr%PAGE_SIZE==0); - free_kpages((vaddr_t)ptr); - } +void kfree(void *ptr) { + /* + * Try subpage first; if that fails, assume it's a big allocation. + */ + if (ptr == NULL) { + return; + } else if (subpage_kfree(ptr)) { + KASSERT((vaddr_t)ptr % PAGE_SIZE == 0); + free_kpages((vaddr_t)ptr); + } } - diff --git a/userland/bin/cat/cat.c b/userland/bin/cat/cat.c index 3415eff..b1ddcea 100644 --- a/userland/bin/cat/cat.c +++ b/userland/bin/cat/cat.c @@ -36,85 +36,73 @@ * Usage: cat [files] */ - - /* Print a file that's already been opened. */ -static -void -docat(const char *name, int fd) -{ - char buf[1024]; - int len, wr, wrtot; +static void docat(const char *name, int fd) { + char buf[1024]; + int len, wr, wrtot; - /* - * As long as we get more than zero bytes, we haven't hit EOF. - * Zero means EOF. Less than zero means an error occurred. - * We may read less than we asked for, though, in various cases - * for various reasons. - */ - while ((len = read(fd, buf, sizeof(buf)))>0) { - /* - * Likewise, we may actually write less than we attempted - * to. So loop until we're done. - */ - wrtot = 0; - while (wrtot < len) { - wr = write(STDOUT_FILENO, buf+wrtot, len-wrtot); - if (wr<0) { - err(1, "stdout"); - } - wrtot += wr; - } - } - /* - * If we got a read error, print it and exit. - */ - if (len<0) { - err(1, "%s", name); - } + /* + * As long as we get more than zero bytes, we haven't hit EOF. + * Zero means EOF. Less than zero means an error occurred. + * We may read less than we asked for, though, in various cases + * for various reasons. + */ + while ((len = read(fd, buf, sizeof(buf))) > 0) { + /* + * Likewise, we may actually write less than we attempted + * to. So loop until we're done. + */ + wrtot = 0; + while (wrtot < len) { + wr = write(STDOUT_FILENO, buf + wrtot, len - wrtot); + if (wr < 0) { + err(1, "stdout"); + } + wrtot += wr; + } + } + /* + * If we got a read error, print it and exit. + */ + if (len < 0) { + err(1, "%s", name); + } } /* Print a file by name. */ -static -void -cat(const char *file) -{ - int fd; +static void cat(const char *file) { + int fd; - /* - * "-" means print stdin. - */ - if (!strcmp(file, "-")) { - docat("stdin", STDIN_FILENO); - return; - } + /* + * "-" means print stdin. + */ + if (!strcmp(file, "-")) { + docat("stdin", STDIN_FILENO); + return; + } - /* - * Open the file, print it, and close it. - * Bail out if we can't open it. - */ - fd = open(file, O_RDONLY); - if (fd<0) { - err(1, "%s", file); - } - docat(file, fd); - close(fd); + /* + * Open the file, print it, and close it. + * Bail out if we can't open it. + */ + fd = open(file, O_RDONLY); + if (fd < 0) { + err(1, "%s", file); + } + docat(file, fd); + close(fd); } - -int -main(int argc, char *argv[]) -{ - if (argc==1) { - /* No args - just do stdin */ - docat("stdin", STDIN_FILENO); - } - else { - /* Print all the files specified on the command line. */ - int i; - for (i=1; i0) { - /* - * Likewise, we may actually write less than we attempted - * to. So loop until we're done. - */ - wrtot = 0; - while (wrtot < len) { - wr = write(tofd, buf+wrtot, len-wrtot); - if (wr<0) { - err(1, "%s", to); - } - wrtot += wr; - } - } - /* - * If we got a read error, print it and exit. - */ - if (len<0) { - err(1, "%s", from); - } + /* + * As long as we get more than zero bytes, we haven't hit EOF. + * Zero means EOF. Less than zero means an error occurred. + * We may read less than we asked for, though, in various cases + * for various reasons. + */ + while ((len = read(fromfd, buf, sizeof(buf))) > 0) { + /* + * Likewise, we may actually write less than we attempted + * to. So loop until we're done. + */ + wrtot = 0; + while (wrtot < len) { + wr = write(tofd, buf + wrtot, len - wrtot); + if (wr < 0) { + err(1, "%s", to); + } + wrtot += wr; + } + } + /* + * If we got a read error, print it and exit. + */ + if (len < 0) { + err(1, "%s", from); + } - if (close(fromfd) < 0) { - err(1, "%s: close", from); - } + if (close(fromfd) < 0) { + err(1, "%s: close", from); + } - if (close(tofd) < 0) { - err(1, "%s: close", to); - } + if (close(tofd) < 0) { + err(1, "%s: close", to); + } } -int -main(int argc, char *argv[]) -{ - /* - * Just do it. - * - * We don't allow the Unix model where you can do - * cp file1 file2 file3 destination-directory - * - * although this would be pretty easy to add. - */ - if (argc!=3) { - errx(1, "Usage: cp OLDFILE NEWFILE"); - } - copy(argv[1], argv[2]); - return 0; +int main(int argc, char *argv[]) { + /* + * Just do it. + * + * We don't allow the Unix model where you can do + * cp file1 file2 file3 destination-directory + * + * although this would be pretty easy to add. + */ + if (argc != 3) { + errx(1, "Usage: cp OLDFILE NEWFILE"); + } + copy(argv[1], argv[2]); + return 0; } diff --git a/userland/bin/false/false.c b/userland/bin/false/false.c index 8b01304..ea357b2 100644 --- a/userland/bin/false/false.c +++ b/userland/bin/false/false.c @@ -37,9 +37,7 @@ * sure does - it fails all the time." */ -int -main(void) -{ - /* Just exit with a failure code. */ - exit(1); +int main(void) { + /* Just exit with a failure code. */ + exit(1); } diff --git a/userland/bin/ln/ln.c b/userland/bin/ln/ln.c index 8d488e5..c85b9f3 100644 --- a/userland/bin/ln/ln.c +++ b/userland/bin/ln/ln.c @@ -39,20 +39,16 @@ * ln -s symlinkcontents symlinkfile */ - /* * Create a symlink with filename PATH that contains text TEXT. * When fed to ls -l, this produces something that looks like * * lrwxrwxrwx [stuff] PATH -> TEXT */ -static -void -dosymlink(const char *text, const char *path) -{ - if (symlink(text, path)) { - err(1, "%s", path); - } +static void dosymlink(const char *text, const char *path) { + if (symlink(text, path)) { + err(1, "%s", path); + } } /* @@ -60,34 +56,27 @@ dosymlink(const char *text, const char *path) * OLDFILE. Since it's a hard link, the two names for the file * are equal; both are the "real" file. */ -static -void -dohardlink(const char *oldfile, const char *newfile) -{ - if (link(oldfile, newfile)) { - err(1, "%s or %s", oldfile, newfile); - exit(1); - } +static void dohardlink(const char *oldfile, const char *newfile) { + if (link(oldfile, newfile)) { + err(1, "%s or %s", oldfile, newfile); + exit(1); + } } -int -main(int argc, char *argv[]) -{ - /* - * Just do whatever was asked for. - * - * We don't allow the Unix model where you can do - * ln [-s] file1 file2 file3 destination-directory - */ - if (argc==4 && !strcmp(argv[1], "-s")) { - dosymlink(argv[2], argv[3]); - } - else if (argc==3) { - dohardlink(argv[1], argv[2]); - } - else { - warnx("Usage: ln oldfile newfile"); - errx(1, " ln -s symlinkcontents symlinkfile\n"); - } - return 0; +int main(int argc, char *argv[]) { + /* + * Just do whatever was asked for. + * + * We don't allow the Unix model where you can do + * ln [-s] file1 file2 file3 destination-directory + */ + if (argc == 4 && !strcmp(argv[1], "-s")) { + dosymlink(argv[2], argv[3]); + } else if (argc == 3) { + dohardlink(argv[1], argv[2]); + } else { + warnx("Usage: ln oldfile newfile"); + errx(1, " ln -s symlinkcontents symlinkfile\n"); + } + return 0; } diff --git a/userland/bin/ls/ls.c b/userland/bin/ls/ls.c index 2041bc8..d07239e 100644 --- a/userland/bin/ls/ls.c +++ b/userland/bin/ls/ls.c @@ -46,300 +46,274 @@ */ /* Flags for which options we're using. */ -static int aopt=0; -static int dopt=0; -static int lopt=0; -static int Ropt=0; -static int sopt=0; +static int aopt = 0; +static int dopt = 0; +static int lopt = 0; +static int Ropt = 0; +static int sopt = 0; /* Process an option character. */ -static -void -option(int ch) -{ - switch (ch) { - case 'a': aopt=1; break; - case 'd': dopt=1; break; - case 'l': lopt=1; break; - case 'R': Ropt=1; break; - case 's': sopt=1; break; - default: - errx(1, "Unknown option -%c", ch); - } +static void option(int ch) { + switch (ch) { + case 'a': + aopt = 1; + break; + case 'd': + dopt = 1; + break; + case 'l': + lopt = 1; + break; + case 'R': + Ropt = 1; + break; + case 's': + sopt = 1; + break; + default: + errx(1, "Unknown option -%c", ch); + } } /* * Utility function to find the non-directory part of a pathname. */ -static -const char * -basename(const char *path) -{ - const char *s; +static const char *basename(const char *path) { + const char *s; - s = strrchr(path, '/'); - if (s) { - return s+1; - } - return path; + s = strrchr(path, '/'); + if (s) { + return s + 1; + } + return path; } /* * Utility function to check if a name refers to a directory. */ -static -int -isdir(const char *path) -{ - struct stat buf; - int fd; +static int isdir(const char *path) { + struct stat buf; + int fd; - /* Assume stat() may not be implemented; use fstat */ - fd = open(path, O_RDONLY); - if (fd<0) { - err(1, "%s", path); - } - if (fstat(fd, &buf)<0) { - err(1, "%s: fstat", path); - } - close(fd); + /* Assume stat() may not be implemented; use fstat */ + fd = open(path, O_RDONLY); + if (fd < 0) { + err(1, "%s", path); + } + if (fstat(fd, &buf) < 0) { + err(1, "%s: fstat", path); + } + close(fd); - return S_ISDIR(buf.st_mode); + return S_ISDIR(buf.st_mode); } /* * When listing one of several subdirectories, show the name of the * directory. */ -static -void -printheader(const char *file) -{ - /* No blank line before the first header */ - static int first=1; - if (first) { - first = 0; - } - else { - printf("\n"); - } - printf("%s:\n", file); +static void printheader(const char *file) { + /* No blank line before the first header */ + static int first = 1; + if (first) { + first = 0; + } else { + printf("\n"); + } + printf("%s:\n", file); } /* * Show a single file. * We don't do the neat multicolumn listing that Unix ls does. */ -static -void -print(const char *path) -{ - struct stat statbuf; - const char *file; - int typech; +static void print(const char *path) { + struct stat statbuf; + const char *file; + int typech; - if (lopt || sopt) { - int fd; + if (lopt || sopt) { + int fd; - fd = open(path, O_RDONLY); - if (fd<0) { - err(1, "%s", path); - } - if (fstat(fd, &statbuf)<0) { - err(1, "%s: fstat", path); - } - close(fd); - } + fd = open(path, O_RDONLY); + if (fd < 0) { + err(1, "%s", path); + } + if (fstat(fd, &statbuf) < 0) { + err(1, "%s: fstat", path); + } + close(fd); + } - file = basename(path); + file = basename(path); - if (sopt) { - printf("%3d ", statbuf.st_blocks); - } + if (sopt) { + printf("%3d ", statbuf.st_blocks); + } - if (lopt) { - if (S_ISREG(statbuf.st_mode)) { - typech = '-'; - } - else if (S_ISDIR(statbuf.st_mode)) { - typech = 'd'; - } - else if (S_ISLNK(statbuf.st_mode)) { - typech = 'l'; - } - else if (S_ISCHR(statbuf.st_mode)) { - typech = 'c'; - } - else if (S_ISBLK(statbuf.st_mode)) { - typech = 'b'; - } - else { - typech = '?'; - } + if (lopt) { + if (S_ISREG(statbuf.st_mode)) { + typech = '-'; + } else if (S_ISDIR(statbuf.st_mode)) { + typech = 'd'; + } else if (S_ISLNK(statbuf.st_mode)) { + typech = 'l'; + } else if (S_ISCHR(statbuf.st_mode)) { + typech = 'c'; + } else if (S_ISBLK(statbuf.st_mode)) { + typech = 'b'; + } else { + typech = '?'; + } - printf("%crwx------ %2d root %-7llu ", - typech, - statbuf.st_nlink, - statbuf.st_size); - } - printf("%s\n", file); + printf("%crwx------ %2d root %-7llu ", typech, statbuf.st_nlink, + statbuf.st_size); + } + printf("%s\n", file); } /* * List a directory. */ -static -void -listdir(const char *path, int showheader) -{ - int fd; - char buf[1024]; - char newpath[1024]; - ssize_t len; +static void listdir(const char *path, int showheader) { + int fd; + char buf[1024]; + char newpath[1024]; + ssize_t len; - if (showheader) { - printheader(path); - } + if (showheader) { + printheader(path); + } - /* - * Open it. - */ - fd = open(path, O_RDONLY); - if (fd<0) { - err(1, "%s", path); - } + /* + * Open it. + */ + fd = open(path, O_RDONLY); + if (fd < 0) { + err(1, "%s", path); + } - /* - * List the directory. - */ - while ((len = getdirentry(fd, buf, sizeof(buf)-1)) > 0) { - buf[len] = 0; + /* + * List the directory. + */ + while ((len = getdirentry(fd, buf, sizeof(buf) - 1)) > 0) { + buf[len] = 0; - /* Assemble the full name of the new item */ - snprintf(newpath, sizeof(newpath), "%s/%s", path, buf); + /* Assemble the full name of the new item */ + snprintf(newpath, sizeof(newpath), "%s/%s", path, buf); - if (aopt || buf[0]!='.') { - /* Print it */ - print(newpath); - } - } - if (len<0) { - err(1, "%s: getdirentry", path); - } + if (aopt || buf[0] != '.') { + /* Print it */ + print(newpath); + } + } + if (len < 0) { + err(1, "%s: getdirentry", path); + } - /* Done */ - close(fd); + /* Done */ + close(fd); } -static -void -recursedir(const char *path) -{ - int fd; - char buf[1024]; - char newpath[1024]; - int len; +static void recursedir(const char *path) { + int fd; + char buf[1024]; + char newpath[1024]; + int len; - /* - * Open it. - */ - fd = open(path, O_RDONLY); - if (fd<0) { - err(1, "%s", path); - } + /* + * Open it. + */ + fd = open(path, O_RDONLY); + if (fd < 0) { + err(1, "%s", path); + } - /* - * List the directory. - */ - while ((len = getdirentry(fd, buf, sizeof(buf)-1)) > 0) { - buf[len] = 0; + /* + * List the directory. + */ + while ((len = getdirentry(fd, buf, sizeof(buf) - 1)) > 0) { + buf[len] = 0; - /* Assemble the full name of the new item */ - snprintf(newpath, sizeof(newpath), "%s/%s", path, buf); + /* Assemble the full name of the new item */ + snprintf(newpath, sizeof(newpath), "%s/%s", path, buf); - if (!aopt && buf[0]=='.') { - /* skip this one */ - continue; - } + if (!aopt && buf[0] == '.') { + /* skip this one */ + continue; + } - if (!strcmp(buf, ".") || !strcmp(buf, "..")) { - /* always skip these */ - continue; - } + if (!strcmp(buf, ".") || !strcmp(buf, "..")) { + /* always skip these */ + continue; + } - if (!isdir(newpath)) { - continue; - } + if (!isdir(newpath)) { + continue; + } - listdir(newpath, 1 /*showheader*/); - if (Ropt) { - recursedir(newpath); - } - } - if (len<0) { - err(1, "%s", path); - } + listdir(newpath, 1 /*showheader*/); + if (Ropt) { + recursedir(newpath); + } + } + if (len < 0) { + err(1, "%s", path); + } - close(fd); + close(fd); } -static -void -listitem(const char *path, int showheader) -{ - if (!dopt && isdir(path)) { - listdir(path, showheader || Ropt); - if (Ropt) { - recursedir(path); - } - } - else { - print(path); - } +static void listitem(const char *path, int showheader) { + if (!dopt && isdir(path)) { + listdir(path, showheader || Ropt); + if (Ropt) { + recursedir(path); + } + } else { + print(path); + } } -int -main(int argc, char *argv[]) -{ - int i,j, items=0; +int main(int argc, char *argv[]) { + int i, j, items = 0; - /* - * Go through the arguments and count how many non-option args. - */ - for (i=1; i1); - } - } + /* + * Now go through the options for real, processing them. + */ + for (i = 1; i < argc; i++) { + if (argv[i][0] == '-') { + /* + * This word is an option. + * Process all the option characters in it. + */ + for (j = 1; argv[i][j]; j++) { + option(argv[i][j]); + } + } else { + /* + * This word isn't an option; list it. + */ + listitem(argv[i], items > 1); + } + } - /* - * If no filenames were specified to list, list the current - * directory. - */ - if (items==0) { - listitem(".", 0); - } + /* + * If no filenames were specified to list, list the current + * directory. + */ + if (items == 0) { + listitem(".", 0); + } - return 0; + return 0; } diff --git a/userland/bin/mkdir/mkdir.c b/userland/bin/mkdir/mkdir.c index c0a7e9e..38ddaac 100644 --- a/userland/bin/mkdir/mkdir.c +++ b/userland/bin/mkdir/mkdir.c @@ -39,15 +39,13 @@ * Just calls the mkdir() system call. */ -int -main(int argc, char *argv[]) -{ - if (argc!=2) { - errx(1, "Usage: mkdir DIRECTORY"); - } +int main(int argc, char *argv[]) { + if (argc != 2) { + errx(1, "Usage: mkdir DIRECTORY"); + } - if (mkdir(argv[1], 0775)) { - err(1, "%s", argv[1]); - } - return 0; + if (mkdir(argv[1], 0775)) { + err(1, "%s", argv[1]); + } + return 0; } diff --git a/userland/bin/mv/mv.c b/userland/bin/mv/mv.c index 2705140..690861b 100644 --- a/userland/bin/mv/mv.c +++ b/userland/bin/mv/mv.c @@ -44,21 +44,16 @@ * mv file1 file2 file3 destination-dir */ -static -void -dorename(const char *oldfile, const char *newfile) -{ - if (rename(oldfile, newfile)) { - err(1, "%s or %s", oldfile, newfile); - } +static void dorename(const char *oldfile, const char *newfile) { + if (rename(oldfile, newfile)) { + err(1, "%s or %s", oldfile, newfile); + } } -int -main(int argc, char *argv[]) -{ - if (argc!=3) { - errx(1, "Usage: mv oldfile newfile"); - } - dorename(argv[1], argv[2]); - return 0; +int main(int argc, char *argv[]) { + if (argc != 3) { + errx(1, "Usage: mv oldfile newfile"); + } + dorename(argv[1], argv[2]); + return 0; } diff --git a/userland/bin/pwd/pwd.c b/userland/bin/pwd/pwd.c index b7e1604..ffdb95d 100644 --- a/userland/bin/pwd/pwd.c +++ b/userland/bin/pwd/pwd.c @@ -41,15 +41,13 @@ * system call.) */ -int -main(void) -{ - char buf[PATH_MAX+1], *p; +int main(void) { + char buf[PATH_MAX + 1], *p; - p = getcwd(buf, sizeof(buf)); - if (p == NULL) { - err(1, "."); - } - printf("%s\n", buf); - return 0; + p = getcwd(buf, sizeof(buf)); + if (p == NULL) { + err(1, "."); + } + printf("%s\n", buf); + return 0; } diff --git a/userland/bin/rm/rm.c b/userland/bin/rm/rm.c index feb2515..555f21c 100644 --- a/userland/bin/rm/rm.c +++ b/userland/bin/rm/rm.c @@ -36,29 +36,24 @@ */ /* Delete a single file. */ -static -void -doremove(const char *file) -{ - if (remove(file)) { - err(1, "%s", file); - } +static void doremove(const char *file) { + if (remove(file)) { + err(1, "%s", file); + } } -int -main(int argc, char *argv[]) -{ - int i; +int main(int argc, char *argv[]) { + int i; - if (argc<2) { - /* Must have at least one file. */ - errx(1, "Usage: rm FILES"); - } + if (argc < 2) { + /* Must have at least one file. */ + errx(1, "Usage: rm FILES"); + } - /* Just delete everything on the command line. */ - for (i=1; ival = code; - ei->signaled = 0; - ei->stopped = 0; - ei->coredump = 0; +static void exitinfo_exit(struct exitinfo *ei, int code) { + ei->val = code; + ei->signaled = 0; + ei->stopped = 0; + ei->coredump = 0; } /* * readstatus * unpack results from wait */ -static -void -readstatus(int status, struct exitinfo *ei) -{ - if (WIFEXITED(status)) { - ei->val = WEXITSTATUS(status); - ei->signaled = 0; - ei->stopped = 0; - ei->coredump = 0; - } - else if (WIFSIGNALED(status) && WCOREDUMP(status)) { - ei->val = WTERMSIG(status); - ei->signaled = 1; - ei->stopped = 0; - ei->coredump = 1; - } - else if (WIFSIGNALED(status)) { - ei->val = WTERMSIG(status); - ei->signaled = 1; - ei->stopped = 0; - ei->coredump = 0; - } - else if (WIFSTOPPED(status)) { - ei->val = WSTOPSIG(status); - ei->signaled = 0; - ei->stopped = 1; - ei->coredump = 0; - } - else { - printf("Invalid status code %d", status); - ei->val = status; - ei->signaled = 0; - ei->stopped = 0; - ei->coredump = 0; - } - +static void readstatus(int status, struct exitinfo *ei) { + if (WIFEXITED(status)) { + ei->val = WEXITSTATUS(status); + ei->signaled = 0; + ei->stopped = 0; + ei->coredump = 0; + } else if (WIFSIGNALED(status) && WCOREDUMP(status)) { + ei->val = WTERMSIG(status); + ei->signaled = 1; + ei->stopped = 0; + ei->coredump = 1; + } else if (WIFSIGNALED(status)) { + ei->val = WTERMSIG(status); + ei->signaled = 1; + ei->stopped = 0; + ei->coredump = 0; + } else if (WIFSTOPPED(status)) { + ei->val = WSTOPSIG(status); + ei->signaled = 0; + ei->stopped = 1; + ei->coredump = 0; + } else { + printf("Invalid status code %d", status); + ei->val = status; + ei->signaled = 0; + ei->stopped = 0; + ei->coredump = 0; + } } /* * printstatus * print results from wait */ -static -void -printstatus(const struct exitinfo *ei, int printexitzero) -{ - if (ei->signaled && ei->coredump) { - printf("Signal %d (core dumped)\n", ei->val); - } - else if (ei->signaled) { - printf("Signal %d\n", ei->val); - } - else if (ei->stopped) { - printf("Stopped on signal %d\n", ei->val); - } - else if (printexitzero || ei->val != 0) { - printf("Exit %d\n", ei->val); - } +static void printstatus(const struct exitinfo *ei, int printexitzero) { + if (ei->signaled && ei->coredump) { + printf("Signal %d (core dumped)\n", ei->val); + } else if (ei->signaled) { + printf("Signal %d\n", ei->val); + } else if (ei->stopped) { + printf("Stopped on signal %d\n", ei->val); + } else if (printexitzero || ei->val != 0) { + printf("Exit %d\n", ei->val); + } } /* * dowait * just does a waitpid. */ -static -void -dowait(pid_t pid) -{ - struct exitinfo ei; - int status; +static void dowait(pid_t pid) { + struct exitinfo ei; + int status; - if (waitpid(pid, &status, 0) < 0) { - warn("pid %d", pid); - } - else { - printf("pid %d: ", pid); - readstatus(status, &ei); - printstatus(&ei, 1); - } + if (waitpid(pid, &status, 0) < 0) { + warn("pid %d", pid); + } else { + printf("pid %d: ", pid); + readstatus(status, &ei); + printstatus(&ei, 1); + } } #ifdef WNOHANG @@ -214,43 +184,36 @@ dowait(pid_t pid) * dowaitpoll * like dowait, but uses WNOHANG. returns true if we got something. */ -static -int -dowaitpoll(pid_t pid) -{ - struct exitinfo ei; - pid_t foundpid; - int status; +static int dowaitpoll(pid_t pid) { + struct exitinfo ei; + pid_t foundpid; + int status; - foundpid = waitpid(pid, &status, WNOHANG); - if (foundpid < 0) { - warn("pid %d", pid); - } - else if (foundpid != 0) { - printf("pid %d: ", pid); - readstatus(status, &ei); - printstatus(&ei, 1); - return 1; - } - return 0; + foundpid = waitpid(pid, &status, WNOHANG); + if (foundpid < 0) { + warn("pid %d", pid); + } else if (foundpid != 0) { + printf("pid %d: ", pid); + readstatus(status, &ei); + printstatus(&ei, 1); + return 1; + } + return 0; } /* * waitpoll * poll all background jobs for having exited. */ -static -void -waitpoll(void) -{ - int i; - for (i=0; i < MAXBG; i++) { - if (bgpids[i] != 0) { - if (dowaitpoll(bgpids[i])) { - bgpids[i] = 0; - } - } - } +static void waitpoll(void) { + int i; + for (i = 0; i < MAXBG; i++) { + if (bgpids[i] != 0) { + if (dowaitpoll(bgpids[i])) { + bgpids[i] = 0; + } + } + } } #endif /* WNOHANG */ @@ -260,36 +223,32 @@ waitpoll(void) * know the pids, this is a little tough to use with an arg, but without an * arg it will wait for all the background jobs. */ -static -void -cmd_wait(int ac, char *av[], struct exitinfo *ei) -{ - int i; - pid_t pid; +static void cmd_wait(int ac, char *av[], struct exitinfo *ei) { + int i; + pid_t pid; - if (ac == 2) { - pid = atoi(av[1]); - dowait(pid); - for (i = 0; i < MAXBG; i++) { - if (bgpids[i]==pid) { - bgpids[i] = 0; - } - } - exitinfo_exit(ei, 0); - return; - } - else if (ac == 1) { - for (i=0; i < MAXBG; i++) { - if (bgpids[i] != 0) { - dowait(bgpids[i]); - bgpids[i] = 0; - } - } - exitinfo_exit(ei, 0); - return; - } - printf("Usage: wait [pid]\n"); - exitinfo_exit(ei, 1); + if (ac == 2) { + pid = atoi(av[1]); + dowait(pid); + for (i = 0; i < MAXBG; i++) { + if (bgpids[i] == pid) { + bgpids[i] = 0; + } + } + exitinfo_exit(ei, 0); + return; + } else if (ac == 1) { + for (i = 0; i < MAXBG; i++) { + if (bgpids[i] != 0) { + dowait(bgpids[i]); + bgpids[i] = 0; + } + } + exitinfo_exit(ei, 0); + return; + } + printf("Usage: wait [pid]\n"); + exitinfo_exit(ei, 1); } /* @@ -297,21 +256,18 @@ cmd_wait(int ac, char *av[], struct exitinfo *ei) * just an interface to the system call. no concept of home directory, so * require the directory. */ -static -void -cmd_chdir(int ac, char *av[], struct exitinfo *ei) -{ - if (ac == 2) { - if (chdir(av[1])) { - warn("chdir: %s", av[1]); - exitinfo_exit(ei, 1); - return; - } - exitinfo_exit(ei, 0); - return; - } - printf("Usage: chdir dir\n"); - exitinfo_exit(ei, 1); +static void cmd_chdir(int ac, char *av[], struct exitinfo *ei) { + if (ac == 2) { + if (chdir(av[1])) { + warn("chdir: %s", av[1]); + exitinfo_exit(ei, 1); + return; + } + exitinfo_exit(ei, 0); + return; + } + printf("Usage: chdir dir\n"); + exitinfo_exit(ei, 1); } /* @@ -319,25 +275,20 @@ cmd_chdir(int ac, char *av[], struct exitinfo *ei) * pretty simple. allow the user to choose the exit code if they want, * otherwise default to 0 (success). */ -static -void -cmd_exit(int ac, char *av[], struct exitinfo *ei) -{ - int code; +static void cmd_exit(int ac, char *av[], struct exitinfo *ei) { + int code; - if (ac == 1) { - code = 0; - } - else if (ac == 2) { - code = atoi(av[1]); - } - else { - printf("Usage: exit [code]\n"); - exitinfo_exit(ei, 1); - return; - } + if (ac == 1) { + code = 0; + } else if (ac == 2) { + code = atoi(av[1]); + } else { + printf("Usage: exit [code]\n"); + exitinfo_exit(ei, 1); + return; + } - exit(code); + exit(code); } /* @@ -345,15 +296,13 @@ cmd_exit(int ac, char *av[], struct exitinfo *ei) * executes it. they must all take an argc and argv. */ static struct { - const char *name; - void (*func)(int, char **, struct exitinfo *); -} builtins[] = { - { "cd", cmd_chdir }, - { "chdir", cmd_chdir }, - { "exit", cmd_exit }, - { "wait", cmd_wait }, - { NULL, NULL } -}; + const char *name; + void (*func)(int, char **, struct exitinfo *); +} builtins[] = {{"cd", cmd_chdir}, + {"chdir", cmd_chdir}, + {"exit", cmd_exit}, + {"wait", cmd_wait}, + {NULL, NULL}}; /* * docommand @@ -362,116 +311,112 @@ static struct { * otherwise, it's a standard command. check for the '&', try to background * the job if possible, otherwise just run it and wait on it. */ -static -void -docommand(char *buf, struct exitinfo *ei) -{ - char *args[NARG_MAX + 1]; - int nargs, i; - char *s; - pid_t pid; - int status; - int bg=0; - time_t startsecs, endsecs; - unsigned long startnsecs, endnsecs; +static void docommand(char *buf, struct exitinfo *ei) { + char *args[NARG_MAX + 1]; + int nargs, i; + char *s; + pid_t pid; + int status; + int bg = 0; + time_t startsecs, endsecs; + unsigned long startnsecs, endnsecs; - nargs = 0; - for (s = strtok(buf, " \t\r\n"); s; s = strtok(NULL, " \t\r\n")) { - if (nargs >= NARG_MAX) { - printf("%s: Too many arguments " - "(exceeds system limit)\n", - args[0]); - exitinfo_exit(ei, 1); - return; - } - args[nargs++] = s; - } - args[nargs] = NULL; + nargs = 0; + for (s = strtok(buf, " \t\r\n"); s; s = strtok(NULL, " \t\r\n")) { + if (nargs >= NARG_MAX) { + printf("%s: Too many arguments " + "(exceeds system limit)\n", + args[0]); + exitinfo_exit(ei, 1); + return; + } + args[nargs++] = s; + } + args[nargs] = NULL; - if (nargs==0) { - /* empty line */ - exitinfo_exit(ei, 0); - return; - } + if (nargs == 0) { + /* empty line */ + exitinfo_exit(ei, 0); + return; + } - for (i=0; builtins[i].name; i++) { - if (!strcmp(builtins[i].name, args[0])) { - builtins[i].func(nargs, args, ei); - return; - } - } + for (i = 0; builtins[i].name; i++) { + if (!strcmp(builtins[i].name, args[0])) { + builtins[i].func(nargs, args, ei); + return; + } + } - /* Not a builtin; run it */ + /* Not a builtin; run it */ - if (nargs > 0 && !strcmp(args[nargs-1], "&")) { - /* background */ - if (!can_bg()) { - printf("%s: Too many background jobs; wait for " - "some to finish before starting more\n", - args[0]); - exitinfo_exit(ei, 1); - return; - } - nargs--; - args[nargs] = NULL; - bg = 1; - } + if (nargs > 0 && !strcmp(args[nargs - 1], "&")) { + /* background */ + if (!can_bg()) { + printf("%s: Too many background jobs; wait for " + "some to finish before starting more\n", + args[0]); + exitinfo_exit(ei, 1); + return; + } + nargs--; + args[nargs] = NULL; + bg = 1; + } - if (timing) { - __time(&startsecs, &startnsecs); - } + if (timing) { + __time(&startsecs, &startnsecs); + } - pid = fork(); - switch (pid) { - case -1: - /* error */ - warn("fork"); - exitinfo_exit(ei, 255); - return; - case 0: - /* child */ - execvp(args[0], args); - warn("%s", args[0]); - /* - * Use _exit() instead of exit() in the child - * process to avoid calling atexit() functions, - * which would cause hostcompat (if present) to - * reset the tty state and mess up our input - * handling. - */ - _exit(1); - default: - break; - } + pid = fork(); + switch (pid) { + case -1: + /* error */ + warn("fork"); + exitinfo_exit(ei, 255); + return; + case 0: + /* child */ + execvp(args[0], args); + warn("%s", args[0]); + /* + * Use _exit() instead of exit() in the child + * process to avoid calling atexit() functions, + * which would cause hostcompat (if present) to + * reset the tty state and mess up our input + * handling. + */ + _exit(1); + default: + break; + } - /* parent */ - if (bg) { - /* background this command */ - remember_bg(pid); - printf("[%d] %s ... &\n", pid, args[0]); - exitinfo_exit(ei, 0); - return; - } + /* parent */ + if (bg) { + /* background this command */ + remember_bg(pid); + printf("[%d] %s ... &\n", pid, args[0]); + exitinfo_exit(ei, 0); + return; + } - if (waitpid(pid, &status, 0) < 0) { - warn("waitpid"); - exitinfo_exit(ei, 255); - } - else { - readstatus(status, ei); - } + if (waitpid(pid, &status, 0) < 0) { + warn("waitpid"); + exitinfo_exit(ei, 255); + } else { + readstatus(status, ei); + } - if (timing) { - __time(&endsecs, &endnsecs); - if (endnsecs < startnsecs) { - endnsecs += 1000000000; - endsecs--; - } - endnsecs -= startnsecs; - endsecs -= startsecs; - warnx("subprocess time: %lu.%09lu seconds", - (unsigned long) endsecs, (unsigned long) endnsecs); - } + if (timing) { + __time(&endsecs, &endnsecs); + if (endnsecs < startnsecs) { + endnsecs += 1000000000; + endsecs--; + } + endnsecs -= startnsecs; + endsecs -= startsecs; + warnx("subprocess time: %lu.%09lu seconds", (unsigned long)endsecs, + (unsigned long)endnsecs); + } } /* @@ -484,40 +429,34 @@ docommand(char *buf, struct exitinfo *ei) * if there's an invalid character or a backspace when there's nothing * in the buffer, putchars an alert (bell). */ -static -void -getcmd(char *buf, size_t len) -{ - size_t pos = 0; - int done=0, ch; +static void getcmd(char *buf, size_t len) { + size_t pos = 0; + int done = 0, ch; - /* - * In the absence of a , assume input is 7-bit ASCII. - */ + /* + * In the absence of a , assume input is 7-bit ASCII. + */ - while (!done) { - ch = getchar(); - if ((ch == '\b' || ch == 127) && pos > 0) { - putchar('\b'); - putchar(' '); - putchar('\b'); - pos--; - } - else if (ch == '\r' || ch == '\n') { - putchar('\r'); - putchar('\n'); - done = 1; - } - else if (ch >= 32 && ch < 127 && pos < len-1) { - buf[pos++] = ch; - putchar(ch); - } - else { - /* alert (bell) character */ - putchar('\a'); - } - } - buf[pos] = 0; + while (!done) { + ch = getchar(); + if ((ch == '\b' || ch == 127) && pos > 0) { + putchar('\b'); + putchar(' '); + putchar('\b'); + pos--; + } else if (ch == '\r' || ch == '\n') { + putchar('\r'); + putchar('\n'); + done = 1; + } else if (ch >= 32 && ch < 127 && pos < len - 1) { + buf[pos++] = ch; + putchar(ch); + } else { + /* alert (bell) character */ + putchar('\a'); + } + } + buf[pos] = 0; } /* @@ -526,34 +465,28 @@ getcmd(char *buf, size_t len) * commands and running them (and printing the exit status if it's not * success.) */ -static -void -interactive(void) -{ - char buf[CMDLINE_MAX]; - struct exitinfo ei; +static void interactive(void) { + char buf[CMDLINE_MAX]; + struct exitinfo ei; - while (1) { - printf("OS/161$ "); - getcmd(buf, sizeof(buf)); - docommand(buf, &ei); - printstatus(&ei, 0); + while (1) { + printf("OS/161$ "); + getcmd(buf, sizeof(buf)); + docommand(buf, &ei); + printstatus(&ei, 0); #ifdef WNOHANG - waitpoll(); + waitpoll(); #endif - } + } } -static -void -check_timing(void) -{ - time_t secs; - unsigned long nsecs; - if (__time(&secs, &nsecs) != -1) { - timing = 1; - warnx("Timing enabled."); - } +static void check_timing(void) { + time_t secs; + unsigned long nsecs; + if (__time(&secs, &nsecs) != -1) { + timing = 1; + warnx("Timing enabled."); + } } /* @@ -561,31 +494,27 @@ check_timing(void) * if there are no arguments, run interactively, otherwise, run a program * from within the shell, but immediately exit. */ -int -main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { #ifdef HOST - hostcompat_init(argc, argv); + hostcompat_init(argc, argv); #endif - check_timing(); + check_timing(); - /* - * Allow argc to be 0 in case we're running on a broken kernel, - * or one that doesn't set argv when starting the first shell. - */ - if (argc == 0 || argc == 1) { - interactive(); - } - else if (argc == 3 && !strcmp(argv[1], "-c")) { - struct exitinfo ei; - docommand(argv[2], &ei); - printstatus(&ei, 0); - if (ei.signaled || ei.stopped || ei.val != 0) { - exit(1); - } - } - else { - errx(1, "Usage: sh [-c command]"); - } - return 0; + /* + * Allow argc to be 0 in case we're running on a broken kernel, + * or one that doesn't set argv when starting the first shell. + */ + if (argc == 0 || argc == 1) { + interactive(); + } else if (argc == 3 && !strcmp(argv[1], "-c")) { + struct exitinfo ei; + docommand(argv[2], &ei); + printstatus(&ei, 0); + if (ei.signaled || ei.stopped || ei.val != 0) { + exit(1); + } + } else { + errx(1, "Usage: sh [-c command]"); + } + return 0; } diff --git a/userland/bin/sync/sync.c b/userland/bin/sync/sync.c index 81b4434..5f136fe 100644 --- a/userland/bin/sync/sync.c +++ b/userland/bin/sync/sync.c @@ -35,9 +35,7 @@ * Just calls the sync() system call. */ -int -main(void) -{ - sync(); - return 0; +int main(void) { + sync(); + return 0; } diff --git a/userland/bin/tac/tac.c b/userland/bin/tac/tac.c index edaa48d..00e9c9c 100644 --- a/userland/bin/tac/tac.c +++ b/userland/bin/tac/tac.c @@ -54,8 +54,8 @@ #include struct indexentry { - off_t pos; - off_t len; + off_t pos; + off_t len; }; static int datafd = -1, indexfd = -1; @@ -67,226 +67,194 @@ static char buf[4096]; // string ops /* this is standard and should go into libc */ -static -void * -memchr(const void *buf, int ch, size_t buflen) -{ - const unsigned char *ubuf = buf; - size_t i; +static void *memchr(const void *buf, int ch, size_t buflen) { + const unsigned char *ubuf = buf; + size_t i; - for (i=0; i 0) { - dowrite(indexfd, indexname, &x, sizeof(x)); - } + x.pos = 0; + x.len = 0; + while (1) { + len = doread(fd, name, buf, sizeof(buf)); + if (len == 0) { + break; + } - if (closefd != -1) { - close(closefd); - } + remaining = len; + for (s = buf; s != NULL; s = t) { + t = memchr(s, '\n', remaining); + if (t != NULL) { + t++; + here = (t - s); + x.len += here; + remaining -= here; + dowrite(indexfd, indexname, &x, sizeof(x)); + x.pos += x.len; + x.len = 0; + } else { + x.len += remaining; + } + } + dowrite(datafd, dataname, buf, len); + } + if (x.len > 0) { + dowrite(indexfd, indexname, &x, sizeof(x)); + } + + if (closefd != -1) { + close(closefd); + } } -static -void -dumpdata(void) -{ - struct indexentry x; - off_t indexsize, pos, done; - size_t amount, len; +static void dumpdata(void) { + struct indexentry x; + off_t indexsize, pos, done; + size_t amount, len; - indexsize = dolseek(indexfd, indexname, 0, SEEK_CUR); - pos = indexsize; - assert(pos % sizeof(x) == 0); - while (pos > 0) { - pos -= sizeof(x); - assert(pos >= 0); - dolseek(indexfd, indexname, pos, SEEK_SET); + indexsize = dolseek(indexfd, indexname, 0, SEEK_CUR); + pos = indexsize; + assert(pos % sizeof(x) == 0); + while (pos > 0) { + pos -= sizeof(x); + assert(pos >= 0); + dolseek(indexfd, indexname, pos, SEEK_SET); - len = doread(indexfd, indexname, &x, sizeof(x)); - if (len != sizeof(x)) { - errx(1, "%s: read: Unexpected EOF", indexname); - } - dolseek(datafd, dataname, x.pos, SEEK_SET); + len = doread(indexfd, indexname, &x, sizeof(x)); + if (len != sizeof(x)) { + errx(1, "%s: read: Unexpected EOF", indexname); + } + dolseek(datafd, dataname, x.pos, SEEK_SET); - for (done = 0; done < x.len; done += amount) { - amount = sizeof(buf); - if ((off_t)amount > x.len - done) { - amount = x.len - done; - } - len = doread(datafd, dataname, buf, amount); - if (len != amount) { - errx(1, "%s: read: Unexpected short count" - " %zu of %zu", dataname, len, amount); - } - dowrite(STDOUT_FILENO, "stdout", buf, len); - } - } + for (done = 0; done < x.len; done += amount) { + amount = sizeof(buf); + if ((off_t)amount > x.len - done) { + amount = x.len - done; + } + len = doread(datafd, dataname, buf, amount); + if (len != amount) { + errx(1, + "%s: read: Unexpected short count" + " %zu of %zu", + dataname, len, amount); + } + dowrite(STDOUT_FILENO, "stdout", buf, len); + } + } } //////////////////////////////////////////////////////////// // main -static -int -openscratch(const char *name, int flags, mode_t mode) -{ - int fd; +static int openscratch(const char *name, int flags, mode_t mode) { + int fd; - fd = open(name, flags, mode); - if (fd < 0) { - err(1, "%s", name); - } - if (remove(name) < 0) { - if (errno != ENOSYS) { - err(1, "%s: remove", name); - } - } - return fd; + fd = open(name, flags, mode); + if (fd < 0) { + err(1, "%s", name); + } + if (remove(name) < 0) { + if (errno != ENOSYS) { + err(1, "%s: remove", name); + } + } + return fd; } -static -void -openfiles(void) -{ - pid_t pid; +static void openfiles(void) { + pid_t pid; - pid = getpid(); + pid = getpid(); - snprintf(dataname, sizeof(dataname), ".tmp.tacdata.%d", (int)pid); - datafd = openscratch(dataname, O_RDWR|O_CREAT|O_TRUNC, 0664); + snprintf(dataname, sizeof(dataname), ".tmp.tacdata.%d", (int)pid); + datafd = openscratch(dataname, O_RDWR | O_CREAT | O_TRUNC, 0664); - snprintf(indexname, sizeof(indexname), ".tmp.tacindex.%d", (int)pid); - indexfd = openscratch(indexname, O_RDWR|O_CREAT|O_TRUNC, 0664); + snprintf(indexname, sizeof(indexname), ".tmp.tacindex.%d", (int)pid); + indexfd = openscratch(indexname, O_RDWR | O_CREAT | O_TRUNC, 0664); } -static -void -closefiles(void) -{ - close(datafd); - close(indexfd); - indexfd = datafd = -1; +static void closefiles(void) { + close(datafd); + close(indexfd); + indexfd = datafd = -1; } -int -main(int argc, char *argv[]) -{ - int i; +int main(int argc, char *argv[]) { + int i; - openfiles(); + openfiles(); - if (argc > 1) { - for (i=1; i 1) { + for (i = 1; i < argc; i++) { + readfile(argv[i]); + } + } else { + readfile(NULL); + } - dumpdata(); + dumpdata(); - closefiles(); - return 0; + closefiles(); + return 0; } diff --git a/userland/bin/true/true.c b/userland/bin/true/true.c index 68ab96e..8caf2a6 100644 --- a/userland/bin/true/true.c +++ b/userland/bin/true/true.c @@ -34,9 +34,7 @@ * true - succeed. */ -int -main(void) -{ - /* Just exit with success. */ - exit(0); +int main(void) { + /* Just exit with success. */ + exit(0); } diff --git a/userland/include/assert.h b/userland/include/assert.h index 4dbc2cd..0796a08 100644 --- a/userland/include/assert.h +++ b/userland/include/assert.h @@ -46,15 +46,14 @@ void __bad_assert(const char *file, int line, const char *msg); #ifdef NDEBUG -#if 0 /* not allowed by the C standard */ -#define assert(x) ((void)(x)) /* retain any side effects of X */ +#if 0 /* not allowed by the C standard */ +#define assert(x) ((void)(x)) /* retain any side effects of X */ #else -#define assert(x) ((void)0) /* mysteriously hide any side effects of X */ +#define assert(x) ((void)0) /* mysteriously hide any side effects of X */ #endif #else #define assert(x) ((x) ? (void)0 : __bad_assert(__FILE__, __LINE__, #x)) #endif - #endif /* _ASSERT_H_ */ diff --git a/userland/include/err.h b/userland/include/err.h index 8d3f9cb..a27a47c 100644 --- a/userland/include/err.h +++ b/userland/include/err.h @@ -30,8 +30,8 @@ #ifndef _ERR_H_ #define _ERR_H_ -#include /* for __DEAD */ -#include /* for __va_list */ +#include /* for __DEAD */ +#include /* for __va_list */ /* * 4.4BSD error-printing functions. diff --git a/userland/include/limits.h b/userland/include/limits.h index f488852..4c85ce8 100644 --- a/userland/include/limits.h +++ b/userland/include/limits.h @@ -38,16 +38,15 @@ #include /* Provide the real names */ -#define NAME_MAX __NAME_MAX -#define PATH_MAX __PATH_MAX -#define ARG_MAX __ARG_MAX -#define PID_MIN __PID_MIN -#define PID_MAX __PID_MAX -#define PIPE_BUF __PIPE_BUF -#define NGROUPS_MAX __NGROUPS_MAX -#define LOGIN_NAME_MAX __LOGIN_NAME_MAX -#define OPEN_MAX __OPEN_MAX -#define IOV_MAX __IOV_MAX - +#define NAME_MAX __NAME_MAX +#define PATH_MAX __PATH_MAX +#define ARG_MAX __ARG_MAX +#define PID_MIN __PID_MIN +#define PID_MAX __PID_MAX +#define PIPE_BUF __PIPE_BUF +#define NGROUPS_MAX __NGROUPS_MAX +#define LOGIN_NAME_MAX __LOGIN_NAME_MAX +#define OPEN_MAX __OPEN_MAX +#define IOV_MAX __IOV_MAX #endif /* _LIMITS_H_ */ diff --git a/userland/include/stdarg.h b/userland/include/stdarg.h index f17f2ab..bc6dce3 100644 --- a/userland/include/stdarg.h +++ b/userland/include/stdarg.h @@ -43,12 +43,12 @@ typedef __va_list va_list; #if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8) -#define va_start(ap, fmt) __builtin_stdarg_start(ap, fmt) +#define va_start(ap, fmt) __builtin_stdarg_start(ap, fmt) #else -#define va_start(ap, fmt) __builtin_va_start(ap, fmt) +#define va_start(ap, fmt) __builtin_va_start(ap, fmt) #endif -#define va_arg(ap,t) __builtin_va_arg(ap,t) -#define va_copy(ap1,ap2) __builtin_va_copy(ap1,ap2) +#define va_arg(ap, t) __builtin_va_arg(ap, t) +#define va_copy(ap1, ap2) __builtin_va_copy(ap1, ap2) #define va_end(ap) __builtin_va_end(ap) #endif /* _STDARG_H_ */ diff --git a/userland/include/stdio.h b/userland/include/stdio.h index 20e96cb..d72f26c 100644 --- a/userland/include/stdio.h +++ b/userland/include/stdio.h @@ -46,9 +46,7 @@ * (for libc internal use only) */ int __vprintf(void (*sendfunc)(void *clientdata, const char *, size_t len), - void *clientdata, - const char *fmt, - __va_list ap); + void *clientdata, const char *fmt, __va_list ap); /* Printf calls for user programs */ int printf(const char *fmt, ...); diff --git a/userland/include/stdlib.h b/userland/include/stdlib.h index eaa3169..ea5a0b6 100644 --- a/userland/include/stdlib.h +++ b/userland/include/stdlib.h @@ -64,7 +64,7 @@ int system(const char *command); /* * Pseudo-random number generator. */ -#define RAND_MAX 0x7fffffff +#define RAND_MAX 0x7fffffff long random(void); void srandom(unsigned long seed); char *initstate(unsigned long, char *, size_t); @@ -80,6 +80,6 @@ void free(void *ptr); * Sort. */ void qsort(void *data, unsigned num, size_t size, - int (*f)(const void *, const void *)); + int (*f)(const void *, const void *)); #endif /* _STDLIB_H_ */ diff --git a/userland/include/string.h b/userland/include/string.h index 2c9de95..b8fefba 100644 --- a/userland/include/string.h +++ b/userland/include/string.h @@ -61,5 +61,4 @@ const char *strerror(int errcode); */ void bzero(void *, size_t); - #endif /* _STRING_H_ */ diff --git a/userland/include/sys/stat.h b/userland/include/sys/stat.h index 5ee6580..863c89a 100644 --- a/userland/include/sys/stat.h +++ b/userland/include/sys/stat.h @@ -44,7 +44,7 @@ #define S_ISDIR(mode) ((mode & _S_IFMT) == _S_IFDIR) #define S_ISLNK(mode) ((mode & _S_IFMT) == _S_IFLNK) #define S_ISIFO(mode) ((mode & _S_IFMT) == _S_IFIFO) -#define S_ISSOCK(mode) ((mode & _S_IFMT) ==_S_IFSOCK) +#define S_ISSOCK(mode) ((mode & _S_IFMT) == _S_IFSOCK) #define S_ISCHR(mode) ((mode & _S_IFMT) == _S_IFCHR) #define S_ISBLK(mode) ((mode & _S_IFMT) == _S_IFBLK) @@ -52,14 +52,14 @@ * Provide non-underscore names. These are not actually standard; for * some reason only the test macros are. */ -#define S_IFMT _S_IFMT -#define S_IFREG _S_IFREG -#define S_IFDIR _S_IFDIR -#define S_IFLNK _S_IFLNK -#define S_IFIFO _S_IFIFO +#define S_IFMT _S_IFMT +#define S_IFREG _S_IFREG +#define S_IFDIR _S_IFDIR +#define S_IFLNK _S_IFLNK +#define S_IFIFO _S_IFIFO #define S_IFSOCK _S_IFSOCK -#define S_IFCHR _S_IFCHR -#define S_IFBLK _S_IFBLK +#define S_IFCHR _S_IFCHR +#define S_IFBLK _S_IFBLK /* * stat is the same as fstat, only on a file that isn't already @@ -79,5 +79,4 @@ int lstat(const char *path, struct stat *buf); */ int mkdir(const char *dirname, int ignore); - #endif /* _SYS_STAT_H_ */ diff --git a/userland/include/sys/types.h b/userland/include/sys/types.h index a3f8f94..63002c3 100644 --- a/userland/include/sys/types.h +++ b/userland/include/sys/types.h @@ -83,5 +83,4 @@ typedef __socklen_t socklen_t; #define CHAR_BIT __CHAR_BIT - #endif /* _SYS_TYPES_H_ */ diff --git a/userland/include/unistd.h b/userland/include/unistd.h index 44f2c6a..9739344 100644 --- a/userland/include/unistd.h +++ b/userland/include/unistd.h @@ -46,7 +46,6 @@ #include #include - /* * Prototypes for OS/161 system calls. * @@ -97,7 +96,6 @@ * the text of the various assignments for an authoritative list. */ - /* * NOTE NOTE NOTE NOTE NOTE * @@ -107,7 +105,6 @@ * functions will usually have slightly different signatures. */ - /* Required. */ __DEAD void _exit(int code); int execv(const char *prog, char *const *args); @@ -156,7 +153,7 @@ ssize_t __getcwd(char *buf, size_t buflen); */ int execvp(const char *prog, char *const *args); /* calls execv */ -char *getcwd(char *buf, size_t buflen); /* calls __getcwd */ -time_t time(time_t *seconds); /* calls __time */ +char *getcwd(char *buf, size_t buflen); /* calls __getcwd */ +time_t time(time_t *seconds); /* calls __time */ #endif /* _UNISTD_H_ */ diff --git a/userland/lib/hostcompat/err.c b/userland/lib/hostcompat/err.c index 7c81928..9b6eab3 100644 --- a/userland/lib/hostcompat/err.c +++ b/userland/lib/hostcompat/err.c @@ -48,45 +48,40 @@ extern const char *hostcompat_progname; /* * Common routine for all the *err* and *warn* functions. */ -static -void -hostcompat_printerr(int use_errno, const char *fmt, va_list ap) -{ - const char *errmsg; +static void hostcompat_printerr(int use_errno, const char *fmt, va_list ap) { + const char *errmsg; - /* - * Get the error message for the current errno. - * Do this early, before doing anything that might change the - * value in errno. - */ - errmsg = strerror(errno); + /* + * Get the error message for the current errno. + * Do this early, before doing anything that might change the + * value in errno. + */ + errmsg = strerror(errno); - /* - * Look up the program name. - * Strictly speaking we should pull off the rightmost - * path component of argv[0] and use that as the program - * name (this is how BSD err* prints) but it doesn't make - * much difference. - */ - if (hostcompat_progname != NULL) { - fprintf(stderr, "%s: ", hostcompat_progname); - } - else { - fprintf(stderr, "libhostcompat: hostcompat_init not called\n"); - fprintf(stderr, "libhostcompat-program: "); - } + /* + * Look up the program name. + * Strictly speaking we should pull off the rightmost + * path component of argv[0] and use that as the program + * name (this is how BSD err* prints) but it doesn't make + * much difference. + */ + if (hostcompat_progname != NULL) { + fprintf(stderr, "%s: ", hostcompat_progname); + } else { + fprintf(stderr, "libhostcompat: hostcompat_init not called\n"); + fprintf(stderr, "libhostcompat-program: "); + } - /* process the printf format and args */ - vfprintf(stderr, fmt, ap); + /* process the printf format and args */ + vfprintf(stderr, fmt, ap); - if (use_errno) { - /* if we're using errno, print the error string from above. */ - fprintf(stderr, ": %s\n", errmsg); - } - else { - /* otherwise, just a newline. */ - fprintf(stderr, "\n"); - } + if (use_errno) { + /* if we're using errno, print the error string from above. */ + fprintf(stderr, ": %s\n", errmsg); + } else { + /* otherwise, just a newline. */ + fprintf(stderr, "\n"); + } } /* @@ -94,33 +89,21 @@ hostcompat_printerr(int use_errno, const char *fmt, va_list ap) */ /* warn/vwarn: use errno, don't exit */ -void -vwarn(const char *fmt, va_list ap) -{ - hostcompat_printerr(1, fmt, ap); -} +void vwarn(const char *fmt, va_list ap) { hostcompat_printerr(1, fmt, ap); } /* warnx/vwarnx: don't use errno, don't exit */ -void -vwarnx(const char *fmt, va_list ap) -{ - hostcompat_printerr(0, fmt, ap); -} +void vwarnx(const char *fmt, va_list ap) { hostcompat_printerr(0, fmt, ap); } /* err/verr: use errno, then exit */ -void -verr(int exitcode, const char *fmt, va_list ap) -{ - hostcompat_printerr(1, fmt, ap); - exit(exitcode); +void verr(int exitcode, const char *fmt, va_list ap) { + hostcompat_printerr(1, fmt, ap); + exit(exitcode); } /* errx/verrx: don't use errno, but do then exit */ -void -verrx(int exitcode, const char *fmt, va_list ap) -{ - hostcompat_printerr(0, fmt, ap); - exit(exitcode); +void verrx(int exitcode, const char *fmt, va_list ap) { + hostcompat_printerr(0, fmt, ap); + exit(exitcode); } /* @@ -128,40 +111,32 @@ verrx(int exitcode, const char *fmt, va_list ap) * Just hand off to the va_list versions. */ -void -warn(const char *fmt, ...) -{ - va_list ap; - va_start(ap, fmt); - vwarn(fmt, ap); - va_end(ap); +void warn(const char *fmt, ...) { + va_list ap; + va_start(ap, fmt); + vwarn(fmt, ap); + va_end(ap); } -void -warnx(const char *fmt, ...) -{ - va_list ap; - va_start(ap, fmt); - vwarnx(fmt, ap); - va_end(ap); +void warnx(const char *fmt, ...) { + va_list ap; + va_start(ap, fmt); + vwarnx(fmt, ap); + va_end(ap); } -void -err(int exitcode, const char *fmt, ...) -{ - va_list ap; - va_start(ap, fmt); - verr(exitcode, fmt, ap); - va_end(ap); +void err(int exitcode, const char *fmt, ...) { + va_list ap; + va_start(ap, fmt); + verr(exitcode, fmt, ap); + va_end(ap); } -void -errx(int exitcode, const char *fmt, ...) -{ - va_list ap; - va_start(ap, fmt); - verrx(exitcode, fmt, ap); - va_end(ap); +void errx(int exitcode, const char *fmt, ...) { + va_list ap; + va_start(ap, fmt); + verrx(exitcode, fmt, ap); + va_end(ap); } #endif /* NEED_ERR */ diff --git a/userland/lib/hostcompat/host-err.h b/userland/lib/hostcompat/host-err.h index fd41a22..d3238f3 100644 --- a/userland/lib/hostcompat/host-err.h +++ b/userland/lib/hostcompat/host-err.h @@ -27,7 +27,6 @@ * SUCH DAMAGE. */ - #ifndef HOSTCOMPAT_ERR_H #define HOSTCOMPAT_ERR_H diff --git a/userland/lib/hostcompat/hostcompat.c b/userland/lib/hostcompat/hostcompat.c index 8e9db6d..187d5ff 100644 --- a/userland/lib/hostcompat/hostcompat.c +++ b/userland/lib/hostcompat/hostcompat.c @@ -51,188 +51,168 @@ static struct termios hostcompat_savetios; /* * Put the tty state back the way it was. */ -static -void -hostcompat_ttyreset(void) -{ - tcsetattr(STDIN_FILENO, TCSADRAIN, &hostcompat_savetios); +static void hostcompat_ttyreset(void) { + tcsetattr(STDIN_FILENO, TCSADRAIN, &hostcompat_savetios); } /* * Set the tty state back to the way we want it for running. */ -static -void -hostcompat_ttyresume(void) -{ - tcsetattr(STDIN_FILENO, TCSADRAIN, &hostcompat_runtios); +static void hostcompat_ttyresume(void) { + tcsetattr(STDIN_FILENO, TCSADRAIN, &hostcompat_runtios); } /* * Set up the tty state stuff. */ -static -int -hostcompat_ttysetup(void) -{ - struct termios tios; +static int hostcompat_ttysetup(void) { + struct termios tios; - /* Get the current tty state. */ - if (tcgetattr(STDIN_FILENO, &tios) < 0) { - /* stdin is not a tty */ - return -1; - } + /* Get the current tty state. */ + if (tcgetattr(STDIN_FILENO, &tios) < 0) { + /* stdin is not a tty */ + return -1; + } - hostcompat_savetios = tios; + hostcompat_savetios = tios; - /* Turn off canonical ("cooked") input. */ - tios.c_lflag &= ~ICANON; + /* Turn off canonical ("cooked") input. */ + tios.c_lflag &= ~ICANON; - /* - * With canonical input off, this says how many characters must be - * typed before read() will return. - */ - tios.c_cc[VMIN] = 1; + /* + * With canonical input off, this says how many characters must be + * typed before read() will return. + */ + tios.c_cc[VMIN] = 1; - /* This can be used to set up read timeouts, but we don't need that. */ - tios.c_cc[VTIME] = 0; + /* This can be used to set up read timeouts, but we don't need that. */ + tios.c_cc[VTIME] = 0; - /* Turn off echoing of keypresses. */ - tios.c_lflag &= ~(ECHO|ECHONL|ECHOCTL); + /* Turn off echoing of keypresses. */ + tios.c_lflag &= ~(ECHO | ECHONL | ECHOCTL); - /* Do not support XON/XOFF flow control. */ - tios.c_iflag &= ~(IXON|IXOFF); + /* Do not support XON/XOFF flow control. */ + tios.c_iflag &= ~(IXON | IXOFF); - /* On input, we want no CR/LF translation. */ - tios.c_iflag &= ~(INLCR|IGNCR|ICRNL); + /* On input, we want no CR/LF translation. */ + tios.c_iflag &= ~(INLCR | IGNCR | ICRNL); - /* However, on output we want LF ('\n') mapped to CRLF. */ -#ifdef OCRNL /* missing on OS X */ - tios.c_oflag &= ~(OCRNL); + /* However, on output we want LF ('\n') mapped to CRLF. */ +#ifdef OCRNL /* missing on OS X */ + tios.c_oflag &= ~(OCRNL); #endif - tios.c_oflag |= OPOST|ONLCR; + tios.c_oflag |= OPOST | ONLCR; - /* Enable keyboard signals (^C, ^Z, etc.) because they're useful. */ - tios.c_lflag |= ISIG; + /* Enable keyboard signals (^C, ^Z, etc.) because they're useful. */ + tios.c_lflag |= ISIG; - /* Set the new tty state. */ - hostcompat_runtios = tios; - tcsetattr(STDIN_FILENO, TCSADRAIN, &tios); + /* Set the new tty state. */ + hostcompat_runtios = tios; + tcsetattr(STDIN_FILENO, TCSADRAIN, &tios); - return 0; + return 0; } /* * Signal handler for all the fatal signals (SIGSEGV, SIGTERM, etc.) */ -static -void -hostcompat_die(int sig) -{ - /* Set the tty back to the way we found it */ - hostcompat_ttyreset(); +static void hostcompat_die(int sig) { + /* Set the tty back to the way we found it */ + hostcompat_ttyreset(); - /* Make sure the default action will occur when we get another signal*/ - signal(sig, SIG_DFL); + /* Make sure the default action will occur when we get another signal*/ + signal(sig, SIG_DFL); - /* Post the signal back to ourselves, to cause the right exit status.*/ - kill(getpid(), sig); + /* Post the signal back to ourselves, to cause the right exit status.*/ + kill(getpid(), sig); - /* Just in case. */ - _exit(255); + /* Just in case. */ + _exit(255); } /* * Signal handler for the stop signals (SIGTSTP, SIGTTIN, etc.) */ -static -void -hostcompat_stop(int sig) -{ - /* Set the tty back to the way we found it */ - hostcompat_ttyreset(); +static void hostcompat_stop(int sig) { + /* Set the tty back to the way we found it */ + hostcompat_ttyreset(); - /* Make sure the default action will occur when we get another signal*/ - signal(sig, SIG_DFL); + /* Make sure the default action will occur when we get another signal*/ + signal(sig, SIG_DFL); - /* Post the signal back to ourselves. */ - kill(getpid(), sig); + /* Post the signal back to ourselves. */ + kill(getpid(), sig); } /* * Signal handler for SIGCONT. */ -static -void -hostcompat_cont(int sig) -{ - (void)sig; +static void hostcompat_cont(int sig) { + (void)sig; - /* Set the tty to the way we want it for running. */ - hostcompat_ttyresume(); + /* Set the tty to the way we want it for running. */ + hostcompat_ttyresume(); - /* - * Reload the signal handlers for stop/continue signals, in case - * they were set up with one-shot signals. - */ - signal(SIGTTIN, hostcompat_stop); - signal(SIGTTOU, hostcompat_stop); - signal(SIGTSTP, hostcompat_stop); - signal(SIGCONT, hostcompat_cont); + /* + * Reload the signal handlers for stop/continue signals, in case + * they were set up with one-shot signals. + */ + signal(SIGTTIN, hostcompat_stop); + signal(SIGTTOU, hostcompat_stop); + signal(SIGTSTP, hostcompat_stop); + signal(SIGCONT, hostcompat_cont); } /* * Initialize the hostcompat library. */ -void -hostcompat_init(int argc, char *argv[]) -{ - /* Set the program name */ - if (argc > 0 && argv[0] != NULL) { - hostcompat_progname = argv[0]; - } +void hostcompat_init(int argc, char *argv[]) { + /* Set the program name */ + if (argc > 0 && argv[0] != NULL) { + hostcompat_progname = argv[0]; + } - /* Set the tty modes */ - if (hostcompat_ttysetup() < 0) { - return; - } + /* Set the tty modes */ + if (hostcompat_ttysetup() < 0) { + return; + } - /* When exit() is called, clean up */ - atexit(hostcompat_ttyreset); + /* When exit() is called, clean up */ + atexit(hostcompat_ttyreset); - /* stdout/stderr should be unbuffered */ - setvbuf(stdout, NULL, _IONBF, 0); - setvbuf(stderr, NULL, _IONBF, 0); + /* stdout/stderr should be unbuffered */ + setvbuf(stdout, NULL, _IONBF, 0); + setvbuf(stderr, NULL, _IONBF, 0); - /* Catch all the fatal signals, so we can clean up */ - signal(SIGHUP, hostcompat_die); - signal(SIGINT, hostcompat_die); - signal(SIGQUIT, hostcompat_die); - signal(SIGILL, hostcompat_die); - signal(SIGTRAP, hostcompat_die); - signal(SIGABRT, hostcompat_die); + /* Catch all the fatal signals, so we can clean up */ + signal(SIGHUP, hostcompat_die); + signal(SIGINT, hostcompat_die); + signal(SIGQUIT, hostcompat_die); + signal(SIGILL, hostcompat_die); + signal(SIGTRAP, hostcompat_die); + signal(SIGABRT, hostcompat_die); #ifdef SIGEMT - signal(SIGEMT, hostcompat_die); + signal(SIGEMT, hostcompat_die); #endif - signal(SIGFPE, hostcompat_die); - signal(SIGBUS, hostcompat_die); - signal(SIGSEGV, hostcompat_die); - signal(SIGSYS, hostcompat_die); - signal(SIGPIPE, hostcompat_die); - signal(SIGALRM, hostcompat_die); - signal(SIGTERM, hostcompat_die); - signal(SIGXCPU, hostcompat_die); - signal(SIGXFSZ, hostcompat_die); - signal(SIGVTALRM, hostcompat_die); - signal(SIGPROF, hostcompat_die); - signal(SIGUSR1, hostcompat_die); - signal(SIGUSR2, hostcompat_die); + signal(SIGFPE, hostcompat_die); + signal(SIGBUS, hostcompat_die); + signal(SIGSEGV, hostcompat_die); + signal(SIGSYS, hostcompat_die); + signal(SIGPIPE, hostcompat_die); + signal(SIGALRM, hostcompat_die); + signal(SIGTERM, hostcompat_die); + signal(SIGXCPU, hostcompat_die); + signal(SIGXFSZ, hostcompat_die); + signal(SIGVTALRM, hostcompat_die); + signal(SIGPROF, hostcompat_die); + signal(SIGUSR1, hostcompat_die); + signal(SIGUSR2, hostcompat_die); - /* Catch the stop signals, so we can adjust the tty */ - signal(SIGTTIN, hostcompat_stop); - signal(SIGTTOU, hostcompat_stop); - signal(SIGTSTP, hostcompat_stop); + /* Catch the stop signals, so we can adjust the tty */ + signal(SIGTTIN, hostcompat_stop); + signal(SIGTTOU, hostcompat_stop); + signal(SIGTSTP, hostcompat_stop); - /* Catch the continue signal, so we can adjust the tty */ - signal(SIGCONT, hostcompat_cont); + /* Catch the continue signal, so we can adjust the tty */ + signal(SIGCONT, hostcompat_cont); } diff --git a/userland/lib/hostcompat/hostcompat.h b/userland/lib/hostcompat/hostcompat.h index 7191964..00e9c0e 100644 --- a/userland/lib/hostcompat/hostcompat.h +++ b/userland/lib/hostcompat/hostcompat.h @@ -27,7 +27,6 @@ * SUCH DAMAGE. */ - #include #include diff --git a/userland/lib/hostcompat/ntohll.c b/userland/lib/hostcompat/ntohll.c index 2131fdc..cc9ce5d 100644 --- a/userland/lib/hostcompat/ntohll.c +++ b/userland/lib/hostcompat/ntohll.c @@ -34,20 +34,18 @@ #ifdef NEED_NTOHLL -uint64_t -ntohll(uint64_t x) -{ - uint32_t x0, x1, y0, y1; +uint64_t ntohll(uint64_t x) { + uint32_t x0, x1, y0, y1; - if (ntohl(1) == 1) { - return x; - } + if (ntohl(1) == 1) { + return x; + } - x0 = x & 0xffffffff; - y0 = ntohl(x0); - x1 = x >> 32; - y1 = ntohl(x1); - return ((uint64_t)y0 << 32) | y1; + x0 = x & 0xffffffff; + y0 = ntohl(x0); + x1 = x >> 32; + y1 = ntohl(x1); + return ((uint64_t)y0 << 32) | y1; } #endif diff --git a/userland/lib/hostcompat/time.c b/userland/lib/hostcompat/time.c index 5a687d4..01cb070 100644 --- a/userland/lib/hostcompat/time.c +++ b/userland/lib/hostcompat/time.c @@ -33,22 +33,20 @@ #include #include -#include /* sometimes required for NULL */ +#include /* sometimes required for NULL */ #include "hostcompat.h" -time_t -__time(time_t *secs, unsigned long *nsecs) -{ - struct timeval tv; - if (gettimeofday(&tv, NULL) < 0) { - return -1; - } - if (secs) { - *secs = tv.tv_sec; - } - if (nsecs) { - *nsecs = tv.tv_usec * 1000; - } - return tv.tv_sec; +time_t __time(time_t *secs, unsigned long *nsecs) { + struct timeval tv; + if (gettimeofday(&tv, NULL) < 0) { + return -1; + } + if (secs) { + *secs = tv.tv_sec; + } + if (nsecs) { + *nsecs = tv.tv_usec * 1000; + } + return tv.tv_sec; } diff --git a/userland/lib/libc/stdio/__puts.c b/userland/lib/libc/stdio/__puts.c index 6db7ea8..d5a08ce 100644 --- a/userland/lib/libc/stdio/__puts.c +++ b/userland/lib/libc/stdio/__puts.c @@ -38,16 +38,14 @@ * Returns the length of the string printed. */ -int -__puts(const char *str) -{ - size_t len; - ssize_t ret; +int __puts(const char *str) { + size_t len; + ssize_t ret; - len = strlen(str); - ret = write(STDOUT_FILENO, str, len); - if (ret == -1) { - return EOF; - } - return len; + len = strlen(str); + ret = write(STDOUT_FILENO, str, len); + if (ret == -1) { + return EOF; + } + return len; } diff --git a/userland/lib/libc/stdio/getchar.c b/userland/lib/libc/stdio/getchar.c index 4f6c94c..8a0ed5f 100644 --- a/userland/lib/libc/stdio/getchar.c +++ b/userland/lib/libc/stdio/getchar.c @@ -35,22 +35,20 @@ * and return it or the symbolic constant EOF (-1). */ -int -getchar(void) -{ - char ch; - int len; +int getchar(void) { + char ch; + int len; - len = read(STDIN_FILENO, &ch, 1); - if (len<=0) { - /* end of file or error */ - return EOF; - } + len = read(STDIN_FILENO, &ch, 1); + if (len <= 0) { + /* end of file or error */ + return EOF; + } - /* - * Cast through unsigned char, to prevent sign extension. This - * sends back values on the range 0-255, rather than -128 to 127, - * so EOF can be distinguished from legal input. - */ - return (int)(unsigned char)ch; + /* + * Cast through unsigned char, to prevent sign extension. This + * sends back values on the range 0-255, rather than -128 to 127, + * so EOF can be distinguished from legal input. + */ + return (int)(unsigned char)ch; } diff --git a/userland/lib/libc/stdio/printf.c b/userland/lib/libc/stdio/printf.c index f0d627b..4dc85b2 100644 --- a/userland/lib/libc/stdio/printf.c +++ b/userland/lib/libc/stdio/printf.c @@ -36,43 +36,35 @@ * printf - C standard I/O function. */ - /* * Function passed to __vprintf to do the actual output. */ -static -void -__printf_send(void *mydata, const char *data, size_t len) -{ - ssize_t ret; - int *err = mydata; +static void __printf_send(void *mydata, const char *data, size_t len) { + ssize_t ret; + int *err = mydata; - ret = write(STDOUT_FILENO, data, len); - *err = (ret == -1) ? errno : 0; + ret = write(STDOUT_FILENO, data, len); + *err = (ret == -1) ? errno : 0; } /* printf: hand off to vprintf */ -int -printf(const char *fmt, ...) -{ - int chars; - va_list ap; +int printf(const char *fmt, ...) { + int chars; + va_list ap; - va_start(ap, fmt); - chars = vprintf(fmt, ap); - va_end(ap); - return chars; + va_start(ap, fmt); + chars = vprintf(fmt, ap); + va_end(ap); + return chars; } /* vprintf: call __vprintf to do the work. */ -int -vprintf(const char *fmt, va_list ap) -{ - int chars, err; - chars = __vprintf(__printf_send, &err, fmt, ap); - if (err) { - errno = err; - return -1; - } - return chars; +int vprintf(const char *fmt, va_list ap) { + int chars, err; + chars = __vprintf(__printf_send, &err, fmt, ap); + if (err) { + errno = err; + return -1; + } + return chars; } diff --git a/userland/lib/libc/stdio/putchar.c b/userland/lib/libc/stdio/putchar.c index 977cdde..15bd9db 100644 --- a/userland/lib/libc/stdio/putchar.c +++ b/userland/lib/libc/stdio/putchar.c @@ -37,14 +37,12 @@ * writing that code is not really worthwhile. */ -int -putchar(int ch) -{ - char c = ch; - int len; - len = write(STDOUT_FILENO, &c, 1); - if (len<=0) { - return EOF; - } - return ch; +int putchar(int ch) { + char c = ch; + int len; + len = write(STDOUT_FILENO, &c, 1); + if (len <= 0) { + return EOF; + } + return ch; } diff --git a/userland/lib/libc/stdio/puts.c b/userland/lib/libc/stdio/puts.c index 8b5724f..67aa8c3 100644 --- a/userland/lib/libc/stdio/puts.c +++ b/userland/lib/libc/stdio/puts.c @@ -33,10 +33,8 @@ * C standard I/O function - print a string and a newline. */ -int -puts(const char *s) -{ - __puts(s); - putchar('\n'); - return 0; +int puts(const char *s) { + __puts(s); + putchar('\n'); + return 0; } diff --git a/userland/lib/libc/stdlib/abort.c b/userland/lib/libc/stdlib/abort.c index 807de26..98c2ca5 100644 --- a/userland/lib/libc/stdlib/abort.c +++ b/userland/lib/libc/stdlib/abort.c @@ -38,8 +38,4 @@ * nonzero exit code, skipping any libc cleanup. */ -void -abort(void) -{ - _exit(255); -} +void abort(void) { _exit(255); } diff --git a/userland/lib/libc/stdlib/exit.c b/userland/lib/libc/stdlib/exit.c index 8838aad..17a933f 100644 --- a/userland/lib/libc/stdlib/exit.c +++ b/userland/lib/libc/stdlib/exit.c @@ -34,50 +34,49 @@ * C standard function: exit process. */ -void -exit(int code) -{ - /* - * In a more complicated libc, this would call functions registered - * with atexit() before calling the syscall to actually exit. - */ +void exit(int code) { + /* + * In a more complicated libc, this would call functions registered + * with atexit() before calling the syscall to actually exit. + */ #ifdef __mips__ - /* - * Because gcc knows that _exit doesn't return, if we call it - * directly it will drop any code that follows it. This means - * that if _exit *does* return, as happens before it's - * implemented, undefined and usually weird behavior ensues. - * - * As a hack (this is quite gross) do the call by hand in an - * asm block. Then gcc doesn't know what it is, and won't - * optimize the following code out, and we can make sure - * that exit() at least really does not return. - * - * This asm block violates gcc's asm rules by destroying a - * register it doesn't declare ($4, which is a0) but this - * hopefully doesn't matter as the only local it can lose - * track of is "code" and we don't use it afterwards. - */ - __asm volatile("jal _exit;" /* call _exit */ - "move $4, %0" /* put code in a0 (delay slot) */ - : /* no outputs */ - : "r" (code)); /* code is an input */ - /* - * Ok, exiting doesn't work; see if we can get our process - * killed by making an illegal memory access. Use a magic - * number address so the symptoms are recognizable and - * unlikely to occur by accident otherwise. - */ - __asm volatile("li $2, 0xeeeee00f;" /* load magic addr into v0 */ - "lw $2, 0($2)" /* fetch from it */ - :: ); /* no args */ + /* + * Because gcc knows that _exit doesn't return, if we call it + * directly it will drop any code that follows it. This means + * that if _exit *does* return, as happens before it's + * implemented, undefined and usually weird behavior ensues. + * + * As a hack (this is quite gross) do the call by hand in an + * asm block. Then gcc doesn't know what it is, and won't + * optimize the following code out, and we can make sure + * that exit() at least really does not return. + * + * This asm block violates gcc's asm rules by destroying a + * register it doesn't declare ($4, which is a0) but this + * hopefully doesn't matter as the only local it can lose + * track of is "code" and we don't use it afterwards. + */ + __asm volatile("jal _exit;" /* call _exit */ + "move $4, %0" /* put code in a0 (delay slot) */ + : /* no outputs */ + : "r"(code)); /* code is an input */ + /* + * Ok, exiting doesn't work; see if we can get our process + * killed by making an illegal memory access. Use a magic + * number address so the symptoms are recognizable and + * unlikely to occur by accident otherwise. + */ + __asm volatile("li $2, 0xeeeee00f;" /* load magic addr into v0 */ + "lw $2, 0($2)" /* fetch from it */ + ::); /* no args */ #else - _exit(code); + _exit(code); #endif - /* - * We can't return; so if we can't exit, the only other choice - * is to loop. - */ - while (1) { } + /* + * We can't return; so if we can't exit, the only other choice + * is to loop. + */ + while (1) { + } } diff --git a/userland/lib/libc/stdlib/getenv.c b/userland/lib/libc/stdlib/getenv.c index 1eda471..c67b105 100644 --- a/userland/lib/libc/stdlib/getenv.c +++ b/userland/lib/libc/stdlib/getenv.c @@ -45,34 +45,28 @@ extern char **__environ; * This is what we use by default if the kernel didn't supply an * environment. */ -static const char *__default_environ[] = { - "PATH=/bin:/sbin:/testbin", - "SHELL=/bin/sh", - "TERM=vt220", - NULL -}; +static const char *__default_environ[] = {"PATH=/bin:/sbin:/testbin", + "SHELL=/bin/sh", "TERM=vt220", NULL}; -char * -getenv(const char *var) -{ - size_t varlen, thislen; - char *s; - unsigned i; +char *getenv(const char *var) { + size_t varlen, thislen; + char *s; + unsigned i; - if (__environ == NULL) { - __environ = (char **)__default_environ; - } - varlen = strlen(var); - for (i=0; __environ[i] != NULL; i++) { - s = strchr(__environ[i], '='); - if (s == NULL) { - /* ? */ - continue; - } - thislen = s - __environ[i]; - if (thislen == varlen && !memcmp(__environ[i], var, thislen)) { - return s + 1; - } - } - return NULL; + if (__environ == NULL) { + __environ = (char **)__default_environ; + } + varlen = strlen(var); + for (i = 0; __environ[i] != NULL; i++) { + s = strchr(__environ[i], '='); + if (s == NULL) { + /* ? */ + continue; + } + thislen = s - __environ[i]; + if (thislen == varlen && !memcmp(__environ[i], var, thislen)) { + return s + 1; + } + } + return NULL; } diff --git a/userland/lib/libc/stdlib/malloc.c b/userland/lib/libc/stdlib/malloc.c index 4a21153..20d0d43 100644 --- a/userland/lib/libc/stdlib/malloc.c +++ b/userland/lib/libc/stdlib/malloc.c @@ -37,7 +37,7 @@ */ #include -#include // for uintptr_t on non-OS/161 platforms +#include // for uintptr_t on non-OS/161 platforms #include #include #include @@ -74,33 +74,33 @@ struct mheader { #define MBLOCKSIZE 8 #define MBLOCKSHIFT 3 #define MMAGIC 2 - /* - * 32-bit platform. size_t is 32 bits (4 bytes). - * Block size is 8 bytes. - */ - unsigned mh_prevblock:29; - unsigned mh_pad:1; - unsigned mh_magic1:2; + /* + * 32-bit platform. size_t is 32 bits (4 bytes). + * Block size is 8 bytes. + */ + unsigned mh_prevblock : 29; + unsigned mh_pad : 1; + unsigned mh_magic1 : 2; - unsigned mh_nextblock:29; - unsigned mh_inuse:1; - unsigned mh_magic2:2; + unsigned mh_nextblock : 29; + unsigned mh_inuse : 1; + unsigned mh_magic2 : 2; #elif defined(MALLOC64) #define MBLOCKSIZE 16 #define MBLOCKSHIFT 4 #define MMAGIC 6 - /* - * 64-bit platform. size_t is 64 bits (8 bytes) - * Block size is 16 bytes. - */ - unsigned mh_prevblock:60; - unsigned mh_pad:1; - unsigned mh_magic1:3; + /* + * 64-bit platform. size_t is 64 bits (8 bytes) + * Block size is 16 bytes. + */ + unsigned mh_prevblock : 60; + unsigned mh_pad : 1; + unsigned mh_magic1 : 3; - unsigned mh_nextblock:60; - unsigned mh_inuse:1; - unsigned mh_magic2:3; + unsigned mh_nextblock : 60; + unsigned mh_inuse : 1; + unsigned mh_magic2 : 3; #else #error "please fix me" @@ -122,17 +122,17 @@ struct mheader { * (value should include the header size) */ -#define M_NEXTOFF(mh) ((size_t)(((size_t)((mh)->mh_nextblock))<mh_prevblock))<mh_nextblock)) << MBLOCKSHIFT)) +#define M_PREVOFF(mh) ((size_t)(((size_t)((mh)->mh_prevblock)) << MBLOCKSHIFT)) +#define M_NEXT(mh) ((struct mheader *)(((char *)(mh)) + M_NEXTOFF(mh))) +#define M_PREV(mh) ((struct mheader *)(((char *)(mh)) - M_PREVOFF(mh))) -#define M_DATA(mh) ((void *)((mh)+1)) -#define M_SIZE(mh) (M_NEXTOFF(mh)-MBLOCKSIZE) +#define M_DATA(mh) ((void *)((mh) + 1)) +#define M_SIZE(mh) (M_NEXTOFF(mh) - MBLOCKSIZE) -#define M_OK(mh) ((mh)->mh_magic1==MMAGIC && (mh)->mh_magic2==MMAGIC) +#define M_OK(mh) ((mh)->mh_magic1 == MMAGIC && (mh)->mh_magic2 == MMAGIC) -#define M_MKFIELD(off) ((off)>>MBLOCKSHIFT) +#define M_MKFIELD(off) ((off) >> MBLOCKSHIFT) /* * System page size. In POSIX you're supposed to call @@ -157,68 +157,65 @@ static uintptr_t __heapbase, __heaptop; /* * Setup function. */ -static -void -__malloc_init(void) -{ - void *x; +static void __malloc_init(void) { + void *x; - /* - * Check various assumed properties of the sizes. - */ - if (sizeof(struct mheader) != MBLOCKSIZE) { - errx(1, "malloc: Internal error - MBLOCKSIZE wrong"); - } - if ((MBLOCKSIZE & (MBLOCKSIZE-1))!=0) { - errx(1, "malloc: Internal error - MBLOCKSIZE not power of 2"); - } - if (1<mh_prevblock != rightprevblock) { - errx(1, "malloc: Heap corrupt; header at 0x%lx" - " has bad previous-block size %lu " - "(should be %lu)", - (unsigned long) i, - (unsigned long) mh->mh_prevblock << MBLOCKSHIFT, - (unsigned long) rightprevblock << MBLOCKSHIFT); - } - rightprevblock = mh->mh_nextblock; + rightprevblock = 0; + for (i = __heapbase; i < __heaptop; i += M_NEXTOFF(mh)) { + mh = (struct mheader *)i; + if (!M_OK(mh)) { + errx(1, + "malloc: Heap corrupt; header at 0x%lx" + " has bad magic bits", + (unsigned long)i); + } + if (mh->mh_prevblock != rightprevblock) { + errx(1, + "malloc: Heap corrupt; header at 0x%lx" + " has bad previous-block size %lu " + "(should be %lu)", + (unsigned long)i, (unsigned long)mh->mh_prevblock << MBLOCKSHIFT, + (unsigned long)rightprevblock << MBLOCKSHIFT); + } + rightprevblock = mh->mh_nextblock; - warnx("heap: 0x%lx 0x%-6lx (next: 0x%lx) %s", - (unsigned long) i + MBLOCKSIZE, - (unsigned long) M_SIZE(mh), - (unsigned long) (i+M_NEXTOFF(mh)), - mh->mh_inuse ? "INUSE" : "FREE"); - } - if (i!=__heaptop) { - errx(1, "malloc: Heap corrupt; ran off end"); - } + warnx("heap: 0x%lx 0x%-6lx (next: 0x%lx) %s", (unsigned long)i + MBLOCKSIZE, + (unsigned long)M_SIZE(mh), (unsigned long)(i + M_NEXTOFF(mh)), + mh->mh_inuse ? "INUSE" : "FREE"); + } + if (i != __heaptop) { + errx(1, "malloc: Heap corrupt; ran off end"); + } - warnx("heap: ************************************************"); + warnx("heap: ************************************************"); } #endif /* MALLOCDEBUG */ @@ -277,25 +270,22 @@ __malloc_dump(void) * Get more memory (at the top of the heap) using sbrk, and * return a pointer to it. */ -static -void * -__malloc_sbrk(size_t size) -{ - void *x; +static void *__malloc_sbrk(size_t size) { + void *x; - x = sbrk(size); - if (x == (void *)-1) { - return NULL; - } + x = sbrk(size); + if (x == (void *)-1) { + return NULL; + } - if ((uintptr_t)x != __heaptop) { - errx(1, "malloc: Internal error - " - "heap top moved itself from 0x%lx to 0x%lx", - (unsigned long) __heaptop, - (unsigned long) (uintptr_t) x); - } - __heaptop += size; - return x; + if ((uintptr_t)x != __heaptop) { + errx(1, + "malloc: Internal error - " + "heap top moved itself from 0x%lx to 0x%lx", + (unsigned long)__heaptop, (unsigned long)(uintptr_t)x); + } + __heaptop += size; + return x; } /* @@ -306,177 +296,171 @@ __malloc_sbrk(size_t size) * Only split if the excess space is at least twice the blocksize - * one blocksize to hold a header and one for data. */ -static -void -__malloc_split(struct mheader *mh, size_t size) -{ - struct mheader *mhnext, *mhnew; - size_t oldsize; +static void __malloc_split(struct mheader *mh, size_t size) { + struct mheader *mhnext, *mhnew; + size_t oldsize; - if (size % MBLOCKSIZE != 0) { - errx(1, "malloc: Internal error (size %lu passed to split)", - (unsigned long) size); - } + if (size % MBLOCKSIZE != 0) { + errx(1, "malloc: Internal error (size %lu passed to split)", + (unsigned long)size); + } - if (M_SIZE(mh) - size < 2*MBLOCKSIZE) { - /* no room */ - return; - } + if (M_SIZE(mh) - size < 2 * MBLOCKSIZE) { + /* no room */ + return; + } - mhnext = M_NEXT(mh); + mhnext = M_NEXT(mh); - oldsize = M_SIZE(mh); - mh->mh_nextblock = M_MKFIELD(size + MBLOCKSIZE); + oldsize = M_SIZE(mh); + mh->mh_nextblock = M_MKFIELD(size + MBLOCKSIZE); - mhnew = M_NEXT(mh); - if (mhnew==mhnext) { - errx(1, "malloc: Internal error (split screwed up?)"); - } + mhnew = M_NEXT(mh); + if (mhnew == mhnext) { + errx(1, "malloc: Internal error (split screwed up?)"); + } - mhnew->mh_prevblock = M_MKFIELD(size + MBLOCKSIZE); - mhnew->mh_pad = 0; - mhnew->mh_magic1 = MMAGIC; - mhnew->mh_nextblock = M_MKFIELD(oldsize - size); - mhnew->mh_inuse = 0; - mhnew->mh_magic2 = MMAGIC; + mhnew->mh_prevblock = M_MKFIELD(size + MBLOCKSIZE); + mhnew->mh_pad = 0; + mhnew->mh_magic1 = MMAGIC; + mhnew->mh_nextblock = M_MKFIELD(oldsize - size); + mhnew->mh_inuse = 0; + mhnew->mh_magic2 = MMAGIC; - if (mhnext != (struct mheader *) __heaptop) { - mhnext->mh_prevblock = mhnew->mh_nextblock; - } + if (mhnext != (struct mheader *)__heaptop) { + mhnext->mh_prevblock = mhnew->mh_nextblock; + } } /* * malloc itself. */ -void * -malloc(size_t size) -{ - struct mheader *mh; - uintptr_t i; - size_t rightprevblock; - size_t morespace; - void *p; +void *malloc(size_t size) { + struct mheader *mh; + uintptr_t i; + size_t rightprevblock; + size_t morespace; + void *p; - if (__heapbase==0) { - __malloc_init(); - } - if (__heapbase==0 || __heaptop==0 || __heapbase > __heaptop) { - warnx("malloc: Internal error - local data corrupt"); - errx(1, "malloc: heapbase 0x%lx; heaptop 0x%lx", - (unsigned long) __heapbase, (unsigned long) __heaptop); - } + if (__heapbase == 0) { + __malloc_init(); + } + if (__heapbase == 0 || __heaptop == 0 || __heapbase > __heaptop) { + warnx("malloc: Internal error - local data corrupt"); + errx(1, "malloc: heapbase 0x%lx; heaptop 0x%lx", (unsigned long)__heapbase, + (unsigned long)__heaptop); + } #ifdef MALLOCDEBUG - warnx("malloc: about to allocate %lu (0x%lx) bytes", - (unsigned long) size, (unsigned long) size); - __malloc_dump(); + warnx("malloc: about to allocate %lu (0x%lx) bytes", (unsigned long)size, + (unsigned long)size); + __malloc_dump(); #endif - /* Round size up to an integral number of blocks. */ - size = ((size + MBLOCKSIZE - 1) & ~(size_t)(MBLOCKSIZE-1)); + /* Round size up to an integral number of blocks. */ + size = ((size + MBLOCKSIZE - 1) & ~(size_t)(MBLOCKSIZE - 1)); - /* - * First-fit search algorithm for available blocks. - * Check to make sure the next/previous sizes all agree. - */ - rightprevblock = 0; - mh = NULL; - for (i=__heapbase; i<__heaptop; i += M_NEXTOFF(mh)) { - mh = (struct mheader *) i; - if (!M_OK(mh)) { - errx(1, "malloc: Heap corrupt; header at 0x%lx" - " has bad magic bits", - (unsigned long) i); - } - if (mh->mh_prevblock != rightprevblock) { - errx(1, "malloc: Heap corrupt; header at 0x%lx" - " has bad previous-block size %lu " - "(should be %lu)", - (unsigned long) i, - (unsigned long) mh->mh_prevblock << MBLOCKSHIFT, - (unsigned long) rightprevblock << MBLOCKSHIFT); - } - rightprevblock = mh->mh_nextblock; + /* + * First-fit search algorithm for available blocks. + * Check to make sure the next/previous sizes all agree. + */ + rightprevblock = 0; + mh = NULL; + for (i = __heapbase; i < __heaptop; i += M_NEXTOFF(mh)) { + mh = (struct mheader *)i; + if (!M_OK(mh)) { + errx(1, + "malloc: Heap corrupt; header at 0x%lx" + " has bad magic bits", + (unsigned long)i); + } + if (mh->mh_prevblock != rightprevblock) { + errx(1, + "malloc: Heap corrupt; header at 0x%lx" + " has bad previous-block size %lu " + "(should be %lu)", + (unsigned long)i, (unsigned long)mh->mh_prevblock << MBLOCKSHIFT, + (unsigned long)rightprevblock << MBLOCKSHIFT); + } + rightprevblock = mh->mh_nextblock; - /* Can't allocate a block that's in use. */ - if (mh->mh_inuse) { - continue; - } + /* Can't allocate a block that's in use. */ + if (mh->mh_inuse) { + continue; + } - /* Can't allocate a block that isn't big enough. */ - if (M_SIZE(mh) < size) { - continue; - } + /* Can't allocate a block that isn't big enough. */ + if (M_SIZE(mh) < size) { + continue; + } - /* Try splitting block. */ - __malloc_split(mh, size); + /* Try splitting block. */ + __malloc_split(mh, size); - /* - * Now, allocate. - */ - mh->mh_inuse = 1; + /* + * Now, allocate. + */ + mh->mh_inuse = 1; #ifdef MALLOCDEBUG - warnx("malloc: allocating at %p", M_DATA(mh)); - __malloc_dump(); + warnx("malloc: allocating at %p", M_DATA(mh)); + __malloc_dump(); #endif - return M_DATA(mh); - } - if (i!=__heaptop) { - errx(1, "malloc: Heap corrupt; ran off end"); - } + return M_DATA(mh); + } + if (i != __heaptop) { + errx(1, "malloc: Heap corrupt; ran off end"); + } - /* - * Didn't find anything. Expand the heap. - * - * If the heap is nonempty and the top block (the one mh is - * left pointing to after the above loop) is free, we can - * expand it. Otherwise we need a new block. - */ - if (mh != NULL && !mh->mh_inuse) { - assert(size > M_SIZE(mh)); - morespace = size - M_SIZE(mh); - } - else { - morespace = MBLOCKSIZE + size; - } + /* + * Didn't find anything. Expand the heap. + * + * If the heap is nonempty and the top block (the one mh is + * left pointing to after the above loop) is free, we can + * expand it. Otherwise we need a new block. + */ + if (mh != NULL && !mh->mh_inuse) { + assert(size > M_SIZE(mh)); + morespace = size - M_SIZE(mh); + } else { + morespace = MBLOCKSIZE + size; + } - /* Round the amount of space we ask for up to a whole page. */ - morespace = PAGE_SIZE * ((morespace + PAGE_SIZE - 1) / PAGE_SIZE); + /* Round the amount of space we ask for up to a whole page. */ + morespace = PAGE_SIZE * ((morespace + PAGE_SIZE - 1) / PAGE_SIZE); - p = __malloc_sbrk(morespace); - if (p == NULL) { - return NULL; - } + p = __malloc_sbrk(morespace); + if (p == NULL) { + return NULL; + } - if (mh != NULL && !mh->mh_inuse) { - /* update old header */ - mh->mh_nextblock = M_MKFIELD(M_NEXTOFF(mh) + morespace); - mh->mh_inuse = 1; - } - else { - /* fill out new header */ - mh = p; - mh->mh_prevblock = rightprevblock; - mh->mh_magic1 = MMAGIC; - mh->mh_magic2 = MMAGIC; - mh->mh_pad = 0; - mh->mh_inuse = 1; - mh->mh_nextblock = M_MKFIELD(morespace); - } + if (mh != NULL && !mh->mh_inuse) { + /* update old header */ + mh->mh_nextblock = M_MKFIELD(M_NEXTOFF(mh) + morespace); + mh->mh_inuse = 1; + } else { + /* fill out new header */ + mh = p; + mh->mh_prevblock = rightprevblock; + mh->mh_magic1 = MMAGIC; + mh->mh_magic2 = MMAGIC; + mh->mh_pad = 0; + mh->mh_inuse = 1; + mh->mh_nextblock = M_MKFIELD(morespace); + } - /* - * Either way, try splitting the block we got as because of - * the page rounding it might be quite a bit bigger than we - * needed. - */ - __malloc_split(mh, size); + /* + * Either way, try splitting the block we got as because of + * the page rounding it might be quite a bit bigger than we + * needed. + */ + __malloc_split(mh, size); #ifdef MALLOCDEBUG - warnx("malloc: allocating at %p", M_DATA(mh)); - __malloc_dump(); + warnx("malloc: allocating at %p", M_DATA(mh)); + __malloc_dump(); #endif - return M_DATA(mh); + return M_DATA(mh); } //////////////////////////////////////////////////////////// @@ -485,107 +469,98 @@ malloc(size_t size) * Clear a range of memory with 0xdeadbeef. * ptr must be suitably aligned. */ -static -void -__malloc_deadbeef(void *ptr, size_t size) -{ - uint32_t *x = ptr; - size_t i, n = size/sizeof(uint32_t); - for (i=0; imh_nextblock != mhnext->mh_prevblock) { - errx(1, "free: Heap corrupt (%p and %p inconsistent)", - mh, mhnext); - } - if (mh->mh_inuse || mhnext->mh_inuse) { - /* can't merge */ - return; - } + if (mh->mh_nextblock != mhnext->mh_prevblock) { + errx(1, "free: Heap corrupt (%p and %p inconsistent)", mh, mhnext); + } + if (mh->mh_inuse || mhnext->mh_inuse) { + /* can't merge */ + return; + } - mhnextnext = M_NEXT(mhnext); + mhnextnext = M_NEXT(mhnext); - mh->mh_nextblock = M_MKFIELD(MBLOCKSIZE + M_SIZE(mh) + - MBLOCKSIZE + M_SIZE(mhnext)); + mh->mh_nextblock = + M_MKFIELD(MBLOCKSIZE + M_SIZE(mh) + MBLOCKSIZE + M_SIZE(mhnext)); - if (mhnextnext != (struct mheader *)__heaptop) { - mhnextnext->mh_prevblock = mh->mh_nextblock; - } + if (mhnextnext != (struct mheader *)__heaptop) { + mhnextnext->mh_prevblock = mh->mh_nextblock; + } - /* Deadbeef out the memory used by the now-obsolete header */ - __malloc_deadbeef(mhnext, sizeof(struct mheader)); + /* Deadbeef out the memory used by the now-obsolete header */ + __malloc_deadbeef(mhnext, sizeof(struct mheader)); } /* * The actual free() implementation. */ -void -free(void *x) -{ - struct mheader *mh, *mhnext, *mhprev; +void free(void *x) { + struct mheader *mh, *mhnext, *mhprev; - if (x==NULL) { - /* safest practice */ - return; - } + if (x == NULL) { + /* safest practice */ + return; + } - /* Consistency check. */ - if (__heapbase==0 || __heaptop==0 || __heapbase > __heaptop) { - warnx("free: Internal error - local data corrupt"); - errx(1, "free: heapbase 0x%lx; heaptop 0x%lx", - (unsigned long) __heapbase, (unsigned long) __heaptop); - } + /* Consistency check. */ + if (__heapbase == 0 || __heaptop == 0 || __heapbase > __heaptop) { + warnx("free: Internal error - local data corrupt"); + errx(1, "free: heapbase 0x%lx; heaptop 0x%lx", (unsigned long)__heapbase, + (unsigned long)__heaptop); + } - /* Don't allow freeing pointers that aren't on the heap. */ - if ((uintptr_t)x < __heapbase || (uintptr_t)x >= __heaptop) { - errx(1, "free: Invalid pointer %p freed (out of range)", x); - } + /* Don't allow freeing pointers that aren't on the heap. */ + if ((uintptr_t)x < __heapbase || (uintptr_t)x >= __heaptop) { + errx(1, "free: Invalid pointer %p freed (out of range)", x); + } #ifdef MALLOCDEBUG - warnx("free: about to free %p", x); - __malloc_dump(); + warnx("free: about to free %p", x); + __malloc_dump(); #endif - mh = ((struct mheader *)x)-1; - if (!M_OK(mh)) { - errx(1, "free: Invalid pointer %p freed (corrupt header)", x); - } + mh = ((struct mheader *)x) - 1; + if (!M_OK(mh)) { + errx(1, "free: Invalid pointer %p freed (corrupt header)", x); + } - if (!mh->mh_inuse) { - errx(1, "free: Invalid pointer %p freed (already free)", x); - } + if (!mh->mh_inuse) { + errx(1, "free: Invalid pointer %p freed (already free)", x); + } - /* mark it free */ - mh->mh_inuse = 0; + /* mark it free */ + mh->mh_inuse = 0; - /* wipe it */ - __malloc_deadbeef(M_DATA(mh), M_SIZE(mh)); + /* wipe it */ + __malloc_deadbeef(M_DATA(mh), M_SIZE(mh)); - /* Try merging with the block above (but not if we're at the top) */ - mhnext = M_NEXT(mh); - if (mhnext != (struct mheader *)__heaptop) { - __malloc_trymerge(mh, mhnext); - } + /* Try merging with the block above (but not if we're at the top) */ + mhnext = M_NEXT(mh); + if (mhnext != (struct mheader *)__heaptop) { + __malloc_trymerge(mh, mhnext); + } - /* Try merging with the block below (but not if we're at the bottom) */ - if (mh != (struct mheader *)__heapbase) { - mhprev = M_PREV(mh); - __malloc_trymerge(mhprev, mh); - } + /* Try merging with the block below (but not if we're at the bottom) */ + if (mh != (struct mheader *)__heapbase) { + mhprev = M_PREV(mh); + __malloc_trymerge(mhprev, mh); + } #ifdef MALLOCDEBUG - warnx("free: freed %p", x); - __malloc_dump(); + warnx("free: freed %p", x); + __malloc_dump(); #endif } diff --git a/userland/lib/libc/stdlib/qsort.c b/userland/lib/libc/stdlib/qsort.c index 095ef7d..1145d1a 100644 --- a/userland/lib/libc/stdlib/qsort.c +++ b/userland/lib/libc/stdlib/qsort.c @@ -34,112 +34,106 @@ /* * qsort() for OS/161, where it isn't in libc. */ -void -qsort(void *vdata, unsigned num, size_t size, - int (*f)(const void *, const void *)) -{ - unsigned pivot, head, tail; - char *data = vdata; - char tmp[size]; +void qsort(void *vdata, unsigned num, size_t size, + int (*f)(const void *, const void *)) { + unsigned pivot, head, tail; + char *data = vdata; + char tmp[size]; -#define COMPARE(aa, bb) \ - ((aa) == (bb) ? 0 : f(data + (aa) * size, data + (bb) * size)) -#define EXCHANGE(aa, bb) \ - memcpy(tmp, data + (aa) * size, size); \ - memcpy(data + (aa) * size, data + (bb) * size, size); \ - memcpy(data + (bb) * size, tmp, size) +#define COMPARE(aa, bb) \ + ((aa) == (bb) ? 0 : f(data + (aa) * size, data + (bb) * size)) +#define EXCHANGE(aa, bb) \ + memcpy(tmp, data + (aa) * size, size); \ + memcpy(data + (aa) * size, data + (bb) * size, size); \ + memcpy(data + (bb) * size, tmp, size) + if (num <= 1) { + return; + } + if (num == 2) { + if (COMPARE(0, 1) > 0) { + EXCHANGE(0, 1); + return; + } + } - if (num <= 1) { - return; - } - if (num == 2) { - if (COMPARE(0, 1) > 0) { - EXCHANGE(0, 1); - return; - } - } + /* + * 1. Pick a pivot value. For simplicity, always use the + * middle of the array. + */ + pivot = num / 2; - /* - * 1. Pick a pivot value. For simplicity, always use the - * middle of the array. - */ - pivot = num / 2; + /* + * 2. Shift all values less than or equal to the pivot value + * to the front of the array. + */ + head = 0; + tail = num - 1; - /* - * 2. Shift all values less than or equal to the pivot value - * to the front of the array. - */ - head = 0; - tail = num - 1; + while (head < tail) { + if (COMPARE(head, pivot) <= 0) { + head++; + } else if (COMPARE(tail, pivot) > 0) { + tail--; + } else { + EXCHANGE(head, tail); + if (pivot == head) { + pivot = tail; + } else if (pivot == tail) { + pivot = head; + } + head++; + tail--; + } + } - while (head < tail) { - if (COMPARE(head, pivot) <= 0) { - head++; - } - else if (COMPARE(tail, pivot) > 0) { - tail--; - } - else { - EXCHANGE(head, tail); - if (pivot == head) { - pivot = tail; - } - else if (pivot == tail) { - pivot = head; - } - head++; - tail--; - } - } + /* + * 3. If there's an even number of elements and we swapped the + * last two, the head and tail indexes will cross. In this + * case the first entry on the tail side is tail+1. If there's + * an odd number of elements, we stop with head == tail, and + * the first entry on the tail side is this value (hence, + * tail) if it's is greater than the pivot value, and the next + * element (hence, tail+1) if it's less than or equal to the + * pivot value. + * + * Henceforth use "tail" to hold the index of the first entry + * of the back portion of the array. + */ + if (head > tail || COMPARE(head, pivot) <= 0) { + tail++; + } - /* - * 3. If there's an even number of elements and we swapped the - * last two, the head and tail indexes will cross. In this - * case the first entry on the tail side is tail+1. If there's - * an odd number of elements, we stop with head == tail, and - * the first entry on the tail side is this value (hence, - * tail) if it's is greater than the pivot value, and the next - * element (hence, tail+1) if it's less than or equal to the - * pivot value. - * - * Henceforth use "tail" to hold the index of the first entry - * of the back portion of the array. - */ - if (head > tail || COMPARE(head, pivot) <= 0) { - tail++; - } + /* + * 4. If we got a bad pivot that gave us only one partition, + * because of the order of the advances in the loop above it + * will always put everything in the front portion of the + * array (so tail == num). This happens if we picked the + * largest value. Move the pivot to the end, if necessary, lop + * off all values equal to it, and recurse on the rest. (If + * there is no rest, the array is already sorted and we're + * done.) + */ + if (tail == num) { + if (pivot < num - 1) { + if (COMPARE(pivot, num - 1) > 0) { + EXCHANGE(pivot, num - 1); + } + } + tail = num - 1; + while (tail > 0 && COMPARE(tail - 1, tail) == 0) { + tail--; + } + if (tail > 0) { + qsort(vdata, tail, size, f); + } + return; + } + assert(tail > 0 && tail < num); - /* - * 4. If we got a bad pivot that gave us only one partition, - * because of the order of the advances in the loop above it - * will always put everything in the front portion of the - * array (so tail == num). This happens if we picked the - * largest value. Move the pivot to the end, if necessary, lop - * off all values equal to it, and recurse on the rest. (If - * there is no rest, the array is already sorted and we're - * done.) - */ - if (tail == num) { - if (pivot < num - 1) { - if (COMPARE(pivot, num - 1) > 0) { - EXCHANGE(pivot, num - 1); - } - } - tail = num - 1; - while (tail > 0 && COMPARE(tail - 1, tail) == 0) { - tail--; - } - if (tail > 0) { - qsort(vdata, tail, size, f); - } - return; - } - assert(tail > 0 && tail < num); - - /* - * 5. Recurse on each subpart of the array. - */ - qsort(vdata, tail, size, f); - qsort((char *)vdata + tail * size, num - tail, size, f); + /* + * 5. Recurse on each subpart of the array. + */ + qsort(vdata, tail, size, f); + qsort((char *)vdata + tail * size, num - tail, size, f); } diff --git a/userland/lib/libc/stdlib/random.c b/userland/lib/libc/stdlib/random.c index 7253813..a9d6a73 100644 --- a/userland/lib/libc/stdlib/random.c +++ b/userland/lib/libc/stdlib/random.c @@ -52,7 +52,6 @@ static void srandom_unlocked(unsigned long); static long random_unlocked(void); - /* * random.c: * @@ -119,39 +118,39 @@ static long random_unlocked(void); * for the polynomial (actually a trinomial) that the R.N.G. is based on, and * the separation between the two lower order coefficients of the trinomial. */ -#define TYPE_0 0 /* linear congruential */ -#define BREAK_0 8 -#define DEG_0 0 -#define SEP_0 0 +#define TYPE_0 0 /* linear congruential */ +#define BREAK_0 8 +#define DEG_0 0 +#define SEP_0 0 -#define TYPE_1 1 /* x**7 + x**3 + 1 */ -#define BREAK_1 32 -#define DEG_1 7 -#define SEP_1 3 +#define TYPE_1 1 /* x**7 + x**3 + 1 */ +#define BREAK_1 32 +#define DEG_1 7 +#define SEP_1 3 -#define TYPE_2 2 /* x**15 + x + 1 */ -#define BREAK_2 64 -#define DEG_2 15 -#define SEP_2 1 +#define TYPE_2 2 /* x**15 + x + 1 */ +#define BREAK_2 64 +#define DEG_2 15 +#define SEP_2 1 -#define TYPE_3 3 /* x**31 + x**3 + 1 */ -#define BREAK_3 128 -#define DEG_3 31 -#define SEP_3 3 +#define TYPE_3 3 /* x**31 + x**3 + 1 */ +#define BREAK_3 128 +#define DEG_3 31 +#define SEP_3 3 -#define TYPE_4 4 /* x**63 + x + 1 */ -#define BREAK_4 256 -#define DEG_4 63 -#define SEP_4 1 +#define TYPE_4 4 /* x**63 + x + 1 */ +#define BREAK_4 256 +#define DEG_4 63 +#define SEP_4 1 /* * Array versions of the above information to make code run faster -- * relies on fact that TYPE_i == i. */ -#define MAX_TYPES 5 /* max number of types above */ +#define MAX_TYPES 5 /* max number of types above */ -static const int degrees[MAX_TYPES] = { DEG_0, DEG_1, DEG_2, DEG_3, DEG_4 }; -static const int seps[MAX_TYPES] = { SEP_0, SEP_1, SEP_2, SEP_3, SEP_4 }; +static const int degrees[MAX_TYPES] = {DEG_0, DEG_1, DEG_2, DEG_3, DEG_4}; +static const int seps[MAX_TYPES] = {SEP_0, SEP_1, SEP_2, SEP_3, SEP_4}; /* * Initially, everything is set up as if from: @@ -168,18 +167,38 @@ static const int seps[MAX_TYPES] = { SEP_0, SEP_1, SEP_2, SEP_3, SEP_4 }; */ static long randtbl[DEG_3 + 1] = { - TYPE_3, - (long)0x9a319039L, (long)0x32d9c024L, (long)0x9b663182L, - (long)0x5da1f342L, (long)0xde3b81e0L, (long)0xdf0a6fb5L, - (long)0xf103bc02L, (long)0x48f340fbL, (long)0x7449e56bL, - (long)0xbeb1dbb0L, (long)0xab5c5918L, (long)0x946554fdL, - (long)0x8c2e680fL, (long)0xeb3d799fL, (long)0xb11ee0b7L, - (long)0x2d436b86L, (long)0xda672e2aL, (long)0x1588ca88L, - (long)0xe369735dL, (long)0x904f35f7L, (long)0xd7158fd6L, - (long)0x6fa6f051L, (long)0x616e6b96L, (long)0xac94efdcL, - (long)0x36413f93L, (long)0xc622c298L, (long)0xf5a42ab8L, - (long)0x8a88d77bL, (long)0xf5ad9d0eL, (long)0x8999220bL, - (long)0x27fb47b9L, + TYPE_3, + (long)0x9a319039L, + (long)0x32d9c024L, + (long)0x9b663182L, + (long)0x5da1f342L, + (long)0xde3b81e0L, + (long)0xdf0a6fb5L, + (long)0xf103bc02L, + (long)0x48f340fbL, + (long)0x7449e56bL, + (long)0xbeb1dbb0L, + (long)0xab5c5918L, + (long)0x946554fdL, + (long)0x8c2e680fL, + (long)0xeb3d799fL, + (long)0xb11ee0b7L, + (long)0x2d436b86L, + (long)0xda672e2aL, + (long)0x1588ca88L, + (long)0xe369735dL, + (long)0x904f35f7L, + (long)0xd7158fd6L, + (long)0x6fa6f051L, + (long)0x616e6b96L, + (long)0xac94efdcL, + (long)0x36413f93L, + (long)0xc622c298L, + (long)0xf5a42ab8L, + (long)0x8a88d77bL, + (long)0xf5ad9d0eL, + (long)0x8999220bL, + (long)0x27fb47b9L, }; /* @@ -227,32 +246,27 @@ static long *end_ptr = &randtbl[DEG_3 + 1]; * introduced by the L.C.R.N.G. Note that the initialization of randtbl[] * for default usage relies on values produced by this routine. */ -static -void -srandom_unlocked(unsigned long x) -{ - int i; +static void srandom_unlocked(unsigned long x) { + int i; - if (rand_type == TYPE_0) - state[0] = x; - else { - state[0] = x; - for (i = 1; i < rand_deg; i++) - state[i] = 1103515245L * state[i - 1] + 12345L; - fptr = &state[rand_sep]; - rptr = &state[0]; - for (i = 0; i < 10 * rand_deg; i++) - (void)random_unlocked(); - } + if (rand_type == TYPE_0) + state[0] = x; + else { + state[0] = x; + for (i = 1; i < rand_deg; i++) + state[i] = 1103515245L * state[i - 1] + 12345L; + fptr = &state[rand_sep]; + rptr = &state[0]; + for (i = 0; i < 10 * rand_deg; i++) + (void)random_unlocked(); + } } -void -srandom(unsigned long x) -{ +void srandom(unsigned long x) { - LOCKME(); - srandom_unlocked(x); - UNLOCKME(); + LOCKME(); + srandom_unlocked(x); + UNLOCKME(); } /* @@ -278,57 +292,55 @@ srandom(unsigned long x) * word boundary; otherwise a bus error will occur. Even so, lint will * complain about mis-alignment, but you should disregard these messages. */ -char * -initstate( - unsigned long seed, /* seed for R.N.G. */ - char *arg_state, /* pointer to state array */ - size_t n) /* # bytes of state info */ +char *initstate(unsigned long seed, /* seed for R.N.G. */ + char *arg_state, /* pointer to state array */ + size_t n) /* # bytes of state info */ { - void *ostate = (void *)(&state[-1]); - long *long_arg_state; + void *ostate = (void *)(&state[-1]); + long *long_arg_state; - assert(arg_state != NULL); + assert(arg_state != NULL); - long_arg_state = (long *)(void *)arg_state; + long_arg_state = (long *)(void *)arg_state; - LOCKME(); - if (rand_type == TYPE_0) - state[-1] = rand_type; - else - state[-1] = MAX_TYPES * (rptr - state) + rand_type; - if (n < BREAK_0) { - UNLOCKME(); - return (NULL); - } else if (n < BREAK_1) { - rand_type = TYPE_0; - rand_deg = DEG_0; - rand_sep = SEP_0; - } else if (n < BREAK_2) { - rand_type = TYPE_1; - rand_deg = DEG_1; - rand_sep = SEP_1; - } else if (n < BREAK_3) { - rand_type = TYPE_2; - rand_deg = DEG_2; - rand_sep = SEP_2; - } else if (n < BREAK_4) { - rand_type = TYPE_3; - rand_deg = DEG_3; - rand_sep = SEP_3; - } else { - rand_type = TYPE_4; - rand_deg = DEG_4; - rand_sep = SEP_4; - } - state = (long *) (long_arg_state + 1); /* first location */ - end_ptr = &state[rand_deg]; /* must set end_ptr before srandom */ - srandom_unlocked(seed); - if (rand_type == TYPE_0) - long_arg_state[0] = rand_type; - else - long_arg_state[0] = MAX_TYPES * (rptr - state) + rand_type; - UNLOCKME(); - return((char *)ostate); + LOCKME(); + if (rand_type == TYPE_0) + state[-1] = rand_type; + else + state[-1] = MAX_TYPES * (rptr - state) + rand_type; + if (n < BREAK_0) { + UNLOCKME(); + return (NULL); + } else if (n < BREAK_1) { + rand_type = TYPE_0; + rand_deg = DEG_0; + rand_sep = SEP_0; + } else if (n < BREAK_2) { + rand_type = TYPE_1; + rand_deg = DEG_1; + rand_sep = SEP_1; + } else if (n < BREAK_3) { + rand_type = TYPE_2; + rand_deg = DEG_2; + rand_sep = SEP_2; + } else if (n < BREAK_4) { + rand_type = TYPE_3; + rand_deg = DEG_3; + rand_sep = SEP_3; + } else { + rand_type = TYPE_4; + rand_deg = DEG_4; + rand_sep = SEP_4; + } + state = (long *)(long_arg_state + 1); /* first location */ + end_ptr = &state[rand_deg]; /* must set end_ptr before srandom */ + srandom_unlocked(seed); + if (rand_type == TYPE_0) + long_arg_state[0] = rand_type; + else + long_arg_state[0] = MAX_TYPES * (rptr - state) + rand_type; + UNLOCKME(); + return ((char *)ostate); } /* @@ -350,47 +362,46 @@ initstate( * word boundary; otherwise a bus error will occur. Even so, lint will * complain about mis-alignment, but you should disregard these messages. */ -char * -setstate(char *arg_state) /* pointer to state array */ +char *setstate(char *arg_state) /* pointer to state array */ { - long *new_state; - int type; - int rear; - void *ostate = (void *)(&state[-1]); + long *new_state; + int type; + int rear; + void *ostate = (void *)(&state[-1]); - assert(arg_state != NULL); + assert(arg_state != NULL); - new_state = (long *)(void *)arg_state; - type = (int)(new_state[0] % MAX_TYPES); - rear = (int)(new_state[0] / MAX_TYPES); + new_state = (long *)(void *)arg_state; + type = (int)(new_state[0] % MAX_TYPES); + rear = (int)(new_state[0] / MAX_TYPES); - LOCKME(); - if (rand_type == TYPE_0) - state[-1] = rand_type; - else - state[-1] = MAX_TYPES * (rptr - state) + rand_type; - switch(type) { - case TYPE_0: - case TYPE_1: - case TYPE_2: - case TYPE_3: - case TYPE_4: - rand_type = type; - rand_deg = degrees[type]; - rand_sep = seps[type]; - break; - default: - UNLOCKME(); - return (NULL); - } - state = (long *) (new_state + 1); - if (rand_type != TYPE_0) { - rptr = &state[rear]; - fptr = &state[(rear + rand_sep) % rand_deg]; - } - end_ptr = &state[rand_deg]; /* set end_ptr too */ - UNLOCKME(); - return((char *)ostate); + LOCKME(); + if (rand_type == TYPE_0) + state[-1] = rand_type; + else + state[-1] = MAX_TYPES * (rptr - state) + rand_type; + switch (type) { + case TYPE_0: + case TYPE_1: + case TYPE_2: + case TYPE_3: + case TYPE_4: + rand_type = type; + rand_deg = degrees[type]; + rand_sep = seps[type]; + break; + default: + UNLOCKME(); + return (NULL); + } + state = (long *)(new_state + 1); + if (rand_type != TYPE_0) { + rptr = &state[rear]; + fptr = &state[(rear + rand_sep) % rand_deg]; + } + end_ptr = &state[rand_deg]; /* set end_ptr too */ + UNLOCKME(); + return ((char *)ostate); } /* @@ -410,44 +421,40 @@ setstate(char *arg_state) /* pointer to state array */ * * Returns a 31-bit random number. */ -static -long -random_unlocked(void) -{ - long i; - long *f, *r; +static long random_unlocked(void) { + long i; + long *f, *r; - if (rand_type == TYPE_0) { - i = state[0]; - state[0] = i = (i * 1103515245L + 12345L) & 0x7fffffff; - } else { - /* - * Use local variables rather than static variables for speed. - */ - f = fptr; r = rptr; - *f += *r; - /* chucking least random bit */ - i = ((unsigned long)*f >> 1) & 0x7fffffff; - if (++f >= end_ptr) { - f = state; - ++r; - } - else if (++r >= end_ptr) { - r = state; - } + if (rand_type == TYPE_0) { + i = state[0]; + state[0] = i = (i * 1103515245L + 12345L) & 0x7fffffff; + } else { + /* + * Use local variables rather than static variables for speed. + */ + f = fptr; + r = rptr; + *f += *r; + /* chucking least random bit */ + i = ((unsigned long)*f >> 1) & 0x7fffffff; + if (++f >= end_ptr) { + f = state; + ++r; + } else if (++r >= end_ptr) { + r = state; + } - fptr = f; rptr = r; - } - return(i); + fptr = f; + rptr = r; + } + return (i); } -long -random(void) -{ - long r; +long random(void) { + long r; - LOCKME(); - r = random_unlocked(); - UNLOCKME(); - return (r); + LOCKME(); + r = random_unlocked(); + UNLOCKME(); + return (r); } diff --git a/userland/lib/libc/stdlib/system.c b/userland/lib/libc/stdlib/system.c index bfb8a39..7cdd449 100644 --- a/userland/lib/libc/stdlib/system.c +++ b/userland/lib/libc/stdlib/system.c @@ -39,53 +39,50 @@ */ #define MAXCMDSIZE 2048 -#define MAXARGS 128 +#define MAXARGS 128 -int -system(const char *cmd) -{ - /* - * Ordinarily, you call the shell to process the command. - * But we don't know that the shell can do that. So, do it - * ourselves. - */ +int system(const char *cmd) { + /* + * Ordinarily, you call the shell to process the command. + * But we don't know that the shell can do that. So, do it + * ourselves. + */ - char tmp[MAXCMDSIZE]; - char *argv[MAXARGS+1]; - int nargs=0; - char *s; - int pid, status; + char tmp[MAXCMDSIZE]; + char *argv[MAXARGS + 1]; + int nargs = 0; + char *s; + int pid, status; - if (strlen(cmd) >= sizeof(tmp)) { - errno = E2BIG; - return -1; - } - strcpy(tmp, cmd); + if (strlen(cmd) >= sizeof(tmp)) { + errno = E2BIG; + return -1; + } + strcpy(tmp, cmd); - for (s = strtok(tmp, " \t"); s; s = strtok(NULL, " \t")) { - if (nargs < MAXARGS) { - argv[nargs++] = s; - } - else { - errno = E2BIG; - return 1; - } - } + for (s = strtok(tmp, " \t"); s; s = strtok(NULL, " \t")) { + if (nargs < MAXARGS) { + argv[nargs++] = s; + } else { + errno = E2BIG; + return 1; + } + } - argv[nargs] = NULL; + argv[nargs] = NULL; - pid = fork(); - switch (pid) { - case -1: - return -1; - case 0: - /* child */ - execv(argv[0], argv); - /* exec only returns if it fails */ - _exit(255); - default: - /* parent */ - waitpid(pid, &status, 0); - return status; - } + pid = fork(); + switch (pid) { + case -1: + return -1; + case 0: + /* child */ + execv(argv[0], argv); + /* exec only returns if it fails */ + _exit(255); + default: + /* parent */ + waitpid(pid, &status, 0); + return status; + } } diff --git a/userland/lib/libc/string/memcmp.c b/userland/lib/libc/string/memcmp.c index 8c9b98e..8ed6201 100644 --- a/userland/lib/libc/string/memcmp.c +++ b/userland/lib/libc/string/memcmp.c @@ -34,17 +34,15 @@ * their sort order. */ -int -memcmp(const void *av, const void *bv, size_t len) -{ - const unsigned char *a = av; - const unsigned char *b = bv; - size_t i; +int memcmp(const void *av, const void *bv, size_t len) { + const unsigned char *a = av; + const unsigned char *b = bv; + size_t i; - for (i=0; i=0 && errcode < sys_nerr) { - return sys_errlist[errcode]; - } - return "Unknown error number"; +const char *strerror(int errcode) { + if (errcode >= 0 && errcode < sys_nerr) { + return sys_errlist[errcode]; + } + return "Unknown error number"; } diff --git a/userland/lib/libc/string/strtok.c b/userland/lib/libc/string/strtok.c index 0656000..ca93fe9 100644 --- a/userland/lib/libc/string/strtok.c +++ b/userland/lib/libc/string/strtok.c @@ -31,8 +31,6 @@ static char *__strtok_context; -char * -strtok(char *str, const char *seps) -{ - return strtok_r(str, seps, &__strtok_context); +char *strtok(char *str, const char *seps) { + return strtok_r(str, seps, &__strtok_context); } diff --git a/userland/lib/libc/time/time.c b/userland/lib/libc/time/time.c index e69a45a..bc2e292 100644 --- a/userland/lib/libc/time/time.c +++ b/userland/lib/libc/time/time.c @@ -35,8 +35,4 @@ * but also returns nanoseconds. */ -time_t -time(time_t *t) -{ - return __time(t, NULL); -} +time_t time(time_t *t) { return __time(t, NULL); } diff --git a/userland/lib/libc/unix/__assert.c b/userland/lib/libc/unix/__assert.c index 0aa42d0..13e965e 100644 --- a/userland/lib/libc/unix/__assert.c +++ b/userland/lib/libc/unix/__assert.c @@ -38,13 +38,11 @@ * Print a message to stderr and bail out of the program. */ -void -__bad_assert(const char *file, int line, const char *expr) -{ - char buf[256]; - snprintf(buf, sizeof(buf), "Assertion failed: %s (%s line %d)\n", - expr, file, line); +void __bad_assert(const char *file, int line, const char *expr) { + char buf[256]; + snprintf(buf, sizeof(buf), "Assertion failed: %s (%s line %d)\n", expr, file, + line); - write(STDERR_FILENO, buf, strlen(buf)); - abort(); + write(STDERR_FILENO, buf, strlen(buf)); + abort(); } diff --git a/userland/lib/libc/unix/err.c b/userland/lib/libc/unix/err.c index a4992d1..65ce3fb 100644 --- a/userland/lib/libc/unix/err.c +++ b/userland/lib/libc/unix/err.c @@ -47,72 +47,60 @@ extern char **__argv; /* * Routine to print error message text to stderr. */ -static -void -__senderr(void *junk, const char *data, size_t len) -{ - (void)junk; /* not needed or used */ +static void __senderr(void *junk, const char *data, size_t len) { + (void)junk; /* not needed or used */ - write(STDERR_FILENO, data, len); + write(STDERR_FILENO, data, len); } /* * Shortcut to call __senderr on a null-terminated string. * (__senderr is set up to be called by __vprintf.) */ -static -void -__senderrstr(const char *str) -{ - __senderr(NULL, str, strlen(str)); -} +static void __senderrstr(const char *str) { __senderr(NULL, str, strlen(str)); } /* * Common routine for all the *err* and *warn* functions. */ -static -void -__printerr(int use_errno, const char *fmt, va_list ap) -{ - const char *errmsg; - const char *prog; +static void __printerr(int use_errno, const char *fmt, va_list ap) { + const char *errmsg; + const char *prog; - /* - * Get the error message for the current errno. - * Do this early, before doing anything that might change the - * value in errno. - */ - errmsg = strerror(errno); + /* + * Get the error message for the current errno. + * Do this early, before doing anything that might change the + * value in errno. + */ + errmsg = strerror(errno); - /* - * Look up the program name. - * Strictly speaking we should pull off the rightmost - * path component of argv[0] and use that as the program - * name (this is how BSD err* prints) but it doesn't make - * much difference. - */ - if (__argv!=NULL && __argv[0]!=NULL) { - prog = __argv[0]; - } - else { - prog = "(program name unknown)"; - } + /* + * Look up the program name. + * Strictly speaking we should pull off the rightmost + * path component of argv[0] and use that as the program + * name (this is how BSD err* prints) but it doesn't make + * much difference. + */ + if (__argv != NULL && __argv[0] != NULL) { + prog = __argv[0]; + } else { + prog = "(program name unknown)"; + } - /* print the program name */ - __senderrstr(prog); - __senderrstr(": "); + /* print the program name */ + __senderrstr(prog); + __senderrstr(": "); - /* process the printf format and args */ - __vprintf(__senderr, NULL, fmt, ap); + /* process the printf format and args */ + __vprintf(__senderr, NULL, fmt, ap); - /* if we're using errno, print the error string from above. */ - if (use_errno) { - __senderrstr(": "); - __senderrstr(errmsg); - } + /* if we're using errno, print the error string from above. */ + if (use_errno) { + __senderrstr(": "); + __senderrstr(errmsg); + } - /* and always add a newline. */ - __senderrstr("\n"); + /* and always add a newline. */ + __senderrstr("\n"); } /* @@ -120,33 +108,21 @@ __printerr(int use_errno, const char *fmt, va_list ap) */ /* warn/vwarn: use errno, don't exit */ -void -vwarn(const char *fmt, va_list ap) -{ - __printerr(1, fmt, ap); -} +void vwarn(const char *fmt, va_list ap) { __printerr(1, fmt, ap); } /* warnx/vwarnx: don't use errno, don't exit */ -void -vwarnx(const char *fmt, va_list ap) -{ - __printerr(0, fmt, ap); -} +void vwarnx(const char *fmt, va_list ap) { __printerr(0, fmt, ap); } /* err/verr: use errno, then exit */ -void -verr(int exitcode, const char *fmt, va_list ap) -{ - __printerr(1, fmt, ap); - exit(exitcode); +void verr(int exitcode, const char *fmt, va_list ap) { + __printerr(1, fmt, ap); + exit(exitcode); } /* errx/verrx: don't use errno, but do then exit */ -void -verrx(int exitcode, const char *fmt, va_list ap) -{ - __printerr(0, fmt, ap); - exit(exitcode); +void verrx(int exitcode, const char *fmt, va_list ap) { + __printerr(0, fmt, ap); + exit(exitcode); } /* @@ -154,38 +130,30 @@ verrx(int exitcode, const char *fmt, va_list ap) * Just hand off to the va_list versions. */ -void -warn(const char *fmt, ...) -{ - va_list ap; - va_start(ap, fmt); - vwarn(fmt, ap); - va_end(ap); +void warn(const char *fmt, ...) { + va_list ap; + va_start(ap, fmt); + vwarn(fmt, ap); + va_end(ap); } -void -warnx(const char *fmt, ...) -{ - va_list ap; - va_start(ap, fmt); - vwarnx(fmt, ap); - va_end(ap); +void warnx(const char *fmt, ...) { + va_list ap; + va_start(ap, fmt); + vwarnx(fmt, ap); + va_end(ap); } -void -err(int exitcode, const char *fmt, ...) -{ - va_list ap; - va_start(ap, fmt); - verr(exitcode, fmt, ap); - va_end(ap); +void err(int exitcode, const char *fmt, ...) { + va_list ap; + va_start(ap, fmt); + verr(exitcode, fmt, ap); + va_end(ap); } -void -errx(int exitcode, const char *fmt, ...) -{ - va_list ap; - va_start(ap, fmt); - verrx(exitcode, fmt, ap); - va_end(ap); +void errx(int exitcode, const char *fmt, ...) { + va_list ap; + va_start(ap, fmt); + verrx(exitcode, fmt, ap); + va_end(ap); } diff --git a/userland/lib/libc/unix/execvp.c b/userland/lib/libc/unix/execvp.c index 6a68c60..449050f 100644 --- a/userland/lib/libc/unix/execvp.c +++ b/userland/lib/libc/unix/execvp.c @@ -38,54 +38,51 @@ * POSIX C function: exec a program on the search path. Tries * execv() repeatedly until one of the choices works. */ -int -execvp(const char *prog, char *const *args) -{ - const char *searchpath, *s, *t; - char progpath[PATH_MAX]; - size_t len; +int execvp(const char *prog, char *const *args) { + const char *searchpath, *s, *t; + char progpath[PATH_MAX]; + size_t len; - if (strchr(prog, '/') != NULL) { - execv(prog, args); - return -1; - } + if (strchr(prog, '/') != NULL) { + execv(prog, args); + return -1; + } - searchpath = getenv("PATH"); - if (searchpath == NULL) { - errno = ENOENT; - return -1; - } + searchpath = getenv("PATH"); + if (searchpath == NULL) { + errno = ENOENT; + return -1; + } - for (s = searchpath; s != NULL; s = t) { - t = strchr(s, ':'); - if (t != NULL) { - len = t - s; - /* advance past the colon */ - t++; - } - else { - len = strlen(s); - } - if (len == 0) { - continue; - } - if (len >= sizeof(progpath)) { - continue; - } - memcpy(progpath, s, len); - snprintf(progpath + len, sizeof(progpath) - len, "/%s", prog); - execv(progpath, args); - switch (errno) { - case ENOENT: - case ENOTDIR: - case ENOEXEC: - /* routine errors, try next dir */ - break; - default: - /* oops, let's fail */ - return -1; - } - } - errno = ENOENT; - return -1; + for (s = searchpath; s != NULL; s = t) { + t = strchr(s, ':'); + if (t != NULL) { + len = t - s; + /* advance past the colon */ + t++; + } else { + len = strlen(s); + } + if (len == 0) { + continue; + } + if (len >= sizeof(progpath)) { + continue; + } + memcpy(progpath, s, len); + snprintf(progpath + len, sizeof(progpath) - len, "/%s", prog); + execv(progpath, args); + switch (errno) { + case ENOENT: + case ENOTDIR: + case ENOEXEC: + /* routine errors, try next dir */ + break; + default: + /* oops, let's fail */ + return -1; + } + } + errno = ENOENT; + return -1; } diff --git a/userland/lib/libc/unix/getcwd.c b/userland/lib/libc/unix/getcwd.c index e8b6e08..2fed7cd 100644 --- a/userland/lib/libc/unix/getcwd.c +++ b/userland/lib/libc/unix/getcwd.c @@ -36,21 +36,19 @@ * all the work. */ -char * -getcwd(char *buf, size_t buflen) -{ - int r; +char *getcwd(char *buf, size_t buflen) { + int r; - if (buflen < 1) { - errno = EINVAL; - return NULL; - } + if (buflen < 1) { + errno = EINVAL; + return NULL; + } - r = __getcwd(buf, buflen-1); - if (r < 0) { - return NULL; - } + r = __getcwd(buf, buflen - 1); + if (r < 0) { + return NULL; + } - buf[r] = 0; - return buf; + buf[r] = 0; + return buf; } diff --git a/userland/lib/libtest/triple.c b/userland/lib/libtest/triple.c index f67a6d1..2a258e3 100644 --- a/userland/lib/libtest/triple.c +++ b/userland/lib/libtest/triple.c @@ -38,74 +38,60 @@ #include #include -static -pid_t -spawnv(const char *prog, char **argv) -{ - pid_t pid = fork(); - switch (pid) { - case -1: - err(1, "fork"); - case 0: - /* child */ - execv(prog, argv); - err(1, "%s: execv", prog); - default: - /* parent */ - break; - } - return pid; +static pid_t spawnv(const char *prog, char **argv) { + pid_t pid = fork(); + switch (pid) { + case -1: + err(1, "fork"); + case 0: + /* child */ + execv(prog, argv); + err(1, "%s: execv", prog); + default: + /* parent */ + break; + } + return pid; } -static -int -dowait(int index, int pid) -{ - int status; +static int dowait(int index, int pid) { + int status; - if (waitpid(pid, &status, 0)<0) { - warn("waitpid for copy #%d (pid %d)", index, pid); - return 1; - } - else if (WIFSIGNALED(status)) { - warnx("copy #%d (pid %d): signal %d", index, pid, - WTERMSIG(status)); - return 1; - } - else if (WEXITSTATUS(status) != 0) { - warnx("copy #%d (pid %d): exit %d", index, pid, - WEXITSTATUS(status)); - return 1; - } - return 0; + if (waitpid(pid, &status, 0) < 0) { + warn("waitpid for copy #%d (pid %d)", index, pid); + return 1; + } else if (WIFSIGNALED(status)) { + warnx("copy #%d (pid %d): signal %d", index, pid, WTERMSIG(status)); + return 1; + } else if (WEXITSTATUS(status) != 0) { + warnx("copy #%d (pid %d): exit %d", index, pid, WEXITSTATUS(status)); + return 1; + } + return 0; } -void -triple(const char *prog) -{ - pid_t pids[3]; - int i, failures = 0; - char *args[2]; +void triple(const char *prog) { + pid_t pids[3]; + int i, failures = 0; + char *args[2]; - /* set up the argv */ - args[0]=(char *)prog; - args[1]=NULL; + /* set up the argv */ + args[0] = (char *)prog; + args[1] = NULL; - warnx("Starting: running three copies of %s...", prog); + warnx("Starting: running three copies of %s...", prog); - for (i=0; i<3; i++) { - pids[i]=spawnv(args[0], args); - } + for (i = 0; i < 3; i++) { + pids[i] = spawnv(args[0], args); + } - for (i=0; i<3; i++) { - failures += dowait(i, pids[i]); - } + for (i = 0; i < 3; i++) { + failures += dowait(i, pids[i]); + } - if (failures > 0) { - warnx("%d failures", failures); - } - else { - warnx("Congratulations! You passed."); - } + if (failures > 0) { + warnx("%d failures", failures); + } else { + warnx("Congratulations! You passed."); + } } - diff --git a/userland/sbin/dumpsfs/dumpsfs.c b/userland/sbin/dumpsfs/dumpsfs.c index 33cbc4e..2356090 100644 --- a/userland/sbin/dumpsfs/dumpsfs.c +++ b/userland/sbin/dumpsfs/dumpsfs.c @@ -41,7 +41,6 @@ #include "support.h" #include "kern/sfs.h" - #ifdef HOST /* * OS/161 runs natively on a big-endian platform, so we can @@ -78,53 +77,44 @@ static bool recurse; static unsigned dumppos; -static -void -dumpval(const char *desc, const char *val) -{ - size_t dlen, vlen, used; +static void dumpval(const char *desc, const char *val) { + size_t dlen, vlen, used; - dlen = strlen(desc); - vlen = strlen(val); + dlen = strlen(desc); + vlen = strlen(val); - printf(" "); + printf(" "); - printf("%s: %s", desc, val); + printf("%s: %s", desc, val); - used = dlen + 2 + vlen; - for (; used < 36; used++) { - putchar(' '); - } + used = dlen + 2 + vlen; + for (; used < 36; used++) { + putchar(' '); + } - if (dumppos % 2 == 1) { - printf("\n"); - } - dumppos++; + if (dumppos % 2 == 1) { + printf("\n"); + } + dumppos++; } -static -void -dumpvalf(const char *desc, const char *valf, ...) -{ - va_list ap; - char buf[128]; +static void dumpvalf(const char *desc, const char *valf, ...) { + va_list ap; + char buf[128]; - va_start(ap, valf); - vsnprintf(buf, sizeof(buf), valf, ap); - va_end(ap); - dumpval(desc, buf); + va_start(ap, valf); + vsnprintf(buf, sizeof(buf), valf, ap); + va_end(ap); + dumpval(desc, buf); } -static -void -dumplval(const char *desc, const char *lval) -{ - if (dumppos % 2 == 1) { - printf("\n"); - dumppos++; - } - printf(" %s: %s\n", desc, lval); - dumppos += 2; +static void dumplval(const char *desc, const char *lval) { + if (dumppos % 2 == 1) { + printf("\n"); + dumppos++; + } + printf(" %s: %s\n", desc, lval); + dumppos += 2; } //////////////////////////////////////////////////////////// @@ -132,476 +122,437 @@ dumplval(const char *desc, const char *lval) static void dumpinode(uint32_t ino, const char *name); -static -uint32_t -readsb(void) -{ - struct sfs_superblock sb; +static uint32_t readsb(void) { + struct sfs_superblock sb; - diskread(&sb, SFS_SUPER_BLOCK); - if (SWAP32(sb.sb_magic) != SFS_MAGIC) { - errx(1, "Not an sfs filesystem"); - } - return SWAP32(sb.sb_nblocks); + diskread(&sb, SFS_SUPER_BLOCK); + if (SWAP32(sb.sb_magic) != SFS_MAGIC) { + errx(1, "Not an sfs filesystem"); + } + return SWAP32(sb.sb_nblocks); } -static -void -dumpsb(void) -{ - struct sfs_superblock sb; - unsigned i; +static void dumpsb(void) { + struct sfs_superblock sb; + unsigned i; - diskread(&sb, SFS_SUPER_BLOCK); - sb.sb_volname[sizeof(sb.sb_volname)-1] = 0; + diskread(&sb, SFS_SUPER_BLOCK); + sb.sb_volname[sizeof(sb.sb_volname) - 1] = 0; - printf("Superblock\n"); - printf("----------\n"); - dumpvalf("Magic", "0x%8x", SWAP32(sb.sb_magic)); - dumpvalf("Size", "%u blocks", SWAP32(sb.sb_nblocks)); - dumpvalf("Freemap size", "%u blocks", - SFS_FREEMAPBLOCKS(SWAP32(sb.sb_nblocks))); - dumpvalf("Block size", "%u bytes", SFS_BLOCKSIZE); - dumplval("Volume name", sb.sb_volname); + printf("Superblock\n"); + printf("----------\n"); + dumpvalf("Magic", "0x%8x", SWAP32(sb.sb_magic)); + dumpvalf("Size", "%u blocks", SWAP32(sb.sb_nblocks)); + dumpvalf("Freemap size", "%u blocks", + SFS_FREEMAPBLOCKS(SWAP32(sb.sb_nblocks))); + dumpvalf("Block size", "%u bytes", SFS_BLOCKSIZE); + dumplval("Volume name", sb.sb_volname); - for (i=0; i= fsblocks) { - if (data[j] & mask) { - putchar('x'); - } - else { - putchar('!'); - } - } - else { - if (data[j] & mask) { - putchar('*'); - } - else { - putchar('.'); - } - } - } - if (j % 8 == 7) { - printf("\n"); - } - else { - printf(" "); - } - } - } - printf("\n"); + printf("Free block bitmap\n"); + printf("-----------------\n"); + for (i = 0; i < freemapblocks; i++) { + diskread(data, SFS_FREEMAP_START + i); + printf(" Freemap block #%u in disk block %u: blocks %u - %u" + " (0x%x - 0x%x)\n", + i, SFS_FREEMAP_START + i, i * SFS_BITSPERBLOCK, + (i + 1) * SFS_BITSPERBLOCK - 1, i * SFS_BITSPERBLOCK, + (i + 1) * SFS_BITSPERBLOCK - 1); + for (j = 0; j < SFS_BLOCKSIZE; j++) { + if (j % 8 == 0) { + snprintf(tmp, sizeof(tmp), "0x%x", i * SFS_BITSPERBLOCK + j * 8); + printf("%-7s ", tmp); + } + for (k = 0; k < 8; k++) { + bn = i * SFS_BITSPERBLOCK + j * 8 + k; + mask = 1U << k; + if (bn >= fsblocks) { + if (data[j] & mask) { + putchar('x'); + } else { + putchar('!'); + } + } else { + if (data[j] & mask) { + putchar('*'); + } else { + putchar('.'); + } + } + } + if (j % 8 == 7) { + printf("\n"); + } else { + printf(" "); + } + } + } + printf("\n"); } -static -void -dumpindirect(uint32_t block) -{ - uint32_t ib[SFS_BLOCKSIZE/sizeof(uint32_t)]; - char tmp[128]; - unsigned i; +static void dumpindirect(uint32_t block) { + uint32_t ib[SFS_BLOCKSIZE / sizeof(uint32_t)]; + char tmp[128]; + unsigned i; - if (block == 0) { - return; - } - printf("Indirect block %u\n", block); + if (block == 0) { + return; + } + printf("Indirect block %u\n", block); - diskread(ib, block); - for (i=0; isfi_size), SFS_BLOCKSIZE); + numblocks = DIVROUNDUP(SWAP32(sfi->sfi_size), SFS_BLOCKSIZE); - fileblock = 0; - for (i=0; isfi_direct[i])); - } - if (fileblock < numblocks) { - fileblock = traverse_ib(fileblock, numblocks, - SWAP32(sfi->sfi_indirect), doblock); - } - assert(fileblock == numblocks); + fileblock = 0; + for (i = 0; i < SFS_NDIRECT && fileblock < numblocks; i++) { + doblock(fileblock++, SWAP32(sfi->sfi_direct[i])); + } + if (fileblock < numblocks) { + fileblock = + traverse_ib(fileblock, numblocks, SWAP32(sfi->sfi_indirect), doblock); + } + assert(fileblock == numblocks); } -static -void -dumpdirblock(uint32_t fileblock, uint32_t diskblock) -{ - struct sfs_direntry sds[SFS_BLOCKSIZE/sizeof(struct sfs_direntry)]; - int nsds = SFS_BLOCKSIZE/sizeof(struct sfs_direntry); - int i; +static void dumpdirblock(uint32_t fileblock, uint32_t diskblock) { + struct sfs_direntry sds[SFS_BLOCKSIZE / sizeof(struct sfs_direntry)]; + int nsds = SFS_BLOCKSIZE / sizeof(struct sfs_direntry); + int i; - (void)fileblock; - if (diskblock == 0) { - printf(" [block %u - empty]\n", diskblock); - return; - } - diskread(&sds, diskblock); + (void)fileblock; + if (diskblock == 0) { + printf(" [block %u - empty]\n", diskblock); + return; + } + diskread(&sds, diskblock); - printf(" [block %u]\n", diskblock); - for (i=0; isfi_size) / sizeof(struct sfs_direntry); - if (SWAP32(sfi->sfi_size) % sizeof(struct sfs_direntry) != 0) { - warnx("Warning: dir size is not a multiple of dir entry size"); - } - printf("Directory contents for inode %u: %d entries\n", ino, nentries); - traverse(sfi, dumpdirblock); + nentries = SWAP32(sfi->sfi_size) / sizeof(struct sfs_direntry); + if (SWAP32(sfi->sfi_size) % sizeof(struct sfs_direntry) != 0) { + warnx("Warning: dir size is not a multiple of dir entry size"); + } + printf("Directory contents for inode %u: %d entries\n", ino, nentries); + traverse(sfi, dumpdirblock); } -static -void -recursedirblock(uint32_t fileblock, uint32_t diskblock) -{ - struct sfs_direntry sds[SFS_BLOCKSIZE/sizeof(struct sfs_direntry)]; - int nsds = SFS_BLOCKSIZE/sizeof(struct sfs_direntry); - int i; +static void recursedirblock(uint32_t fileblock, uint32_t diskblock) { + struct sfs_direntry sds[SFS_BLOCKSIZE / sizeof(struct sfs_direntry)]; + int nsds = SFS_BLOCKSIZE / sizeof(struct sfs_direntry); + int i; - (void)fileblock; - if (diskblock == 0) { - return; - } - diskread(&sds, diskblock); + (void)fileblock; + if (diskblock == 0) { + return; + } + diskread(&sds, diskblock); - for (i=0; isfi_size) / sizeof(struct sfs_direntry); - printf("Reading files in directory %u: %d entries\n", ino, nentries); - traverse(sfi, recursedirblock); - printf("Done with directory %u\n", ino); + nentries = SWAP32(sfi->sfi_size) / sizeof(struct sfs_direntry); + printf("Reading files in directory %u: %d entries\n", ino, nentries); + traverse(sfi, recursedirblock); + printf("Done with directory %u\n", ino); } -static -void dumpfileblock(uint32_t fileblock, uint32_t diskblock) -{ - uint8_t data[SFS_BLOCKSIZE]; - unsigned i, j; - char tmp[128]; +static void dumpfileblock(uint32_t fileblock, uint32_t diskblock) { + uint8_t data[SFS_BLOCKSIZE]; + unsigned i, j; + char tmp[128]; - if (diskblock == 0) { - printf(" 0x%6x [sparse]\n", fileblock * SFS_BLOCKSIZE); - return; - } + if (diskblock == 0) { + printf(" 0x%6x [sparse]\n", fileblock * SFS_BLOCKSIZE); + return; + } - diskread(data, diskblock); - for (i=0; i 126) { - putchar('.'); - } - else { - putchar(data[j]); - } - } - printf("\n"); - } - } + diskread(data, diskblock); + for (i = 0; i < SFS_BLOCKSIZE; i++) { + if (i % 16 == 0) { + snprintf(tmp, sizeof(tmp), "0x%x", fileblock * SFS_BLOCKSIZE + i); + printf("%8s", tmp); + } + if (i % 8 == 0) { + printf(" "); + } else { + printf(" "); + } + printf("%02x", data[i]); + if (i % 16 == 15) { + printf(" "); + for (j = i - 15; j <= i; j++) { + if (data[j] < 32 || data[j] > 126) { + putchar('.'); + } else { + putchar(data[j]); + } + } + printf("\n"); + } + } } -static -void -dumpfile(uint32_t ino, const struct sfs_dinode *sfi) -{ - printf("File contents for inode %u:\n", ino); - traverse(sfi, dumpfileblock); +static void dumpfile(uint32_t ino, const struct sfs_dinode *sfi) { + printf("File contents for inode %u:\n", ino); + traverse(sfi, dumpfileblock); } -static -void -dumpinode(uint32_t ino, const char *name) -{ - struct sfs_dinode sfi; - const char *typename; - char tmp[128]; - unsigned i; +static void dumpinode(uint32_t ino, const char *name) { + struct sfs_dinode sfi; + const char *typename; + char tmp[128]; + unsigned i; - diskread(&sfi, ino); + diskread(&sfi, ino); - printf("Inode %u", ino); - if (name != NULL) { - printf(" (%s)", name); - } - printf("\n"); - printf("--------------\n"); + printf("Inode %u", ino); + if (name != NULL) { + printf(" (%s)", name); + } + printf("\n"); + printf("--------------\n"); - switch (SWAP16(sfi.sfi_type)) { - case SFS_TYPE_FILE: typename = "regular file"; break; - case SFS_TYPE_DIR: typename = "directory"; break; - default: typename = "invalid"; break; - } - dumpvalf("Type", "%u (%s)", SWAP16(sfi.sfi_type), typename); - dumpvalf("Size", "%u", SWAP32(sfi.sfi_size)); - dumpvalf("Link count", "%u", SWAP16(sfi.sfi_linkcount)); - printf("\n"); + switch (SWAP16(sfi.sfi_type)) { + case SFS_TYPE_FILE: + typename = "regular file"; + break; + case SFS_TYPE_DIR: + typename = "directory"; + break; + default: + typename = "invalid"; + break; + } + dumpvalf("Type", "%u (%s)", SWAP16(sfi.sfi_type), typename); + dumpvalf("Size", "%u", SWAP32(sfi.sfi_size)); + dumpvalf("Link count", "%u", SWAP16(sfi.sfi_linkcount)); + printf("\n"); - printf(" Direct blocks:\n"); - for (i=0; i 64K sectors (which - * would be 32M) but is < 1024K sectors (512M) so we - * need up to 5 hex digits for a block number. And - * assume it's actually < 1 million sectors so we need - * only up to 6 decimal digits. The complete block - * number print then needs up to 16 digits. - */ - snprintf(tmp, sizeof(tmp), "%u (0x%x)", - SWAP32(sfi.sfi_direct[i]), SWAP32(sfi.sfi_direct[i])); - printf(" %-16s", tmp); - if (i % 4 == 3) { - printf("\n"); - } - } - if (i % 4 != 0) { - printf("\n"); - } - printf(" Indirect block: %u (0x%x)\n", - SWAP32(sfi.sfi_indirect), SWAP32(sfi.sfi_indirect)); - for (i=0; i 64K sectors (which + * would be 32M) but is < 1024K sectors (512M) so we + * need up to 5 hex digits for a block number. And + * assume it's actually < 1 million sectors so we need + * only up to 6 decimal digits. The complete block + * number print then needs up to 16 digits. + */ + snprintf(tmp, sizeof(tmp), "%u (0x%x)", SWAP32(sfi.sfi_direct[i]), + SWAP32(sfi.sfi_direct[i])); + printf(" %-16s", tmp); + if (i % 4 == 3) { + printf("\n"); + } + } + if (i % 4 != 0) { + printf("\n"); + } + printf(" Indirect block: %u (0x%x)\n", SWAP32(sfi.sfi_indirect), + SWAP32(sfi.sfi_indirect)); + for (i = 0; i < ARRAYCOUNT(sfi.sfi_waste); i++) { + if (sfi.sfi_waste[i] != 0) { + printf(" Word %u in waste area: 0x%x\n", i, SWAP32(sfi.sfi_waste[i])); + } + } - if (doindirect) { - dumpindirect(SWAP32(sfi.sfi_indirect)); - } + if (doindirect) { + dumpindirect(SWAP32(sfi.sfi_indirect)); + } - if (SWAP16(sfi.sfi_type) == SFS_TYPE_DIR && dodirs) { - dumpdir(ino, &sfi); - } - if (SWAP16(sfi.sfi_type) == SFS_TYPE_FILE && dofiles) { - dumpfile(ino, &sfi); - } - if (SWAP16(sfi.sfi_type) == SFS_TYPE_DIR && recurse) { - recursedir(ino, &sfi); - } + if (SWAP16(sfi.sfi_type) == SFS_TYPE_DIR && dodirs) { + dumpdir(ino, &sfi); + } + if (SWAP16(sfi.sfi_type) == SFS_TYPE_FILE && dofiles) { + dumpfile(ino, &sfi); + } + if (SWAP16(sfi.sfi_type) == SFS_TYPE_DIR && recurse) { + recursedir(ino, &sfi); + } } //////////////////////////////////////////////////////////// // main -static -void -usage(void) -{ - warnx("Usage: dumpsfs [options] device/diskfile"); - warnx(" -s: dump superblock"); - warnx(" -b: dump free block bitmap"); - warnx(" -i ino: dump specified inode"); - warnx(" -I: dump indirect blocks"); - warnx(" -f: dump file contents"); - warnx(" -d: dump directory contents"); - warnx(" -r: recurse into directory contents"); - warnx(" -a: equivalent to -sbdfr -i 1"); - errx(1, " Default is -i 1"); +static void usage(void) { + warnx("Usage: dumpsfs [options] device/diskfile"); + warnx(" -s: dump superblock"); + warnx(" -b: dump free block bitmap"); + warnx(" -i ino: dump specified inode"); + warnx(" -I: dump indirect blocks"); + warnx(" -f: dump file contents"); + warnx(" -d: dump directory contents"); + warnx(" -r: recurse into directory contents"); + warnx(" -a: equivalent to -sbdfr -i 1"); + errx(1, " Default is -i 1"); } -int -main(int argc, char **argv) -{ - bool dosb = false; - bool dofreemap = false; - uint32_t dumpino = 0; - const char *dumpdisk = NULL; +int main(int argc, char **argv) { + bool dosb = false; + bool dofreemap = false; + uint32_t dumpino = 0; + const char *dumpdisk = NULL; - int i, j; - uint32_t nblocks; + int i, j; + uint32_t nblocks; #ifdef HOST - /* Don't do this; it frobs the tty and you can't pipe to less */ - /*hostcompat_init(argc, argv);*/ - hostcompat_progname = argv[0]; + /* Don't do this; it frobs the tty and you can't pipe to less */ + /*hostcompat_init(argc, argv);*/ + hostcompat_progname = argv[0]; #endif - for (i=1; i=0); - return BLOCKSIZE; +uint32_t diskblocksize(void) { + assert(fd >= 0); + return BLOCKSIZE; } /* * Return the device/image size in blocks. */ -uint32_t -diskblocks(void) -{ - assert(fd>=0); - return nblocks; +uint32_t diskblocks(void) { + assert(fd >= 0); + return nblocks; } /* * Write a block. */ -void -diskwrite(const void *data, uint32_t block) -{ - const char *cdata = data; - uint32_t tot=0; - int len; +void diskwrite(const void *data, uint32_t block) { + const char *cdata = data; + uint32_t tot = 0; + int len; - assert(fd>=0); + assert(fd >= 0); #ifdef HOST - // skip over disk file header - block++; + // skip over disk file header + block++; #endif - if (lseek(fd, block*BLOCKSIZE, SEEK_SET)<0) { - err(1, "lseek"); - } + if (lseek(fd, block * BLOCKSIZE, SEEK_SET) < 0) { + err(1, "lseek"); + } - while (tot < BLOCKSIZE) { - len = write(fd, cdata + tot, BLOCKSIZE - tot); - if (len < 0) { - if (errno==EINTR || errno==EAGAIN) { - continue; - } - err(1, "write"); - } - if (len==0) { - err(1, "write returned 0?"); - } - tot += len; - } + while (tot < BLOCKSIZE) { + len = write(fd, cdata + tot, BLOCKSIZE - tot); + if (len < 0) { + if (errno == EINTR || errno == EAGAIN) { + continue; + } + err(1, "write"); + } + if (len == 0) { + err(1, "write returned 0?"); + } + tot += len; + } } /* * Read a block. */ -void -diskread(void *data, uint32_t block) -{ - char *cdata = data; - uint32_t tot=0; - int len; +void diskread(void *data, uint32_t block) { + char *cdata = data; + uint32_t tot = 0; + int len; - assert(fd>=0); + assert(fd >= 0); #ifdef HOST - // skip over disk file header - block++; + // skip over disk file header + block++; #endif - if (lseek(fd, block*BLOCKSIZE, SEEK_SET)<0) { - err(1, "lseek"); - } + if (lseek(fd, block * BLOCKSIZE, SEEK_SET) < 0) { + err(1, "lseek"); + } - while (tot < BLOCKSIZE) { - len = read(fd, cdata + tot, BLOCKSIZE - tot); - if (len < 0) { - if (errno==EINTR || errno==EAGAIN) { - continue; - } - err(1, "read"); - } - if (len==0) { - err(1, "unexpected EOF in mid-sector"); - } - tot += len; - } + while (tot < BLOCKSIZE) { + len = read(fd, cdata + tot, BLOCKSIZE - tot); + if (len < 0) { + if (errno == EINTR || errno == EAGAIN) { + continue; + } + err(1, "read"); + } + if (len == 0) { + err(1, "unexpected EOF in mid-sector"); + } + tot += len; + } } /* * Close the disk. */ -void -closedisk(void) -{ - assert(fd>=0); - if (close(fd)) { - err(1, "close"); - } - fd = -1; +void closedisk(void) { + assert(fd >= 0); + if (close(fd)) { + err(1, "close"); + } + fd = -1; } diff --git a/userland/sbin/mksfs/mksfs.c b/userland/sbin/mksfs/mksfs.c index 5e32252..e3b8a77 100644 --- a/userland/sbin/mksfs/mksfs.c +++ b/userland/sbin/mksfs/mksfs.c @@ -37,7 +37,6 @@ #include "support.h" #include "kern/sfs.h" - #ifdef HOST #include // for arpa/inet.h @@ -66,175 +65,155 @@ static char freemapbuf[MAXFREEMAPBLOCKS * SFS_BLOCKSIZE]; /* * Assert that the on-disk data structures are correctly sized. */ -static -void -check(void) -{ - assert(sizeof(struct sfs_superblock)==SFS_BLOCKSIZE); - assert(sizeof(struct sfs_dinode)==SFS_BLOCKSIZE); - assert(SFS_BLOCKSIZE % sizeof(struct sfs_direntry) == 0); +static void check(void) { + assert(sizeof(struct sfs_superblock) == SFS_BLOCKSIZE); + assert(sizeof(struct sfs_dinode) == SFS_BLOCKSIZE); + assert(SFS_BLOCKSIZE % sizeof(struct sfs_direntry) == 0); } /* * Mark a block allocated. */ -static -void -allocblock(uint32_t block) -{ - uint32_t mapbyte = block/CHAR_BIT; - unsigned char mask = (1<<(block % CHAR_BIT)); +static void allocblock(uint32_t block) { + uint32_t mapbyte = block / CHAR_BIT; + unsigned char mask = (1 << (block % CHAR_BIT)); - assert((freemapbuf[mapbyte] & mask) == 0); - freemapbuf[mapbyte] |= mask; + assert((freemapbuf[mapbyte] & mask) == 0); + freemapbuf[mapbyte] |= mask; } /* * Initialize the free block bitmap. */ -static -void -initfreemap(uint32_t fsblocks) -{ - uint32_t freemapbits = SFS_FREEMAPBITS(fsblocks); - uint32_t freemapblocks = SFS_FREEMAPBLOCKS(fsblocks); - uint32_t i; +static void initfreemap(uint32_t fsblocks) { + uint32_t freemapbits = SFS_FREEMAPBITS(fsblocks); + uint32_t freemapblocks = SFS_FREEMAPBLOCKS(fsblocks); + uint32_t i; - if (freemapblocks > MAXFREEMAPBLOCKS) { - errx(1, "Filesystem too large -- " - "increase MAXFREEMAPBLOCKS and recompile"); - } + if (freemapblocks > MAXFREEMAPBLOCKS) { + errx(1, "Filesystem too large -- " + "increase MAXFREEMAPBLOCKS and recompile"); + } - /* mark the superblock and root inode in use */ - allocblock(SFS_SUPER_BLOCK); - allocblock(SFS_ROOTDIR_INO); + /* mark the superblock and root inode in use */ + allocblock(SFS_SUPER_BLOCK); + allocblock(SFS_ROOTDIR_INO); - /* the freemap blocks must be in use */ - for (i=0; i= SFS_VOLNAME_SIZE) { - errx(1, "Volume name %s too long", volname); - } + if (strlen(volname) >= SFS_VOLNAME_SIZE) { + errx(1, "Volume name %s too long", volname); + } - /* Initialize the superblock structure */ - sb.sb_magic = SWAP32(SFS_MAGIC); - sb.sb_nblocks = SWAP32(nblocks); - strcpy(sb.sb_volname, volname); + /* Initialize the superblock structure */ + sb.sb_magic = SWAP32(SFS_MAGIC); + sb.sb_nblocks = SWAP32(nblocks); + strcpy(sb.sb_volname, volname); - /* and write it out. */ - diskwrite(&sb, SFS_SUPER_BLOCK); + /* and write it out. */ + diskwrite(&sb, SFS_SUPER_BLOCK); } /* * Write out the free block bitmap. */ -static -void -writefreemap(uint32_t fsblocks) -{ - uint32_t freemapblocks; - char *ptr; - uint32_t i; +static void writefreemap(uint32_t fsblocks) { + uint32_t freemapblocks; + char *ptr; + uint32_t i; - /* Write out each of the blocks in the free block bitmap. */ - freemapblocks = SFS_FREEMAPBLOCKS(fsblocks); - for (i=0; i /* for CHAR_BIT */ -#include /* also for CHAR_BIT */ +#include /* for CHAR_BIT */ +#include /* also for CHAR_BIT */ #include #include #include @@ -52,69 +52,62 @@ static uint8_t *tofreedata; * called after the superblock is loaded so we can ask how big the * volume is. */ -void -freemap_setup(void) -{ - size_t i, mapbytes; - uint32_t fsblocks, mapblocks; +void freemap_setup(void) { + size_t i, mapbytes; + uint32_t fsblocks, mapblocks; - fsblocks = sb_totalblocks(); - mapblocks = sb_freemapblocks(); - mapbytes = mapblocks * SFS_BLOCKSIZE; + fsblocks = sb_totalblocks(); + mapblocks = sb_freemapblocks(); + mapbytes = mapblocks * SFS_BLOCKSIZE; - freemapdata = domalloc(mapbytes * sizeof(uint8_t)); - tofreedata = domalloc(mapbytes * sizeof(uint8_t)); - for (i=0; i INOMAX_D) got partially completed. */ -void -freemap_blockfree(uint32_t block) -{ - unsigned index = block/8; - uint8_t mask = ((uint8_t)1)<<(block%8); +void freemap_blockfree(uint32_t block) { + unsigned index = block / 8; + uint8_t mask = ((uint8_t)1) << (block % 8); - if (tofreedata[index] & mask) { - /* already marked to free once, ignore */ - return; - } - if (freemapdata[index] & mask) { - /* block is used elsewhere, ignore */ - return; - } - tofreedata[index] |= mask; + if (tofreedata[index] & mask) { + /* already marked to free once, ignore */ + return; + } + if (freemapdata[index] & mask) { + /* block is used elsewhere, ignore */ + return; + } + tofreedata[index] |= mask; } /* * Count the number of bits set. */ -static -int -countbits(uint8_t val) -{ - uint8_t x; - int ct=0; +static int countbits(uint8_t val) { + uint8_t x; + int ct = 0; - for (x=1; x; x<<=1) { - if (val & x) ct++; - } - return ct; + for (x = 1; x; x <<= 1) { + if (val & x) + ct++; + } + return ct; } /* @@ -198,21 +185,18 @@ countbits(uint8_t val) * byte offset within that block; VAL is the byte value; WHAT is a * string indicating what happened. */ -static -void -reportfreemap(uint32_t mapblock, uint32_t byte, uint8_t val, const char *what) -{ - uint8_t x, y; - uint32_t blocknum; +static void reportfreemap(uint32_t mapblock, uint32_t byte, uint8_t val, + const char *what) { + uint8_t x, y; + uint32_t blocknum; - for (x=1, y=0; x; x<<=1, y++) { - if (val & x) { - blocknum = mapblock*SFS_BITSPERBLOCK + - byte*CHAR_BIT + y; - warnx("Block %lu erroneously shown %s in freemap", - (unsigned long) blocknum, what); - } - } + for (x = 1, y = 0; x; x <<= 1, y++) { + if (val & x) { + blocknum = mapblock * SFS_BITSPERBLOCK + byte * CHAR_BIT + y; + warnx("Block %lu erroneously shown %s in freemap", + (unsigned long)blocknum, what); + } + } } /* @@ -221,90 +205,84 @@ reportfreemap(uint32_t mapblock, uint32_t byte, uint8_t val, const char *what) * This is called after (at the end of) pass 1, when we've recursively * found all the reachable blocks and marked them. */ -void -freemap_check(void) -{ - uint8_t actual[SFS_BLOCKSIZE], *expected, *tofree, tmp; - uint32_t alloccount=0, freecount=0, i, j; - int bchanged; - uint32_t bitblocks; +void freemap_check(void) { + uint8_t actual[SFS_BLOCKSIZE], *expected, *tofree, tmp; + uint32_t alloccount = 0, freecount = 0, i, j; + int bchanged; + uint32_t bitblocks; - bitblocks = sb_freemapblocks(); + bitblocks = sb_freemapblocks(); - for (i=0; i 0) { - warnx("%lu blocks erroneously shown free in freemap (fixed)", - (unsigned long) alloccount); - setbadness(EXIT_RECOV); - } - if (freecount > 0) { - warnx("%lu blocks erroneously shown used in freemap (fixed)", - (unsigned long) freecount); - setbadness(EXIT_RECOV); - } + if (alloccount > 0) { + warnx("%lu blocks erroneously shown free in freemap (fixed)", + (unsigned long)alloccount); + setbadness(EXIT_RECOV); + } + if (freecount > 0) { + warnx("%lu blocks erroneously shown used in freemap (fixed)", + (unsigned long)freecount); + setbadness(EXIT_RECOV); + } } /* * Return the total number of blocks in use, which we count during * pass 1. */ -unsigned long -freemap_blocksused(void) -{ - return blocksinuse; -} +unsigned long freemap_blocksused(void) { return blocksinuse; } diff --git a/userland/sbin/sfsck/freemap.h b/userland/sbin/sfsck/freemap.h index 3fabc59..25bd1fc 100644 --- a/userland/sbin/sfsck/freemap.h +++ b/userland/sbin/sfsck/freemap.h @@ -39,13 +39,13 @@ #include typedef enum { - B_SUPERBLOCK, /* Block that is the superblock */ - B_FREEMAPBLOCK, /* Block used by free-block bitmap */ - B_INODE, /* Block that is an inode */ - B_IBLOCK, /* Indirect (or doubly-indirect etc.) block */ - B_DIRDATA, /* Data block of a directory */ - B_DATA, /* Data block */ - B_PASTEND, /* Block off the end of the fs */ + B_SUPERBLOCK, /* Block that is the superblock */ + B_FREEMAPBLOCK, /* Block used by free-block bitmap */ + B_INODE, /* Block that is an inode */ + B_IBLOCK, /* Indirect (or doubly-indirect etc.) block */ + B_DIRDATA, /* Data block of a directory */ + B_DATA, /* Data block */ + B_PASTEND, /* Block off the end of the fs */ } blockusage_t; /* Call this after loading the superblock but before doing any checks. */ @@ -63,5 +63,4 @@ void freemap_check(void); /* Return the number of blocks in use. Valid after freemap_check(). */ unsigned long freemap_blocksused(void); - #endif /* FREEMAP_H */ diff --git a/userland/sbin/sfsck/ibmacros.h b/userland/sbin/sfsck/ibmacros.h index 4f62d3f..c834e82 100644 --- a/userland/sbin/sfsck/ibmacros.h +++ b/userland/sbin/sfsck/ibmacros.h @@ -80,80 +80,79 @@ /* numbers */ -#define NUM_D SFS_NDIRECT -#define NUM_I SFS_NINDIRECT -#define NUM_II SFS_NDINDIRECT -#define NUM_III SFS_NTINDIRECT +#define NUM_D SFS_NDIRECT +#define NUM_I SFS_NINDIRECT +#define NUM_II SFS_NDINDIRECT +#define NUM_III SFS_NTINDIRECT /* blocks */ #if NUM_D == 0 -#define GET_D(sfi, i) GET0_x(sfi, sfi_direct, i) -#define SET_D(sfi, i) SET0_x(sfi, sfi_direct, i) +#define GET_D(sfi, i) GET0_x(sfi, sfi_direct, i) +#define SET_D(sfi, i) SET0_x(sfi, sfi_direct, i) #elif NUM_D == 1 -#define GET_D(sfi, i) GET1_x(sfi, sfi_direct, i) -#define SET_D(sfi, i) SET1_x(sfi, sfi_direct, i) +#define GET_D(sfi, i) GET1_x(sfi, sfi_direct, i) +#define SET_D(sfi, i) SET1_x(sfi, sfi_direct, i) #else -#define GET_D(sfi, i) GETN_x(sfi, sfi_direct, i) -#define SET_D(sfi, i) SETN_x(sfi, sfi_direct, i) +#define GET_D(sfi, i) GETN_x(sfi, sfi_direct, i) +#define SET_D(sfi, i) SETN_x(sfi, sfi_direct, i) #endif #if NUM_I == 0 -#define GET_I(sfi, i) GET0_x(sfi, sfi_indirect, i) -#define SET_I(sfi, i) SET0_x(sfi, sfi_indirect, i) +#define GET_I(sfi, i) GET0_x(sfi, sfi_indirect, i) +#define SET_I(sfi, i) SET0_x(sfi, sfi_indirect, i) #elif NUM_I == 1 -#define GET_I(sfi, i) GET1_x(sfi, sfi_indirect, i) -#define SET_I(sfi, i) SET1_x(sfi, sfi_indirect, i) +#define GET_I(sfi, i) GET1_x(sfi, sfi_indirect, i) +#define SET_I(sfi, i) SET1_x(sfi, sfi_indirect, i) #else -#define GET_I(sfi, i) GETN_x(sfi, sfi_indirect, i) -#define SET_I(sfi, i) SETN_x(sfi, sfi_indirect, i) +#define GET_I(sfi, i) GETN_x(sfi, sfi_indirect, i) +#define SET_I(sfi, i) SETN_x(sfi, sfi_indirect, i) #endif #if NUM_II == 0 -#define GET_II(sfi, i) GET0_x(sfi, sfi_dindirect, i) -#define SET_II(sfi, i) SET0_x(sfi, sfi_dindirect, i) +#define GET_II(sfi, i) GET0_x(sfi, sfi_dindirect, i) +#define SET_II(sfi, i) SET0_x(sfi, sfi_dindirect, i) #elif NUM_II == 1 -#define GET_II(sfi, i) GET1_x(sfi, sfi_dindirect, i) -#define SET_II(sfi, i) SET1_x(sfi, sfi_dindirect, i) +#define GET_II(sfi, i) GET1_x(sfi, sfi_dindirect, i) +#define SET_II(sfi, i) SET1_x(sfi, sfi_dindirect, i) #else -#define GET_II(sfi, i) GETN_x(sfi, sfi_dindirect, i) -#define SET_II(sfi, i) SETN_x(sfi, sfi_dindirect, i) +#define GET_II(sfi, i) GETN_x(sfi, sfi_dindirect, i) +#define SET_II(sfi, i) SETN_x(sfi, sfi_dindirect, i) #endif #if NUM_III == 0 -#define GET_III(sfi, i) GET0_x(sfi, sfi_tindirect, i) -#define SET_III(sfi, i) SET0_x(sfi, sfi_tindirect, i) +#define GET_III(sfi, i) GET0_x(sfi, sfi_tindirect, i) +#define SET_III(sfi, i) SET0_x(sfi, sfi_tindirect, i) #elif NUM_III == 1 -#define GET_III(sfi, i) GET1_x(sfi, sfi_tindirect, i) -#define SET_III(sfi, i) SET1_x(sfi, sfi_tindirect, i) +#define GET_III(sfi, i) GET1_x(sfi, sfi_tindirect, i) +#define SET_III(sfi, i) SET1_x(sfi, sfi_tindirect, i) #else -#define GET_III(sfi, i) GETN_x(sfi, sfi_tindirect, i) -#define SET_III(sfi, i) SETN_x(sfi, sfi_tindirect, i) +#define GET_III(sfi, i) GETN_x(sfi, sfi_tindirect, i) +#define SET_III(sfi, i) SETN_x(sfi, sfi_tindirect, i) #endif /* the generic forms of the block macros */ -#define GET0_x(sfi, field, i) ((void)(i), (void)(sfi), 0) -#define GET1_x(sfi, field, i) ((void)(i), (sfi)->field) -#define GETN_x(sfi, field, i) ((sfi)->field[(i)]) +#define GET0_x(sfi, field, i) ((void)(i), (void)(sfi), 0) +#define GET1_x(sfi, field, i) ((void)(i), (sfi)->field) +#define GETN_x(sfi, field, i) ((sfi)->field[(i)]) -#define SET0_x(sfi, field, i) (*((void)(i), (void)(sfi), (uint32_t *)NULL)) -#define SET1_x(sfi, field, i) (*((void)(i), &(sfi)->field)) -#define SETN_x(sfi, field, i) ((sfi)->field[(i)]) +#define SET0_x(sfi, field, i) (*((void)(i), (void)(sfi), (uint32_t *)NULL)) +#define SET1_x(sfi, field, i) (*((void)(i), &(sfi)->field)) +#define SETN_x(sfi, field, i) ((sfi)->field[(i)]) /* region sizes */ -#define RANGE_D 1 -#define RANGE_I (RANGE_D * SFS_DBPERIDB) -#define RANGE_II (RANGE_I * SFS_DBPERIDB) -#define RANGE_III (RANGE_II * SFS_DBPERIDB) +#define RANGE_D 1 +#define RANGE_I (RANGE_D * SFS_DBPERIDB) +#define RANGE_II (RANGE_I * SFS_DBPERIDB) +#define RANGE_III (RANGE_II * SFS_DBPERIDB) /* max blocks */ -#define INOMAX_D NUM_D -#define INOMAX_I (INOMAX_D + SFS_DBPERIDB * NUM_I) -#define INOMAX_II (INOMAX_I + SFS_DBPERIDB * NUM_II) -#define INOMAX_III (INOMAX_II + SFS_DBPERIDB * NUM_III) - +#define INOMAX_D NUM_D +#define INOMAX_I (INOMAX_D + SFS_DBPERIDB * NUM_I) +#define INOMAX_II (INOMAX_I + SFS_DBPERIDB * NUM_II) +#define INOMAX_III (INOMAX_II + SFS_DBPERIDB * NUM_III) #endif /* IBMACROS_H */ diff --git a/userland/sbin/sfsck/inode.c b/userland/sbin/sfsck/inode.c index 2ca1a51..94e5345 100644 --- a/userland/sbin/sfsck/inode.c +++ b/userland/sbin/sfsck/inode.c @@ -47,10 +47,10 @@ * FUTURE: should count the number of blocks allocated to this inode */ struct inodeinfo { - uint32_t ino; - uint32_t linkcount; /* files only */ - int visited; /* dirs only */ - int type; + uint32_t ino; + uint32_t linkcount; /* files only */ + int visited; /* dirs only */ + int type; }; /* Table of inodes found. */ @@ -66,61 +66,53 @@ static int inodes_sorted = 0; /* * Add an entry to the inode table, realloc'ing it if needed. */ -static -void -inode_addtable(uint32_t ino, int type) -{ - unsigned newmax; +static void inode_addtable(uint32_t ino, int type) { + unsigned newmax; - assert(ninodes <= maxinodes); - if (ninodes == maxinodes) { - newmax = maxinodes ? maxinodes * 2 : 4; - inodes = dorealloc(inodes, maxinodes * sizeof(inodes[0]), - newmax * sizeof(inodes[0])); - maxinodes = newmax; - } - inodes[ninodes].ino = ino; - inodes[ninodes].linkcount = 0; - inodes[ninodes].visited = 0; - inodes[ninodes].type = type; - ninodes++; - inodes_sorted = 0; + assert(ninodes <= maxinodes); + if (ninodes == maxinodes) { + newmax = maxinodes ? maxinodes * 2 : 4; + inodes = dorealloc(inodes, maxinodes * sizeof(inodes[0]), + newmax * sizeof(inodes[0])); + maxinodes = newmax; + } + inodes[ninodes].ino = ino; + inodes[ninodes].linkcount = 0; + inodes[ninodes].visited = 0; + inodes[ninodes].type = type; + ninodes++; + inodes_sorted = 0; } /* * Compare function for inodes. */ -static -int -inode_compare(const void *av, const void *bv) -{ - const struct inodeinfo *a = av; - const struct inodeinfo *b = bv; +static int inode_compare(const void *av, const void *bv) { + const struct inodeinfo *a = av; + const struct inodeinfo *b = bv; - if (a->ino < b->ino) { - return -1; - } - if (a->ino > b->ino) { - return 1; - } - /* - * There should be no duplicates in the table! But C99 makes - * no guarantees about whether the implementation of qsort can - * ask us to compare an element to itself. Assert that this is - * what happened. - */ - assert(av == bv); - return 0; + if (a->ino < b->ino) { + return -1; + } + if (a->ino > b->ino) { + return 1; + } + /* + * There should be no duplicates in the table! But C99 makes + * no guarantees about whether the implementation of qsort can + * ask us to compare an element to itself. Assert that this is + * what happened. + */ + assert(av == bv); + return 0; } /* * After pass1, we sort the inode table for faster access. */ -void -inode_sorttable(void) -{ - qsort(inodes, ninodes, sizeof(inodes[0]), inode_compare); - inodes_sorted = 1; +void inode_sorttable(void) { + qsort(inodes, ninodes, sizeof(inodes[0]), inode_compare); + inodes_sorted = 1; } /* @@ -132,35 +124,30 @@ inode_sorttable(void) * pass2.c, we'll need to be able to ask if an inode number is valid * and names a directory.) */ -static -struct inodeinfo * -inode_find(uint32_t ino) -{ - unsigned min, max, i; +static struct inodeinfo *inode_find(uint32_t ino) { + unsigned min, max, i; - assert(inodes_sorted); - assert(ninodes > 0); + assert(inodes_sorted); + assert(ninodes > 0); - min = 0; - max = ninodes; - while (1) { - assert(min <= max); - if (min == max) { - errx(EXIT_UNRECOV, "FATAL: inode %u wasn't found in my inode table", ino); - } - i = min + (max - min)/2; - if (inodes[i].ino < ino) { - min = i + 1; - } - else if (inodes[i].ino > ino) { - max = i; - } - else { - assert(inodes[i].ino == ino); - return &inodes[i]; - } - } - /* NOTREACHED */ + min = 0; + max = ninodes; + while (1) { + assert(min <= max); + if (min == max) { + errx(EXIT_UNRECOV, "FATAL: inode %u wasn't found in my inode table", ino); + } + i = min + (max - min) / 2; + if (inodes[i].ino < ino) { + min = i + 1; + } else if (inodes[i].ino > ino) { + max = i; + } else { + assert(inodes[i].ino == ino); + return &inodes[i]; + } + } + /* NOTREACHED */ } //////////////////////////////////////////////////////////// @@ -173,22 +160,20 @@ inode_find(uint32_t ino) * after all inodes have been added. In the FUTURE this could be * changed to a better data structure. */ -int -inode_add(uint32_t ino, int type) -{ - unsigned i; +int inode_add(uint32_t ino, int type) { + unsigned i; - for (i=0; itype == SFS_TYPE_DIR); - assert(inf->linkcount == 0); - if (inf->visited) { - return 1; - } - inf->visited = 1; - return 0; + inf = inode_find(ino); + assert(inf->type == SFS_TYPE_DIR); + assert(inf->linkcount == 0); + if (inf->visited) { + return 1; + } + inf->visited = 1; + return 0; } /* @@ -218,49 +201,43 @@ inode_visitdir(uint32_t ino) * does. (And that, in turn, is because the link count of a directory * is a local property.) */ -void -inode_addlink(uint32_t ino) -{ - struct inodeinfo *inf; +void inode_addlink(uint32_t ino) { + struct inodeinfo *inf; - inf = inode_find(ino); - assert(inf->type == SFS_TYPE_FILE); - assert(inf->visited == 0); - inf->linkcount++; + inf = inode_find(ino); + assert(inf->type == SFS_TYPE_FILE); + assert(inf->visited == 0); + inf->linkcount++; } /* * Correct link counts. This is effectively pass3. (FUTURE: change the * name accordingly.) */ -void -inode_adjust_filelinks(void) -{ - struct sfs_dinode sfi; - unsigned i; +void inode_adjust_filelinks(void) { + struct sfs_dinode sfi; + unsigned i; - for (i=0; i 0); + /* because we've seen it, there must be at least one link */ + assert(inodes[i].linkcount > 0); - sfs_readinode(inodes[i].ino, &sfi); - assert(sfi.sfi_type == SFS_TYPE_FILE); + sfs_readinode(inodes[i].ino, &sfi); + assert(sfi.sfi_type == SFS_TYPE_FILE); - if (sfi.sfi_linkcount != inodes[i].linkcount) { - warnx("File %lu link count %lu should be %lu (fixed)", - (unsigned long) inodes[i].ino, - (unsigned long) sfi.sfi_linkcount, - (unsigned long) inodes[i].linkcount); - sfi.sfi_linkcount = inodes[i].linkcount; - setbadness(EXIT_RECOV); - sfs_writeinode(inodes[i].ino, &sfi); - } - } + if (sfi.sfi_linkcount != inodes[i].linkcount) { + warnx("File %lu link count %lu should be %lu (fixed)", + (unsigned long)inodes[i].ino, (unsigned long)sfi.sfi_linkcount, + (unsigned long)inodes[i].linkcount); + sfi.sfi_linkcount = inodes[i].linkcount; + setbadness(EXIT_RECOV); + sfs_writeinode(inodes[i].ino, &sfi); + } + } } - diff --git a/userland/sbin/sfsck/inode.h b/userland/sbin/sfsck/inode.h index 7a69311..556609a 100644 --- a/userland/sbin/sfsck/inode.h +++ b/userland/sbin/sfsck/inode.h @@ -61,5 +61,4 @@ void inode_addlink(uint32_t ino); */ void inode_adjust_filelinks(void); - #endif /* INODE_H */ diff --git a/userland/sbin/sfsck/main.c b/userland/sbin/sfsck/main.c index 1e50fcf..f691481 100644 --- a/userland/sbin/sfsck/main.c +++ b/userland/sbin/sfsck/main.c @@ -42,7 +42,7 @@ #include "passes.h" #include "main.h" -static int badness=0; +static int badness = 0; /* * Update the badness state. (codes are in main.h) @@ -50,69 +50,65 @@ static int badness=0; * The badness state only gets worse, and is ultimately the process * exit code. */ -void -setbadness(int code) -{ - if (badness < code) { - badness = code; - } +void setbadness(int code) { + if (badness < code) { + badness = code; + } } /* * Main. */ -int -main(int argc, char **argv) -{ +int main(int argc, char **argv) { #ifdef HOST - hostcompat_init(argc, argv); + hostcompat_init(argc, argv); #endif - /* FUTURE: add -n option */ - if (argc!=2) { - errx(EXIT_USAGE, "Usage: sfsck device/diskfile"); - } + /* FUTURE: add -n option */ + if (argc != 2) { + errx(EXIT_USAGE, "Usage: sfsck device/diskfile"); + } - opendisk(argv[1]); + opendisk(argv[1]); - sfs_setup(); - sb_load(); - sb_check(); - freemap_setup(); + sfs_setup(); + sb_load(); + sb_check(); + freemap_setup(); - printf("Phase 1 -- check blocks and sizes\n"); - pass1(); - freemap_check(); + printf("Phase 1 -- check blocks and sizes\n"); + pass1(); + freemap_check(); - printf("Phase 2 -- check directory tree\n"); - inode_sorttable(); - pass2(); + printf("Phase 2 -- check directory tree\n"); + inode_sorttable(); + pass2(); - printf("Phase 3 -- check reference counts\n"); - inode_adjust_filelinks(); + printf("Phase 3 -- check reference counts\n"); + inode_adjust_filelinks(); - closedisk(); + closedisk(); - warnx("%lu blocks used (of %lu); %lu directories; %lu files", - freemap_blocksused(), (unsigned long)sb_totalblocks(), - pass1_founddirs(), pass1_foundfiles()); + warnx("%lu blocks used (of %lu); %lu directories; %lu files", + freemap_blocksused(), (unsigned long)sb_totalblocks(), + pass1_founddirs(), pass1_foundfiles()); - switch (badness) { - case EXIT_USAGE: - case EXIT_FATAL: - default: - /* not supposed to happen here */ - assert(0); - break; - case EXIT_UNRECOV: - warnx("WARNING - unrecoverable errors. Maybe try again?"); - break; - case EXIT_RECOV: - warnx("Caution - filesystem modified. Run again for luck."); - break; - case EXIT_CLEAN: - break; - } + switch (badness) { + case EXIT_USAGE: + case EXIT_FATAL: + default: + /* not supposed to happen here */ + assert(0); + break; + case EXIT_UNRECOV: + warnx("WARNING - unrecoverable errors. Maybe try again?"); + break; + case EXIT_RECOV: + warnx("Caution - filesystem modified. Run again for luck."); + break; + case EXIT_CLEAN: + break; + } - return badness; + return badness; } diff --git a/userland/sbin/sfsck/main.h b/userland/sbin/sfsck/main.h index 1fde332..3ded4ff 100644 --- a/userland/sbin/sfsck/main.h +++ b/userland/sbin/sfsck/main.h @@ -37,11 +37,11 @@ * the ultimate exit code of sfsck. */ -#define EXIT_USAGE 4 -#define EXIT_FATAL 3 -#define EXIT_UNRECOV 2 -#define EXIT_RECOV 1 -#define EXIT_CLEAN 0 +#define EXIT_USAGE 4 +#define EXIT_FATAL 3 +#define EXIT_UNRECOV 2 +#define EXIT_RECOV 1 +#define EXIT_CLEAN 0 void setbadness(int code); diff --git a/userland/sbin/sfsck/pass1.c b/userland/sbin/sfsck/pass1.c index 3d53662..d6a1aba 100644 --- a/userland/sbin/sfsck/pass1.c +++ b/userland/sbin/sfsck/pass1.c @@ -47,18 +47,18 @@ #include "passes.h" #include "main.h" -static unsigned long count_dirs=0, count_files=0; +static unsigned long count_dirs = 0, count_files = 0; /* * State for checking indirect blocks. */ struct ibstate { - uint32_t ino; /* inode we're doing (constant) */ - uint32_t curfileblock; /* current block offset in the file */ - uint32_t fileblocks; /* file size in blocks (constant) */ - uint32_t volblocks; /* volume size in blocks (constant) */ - unsigned pasteofcount; /* number of blocks found past eof */ - blockusage_t usagetype; /* how to call freemap_blockinuse() */ + uint32_t ino; /* inode we're doing (constant) */ + uint32_t curfileblock; /* current block offset in the file */ + uint32_t fileblocks; /* file size in blocks (constant) */ + uint32_t volblocks; /* volume size in blocks (constant) */ + unsigned pasteofcount; /* number of blocks found past eof */ + blockusage_t usagetype; /* how to call freemap_blockinuse() */ }; /* @@ -76,100 +76,88 @@ struct ibstate { * scanning. IECHANGEDP should be set to 1 if *IENTRY is changed. * INDIRECTION is the indirection level of this block (1, 2, or 3). */ -static -void -check_indirect_block(struct ibstate *ibs, uint32_t *ientry, int *iechangedp, - int indirection) -{ - uint32_t entries[SFS_DBPERIDB]; - uint32_t i, ct; - uint32_t coveredblocks; - int localchanged = 0; - int j; +static void check_indirect_block(struct ibstate *ibs, uint32_t *ientry, + int *iechangedp, int indirection) { + uint32_t entries[SFS_DBPERIDB]; + uint32_t i, ct; + uint32_t coveredblocks; + int localchanged = 0; + int j; - if (*ientry > 0 && *ientry < ibs->volblocks) { - sfs_readindirect(*ientry, entries); - freemap_blockinuse(*ientry, B_IBLOCK, ibs->ino); - } - else { - if (*ientry >= ibs->volblocks) { - setbadness(EXIT_RECOV); - warnx("Inode %lu: indirect block pointer (level %d) " - "for block %lu outside of volume: %lu " - "(cleared)\n", - (unsigned long)ibs->ino, indirection, - (unsigned long)ibs->curfileblock, - (unsigned long)*ientry); - *ientry = 0; - *iechangedp = 1; - } - coveredblocks = 1; - for (j=0; jcurfileblock += coveredblocks; - return; - } + if (*ientry > 0 && *ientry < ibs->volblocks) { + sfs_readindirect(*ientry, entries); + freemap_blockinuse(*ientry, B_IBLOCK, ibs->ino); + } else { + if (*ientry >= ibs->volblocks) { + setbadness(EXIT_RECOV); + warnx("Inode %lu: indirect block pointer (level %d) " + "for block %lu outside of volume: %lu " + "(cleared)\n", + (unsigned long)ibs->ino, indirection, + (unsigned long)ibs->curfileblock, (unsigned long)*ientry); + *ientry = 0; + *iechangedp = 1; + } + coveredblocks = 1; + for (j = 0; j < indirection; j++) { + coveredblocks *= SFS_DBPERIDB; + } + ibs->curfileblock += coveredblocks; + return; + } - if (indirection > 1) { - for (i=0; i 1) { + for (i = 0; i < SFS_DBPERIDB; i++) { + check_indirect_block(ibs, &entries[i], &localchanged, indirection - 1); + } + } else { + assert(indirection == 1); - for (i=0; i= ibs->volblocks) { - setbadness(EXIT_RECOV); - warnx("Inode %lu: direct block pointer for " - "block %lu outside of volume: %lu " - "(cleared)\n", - (unsigned long)ibs->ino, - (unsigned long)ibs->curfileblock, - (unsigned long)entries[i]); - entries[i] = 0; - localchanged = 1; - } - else if (entries[i] != 0) { - if (ibs->curfileblock < ibs->fileblocks) { - freemap_blockinuse(entries[i], - ibs->usagetype, - ibs->ino); - } - else { - setbadness(EXIT_RECOV); - ibs->pasteofcount++; - freemap_blockfree(entries[i]); - entries[i] = 0; - localchanged = 1; - } - } - ibs->curfileblock++; - } - } + for (i = 0; i < SFS_DBPERIDB; i++) { + if (entries[i] >= ibs->volblocks) { + setbadness(EXIT_RECOV); + warnx("Inode %lu: direct block pointer for " + "block %lu outside of volume: %lu " + "(cleared)\n", + (unsigned long)ibs->ino, (unsigned long)ibs->curfileblock, + (unsigned long)entries[i]); + entries[i] = 0; + localchanged = 1; + } else if (entries[i] != 0) { + if (ibs->curfileblock < ibs->fileblocks) { + freemap_blockinuse(entries[i], ibs->usagetype, ibs->ino); + } else { + setbadness(EXIT_RECOV); + ibs->pasteofcount++; + freemap_blockfree(entries[i]); + entries[i] = 0; + localchanged = 1; + } + } + ibs->curfileblock++; + } + } - ct=0; - for (i=ct=0; ipasteofcount++;*/ - *iechangedp = 1; - freemap_blockfree(*ientry); - *ientry = 0; - } - } - else { - assert(*ientry != 0); - if (localchanged) { - sfs_writeindirect(*ientry, entries); - } - } + ct = 0; + for (i = ct = 0; i < SFS_DBPERIDB; i++) { + if (entries[i] != 0) + ct++; + } + if (ct == 0) { + if (*ientry != 0) { + setbadness(EXIT_RECOV); + /* this is not necessarily correct */ + /*ibs->pasteofcount++;*/ + *iechangedp = 1; + freemap_blockfree(*ientry); + *ientry = 0; + } + } else { + assert(*ientry != 0); + if (localchanged) { + sfs_writeindirect(*ientry, entries); + } + } } /* @@ -180,71 +168,64 @@ check_indirect_block(struct ibstate *ibs, uint32_t *ientry, int *iechangedp, * Returns nonzero if SFI has been modified and needs to be written * back. */ -static -int -check_inode_blocks(uint32_t ino, struct sfs_dinode *sfi, int isdir) -{ - struct ibstate ibs; - uint32_t size, datablock; - int changed; - int i; +static int check_inode_blocks(uint32_t ino, struct sfs_dinode *sfi, int isdir) { + struct ibstate ibs; + uint32_t size, datablock; + int changed; + int i; - size = SFS_ROUNDUP(sfi->sfi_size, SFS_BLOCKSIZE); + size = SFS_ROUNDUP(sfi->sfi_size, SFS_BLOCKSIZE); - ibs.ino = ino; - /*ibs.curfileblock = 0;*/ - ibs.fileblocks = size/SFS_BLOCKSIZE; - ibs.volblocks = sb_totalblocks(); - ibs.pasteofcount = 0; - ibs.usagetype = isdir ? B_DIRDATA : B_DATA; + ibs.ino = ino; + /*ibs.curfileblock = 0;*/ + ibs.fileblocks = size / SFS_BLOCKSIZE; + ibs.volblocks = sb_totalblocks(); + ibs.pasteofcount = 0; + ibs.usagetype = isdir ? B_DIRDATA : B_DATA; - changed = 0; + changed = 0; - for (ibs.curfileblock=0; ibs.curfileblock= ibs.volblocks) { - setbadness(EXIT_RECOV); - warnx("Inode %lu: direct block pointer for " - "block %lu outside of volume: %lu " - "(cleared)\n", - (unsigned long)ibs.ino, - (unsigned long)ibs.curfileblock, - (unsigned long)datablock); - SET_D(sfi, ibs.curfileblock) = 0; - changed = 1; - } - else if (datablock > 0) { - if (ibs.curfileblock < ibs.fileblocks) { - freemap_blockinuse(datablock, ibs.usagetype, - ibs.ino); - } - else { - setbadness(EXIT_RECOV); - ibs.pasteofcount++; - changed = 1; - freemap_blockfree(datablock); - SET_D(sfi, ibs.curfileblock) = 0; - } - } - } + for (ibs.curfileblock = 0; ibs.curfileblock < NUM_D; ibs.curfileblock++) { + datablock = GET_D(sfi, ibs.curfileblock); + if (datablock >= ibs.volblocks) { + setbadness(EXIT_RECOV); + warnx("Inode %lu: direct block pointer for " + "block %lu outside of volume: %lu " + "(cleared)\n", + (unsigned long)ibs.ino, (unsigned long)ibs.curfileblock, + (unsigned long)datablock); + SET_D(sfi, ibs.curfileblock) = 0; + changed = 1; + } else if (datablock > 0) { + if (ibs.curfileblock < ibs.fileblocks) { + freemap_blockinuse(datablock, ibs.usagetype, ibs.ino); + } else { + setbadness(EXIT_RECOV); + ibs.pasteofcount++; + changed = 1; + freemap_blockfree(datablock); + SET_D(sfi, ibs.curfileblock) = 0; + } + } + } - for (i=0; i 0) { - warnx("Inode %lu: %u blocks after EOF (freed)", - (unsigned long) ibs.ino, ibs.pasteofcount); - setbadness(EXIT_RECOV); - } + if (ibs.pasteofcount > 0) { + warnx("Inode %lu: %u blocks after EOF (freed)", (unsigned long)ibs.ino, + ibs.pasteofcount); + setbadness(EXIT_RECOV); + } - return changed; + return changed; } /* @@ -255,99 +236,90 @@ check_inode_blocks(uint32_t ino, struct sfs_dinode *sfi, int isdir) * Returns nonzero if SFI has been modified and needs to be written * back. */ -static -int -pass1_inode(uint32_t ino, struct sfs_dinode *sfi, int alreadychanged) -{ - int changed = alreadychanged; - int isdir = sfi->sfi_type == SFS_TYPE_DIR; +static int pass1_inode(uint32_t ino, struct sfs_dinode *sfi, + int alreadychanged) { + int changed = alreadychanged; + int isdir = sfi->sfi_type == SFS_TYPE_DIR; - if (inode_add(ino, sfi->sfi_type)) { - /* Already been here. */ - assert(changed == 0); - return 1; - } + if (inode_add(ino, sfi->sfi_type)) { + /* Already been here. */ + assert(changed == 0); + return 1; + } - freemap_blockinuse(ino, B_INODE, ino); + freemap_blockinuse(ino, B_INODE, ino); - if (checkzeroed(sfi->sfi_waste, sizeof(sfi->sfi_waste))) { - warnx("Inode %lu: sfi_waste section not zeroed (fixed)", - (unsigned long) ino); - setbadness(EXIT_RECOV); - changed = 1; - } + if (checkzeroed(sfi->sfi_waste, sizeof(sfi->sfi_waste))) { + warnx("Inode %lu: sfi_waste section not zeroed (fixed)", + (unsigned long)ino); + setbadness(EXIT_RECOV); + changed = 1; + } - if (check_inode_blocks(ino, sfi, isdir)) { - changed = 1; - } + if (check_inode_blocks(ino, sfi, isdir)) { + changed = 1; + } - if (changed) { - sfs_writeinode(ino, sfi); - } - return 0; + if (changed) { + sfs_writeinode(ino, sfi); + } + return 0; } /* * Check the directory entry in SFD. INDEX is its offset, and PATH is * its name; these are used for printing messages. */ -static -int -pass1_direntry(const char *path, uint32_t index, struct sfs_direntry *sfd) -{ - int dchanged = 0; - uint32_t nblocks; +static int pass1_direntry(const char *path, uint32_t index, + struct sfs_direntry *sfd) { + int dchanged = 0; + uint32_t nblocks; - nblocks = sb_totalblocks(); + nblocks = sb_totalblocks(); - if (sfd->sfd_ino == SFS_NOINO) { - if (sfd->sfd_name[0] != 0) { - setbadness(EXIT_RECOV); - warnx("Directory %s entry %lu has name but no file", - path, (unsigned long) index); - sfd->sfd_name[0] = 0; - dchanged = 1; - } - } - else if (sfd->sfd_ino >= nblocks) { - setbadness(EXIT_RECOV); - warnx("Directory %s entry %lu has out of range " - "inode (cleared)", - path, (unsigned long) index); - sfd->sfd_ino = SFS_NOINO; - sfd->sfd_name[0] = 0; - dchanged = 1; - } - else { - if (sfd->sfd_name[0] == 0) { - /* XXX: what happens if FSCK.n.m already exists? */ - snprintf(sfd->sfd_name, sizeof(sfd->sfd_name), - "FSCK.%lu.%lu", - (unsigned long) sfd->sfd_ino, - (unsigned long) uniqueid()); - setbadness(EXIT_RECOV); - warnx("Directory %s entry %lu has file but " - "no name (fixed: %s)", - path, (unsigned long) index, - sfd->sfd_name); - dchanged = 1; - } - if (checknullstring(sfd->sfd_name, sizeof(sfd->sfd_name))) { - setbadness(EXIT_RECOV); - warnx("Directory %s entry %lu not " - "null-terminated (fixed)", - path, (unsigned long) index); - dchanged = 1; - } - if (checkbadstring(sfd->sfd_name)) { - setbadness(EXIT_RECOV); - warnx("Directory %s entry %lu contains invalid " - "characters (fixed)", - path, (unsigned long) index); - dchanged = 1; - } - } - return dchanged; + if (sfd->sfd_ino == SFS_NOINO) { + if (sfd->sfd_name[0] != 0) { + setbadness(EXIT_RECOV); + warnx("Directory %s entry %lu has name but no file", path, + (unsigned long)index); + sfd->sfd_name[0] = 0; + dchanged = 1; + } + } else if (sfd->sfd_ino >= nblocks) { + setbadness(EXIT_RECOV); + warnx("Directory %s entry %lu has out of range " + "inode (cleared)", + path, (unsigned long)index); + sfd->sfd_ino = SFS_NOINO; + sfd->sfd_name[0] = 0; + dchanged = 1; + } else { + if (sfd->sfd_name[0] == 0) { + /* XXX: what happens if FSCK.n.m already exists? */ + snprintf(sfd->sfd_name, sizeof(sfd->sfd_name), "FSCK.%lu.%lu", + (unsigned long)sfd->sfd_ino, (unsigned long)uniqueid()); + setbadness(EXIT_RECOV); + warnx("Directory %s entry %lu has file but " + "no name (fixed: %s)", + path, (unsigned long)index, sfd->sfd_name); + dchanged = 1; + } + if (checknullstring(sfd->sfd_name, sizeof(sfd->sfd_name))) { + setbadness(EXIT_RECOV); + warnx("Directory %s entry %lu not " + "null-terminated (fixed)", + path, (unsigned long)index); + dchanged = 1; + } + if (checkbadstring(sfd->sfd_name)) { + setbadness(EXIT_RECOV); + warnx("Directory %s entry %lu contains invalid " + "characters (fixed)", + path, (unsigned long)index); + dchanged = 1; + } + } + return dchanged; } /* @@ -355,142 +327,120 @@ pass1_direntry(const char *path, uint32_t index, struct sfs_direntry *sfd) * to this directory. This traverses the volume directory tree * recursively. */ -static -void -pass1_dir(uint32_t ino, const char *pathsofar) -{ - struct sfs_dinode sfi; - struct sfs_direntry *direntries; - uint32_t ndirentries, i; - int ichanged=0, dchanged=0; +static void pass1_dir(uint32_t ino, const char *pathsofar) { + struct sfs_dinode sfi; + struct sfs_direntry *direntries; + uint32_t ndirentries, i; + int ichanged = 0, dchanged = 0; - sfs_readinode(ino, &sfi); + sfs_readinode(ino, &sfi); - if (sfi.sfi_size % sizeof(struct sfs_direntry) != 0) { - setbadness(EXIT_RECOV); - warnx("Directory %s has illegal size %lu (fixed)", - pathsofar, (unsigned long) sfi.sfi_size); - sfi.sfi_size = SFS_ROUNDUP(sfi.sfi_size, - sizeof(struct sfs_direntry)); - ichanged = 1; - } - count_dirs++; + if (sfi.sfi_size % sizeof(struct sfs_direntry) != 0) { + setbadness(EXIT_RECOV); + warnx("Directory %s has illegal size %lu (fixed)", pathsofar, + (unsigned long)sfi.sfi_size); + sfi.sfi_size = SFS_ROUNDUP(sfi.sfi_size, sizeof(struct sfs_direntry)); + ichanged = 1; + } + count_dirs++; - if (pass1_inode(ino, &sfi, ichanged)) { - /* been here before; crosslinked dir, sort it out in pass 2 */ - return; - } + if (pass1_inode(ino, &sfi, ichanged)) { + /* been here before; crosslinked dir, sort it out in pass 2 */ + return; + } - ndirentries = sfi.sfi_size/sizeof(struct sfs_direntry); - direntries = domalloc(sfi.sfi_size); + ndirentries = sfi.sfi_size / sizeof(struct sfs_direntry); + direntries = domalloc(sfi.sfi_size); - sfs_readdir(&sfi, direntries, ndirentries); + sfs_readdir(&sfi, direntries, ndirentries); - for (i=0; isfd_ino == SFS_NOINO || d2->sfd_ino == SFS_NOINO) { - /* sfsdir_sort puts these last */ - continue; - } + if (d1->sfd_ino == SFS_NOINO || d2->sfd_ino == SFS_NOINO) { + /* sfsdir_sort puts these last */ + continue; + } - if (!strcmp(d1->sfd_name, d2->sfd_name)) { - if (d1->sfd_ino == d2->sfd_ino) { - setbadness(EXIT_RECOV); - warnx("Directory %s: Duplicate entries for " - "%s (merged)", - pathsofar, d1->sfd_name); - d1->sfd_ino = SFS_NOINO; - d1->sfd_name[0] = 0; - } - else { - /* XXX: what if FSCK.n.m already exists? */ - snprintf(d1->sfd_name, sizeof(d1->sfd_name), - "FSCK.%lu.%lu", - (unsigned long) d1->sfd_ino, - (unsigned long) uniqueid()); - setbadness(EXIT_RECOV); - warnx("Directory %s: Duplicate names %s " - "(one renamed: %s)", - pathsofar, d2->sfd_name, d1->sfd_name); - } - dchanged = 1; - } - } + if (!strcmp(d1->sfd_name, d2->sfd_name)) { + if (d1->sfd_ino == d2->sfd_ino) { + setbadness(EXIT_RECOV); + warnx("Directory %s: Duplicate entries for " + "%s (merged)", + pathsofar, d1->sfd_name); + d1->sfd_ino = SFS_NOINO; + d1->sfd_name[0] = 0; + } else { + /* XXX: what if FSCK.n.m already exists? */ + snprintf(d1->sfd_name, sizeof(d1->sfd_name), "FSCK.%lu.%lu", + (unsigned long)d1->sfd_ino, (unsigned long)uniqueid()); + setbadness(EXIT_RECOV); + warnx("Directory %s: Duplicate names %s " + "(one renamed: %s)", + pathsofar, d2->sfd_name, d1->sfd_name); + } + dchanged = 1; + } + } - /* - * Look for the . and .. entries. - */ + /* + * Look for the . and .. entries. + */ - for (i=0; i only one . here */ - assert(dotseen==0); - dotseen = 1; - } - else if (!strcmp(direntries[i].sfd_name, "..")) { - if (direntries[i].sfd_ino != parentino) { - setbadness(EXIT_RECOV); - warnx("Directory %s: Incorrect `..' entry " - "(fixed)", pathsofar); - direntries[i].sfd_ino = parentino; - dchanged = 1; - } - /* duplicates are checked above -> only one .. here */ - assert(dotdotseen==0); - dotdotseen = 1; - } - } + for (i = 0; i < ndirentries; i++) { + if (!strcmp(direntries[i].sfd_name, ".")) { + if (direntries[i].sfd_ino != ino) { + setbadness(EXIT_RECOV); + warnx("Directory %s: Incorrect `.' entry " + "(fixed)", + pathsofar); + direntries[i].sfd_ino = ino; + dchanged = 1; + } + /* duplicates are checked above -> only one . here */ + assert(dotseen == 0); + dotseen = 1; + } else if (!strcmp(direntries[i].sfd_name, "..")) { + if (direntries[i].sfd_ino != parentino) { + setbadness(EXIT_RECOV); + warnx("Directory %s: Incorrect `..' entry " + "(fixed)", + pathsofar); + direntries[i].sfd_ino = parentino; + dchanged = 1; + } + /* duplicates are checked above -> only one .. here */ + assert(dotdotseen == 0); + dotdotseen = 1; + } + } - /* - * If no . entry, try to insert one. - */ + /* + * If no . entry, try to insert one. + */ - if (!dotseen) { - if (sfsdir_tryadd(direntries, ndirentries, ".", ino)==0) { - setbadness(EXIT_RECOV); - warnx("Directory %s: No `.' entry (added)", - pathsofar); - dchanged = 1; - } - else if (sfsdir_tryadd(direntries, maxdirentries, ".", - ino)==0) { - setbadness(EXIT_RECOV); - warnx("Directory %s: No `.' entry (added)", - pathsofar); - ndirentries++; - dchanged = 1; - sfi.sfi_size += sizeof(struct sfs_direntry); - ichanged = 1; - } - else { - setbadness(EXIT_UNRECOV); - warnx("Directory %s: No `.' entry (NOT FIXED)", - pathsofar); - } - } + if (!dotseen) { + if (sfsdir_tryadd(direntries, ndirentries, ".", ino) == 0) { + setbadness(EXIT_RECOV); + warnx("Directory %s: No `.' entry (added)", pathsofar); + dchanged = 1; + } else if (sfsdir_tryadd(direntries, maxdirentries, ".", ino) == 0) { + setbadness(EXIT_RECOV); + warnx("Directory %s: No `.' entry (added)", pathsofar); + ndirentries++; + dchanged = 1; + sfi.sfi_size += sizeof(struct sfs_direntry); + ichanged = 1; + } else { + setbadness(EXIT_UNRECOV); + warnx("Directory %s: No `.' entry (NOT FIXED)", pathsofar); + } + } - /* - * If no .. entry, try to insert one. - */ + /* + * If no .. entry, try to insert one. + */ - if (!dotdotseen) { - if (sfsdir_tryadd(direntries, ndirentries, "..", - parentino)==0) { - setbadness(EXIT_RECOV); - warnx("Directory %s: No `..' entry (added)", - pathsofar); - dchanged = 1; - } - else if (sfsdir_tryadd(direntries, maxdirentries, "..", - parentino)==0) { - setbadness(EXIT_RECOV); - warnx("Directory %s: No `..' entry (added)", - pathsofar); - ndirentries++; - dchanged = 1; - sfi.sfi_size += sizeof(struct sfs_direntry); - ichanged = 1; - } - else { - setbadness(EXIT_UNRECOV); - warnx("Directory %s: No `..' entry (NOT FIXED)", - pathsofar); - } - } + if (!dotdotseen) { + if (sfsdir_tryadd(direntries, ndirentries, "..", parentino) == 0) { + setbadness(EXIT_RECOV); + warnx("Directory %s: No `..' entry (added)", pathsofar); + dchanged = 1; + } else if (sfsdir_tryadd(direntries, maxdirentries, "..", parentino) == 0) { + setbadness(EXIT_RECOV); + warnx("Directory %s: No `..' entry (added)", pathsofar); + ndirentries++; + dchanged = 1; + sfi.sfi_size += sizeof(struct sfs_direntry); + ichanged = 1; + } else { + setbadness(EXIT_UNRECOV); + warnx("Directory %s: No `..' entry (NOT FIXED)", pathsofar); + } + } - /* - * Now load each inode in the directory. - * - * For regular files, count the number of links we see; for - * directories, recurse. Count the number of subdirs seen - * so we can correct our own link count if necessary. - */ + /* + * Now load each inode in the directory. + * + * For regular files, count the number of links we see; for + * directories, recurse. Count the number of subdirs seen + * so we can correct our own link count if necessary. + */ - subdircount=0; - for (i=0; i /* for CHAR_BIT */ -#include /* also for CHAR_BIT */ +#include /* for CHAR_BIT */ +#include /* also for CHAR_BIT */ #include #include #include @@ -47,78 +47,62 @@ static struct sfs_superblock sb; /* * Load the superblock. */ -void -sb_load(void) -{ - sfs_readsb(SFS_SUPER_BLOCK, &sb); - if (sb.sb_magic != SFS_MAGIC) { - errx(EXIT_FATAL, "Not an sfs filesystem"); - } +void sb_load(void) { + sfs_readsb(SFS_SUPER_BLOCK, &sb); + if (sb.sb_magic != SFS_MAGIC) { + errx(EXIT_FATAL, "Not an sfs filesystem"); + } - assert(sb.sb_nblocks > 0); - assert(SFS_FREEMAPBLOCKS(sb.sb_nblocks) > 0); + assert(sb.sb_nblocks > 0); + assert(SFS_FREEMAPBLOCKS(sb.sb_nblocks) > 0); } /* * Validate the superblock. */ -void -sb_check(void) -{ - int schanged=0; +void sb_check(void) { + int schanged = 0; - /* - * FUTURE: should we check sb.sb_nblocks against diskblocks()? - */ + /* + * FUTURE: should we check sb.sb_nblocks against diskblocks()? + */ - /* Check the superblock fields */ + /* Check the superblock fields */ - if (checknullstring(sb.sb_volname, sizeof(sb.sb_volname))) { - warnx("Volume name not null-terminated (fixed)"); - setbadness(EXIT_RECOV); - schanged = 1; - } - if (checkbadstring(sb.sb_volname)) { - warnx("Volume name contains illegal characters (fixed)"); - setbadness(EXIT_RECOV); - schanged = 1; - } - if (checkzeroed(sb.reserved, sizeof(sb.reserved))) { - warnx("Reserved section of superblock not zeroed (fixed)"); - setbadness(EXIT_RECOV); - schanged = 1; - } + if (checknullstring(sb.sb_volname, sizeof(sb.sb_volname))) { + warnx("Volume name not null-terminated (fixed)"); + setbadness(EXIT_RECOV); + schanged = 1; + } + if (checkbadstring(sb.sb_volname)) { + warnx("Volume name contains illegal characters (fixed)"); + setbadness(EXIT_RECOV); + schanged = 1; + } + if (checkzeroed(sb.reserved, sizeof(sb.reserved))) { + warnx("Reserved section of superblock not zeroed (fixed)"); + setbadness(EXIT_RECOV); + schanged = 1; + } - /* Write the superblock back if necessary */ - if (schanged) { - sfs_writesb(SFS_SUPER_BLOCK, &sb); - } + /* Write the superblock back if necessary */ + if (schanged) { + sfs_writesb(SFS_SUPER_BLOCK, &sb); + } } /* * Return the total number of blocks in the volume. */ -uint32_t -sb_totalblocks(void) -{ - return sb.sb_nblocks; -} +uint32_t sb_totalblocks(void) { return sb.sb_nblocks; } /* * Return the number of freemap blocks. * (this function probably ought to go away) */ -uint32_t -sb_freemapblocks(void) -{ - return SFS_FREEMAPBLOCKS(sb.sb_nblocks); -} +uint32_t sb_freemapblocks(void) { return SFS_FREEMAPBLOCKS(sb.sb_nblocks); } /* * Return the volume name. */ -const char * -sb_volname(void) -{ - return sb.sb_volname; -} +const char *sb_volname(void) { return sb.sb_volname; } diff --git a/userland/sbin/sfsck/sfs.c b/userland/sbin/sfsck/sfs.c index a2469ff..b657cc2 100644 --- a/userland/sbin/sfsck/sfs.c +++ b/userland/sbin/sfsck/sfs.c @@ -45,75 +45,58 @@ //////////////////////////////////////////////////////////// // global setup -void -sfs_setup(void) -{ - assert(sizeof(struct sfs_superblock)==SFS_BLOCKSIZE); - assert(sizeof(struct sfs_dinode)==SFS_BLOCKSIZE); - assert(SFS_BLOCKSIZE % sizeof(struct sfs_direntry) == 0); +void sfs_setup(void) { + assert(sizeof(struct sfs_superblock) == SFS_BLOCKSIZE); + assert(sizeof(struct sfs_dinode) == SFS_BLOCKSIZE); + assert(SFS_BLOCKSIZE % sizeof(struct sfs_direntry) == 0); } //////////////////////////////////////////////////////////// // byte-swap functions -static -void -swapsb(struct sfs_superblock *sb) -{ - sb->sb_magic = SWAP32(sb->sb_magic); - sb->sb_nblocks = SWAP32(sb->sb_nblocks); +static void swapsb(struct sfs_superblock *sb) { + sb->sb_magic = SWAP32(sb->sb_magic); + sb->sb_nblocks = SWAP32(sb->sb_nblocks); } -static -void -swapbits(uint8_t *bits) -{ - /* nothing to do */ - (void)bits; +static void swapbits(uint8_t *bits) { + /* nothing to do */ + (void)bits; } -static -void -swapinode(struct sfs_dinode *sfi) -{ - int i; +static void swapinode(struct sfs_dinode *sfi) { + int i; - sfi->sfi_size = SWAP32(sfi->sfi_size); - sfi->sfi_type = SWAP16(sfi->sfi_type); - sfi->sfi_linkcount = SWAP16(sfi->sfi_linkcount); + sfi->sfi_size = SWAP32(sfi->sfi_size); + sfi->sfi_type = SWAP16(sfi->sfi_type); + sfi->sfi_linkcount = SWAP16(sfi->sfi_linkcount); - for (i=0; isfd_ino = SWAP32(sfd->sfd_ino); +static void swapdir(struct sfs_direntry *sfd) { + sfd->sfd_ino = SWAP32(sfd->sfd_ino); } -static -void -swapindir(uint32_t *entries) -{ - int i; - for (i=0; i 1) { - uint32_t index = offset / entrysize; - offset %= entrysize; - return ibmap(entries[index], offset, entrysize/SFS_DBPERIDB); - } - else { - assert(offset < SFS_DBPERIDB); - return entries[offset]; - } + if (entrysize > 1) { + uint32_t index = offset / entrysize; + offset %= entrysize; + return ibmap(entries[index], offset, entrysize / SFS_DBPERIDB); + } else { + assert(offset < SFS_DBPERIDB); + return entries[offset]; + } } /* @@ -157,31 +136,25 @@ ibmap(uint32_t iblock, uint32_t offset, uint32_t entrysize) * * Given an inode and a file block, returns a disk block. */ -static -uint32_t -bmap(const struct sfs_dinode *sfi, uint32_t fileblock) -{ - uint32_t iblock, offset; +static uint32_t bmap(const struct sfs_dinode *sfi, uint32_t fileblock) { + uint32_t iblock, offset; - if (fileblock < INOMAX_D) { - return GET_D(sfi, fileblock); - } - else if (fileblock < INOMAX_I) { - iblock = (fileblock - INOMAX_D) / RANGE_I; - offset = (fileblock - INOMAX_D) % RANGE_I; - return ibmap(GET_I(sfi, iblock), offset, RANGE_D); - } - else if (fileblock < INOMAX_II) { - iblock = (fileblock - INOMAX_I) / RANGE_II; - offset = (fileblock - INOMAX_I) % RANGE_II; - return ibmap(GET_II(sfi, iblock), offset, RANGE_I); - } - else if (fileblock < INOMAX_III) { - iblock = (fileblock - INOMAX_II) / RANGE_III; - offset = (fileblock - INOMAX_II) % RANGE_III; - return ibmap(GET_III(sfi, iblock), offset, RANGE_II); - } - return 0; + if (fileblock < INOMAX_D) { + return GET_D(sfi, fileblock); + } else if (fileblock < INOMAX_I) { + iblock = (fileblock - INOMAX_D) / RANGE_I; + offset = (fileblock - INOMAX_D) % RANGE_I; + return ibmap(GET_I(sfi, iblock), offset, RANGE_D); + } else if (fileblock < INOMAX_II) { + iblock = (fileblock - INOMAX_I) / RANGE_II; + offset = (fileblock - INOMAX_I) % RANGE_II; + return ibmap(GET_II(sfi, iblock), offset, RANGE_I); + } else if (fileblock < INOMAX_III) { + iblock = (fileblock - INOMAX_II) / RANGE_III; + offset = (fileblock - INOMAX_II) % RANGE_III; + return ibmap(GET_III(sfi, iblock), offset, RANGE_II); + } + return 0; } //////////////////////////////////////////////////////////// @@ -191,19 +164,15 @@ bmap(const struct sfs_dinode *sfi, uint32_t fileblock) * superblock - blocknum is a disk block number. */ -void -sfs_readsb(uint32_t blocknum, struct sfs_superblock *sb) -{ - diskread(sb, blocknum); - swapsb(sb); +void sfs_readsb(uint32_t blocknum, struct sfs_superblock *sb) { + diskread(sb, blocknum); + swapsb(sb); } -void -sfs_writesb(uint32_t blocknum, struct sfs_superblock *sb) -{ - swapsb(sb); - diskwrite(sb, blocknum); - swapsb(sb); +void sfs_writesb(uint32_t blocknum, struct sfs_superblock *sb) { + swapsb(sb); + diskwrite(sb, blocknum); + swapsb(sb); } /* @@ -211,57 +180,45 @@ sfs_writesb(uint32_t blocknum, struct sfs_superblock *sb) * bitmap. */ -void -sfs_readfreemapblock(uint32_t whichblock, uint8_t *bits) -{ - diskread(bits, SFS_FREEMAP_START + whichblock); - swapbits(bits); +void sfs_readfreemapblock(uint32_t whichblock, uint8_t *bits) { + diskread(bits, SFS_FREEMAP_START + whichblock); + swapbits(bits); } -void -sfs_writefreemapblock(uint32_t whichblock, uint8_t *bits) -{ - swapbits(bits); - diskwrite(bits, SFS_FREEMAP_START + whichblock); - swapbits(bits); +void sfs_writefreemapblock(uint32_t whichblock, uint8_t *bits) { + swapbits(bits); + diskwrite(bits, SFS_FREEMAP_START + whichblock); + swapbits(bits); } /* * inodes - ino is an inode number, which is a disk block number. */ -void -sfs_readinode(uint32_t ino, struct sfs_dinode *sfi) -{ - diskread(sfi, ino); - swapinode(sfi); +void sfs_readinode(uint32_t ino, struct sfs_dinode *sfi) { + diskread(sfi, ino); + swapinode(sfi); } -void -sfs_writeinode(uint32_t ino, struct sfs_dinode *sfi) -{ - swapinode(sfi); - diskwrite(sfi, ino); - swapinode(sfi); +void sfs_writeinode(uint32_t ino, struct sfs_dinode *sfi) { + swapinode(sfi); + diskwrite(sfi, ino); + swapinode(sfi); } /* * indirect blocks - blocknum is a disk block number. */ -void -sfs_readindirect(uint32_t blocknum, uint32_t *entries) -{ - diskread(entries, blocknum); - swapindir(entries); +void sfs_readindirect(uint32_t blocknum, uint32_t *entries) { + diskread(entries, blocknum); + swapindir(entries); } -void -sfs_writeindirect(uint32_t blocknum, uint32_t *entries) -{ - swapindir(entries); - diskwrite(entries, blocknum); - swapindir(entries); +void sfs_writeindirect(uint32_t blocknum, uint32_t *entries) { + swapindir(entries); + diskwrite(entries, blocknum); + swapindir(entries); } //////////////////////////////////////////////////////////// @@ -270,23 +227,19 @@ sfs_writeindirect(uint32_t blocknum, uint32_t *entries) /* * Read the directory block at DISKBLOCK into D. */ -static -void -sfs_readdirblock(struct sfs_direntry *d, uint32_t diskblock) -{ - const unsigned atonce = SFS_BLOCKSIZE/sizeof(struct sfs_direntry); - unsigned j; +static void sfs_readdirblock(struct sfs_direntry *d, uint32_t diskblock) { + const unsigned atonce = SFS_BLOCKSIZE / sizeof(struct sfs_direntry); + unsigned j; - if (diskblock != 0) { - diskread(d, diskblock); - for (j=0; jsfd_ino == SFS_NOINO && bd->sfd_ino == SFS_NOINO) { - return 0; - } - if (ad->sfd_ino == SFS_NOINO) { - return 1; - } - if (bd->sfd_ino == SFS_NOINO) { - return -1; - } + /* Sort unallocated entries last */ + if (ad->sfd_ino == SFS_NOINO && bd->sfd_ino == SFS_NOINO) { + return 0; + } + if (ad->sfd_ino == SFS_NOINO) { + return 1; + } + if (bd->sfd_ino == SFS_NOINO) { + return -1; + } - return strcmp(ad->sfd_name, bd->sfd_name); + return strcmp(ad->sfd_name, bd->sfd_name); } /* @@ -429,17 +369,15 @@ dirsortfunc(const void *aa, const void *bb) * permutation vector into VECTOR, which should be allocated to hold * ND ints. */ -void -sfsdir_sort(struct sfs_direntry *d, unsigned nd, int *vector) -{ - unsigned i; +void sfsdir_sort(struct sfs_direntry *d, unsigned nd, int *vector) { + unsigned i; - for (i=0; i /* for size_t */ -#include /* for uint32_t */ +#include /* for size_t */ +#include /* for uint32_t */ /* non-failing wrapper around malloc */ void *domalloc(size_t len); diff --git a/userland/testbin/add/add.c b/userland/testbin/add/add.c index 856e4ec..3e584cb 100644 --- a/userland/testbin/add/add.c +++ b/userland/testbin/add/add.c @@ -39,19 +39,17 @@ #include #include -int -main(int argc, char *argv[]) -{ - int i, j; +int main(int argc, char *argv[]) { + int i, j; - if (argc != 3) { - errx(1, "Usage: add num1 num2"); - } + if (argc != 3) { + errx(1, "Usage: add num1 num2"); + } - i = atoi(argv[1]); - j = atoi(argv[2]); + i = atoi(argv[1]); + j = atoi(argv[2]); - printf("Answer: %d\n", i+j); + printf("Answer: %d\n", i + j); - return 0; + return 0; } diff --git a/userland/testbin/argtest/argtest.c b/userland/testbin/argtest/argtest.c index 7ed552e..54c8ec1 100644 --- a/userland/testbin/argtest/argtest.c +++ b/userland/testbin/argtest/argtest.c @@ -37,21 +37,19 @@ #include -int -main(int argc, char *argv[]) -{ - const char *tmp; - int i; +int main(int argc, char *argv[]) { + const char *tmp; + int i; - printf("argc: %d\n", argc); + printf("argc: %d\n", argc); - for (i=0; i<=argc; i++) { - tmp = argv[i]; - if (tmp==NULL) { - tmp = "[NULL]"; - } - printf("argv[%d]: %s\n", i, tmp); - } + for (i = 0; i <= argc; i++) { + tmp = argv[i]; + if (tmp == NULL) { + tmp = "[NULL]"; + } + printf("argv[%d]: %s\n", i, tmp); + } - return 0; + return 0; } diff --git a/userland/testbin/badcall/bad_chdir.c b/userland/testbin/badcall/bad_chdir.c index cf98845..da411fc 100644 --- a/userland/testbin/badcall/bad_chdir.c +++ b/userland/testbin/badcall/bad_chdir.c @@ -37,25 +37,19 @@ #include "test.h" -static -void -chdir_empty(void) -{ - int rv; +static void chdir_empty(void) { + int rv; - /* - * This is actually valid by some interpretations. - */ + /* + * This is actually valid by some interpretations. + */ - report_begin("chdir to empty string"); - rv = chdir(""); - report_check2(rv, errno, EINVAL, 0); + report_begin("chdir to empty string"); + rv = chdir(""); + report_check2(rv, errno, EINVAL, 0); } -void -test_chdir(void) -{ - test_chdir_path(); - chdir_empty(); +void test_chdir(void) { + test_chdir_path(); + chdir_empty(); } - diff --git a/userland/testbin/badcall/bad_close.c b/userland/testbin/badcall/bad_close.c index 6d70e66..75a0905 100644 --- a/userland/testbin/badcall/bad_close.c +++ b/userland/testbin/badcall/bad_close.c @@ -33,8 +33,4 @@ #include "test.h" -void -test_close(void) -{ - test_close_fd(); -} +void test_close(void) { test_close_fd(); } diff --git a/userland/testbin/badcall/bad_dup2.c b/userland/testbin/badcall/bad_dup2.c index db3a216..20bd793 100644 --- a/userland/testbin/badcall/bad_dup2.c +++ b/userland/testbin/badcall/bad_dup2.c @@ -44,99 +44,86 @@ #include "config.h" #include "test.h" -static -void -dup2_fd2(int fd, const char *desc) -{ - int rv; +static void dup2_fd2(int fd, const char *desc) { + int rv; - report_begin("%s", desc); - rv = dup2(STDIN_FILENO, fd); - report_check(rv, errno, EBADF); + report_begin("%s", desc); + rv = dup2(STDIN_FILENO, fd); + report_check(rv, errno, EBADF); - if (rv != -1) { - close(fd); /* just in case */ - } + if (rv != -1) { + close(fd); /* just in case */ + } } -static -void -dup2_self(void) -{ - struct stat sb; - int rv; - int testfd; +static void dup2_self(void) { + struct stat sb; + int rv; + int testfd; - /* use fd that isn't in use */ - testfd = CLOSED_FD; + /* use fd that isn't in use */ + testfd = CLOSED_FD; - report_begin("copying stdin to test with"); + report_begin("copying stdin to test with"); - rv = dup2(STDIN_FILENO, testfd); - if (rv == -1) { - report_result(rv, errno); - report_aborted(); - return; - } + rv = dup2(STDIN_FILENO, testfd); + if (rv == -1) { + report_result(rv, errno); + report_aborted(); + return; + } - report_begin("dup2 to same fd"); - rv = dup2(testfd, testfd); - if (rv == testfd) { - report_passed(); - } - else if (rv<0) { - report_result(rv, errno); - report_failure(); - } - else { - report_warnx("returned %d instead", rv); - report_failure(); - } + report_begin("dup2 to same fd"); + rv = dup2(testfd, testfd); + if (rv == testfd) { + report_passed(); + } else if (rv < 0) { + report_result(rv, errno); + report_failure(); + } else { + report_warnx("returned %d instead", rv); + report_failure(); + } - report_begin("fstat fd after dup2 to itself"); - rv = fstat(testfd, &sb); - if (errno == ENOSYS) { - report_saw_enosys(); - } - report_result(rv, errno); - if (rv==0) { - report_passed(); - } - else if (errno != ENOSYS) { - report_failure(); - } - else { - report_skipped(); - /* no support for fstat; try lseek */ - report_begin("lseek fd after dup2 to itself"); - rv = lseek(testfd, 0, SEEK_CUR); - report_result(rv, errno); - if (rv==0 || (rv==-1 && errno==ESPIPE)) { - report_passed(); - } - else { - report_failure(); - } - } + report_begin("fstat fd after dup2 to itself"); + rv = fstat(testfd, &sb); + if (errno == ENOSYS) { + report_saw_enosys(); + } + report_result(rv, errno); + if (rv == 0) { + report_passed(); + } else if (errno != ENOSYS) { + report_failure(); + } else { + report_skipped(); + /* no support for fstat; try lseek */ + report_begin("lseek fd after dup2 to itself"); + rv = lseek(testfd, 0, SEEK_CUR); + report_result(rv, errno); + if (rv == 0 || (rv == -1 && errno == ESPIPE)) { + report_passed(); + } else { + report_failure(); + } + } - close(testfd); + close(testfd); } -void -test_dup2(void) -{ - /* This does the first fd. */ - test_dup2_fd(); +void test_dup2(void) { + /* This does the first fd. */ + test_dup2_fd(); - /* Any interesting cases added here should also go in common_fds.c */ - dup2_fd2(-1, "dup2 to -1"); - dup2_fd2(-5, "dup2 to -5"); - dup2_fd2(IMPOSSIBLE_FD, "dup2 to impossible fd"); + /* Any interesting cases added here should also go in common_fds.c */ + dup2_fd2(-1, "dup2 to -1"); + dup2_fd2(-5, "dup2 to -5"); + dup2_fd2(IMPOSSIBLE_FD, "dup2 to impossible fd"); #ifdef OPEN_MAX - dup2_fd2(OPEN_MAX, "dup2 to OPEN_MAX"); + dup2_fd2(OPEN_MAX, "dup2 to OPEN_MAX"); #else - warnx("Warning: OPEN_MAX not defined - test skipped"); + warnx("Warning: OPEN_MAX not defined - test skipped"); #endif - dup2_self(); + dup2_self(); } diff --git a/userland/testbin/badcall/bad_execv.c b/userland/testbin/badcall/bad_execv.c index 24ad1cb..f42b4c7 100644 --- a/userland/testbin/badcall/bad_execv.c +++ b/userland/testbin/badcall/bad_execv.c @@ -40,142 +40,124 @@ #include "config.h" #include "test.h" -static -int -exec_common_fork(void) -{ - int pid, rv, status, err; +static int exec_common_fork(void) { + int pid, rv, status, err; - /* - * This does not happen in a test context (from the point of - * view of report.c) so we have to fiddle a bit. - */ + /* + * This does not happen in a test context (from the point of + * view of report.c) so we have to fiddle a bit. + */ - pid = fork(); - if (pid<0) { - err = errno; - report_begin("forking for test"); - report_result(pid, err); - report_aborted(); - return -1; - } + pid = fork(); + if (pid < 0) { + err = errno; + report_begin("forking for test"); + report_result(pid, err); + report_aborted(); + return -1; + } - if (pid==0) { - /* child */ - return 0; - } + if (pid == 0) { + /* child */ + return 0; + } - rv = waitpid(pid, &status, 0); - if (rv == -1) { - err = errno; - report_begin("waiting for test subprocess"); - report_result(rv, err); - report_failure(); - return -1; - } - if (WIFEXITED(status) && WEXITSTATUS(status) == MAGIC_STATUS) { - return 1; - } - /* Oops... */ - report_begin("exit code of subprocess; should be %d", MAGIC_STATUS); - if (WIFSIGNALED(status)) { - report_warnx("signal %d", WTERMSIG(status)); - } - else { - report_warnx("exit %d", WEXITSTATUS(status)); - } - report_failure(); - return -1; + rv = waitpid(pid, &status, 0); + if (rv == -1) { + err = errno; + report_begin("waiting for test subprocess"); + report_result(rv, err); + report_failure(); + return -1; + } + if (WIFEXITED(status) && WEXITSTATUS(status) == MAGIC_STATUS) { + return 1; + } + /* Oops... */ + report_begin("exit code of subprocess; should be %d", MAGIC_STATUS); + if (WIFSIGNALED(status)) { + report_warnx("signal %d", WTERMSIG(status)); + } else { + report_warnx("exit %d", WEXITSTATUS(status)); + } + report_failure(); + return -1; } -static -void -exec_badprog(const void *prog, const char *desc) -{ - int rv; - char *args[2]; - args[0] = (char *)"foo"; - args[1] = NULL; +static void exec_badprog(const void *prog, const char *desc) { + int rv; + char *args[2]; + args[0] = (char *)"foo"; + args[1] = NULL; - if (exec_common_fork() != 0) { - return; - } + if (exec_common_fork() != 0) { + return; + } - report_begin(desc); - rv = execv(prog, args); - report_check(rv, errno, EFAULT); - exit(MAGIC_STATUS); + report_begin(desc); + rv = execv(prog, args); + report_check(rv, errno, EFAULT); + exit(MAGIC_STATUS); } -static -void -exec_emptyprog(void) -{ - int rv; - char *args[2]; - args[0] = (char *)"foo"; - args[1] = NULL; +static void exec_emptyprog(void) { + int rv; + char *args[2]; + args[0] = (char *)"foo"; + args[1] = NULL; - if (exec_common_fork() != 0) { - return; - } + if (exec_common_fork() != 0) { + return; + } - report_begin("exec the empty string"); - rv = execv("", args); - report_check2(rv, errno, EINVAL, EISDIR); - exit(MAGIC_STATUS); + report_begin("exec the empty string"); + rv = execv("", args); + report_check2(rv, errno, EINVAL, EISDIR); + exit(MAGIC_STATUS); } -static -void -exec_badargs(void *args, const char *desc) -{ - int rv; +static void exec_badargs(void *args, const char *desc) { + int rv; - if (exec_common_fork() != 0) { - return; - } + if (exec_common_fork() != 0) { + return; + } - report_begin(desc); - rv = execv("/bin/true", args); - report_check(rv, errno, EFAULT); - exit(MAGIC_STATUS); + report_begin(desc); + rv = execv("/bin/true", args); + report_check(rv, errno, EFAULT); + exit(MAGIC_STATUS); } -static -void -exec_onearg(void *ptr, const char *desc) -{ - int rv; +static void exec_onearg(void *ptr, const char *desc) { + int rv; - char *args[3]; - args[0] = (char *)"foo"; - args[1] = (char *)ptr; - args[2] = NULL; + char *args[3]; + args[0] = (char *)"foo"; + args[1] = (char *)ptr; + args[2] = NULL; - if (exec_common_fork() != 0) { - return; - } + if (exec_common_fork() != 0) { + return; + } - report_begin(desc); - rv = execv("/bin/true", args); - report_check(rv, errno, EFAULT); - exit(MAGIC_STATUS); + report_begin(desc); + rv = execv("/bin/true", args); + report_check(rv, errno, EFAULT); + exit(MAGIC_STATUS); } -void -test_execv(void) -{ - exec_badprog(NULL, "exec with NULL program"); - exec_badprog(INVAL_PTR, "exec with invalid pointer program"); - exec_badprog(KERN_PTR, "exec with kernel pointer program"); +void test_execv(void) { + exec_badprog(NULL, "exec with NULL program"); + exec_badprog(INVAL_PTR, "exec with invalid pointer program"); + exec_badprog(KERN_PTR, "exec with kernel pointer program"); - exec_emptyprog(); + exec_emptyprog(); - exec_badargs(NULL, "exec with NULL arglist"); - exec_badargs(INVAL_PTR, "exec with invalid pointer arglist"); - exec_badargs(KERN_PTR, "exec with kernel pointer arglist"); + exec_badargs(NULL, "exec with NULL arglist"); + exec_badargs(INVAL_PTR, "exec with invalid pointer arglist"); + exec_badargs(KERN_PTR, "exec with kernel pointer arglist"); - exec_onearg(INVAL_PTR, "exec with invalid pointer arg"); - exec_onearg(KERN_PTR, "exec with kernel pointer arg"); + exec_onearg(INVAL_PTR, "exec with invalid pointer arg"); + exec_onearg(KERN_PTR, "exec with kernel pointer arg"); } diff --git a/userland/testbin/badcall/bad_fsync.c b/userland/testbin/badcall/bad_fsync.c index fd67384..f926a5e 100644 --- a/userland/testbin/badcall/bad_fsync.c +++ b/userland/testbin/badcall/bad_fsync.c @@ -33,9 +33,4 @@ #include "test.h" -void -test_fsync(void) -{ - test_fsync_fd(); -} - +void test_fsync(void) { test_fsync_fd(); } diff --git a/userland/testbin/badcall/bad_ftruncate.c b/userland/testbin/badcall/bad_ftruncate.c index f88d7c8..79bd9eb 100644 --- a/userland/testbin/badcall/bad_ftruncate.c +++ b/userland/testbin/badcall/bad_ftruncate.c @@ -43,53 +43,45 @@ #include "config.h" #include "test.h" -static -void -ftruncate_fd_device(void) -{ - int rv, fd; +static void ftruncate_fd_device(void) { + int rv, fd; - report_begin("ftruncate on device"); + report_begin("ftruncate on device"); - fd = open("null:", O_RDWR); - if (fd<0) { - report_warn("opening null: failed"); - report_aborted(); - return; - } + fd = open("null:", O_RDWR); + if (fd < 0) { + report_warn("opening null: failed"); + report_aborted(); + return; + } - rv = ftruncate(fd, 6); - report_check(rv, errno, EINVAL); + rv = ftruncate(fd, 6); + report_check(rv, errno, EINVAL); - close(fd); + close(fd); } -static -void -ftruncate_size_neg(void) -{ - int rv, fd; +static void ftruncate_size_neg(void) { + int rv, fd; - report_begin("ftruncate to negative size"); + report_begin("ftruncate to negative size"); - fd = open_testfile(NULL); - if (fd<0) { - report_aborted(); - return; - } + fd = open_testfile(NULL); + if (fd < 0) { + report_aborted(); + return; + } - rv = ftruncate(fd, -60); - report_check(rv, errno, EINVAL); + rv = ftruncate(fd, -60); + report_check(rv, errno, EINVAL); - close(fd); - remove(TESTFILE); + close(fd); + remove(TESTFILE); } -void -test_ftruncate(void) -{ - test_ftruncate_fd(); +void test_ftruncate(void) { + test_ftruncate_fd(); - ftruncate_fd_device(); - ftruncate_size_neg(); + ftruncate_fd_device(); + ftruncate_size_neg(); } diff --git a/userland/testbin/badcall/bad_getcwd.c b/userland/testbin/badcall/bad_getcwd.c index 4f94ba1..cc0de4f 100644 --- a/userland/testbin/badcall/bad_getcwd.c +++ b/userland/testbin/badcall/bad_getcwd.c @@ -33,8 +33,4 @@ #include "test.h" -void -test_getcwd(void) -{ - test_getcwd_buf(); -} +void test_getcwd(void) { test_getcwd_buf(); } diff --git a/userland/testbin/badcall/bad_getdirentry.c b/userland/testbin/badcall/bad_getdirentry.c index 02806d2..392c9f8 100644 --- a/userland/testbin/badcall/bad_getdirentry.c +++ b/userland/testbin/badcall/bad_getdirentry.c @@ -33,9 +33,7 @@ #include "test.h" -void -test_getdirentry(void) -{ - test_getdirentry_fd(); - test_getdirentry_buf(); +void test_getdirentry(void) { + test_getdirentry_fd(); + test_getdirentry_buf(); } diff --git a/userland/testbin/badcall/bad_ioctl.c b/userland/testbin/badcall/bad_ioctl.c index 8ce38bc..08f5399 100644 --- a/userland/testbin/badcall/bad_ioctl.c +++ b/userland/testbin/badcall/bad_ioctl.c @@ -40,64 +40,49 @@ #include "config.h" #include "test.h" -static -void -one_ioctl_badbuf(int fd, int code, const char *codename, - void *ptr, const char *ptrdesc) -{ - int rv; +static void one_ioctl_badbuf(int fd, int code, const char *codename, void *ptr, + const char *ptrdesc) { + int rv; - report_begin("ioctl %s with %s", codename, ptrdesc); - rv = ioctl(fd, code, ptr); - report_check(rv, errno, EFAULT); + report_begin("ioctl %s with %s", codename, ptrdesc); + rv = ioctl(fd, code, ptr); + report_check(rv, errno, EFAULT); } -static -void -any_ioctl_badbuf(int fd, int code, const char *codename) -{ - one_ioctl_badbuf(fd, code, codename, NULL, "NULL pointer"); - one_ioctl_badbuf(fd, code, codename, INVAL_PTR, "invalid pointer"); - one_ioctl_badbuf(fd, code, codename, KERN_PTR, "kernel pointer"); +static void any_ioctl_badbuf(int fd, int code, const char *codename) { + one_ioctl_badbuf(fd, code, codename, NULL, "NULL pointer"); + one_ioctl_badbuf(fd, code, codename, INVAL_PTR, "invalid pointer"); + one_ioctl_badbuf(fd, code, codename, KERN_PTR, "kernel pointer"); } #define IOCTL(fd, sym) any_ioctl_badbuf(fd, sym, #sym) -static -void -ioctl_badbuf(void) -{ - /* - * Since we don't actually define any ioctls, this code won't - * actually run. But if you do define ioctls, turn these tests - * on for those that actually use the data buffer argument for - * anything. - */ +static void ioctl_badbuf(void) { + /* + * Since we don't actually define any ioctls, this code won't + * actually run. But if you do define ioctls, turn these tests + * on for those that actually use the data buffer argument for + * anything. + */ - /* IOCTL(STDIN_FILENO, TIOCGETA); */ + /* IOCTL(STDIN_FILENO, TIOCGETA); */ - - /* suppress gcc warning */ - (void)any_ioctl_badbuf; + /* suppress gcc warning */ + (void)any_ioctl_badbuf; } -static -void -ioctl_badcode(void) -{ - int rv; +static void ioctl_badcode(void) { + int rv; - report_begin("invalid ioctl"); - rv = ioctl(STDIN_FILENO, NONEXIST_IOCTL, NULL); - report_check(rv, errno, EIOCTL); + report_begin("invalid ioctl"); + rv = ioctl(STDIN_FILENO, NONEXIST_IOCTL, NULL); + report_check(rv, errno, EIOCTL); } -void -test_ioctl(void) -{ - test_ioctl_fd(); +void test_ioctl(void) { + test_ioctl_fd(); - /* Since we don't actually define any ioctls, this is not meaningful */ - ioctl_badcode(); - ioctl_badbuf(); + /* Since we don't actually define any ioctls, this is not meaningful */ + ioctl_badcode(); + ioctl_badbuf(); } diff --git a/userland/testbin/badcall/bad_link.c b/userland/testbin/badcall/bad_link.c index 63ecc15..075d4f9 100644 --- a/userland/testbin/badcall/bad_link.c +++ b/userland/testbin/badcall/bad_link.c @@ -36,53 +36,42 @@ #include "test.h" -static -void -link_dir(void) -{ - int rv; +static void link_dir(void) { + int rv; - report_begin("hard link of ."); - rv = link(".", TESTDIR); - report_check(rv, errno, EINVAL); - if (rv==0) { - /* this might help recover... maybe */ - remove(TESTDIR); - } + report_begin("hard link of ."); + rv = link(".", TESTDIR); + report_check(rv, errno, EINVAL); + if (rv == 0) { + /* this might help recover... maybe */ + remove(TESTDIR); + } } -static -void -link_empty1(void) -{ - int rv; +static void link_empty1(void) { + int rv; - report_begin("hard link of empty string"); - rv = link("", TESTDIR); - report_check(rv, errno, EINVAL); + report_begin("hard link of empty string"); + rv = link("", TESTDIR); + report_check(rv, errno, EINVAL); } -static -void -link_empty2(void) -{ - int rv; +static void link_empty2(void) { + int rv; - report_begin("hard link to empty string"); - if (create_testdir()<0) { - /*report_aborted();*/ /* XXX in create_testdir */ - return; - } - rv = link(TESTDIR, ""); - report_check(rv, errno, EINVAL); - rmdir(TESTDIR); + report_begin("hard link to empty string"); + if (create_testdir() < 0) { + /*report_aborted();*/ /* XXX in create_testdir */ + return; + } + rv = link(TESTDIR, ""); + report_check(rv, errno, EINVAL); + rmdir(TESTDIR); } -void -test_link(void) -{ - test_link_paths(); - link_dir(); - link_empty1(); - link_empty2(); +void test_link(void) { + test_link_paths(); + link_dir(); + link_empty1(); + link_empty2(); } diff --git a/userland/testbin/badcall/bad_lseek.c b/userland/testbin/badcall/bad_lseek.c index a521754..f3002dc 100644 --- a/userland/testbin/badcall/bad_lseek.c +++ b/userland/testbin/badcall/bad_lseek.c @@ -43,236 +43,213 @@ #include "config.h" #include "test.h" -static -void -lseek_fd_device(void) -{ - int fd, rv; +static void lseek_fd_device(void) { + int fd, rv; - report_begin("lseek on device"); + report_begin("lseek on device"); - fd = open("null:", O_RDONLY); - if (fd<0) { - report_warn("opening null: failed"); - report_aborted(); - return; - } + fd = open("null:", O_RDONLY); + if (fd < 0) { + report_warn("opening null: failed"); + report_aborted(); + return; + } - rv = lseek(fd, 309, SEEK_SET); - report_check(rv, errno, ESPIPE); + rv = lseek(fd, 309, SEEK_SET); + report_check(rv, errno, ESPIPE); - close(fd); + close(fd); } -static -void -lseek_file_stdin(void) -{ - int fd, fd2, rv, status; - const char slogan[] = "There ain't no such thing as a free lunch"; - size_t len = strlen(slogan); - pid_t pid; +static void lseek_file_stdin(void) { + int fd, fd2, rv, status; + const char slogan[] = "There ain't no such thing as a free lunch"; + size_t len = strlen(slogan); + pid_t pid; - report_begin("lseek stdin when open on file"); + report_begin("lseek stdin when open on file"); - /* fork so we don't affect our own stdin */ - pid = fork(); - if (pid<0) { - report_warn("fork failed"); - report_aborted(); - return; - } - else if (pid!=0) { - /* parent */ - rv = waitpid(pid, &status, 0); - if (rv<0) { - report_warn("waitpid failed"); - report_aborted(); - } - if (WIFSIGNALED(status)) { - report_warnx("subprocess exited with signal %d", - WTERMSIG(status)); - report_aborted(); - } - else if (WIFEXITED(status) && WEXITSTATUS(status) != 0) { - report_warnx("subprocess exited with code %d", - WEXITSTATUS(status)); - report_aborted(); - } - return; - } + /* fork so we don't affect our own stdin */ + pid = fork(); + if (pid < 0) { + report_warn("fork failed"); + report_aborted(); + return; + } else if (pid != 0) { + /* parent */ + rv = waitpid(pid, &status, 0); + if (rv < 0) { + report_warn("waitpid failed"); + report_aborted(); + } + if (WIFSIGNALED(status)) { + report_warnx("subprocess exited with signal %d", WTERMSIG(status)); + report_aborted(); + } else if (WIFEXITED(status) && WEXITSTATUS(status) != 0) { + report_warnx("subprocess exited with code %d", WEXITSTATUS(status)); + report_aborted(); + } + return; + } - /* child */ + /* child */ - fd = open_testfile(NULL); - if (fd<0) { - _exit(0); - } + fd = open_testfile(NULL); + if (fd < 0) { + _exit(0); + } - /* - * Move file to stdin. - * Use stdin (rather than stdout or stderr) to maximize the - * chances of detecting any special-case handling of fds 0-2. - * (Writing to stdin is fine as long as it's open for write, - * and it will be.) - */ - fd2 = dup2(fd, STDIN_FILENO); - if (fd2<0) { - report_warn("dup2 to stdin failed"); - close(fd); - remove(TESTFILE); - _exit(1); - } - if (fd2 != STDIN_FILENO) { - report_warn("dup2 returned wrong file handle"); - close(fd); - remove(TESTFILE); - _exit(1); - } - close(fd); + /* + * Move file to stdin. + * Use stdin (rather than stdout or stderr) to maximize the + * chances of detecting any special-case handling of fds 0-2. + * (Writing to stdin is fine as long as it's open for write, + * and it will be.) + */ + fd2 = dup2(fd, STDIN_FILENO); + if (fd2 < 0) { + report_warn("dup2 to stdin failed"); + close(fd); + remove(TESTFILE); + _exit(1); + } + if (fd2 != STDIN_FILENO) { + report_warn("dup2 returned wrong file handle"); + close(fd); + remove(TESTFILE); + _exit(1); + } + close(fd); - rv = write(STDIN_FILENO, slogan, len); - if (rv<0) { - report_warn("write to %s (via stdin) failed", TESTFILE); - remove(TESTFILE); - _exit(1); - } + rv = write(STDIN_FILENO, slogan, len); + if (rv < 0) { + report_warn("write to %s (via stdin) failed", TESTFILE); + remove(TESTFILE); + _exit(1); + } - if ((unsigned)rv != len) { - report_warnx("write to %s (via stdin) got short count", - TESTFILE); - remove(TESTFILE); - _exit(1); - } + if ((unsigned)rv != len) { + report_warnx("write to %s (via stdin) got short count", TESTFILE); + remove(TESTFILE); + _exit(1); + } - /* blah */ - report_skipped(); + /* blah */ + report_skipped(); - rv = lseek(STDIN_FILENO, 0, SEEK_SET); - report_begin("try 1: SEEK_SET"); - report_check(rv, errno, 0); + rv = lseek(STDIN_FILENO, 0, SEEK_SET); + report_begin("try 1: SEEK_SET"); + report_check(rv, errno, 0); - rv = lseek(STDIN_FILENO, 0, SEEK_END); - report_begin("try 2: SEEK_END"); - report_check(rv, errno, 0); + rv = lseek(STDIN_FILENO, 0, SEEK_END); + report_begin("try 2: SEEK_END"); + report_check(rv, errno, 0); - remove(TESTFILE); - _exit(0); + remove(TESTFILE); + _exit(0); } -static -void -lseek_loc_negative(void) -{ - int fd, rv; +static void lseek_loc_negative(void) { + int fd, rv; - report_begin("lseek to negative offset"); + report_begin("lseek to negative offset"); - fd = open_testfile(NULL); - if (fd<0) { - report_aborted(); - return; - } + fd = open_testfile(NULL); + if (fd < 0) { + report_aborted(); + return; + } - rv = lseek(fd, -309, SEEK_SET); - report_check(rv, errno, EINVAL); + rv = lseek(fd, -309, SEEK_SET); + report_check(rv, errno, EINVAL); - close(fd); - remove(TESTFILE); + close(fd); + remove(TESTFILE); } -static -void -lseek_whence_inval(void) -{ - int fd, rv; +static void lseek_whence_inval(void) { + int fd, rv; - report_begin("lseek with invalid whence code"); + report_begin("lseek with invalid whence code"); - fd = open_testfile(NULL); - if (fd<0) { - report_aborted(); - return; - } + fd = open_testfile(NULL); + if (fd < 0) { + report_aborted(); + return; + } - rv = lseek(fd, 0, 3594); - report_check(rv, errno, EINVAL); + rv = lseek(fd, 0, 3594); + report_check(rv, errno, EINVAL); - close(fd); - remove(TESTFILE); + close(fd); + remove(TESTFILE); } -static -void -lseek_loc_pasteof(void) -{ - const char *message = "blahblah"; - int fd; - off_t pos; +static void lseek_loc_pasteof(void) { + const char *message = "blahblah"; + int fd; + off_t pos; - report_begin("seek past/to EOF"); + report_begin("seek past/to EOF"); - fd = open_testfile(message); - if (fd<0) { - report_aborted(); - return; - } + fd = open_testfile(message); + if (fd < 0) { + report_aborted(); + return; + } - pos = lseek(fd, 5340, SEEK_SET); - if (pos == -1) { - report_warn("lseek past EOF failed"); - report_failure(); - goto out; - } - if (pos != 5340) { - report_warnx("lseek to 5340 got offset %lld", (long long) pos); - report_failure(); - goto out; - } + pos = lseek(fd, 5340, SEEK_SET); + if (pos == -1) { + report_warn("lseek past EOF failed"); + report_failure(); + goto out; + } + if (pos != 5340) { + report_warnx("lseek to 5340 got offset %lld", (long long)pos); + report_failure(); + goto out; + } - pos = lseek(fd, -50, SEEK_CUR); - if (pos == -1) { - report_warn("small seek beyond EOF failed"); - report_failure(); - goto out; - } - if (pos != 5290) { - report_warnx("SEEK_CUR to 5290 got offset %lld", - (long long) pos); - report_failure(); - goto out; - } + pos = lseek(fd, -50, SEEK_CUR); + if (pos == -1) { + report_warn("small seek beyond EOF failed"); + report_failure(); + goto out; + } + if (pos != 5290) { + report_warnx("SEEK_CUR to 5290 got offset %lld", (long long)pos); + report_failure(); + goto out; + } - pos = lseek(fd, 0, SEEK_END); - if (pos == -1) { - report_warn("seek to EOF failed"); - report_failure(); - goto out; - } + pos = lseek(fd, 0, SEEK_END); + if (pos == -1) { + report_warn("seek to EOF failed"); + report_failure(); + goto out; + } - if (pos != (off_t) strlen(message)) { - report_warnx("seek to EOF got %lld (should be %zu)", - (long long) pos, strlen(message)); - report_failure(); - goto out; - } + if (pos != (off_t)strlen(message)) { + report_warnx("seek to EOF got %lld (should be %zu)", (long long)pos, + strlen(message)); + report_failure(); + goto out; + } - report_passed(); + report_passed(); - out: - close(fd); - remove(TESTFILE); - return; +out: + close(fd); + remove(TESTFILE); + return; } -void -test_lseek(void) -{ - test_lseek_fd(); +void test_lseek(void) { + test_lseek_fd(); - lseek_fd_device(); - lseek_file_stdin(); - lseek_loc_negative(); - lseek_loc_pasteof(); - lseek_whence_inval(); + lseek_fd_device(); + lseek_file_stdin(); + lseek_loc_negative(); + lseek_loc_pasteof(); + lseek_whence_inval(); } diff --git a/userland/testbin/badcall/bad_mkdir.c b/userland/testbin/badcall/bad_mkdir.c index 4500dbd..9e87829 100644 --- a/userland/testbin/badcall/bad_mkdir.c +++ b/userland/testbin/badcall/bad_mkdir.c @@ -43,45 +43,34 @@ #include "config.h" #include "test.h" -static -void -mkdir_dot(void) -{ - int rv; +static void mkdir_dot(void) { + int rv; - report_begin("mkdir ."); - rv = mkdir(".", 0775); - report_check(rv, errno, EEXIST); + report_begin("mkdir ."); + rv = mkdir(".", 0775); + report_check(rv, errno, EEXIST); } -static -void -mkdir_dotdot(void) -{ - int rv; +static void mkdir_dotdot(void) { + int rv; - report_begin("mkdir .."); - rv = mkdir("..", 0775); - report_check(rv, errno, EEXIST); + report_begin("mkdir .."); + rv = mkdir("..", 0775); + report_check(rv, errno, EEXIST); } -static -void -mkdir_empty(void) -{ - int rv; +static void mkdir_empty(void) { + int rv; - report_begin("mkdir of empty string"); - rv = mkdir("", 0775); - report_check(rv, errno, EINVAL); + report_begin("mkdir of empty string"); + rv = mkdir("", 0775); + report_check(rv, errno, EINVAL); } -void -test_mkdir(void) -{ - test_mkdir_path(); +void test_mkdir(void) { + test_mkdir_path(); - mkdir_dot(); - mkdir_dotdot(); - mkdir_empty(); + mkdir_dot(); + mkdir_dotdot(); + mkdir_empty(); } diff --git a/userland/testbin/badcall/bad_open.c b/userland/testbin/badcall/bad_open.c index 3d317ed..010c19e 100644 --- a/userland/testbin/badcall/bad_open.c +++ b/userland/testbin/badcall/bad_open.c @@ -43,36 +43,28 @@ #include "config.h" #include "test.h" -static -void -open_badflags(void) -{ - int fd; +static void open_badflags(void) { + int fd; - report_begin("open null: with bad flags"); - fd = open("null:", 309842); - report_check(fd, errno, EINVAL); + report_begin("open null: with bad flags"); + fd = open("null:", 309842); + report_check(fd, errno, EINVAL); } -static -void -open_empty(void) -{ - int rv; +static void open_empty(void) { + int rv; - report_begin("open empty string"); - rv = open("", O_RDONLY); - report_check(rv, errno, EINVAL); - if (rv>=0) { - close(rv); - } + report_begin("open empty string"); + rv = open("", O_RDONLY); + report_check(rv, errno, EINVAL); + if (rv >= 0) { + close(rv); + } } -void -test_open(void) -{ - test_open_path(); +void test_open(void) { + test_open_path(); - open_badflags(); - open_empty(); + open_badflags(); + open_empty(); } diff --git a/userland/testbin/badcall/bad_pipe.c b/userland/testbin/badcall/bad_pipe.c index 172579c..8c67f45 100644 --- a/userland/testbin/badcall/bad_pipe.c +++ b/userland/testbin/badcall/bad_pipe.c @@ -43,44 +43,36 @@ #include "config.h" #include "test.h" -static -void -pipe_badptr(void *ptr, const char *desc) -{ - int rv; +static void pipe_badptr(void *ptr, const char *desc) { + int rv; - report_begin("%s", desc); - rv = pipe(ptr); - report_check(rv, errno, EFAULT); + report_begin("%s", desc); + rv = pipe(ptr); + report_check(rv, errno, EFAULT); } -static -void -pipe_unaligned(void) -{ - int fds[3], rv; - char *ptr; +static void pipe_unaligned(void) { + int fds[3], rv; + char *ptr; - report_begin("pipe with unaligned pointer"); + report_begin("pipe with unaligned pointer"); - ptr = (char *)&fds[0]; - ptr++; + ptr = (char *)&fds[0]; + ptr++; - rv = pipe((int *)ptr); - report_survival(rv, errno); - if (rv == 0) { - memmove(fds, ptr, 2*sizeof(int)); - close(fds[0]); - close(fds[1]); - } + rv = pipe((int *)ptr); + report_survival(rv, errno); + if (rv == 0) { + memmove(fds, ptr, 2 * sizeof(int)); + close(fds[0]); + close(fds[1]); + } } -void -test_pipe(void) -{ - pipe_badptr(NULL, "pipe with NULL pointer"); - pipe_badptr(INVAL_PTR, "pipe with invalid pointer"); - pipe_badptr(KERN_PTR, "pipe with kernel pointer"); +void test_pipe(void) { + pipe_badptr(NULL, "pipe with NULL pointer"); + pipe_badptr(INVAL_PTR, "pipe with invalid pointer"); + pipe_badptr(KERN_PTR, "pipe with kernel pointer"); - pipe_unaligned(); + pipe_unaligned(); } diff --git a/userland/testbin/badcall/bad_read.c b/userland/testbin/badcall/bad_read.c index c4e3215..5a8c29e 100644 --- a/userland/testbin/badcall/bad_read.c +++ b/userland/testbin/badcall/bad_read.c @@ -33,10 +33,7 @@ #include "test.h" -void -test_read(void) -{ - test_read_fd(); - test_read_buf(); +void test_read(void) { + test_read_fd(); + test_read_buf(); } - diff --git a/userland/testbin/badcall/bad_readlink.c b/userland/testbin/badcall/bad_readlink.c index 4399851..030492f 100644 --- a/userland/testbin/badcall/bad_readlink.c +++ b/userland/testbin/badcall/bad_readlink.c @@ -36,57 +36,45 @@ #include "test.h" -static -void -readlink_file(void) -{ - char buf[128]; - int fd, rv; +static void readlink_file(void) { + char buf[128]; + int fd, rv; - report_begin("readlink on file"); - fd = open_testfile("the question contains an invalid assumption"); - if (fd<0) { - report_aborted(); - return; - } - close(fd); - rv = readlink(TESTFILE, buf, sizeof(buf)); - report_check(rv, errno, EINVAL); - remove(TESTFILE); + report_begin("readlink on file"); + fd = open_testfile("the question contains an invalid assumption"); + if (fd < 0) { + report_aborted(); + return; + } + close(fd); + rv = readlink(TESTFILE, buf, sizeof(buf)); + report_check(rv, errno, EINVAL); + remove(TESTFILE); } -static -void -readlink_dir(void) -{ - char buf[128]; - int rv; +static void readlink_dir(void) { + char buf[128]; + int rv; - report_begin("readlink on ."); - rv = readlink(".", buf, sizeof(buf)); - report_check(rv, errno, EISDIR); + report_begin("readlink on ."); + rv = readlink(".", buf, sizeof(buf)); + report_check(rv, errno, EISDIR); } -static -void -readlink_empty(void) -{ - char buf[128]; - int rv; +static void readlink_empty(void) { + char buf[128]; + int rv; - report_begin("readlink on empty string"); - rv = readlink("", buf, sizeof(buf)); - report_check2(rv, errno, EISDIR, EINVAL); + report_begin("readlink on empty string"); + rv = readlink("", buf, sizeof(buf)); + report_check2(rv, errno, EISDIR, EINVAL); } -void -test_readlink(void) -{ - test_readlink_path(); - test_readlink_buf(); +void test_readlink(void) { + test_readlink_path(); + test_readlink_buf(); - readlink_file(); - readlink_dir(); - readlink_empty(); + readlink_file(); + readlink_dir(); + readlink_empty(); } - diff --git a/userland/testbin/badcall/bad_reboot.c b/userland/testbin/badcall/bad_reboot.c index add8fb9..10ba0bb 100644 --- a/userland/testbin/badcall/bad_reboot.c +++ b/userland/testbin/badcall/bad_reboot.c @@ -43,20 +43,13 @@ #include "config.h" #include "test.h" -static -void -reboot_badflags(void) -{ - int rv; +static void reboot_badflags(void) { + int rv; - printf("(This should not kill the system...)\n"); - report_begin("reboot with invalid flags"); - rv = reboot(15353); - report_check(rv, errno, EINVAL); + printf("(This should not kill the system...)\n"); + report_begin("reboot with invalid flags"); + rv = reboot(15353); + report_check(rv, errno, EINVAL); } -void -test_reboot(void) -{ - reboot_badflags(); -} +void test_reboot(void) { reboot_badflags(); } diff --git a/userland/testbin/badcall/bad_remove.c b/userland/testbin/badcall/bad_remove.c index 02621ac..ad23bf9 100644 --- a/userland/testbin/badcall/bad_remove.c +++ b/userland/testbin/badcall/bad_remove.c @@ -43,64 +43,50 @@ #include "config.h" #include "test.h" -static -void -remove_dir(void) -{ - int rv; +static void remove_dir(void) { + int rv; - report_begin("remove() on a directory"); + report_begin("remove() on a directory"); - if (create_testdir() < 0) { - /*report_aborted();*/ /* XXX in create_testdir */ - return; - } + if (create_testdir() < 0) { + /*report_aborted();*/ /* XXX in create_testdir */ + return; + } - rv = remove(TESTDIR); - report_check(rv, errno, EISDIR); - rmdir(TESTDIR); + rv = remove(TESTDIR); + report_check(rv, errno, EISDIR); + rmdir(TESTDIR); } -static -void -remove_dot(void) -{ - int rv; +static void remove_dot(void) { + int rv; - report_begin("remove() on ."); - rv = remove("."); - report_check2(rv, errno, EISDIR, EINVAL); + report_begin("remove() on ."); + rv = remove("."); + report_check2(rv, errno, EISDIR, EINVAL); } -static -void -remove_dotdot(void) -{ - int rv; +static void remove_dotdot(void) { + int rv; - report_begin("remove() on .."); - rv = remove(".."); - report_check2(rv, errno, EISDIR, EINVAL); + report_begin("remove() on .."); + rv = remove(".."); + report_check2(rv, errno, EISDIR, EINVAL); } -static -void -remove_empty(void) -{ - int rv; +static void remove_empty(void) { + int rv; - report_begin("remove() on empty string"); - rv = remove(""); - report_check2(rv, errno, EISDIR, EINVAL); + report_begin("remove() on empty string"); + rv = remove(""); + report_check2(rv, errno, EISDIR, EINVAL); } -void -test_remove(void) -{ - test_remove_path(); +void test_remove(void) { + test_remove_path(); - remove_dir(); - remove_dot(); - remove_dotdot(); - remove_empty(); + remove_dir(); + remove_dot(); + remove_dotdot(); + remove_empty(); } diff --git a/userland/testbin/badcall/bad_rename.c b/userland/testbin/badcall/bad_rename.c index 814dcb6..34ad6f2 100644 --- a/userland/testbin/badcall/bad_rename.c +++ b/userland/testbin/badcall/bad_rename.c @@ -36,76 +36,61 @@ #include "test.h" -static -void -rename_dot(void) -{ - int rv; +static void rename_dot(void) { + int rv; - report_begin("rename ."); + report_begin("rename ."); - rv = rename(".", TESTDIR); - report_check(rv, errno, EINVAL); - if (rv==0) { - /* oops... put it back */ - rename(TESTDIR, "."); - } + rv = rename(".", TESTDIR); + report_check(rv, errno, EINVAL); + if (rv == 0) { + /* oops... put it back */ + rename(TESTDIR, "."); + } } -static -void -rename_dotdot(void) -{ - int rv; +static void rename_dotdot(void) { + int rv; - report_begin("rename .."); - rv = rename("..", TESTDIR); - report_check(rv, errno, EINVAL); - if (rv==0) { - /* oops... put it back */ - rename(TESTDIR, ".."); - } + report_begin("rename .."); + rv = rename("..", TESTDIR); + report_check(rv, errno, EINVAL); + if (rv == 0) { + /* oops... put it back */ + rename(TESTDIR, ".."); + } } -static -void -rename_empty1(void) -{ - int rv; +static void rename_empty1(void) { + int rv; - report_begin("rename empty string"); - rv = rename("", TESTDIR); - report_check2(rv, errno, EISDIR, EINVAL); - if (rv==0) { - /* don't try to remove it */ - rename(TESTDIR, TESTDIR "-foo"); - } + report_begin("rename empty string"); + rv = rename("", TESTDIR); + report_check2(rv, errno, EISDIR, EINVAL); + if (rv == 0) { + /* don't try to remove it */ + rename(TESTDIR, TESTDIR "-foo"); + } } -static -void -rename_empty2(void) -{ - int rv; +static void rename_empty2(void) { + int rv; - report_begin("rename to empty string"); - if (create_testdir()<0) { - /*report_aborted();*/ /* XXX in create_testdir */ - return; - } - rv = rename(TESTDIR, ""); - report_check2(rv, errno, EISDIR, EINVAL); - rmdir(TESTDIR); + report_begin("rename to empty string"); + if (create_testdir() < 0) { + /*report_aborted();*/ /* XXX in create_testdir */ + return; + } + rv = rename(TESTDIR, ""); + report_check2(rv, errno, EISDIR, EINVAL); + rmdir(TESTDIR); } -void -test_rename(void) -{ - test_rename_paths(); +void test_rename(void) { + test_rename_paths(); - rename_dot(); - rename_dotdot(); - rename_empty1(); - rename_empty2(); + rename_dot(); + rename_dotdot(); + rename_empty1(); + rename_empty2(); } - diff --git a/userland/testbin/badcall/bad_rmdir.c b/userland/testbin/badcall/bad_rmdir.c index b1f6883..dd9a171 100644 --- a/userland/testbin/badcall/bad_rmdir.c +++ b/userland/testbin/badcall/bad_rmdir.c @@ -43,62 +43,48 @@ #include "config.h" #include "test.h" -static -void -rmdir_file(void) -{ - int rv; +static void rmdir_file(void) { + int rv; - report_begin("rmdir a file"); - if (create_testfile()<0) { - report_aborted(); - return; - } - rv = rmdir(TESTFILE); - report_check(rv, errno, ENOTDIR); - remove(TESTFILE); + report_begin("rmdir a file"); + if (create_testfile() < 0) { + report_aborted(); + return; + } + rv = rmdir(TESTFILE); + report_check(rv, errno, ENOTDIR); + remove(TESTFILE); } -static -void -rmdir_dot(void) -{ - int rv; +static void rmdir_dot(void) { + int rv; - report_begin("rmdir ."); - rv = rmdir("."); - report_check(rv, errno, EINVAL); + report_begin("rmdir ."); + rv = rmdir("."); + report_check(rv, errno, EINVAL); } -static -void -rmdir_dotdot(void) -{ - int rv; +static void rmdir_dotdot(void) { + int rv; - report_begin("rmdir .."); - rv = rmdir(".."); - report_check2(rv, errno, EINVAL, ENOTEMPTY); + report_begin("rmdir .."); + rv = rmdir(".."); + report_check2(rv, errno, EINVAL, ENOTEMPTY); } -static -void -rmdir_empty(void) -{ - int rv; +static void rmdir_empty(void) { + int rv; - report_begin("rmdir empty string"); - rv = rmdir(""); - report_check(rv, errno, EINVAL); + report_begin("rmdir empty string"); + rv = rmdir(""); + report_check(rv, errno, EINVAL); } -void -test_rmdir(void) -{ - test_rmdir_path(); +void test_rmdir(void) { + test_rmdir_path(); - rmdir_file(); - rmdir_dot(); - rmdir_dotdot(); - rmdir_empty(); + rmdir_file(); + rmdir_dot(); + rmdir_dotdot(); + rmdir_empty(); } diff --git a/userland/testbin/badcall/bad_sbrk.c b/userland/testbin/badcall/bad_sbrk.c index b482a92..3fab17d 100644 --- a/userland/testbin/badcall/bad_sbrk.c +++ b/userland/testbin/badcall/bad_sbrk.c @@ -46,80 +46,56 @@ /* * typing wrapper around sbrk */ -static -int -try_sbrk(long val) -{ - void *rv; - rv = sbrk(val); - if (rv==(void *)-1) { - return -1; - } - return 0; +static int try_sbrk(long val) { + void *rv; + rv = sbrk(val); + if (rv == (void *)-1) { + return -1; + } + return 0; } -static -void -enforce_sbrk(long val, const char *desc, int err) -{ - int result; +static void enforce_sbrk(long val, const char *desc, int err) { + int result; - report_begin("sbrk %s", desc); + report_begin("sbrk %s", desc); - result = try_sbrk(val); - report_check(result, errno, err); + result = try_sbrk(val); + report_check(result, errno, err); } -static -void -sbrk_bigpos(void) -{ - enforce_sbrk(4096*1024*256, "huge positive", ENOMEM); +static void sbrk_bigpos(void) { + enforce_sbrk(4096 * 1024 * 256, "huge positive", ENOMEM); } -static -void -sbrk_bigneg(void) -{ - enforce_sbrk(-4096*1024*256, "huge negative", EINVAL); +static void sbrk_bigneg(void) { + enforce_sbrk(-4096 * 1024 * 256, "huge negative", EINVAL); } -static -void -sbrk_neg(void) -{ - enforce_sbrk(-8192, "too-large negative", EINVAL); +static void sbrk_neg(void) { + enforce_sbrk(-8192, "too-large negative", EINVAL); } -static -void -sbrk_unalignedpos(void) -{ - int result; +static void sbrk_unalignedpos(void) { + int result; - report_begin("sbrk unaligned positive"); - result = try_sbrk(17); - report_check2(result, errno, 0, EINVAL); + report_begin("sbrk unaligned positive"); + result = try_sbrk(17); + report_check2(result, errno, 0, EINVAL); } -static -void -sbrk_unalignedneg(void) -{ - int result; +static void sbrk_unalignedneg(void) { + int result; - report_begin("sbrk unaligned negative"); - result = try_sbrk(-17); - report_check2(result, errno, 0, EINVAL); + report_begin("sbrk unaligned negative"); + result = try_sbrk(-17); + report_check2(result, errno, 0, EINVAL); } -void -test_sbrk(void) -{ - sbrk_neg(); - sbrk_bigpos(); - sbrk_bigneg(); - sbrk_unalignedpos(); - sbrk_unalignedneg(); +void test_sbrk(void) { + sbrk_neg(); + sbrk_bigpos(); + sbrk_bigneg(); + sbrk_unalignedpos(); + sbrk_unalignedneg(); } - diff --git a/userland/testbin/badcall/bad_stat.c b/userland/testbin/badcall/bad_stat.c index 726f9b1..870633d 100644 --- a/userland/testbin/badcall/bad_stat.c +++ b/userland/testbin/badcall/bad_stat.c @@ -45,84 +45,54 @@ //////////////////////////////////////////////////////////// -static -int -badbuf_fstat(struct stat *sb) -{ - return fstat(STDIN_FILENO, sb); +static int badbuf_fstat(struct stat *sb) { return fstat(STDIN_FILENO, sb); } + +static int badbuf_lstat(struct stat *sb) { return lstat("null:", sb); } + +static int badbuf_stat(struct stat *sb) { return stat("null:", sb); } + +static void common_badbuf(int (*statfunc)(struct stat *), void *ptr, + const char *call, const char *ptrdesc) { + int rv; + + report_begin("%s with %s buf", call, ptrdesc); + rv = statfunc(ptr); + report_check(rv, errno, EFAULT); } -static -int -badbuf_lstat(struct stat *sb) -{ - return lstat("null:", sb); -} - -static -int -badbuf_stat(struct stat *sb) -{ - return stat("null:", sb); -} - -static -void -common_badbuf(int (*statfunc)(struct stat *), void *ptr, - const char *call, const char *ptrdesc) -{ - int rv; - - report_begin("%s with %s buf", call, ptrdesc); - rv = statfunc(ptr); - report_check(rv, errno, EFAULT); -} - -static -void -any_badbuf(int (*statfunc)(struct stat *), const char *call) -{ - common_badbuf(statfunc, NULL, call, "NULL"); - common_badbuf(statfunc, INVAL_PTR, call, "invalid pointer"); - common_badbuf(statfunc, KERN_PTR, call, "kernel pointer"); +static void any_badbuf(int (*statfunc)(struct stat *), const char *call) { + common_badbuf(statfunc, NULL, call, "NULL"); + common_badbuf(statfunc, INVAL_PTR, call, "invalid pointer"); + common_badbuf(statfunc, KERN_PTR, call, "kernel pointer"); } //////////////////////////////////////////////////////////// -static -void -any_empty(int (*statfunc)(const char *, struct stat *), const char *call) -{ - struct stat sb; - int rv; +static void any_empty(int (*statfunc)(const char *, struct stat *), + const char *call) { + struct stat sb; + int rv; - report_begin("%s on empty string", call); - rv = statfunc("", &sb); - report_check2(rv, errno, 0, EINVAL); + report_begin("%s on empty string", call); + rv = statfunc("", &sb); + report_check2(rv, errno, 0, EINVAL); } //////////////////////////////////////////////////////////// -void -test_fstat(void) -{ - test_fstat_fd(); - any_badbuf(badbuf_fstat, "fstat"); +void test_fstat(void) { + test_fstat_fd(); + any_badbuf(badbuf_fstat, "fstat"); } -void -test_lstat(void) -{ - test_lstat_path(); - any_empty(lstat, "lstat"); - any_badbuf(badbuf_lstat, "lstat"); +void test_lstat(void) { + test_lstat_path(); + any_empty(lstat, "lstat"); + any_badbuf(badbuf_lstat, "lstat"); } -void -test_stat(void) -{ - test_stat_path(); - any_empty(stat, "stat"); - any_badbuf(badbuf_stat, "stat"); +void test_stat(void) { + test_stat_path(); + any_empty(stat, "stat"); + any_badbuf(badbuf_stat, "stat"); } - diff --git a/userland/testbin/badcall/bad_symlink.c b/userland/testbin/badcall/bad_symlink.c index 68a3463..507efd7 100644 --- a/userland/testbin/badcall/bad_symlink.c +++ b/userland/testbin/badcall/bad_symlink.c @@ -36,33 +36,25 @@ #include "test.h" -static -void -symlink_empty1(void) -{ - int rv; +static void symlink_empty1(void) { + int rv; - report_begin("symlink -> empty string"); - rv = symlink("", TESTLINK); - report_check2(rv, errno, 0, EINVAL); - remove(TESTLINK); + report_begin("symlink -> empty string"); + rv = symlink("", TESTLINK); + report_check2(rv, errno, 0, EINVAL); + remove(TESTLINK); } -static -void -symlink_empty2(void) -{ - int rv; +static void symlink_empty2(void) { + int rv; - report_begin("symlink named empty string"); - rv = symlink("foo", ""); - report_check(rv, errno, EINVAL); + report_begin("symlink named empty string"); + rv = symlink("foo", ""); + report_check(rv, errno, EINVAL); } -void -test_symlink(void) -{ - test_symlink_paths(); - symlink_empty1(); - symlink_empty2(); +void test_symlink(void) { + test_symlink_paths(); + symlink_empty1(); + symlink_empty2(); } diff --git a/userland/testbin/badcall/bad_time.c b/userland/testbin/badcall/bad_time.c index c5df61c..ef2b5f5 100644 --- a/userland/testbin/badcall/bad_time.c +++ b/userland/testbin/badcall/bad_time.c @@ -43,34 +43,26 @@ #include "config.h" #include "test.h" -static -void -time_badsecs(void *ptr, const char *desc) -{ - int rv; +static void time_badsecs(void *ptr, const char *desc) { + int rv; - report_begin("%s", desc); - rv = __time(ptr, NULL); - report_check(rv, errno, EFAULT); + report_begin("%s", desc); + rv = __time(ptr, NULL); + report_check(rv, errno, EFAULT); } -static -void -time_badnsecs(void *ptr, const char *desc) -{ - int rv; +static void time_badnsecs(void *ptr, const char *desc) { + int rv; - report_begin("%s", desc); - rv = __time(NULL, ptr); - report_check(rv, errno, EFAULT); + report_begin("%s", desc); + rv = __time(NULL, ptr); + report_check(rv, errno, EFAULT); } -void -test_time(void) -{ - time_badsecs(INVAL_PTR, "__time with invalid seconds pointer"); - time_badsecs(KERN_PTR, "__time with kernel seconds pointer"); +void test_time(void) { + time_badsecs(INVAL_PTR, "__time with invalid seconds pointer"); + time_badsecs(KERN_PTR, "__time with kernel seconds pointer"); - time_badnsecs(INVAL_PTR, "__time with invalid nsecs pointer"); - time_badnsecs(KERN_PTR, "__time with kernel nsecs pointer"); + time_badnsecs(INVAL_PTR, "__time with invalid nsecs pointer"); + time_badnsecs(KERN_PTR, "__time with kernel nsecs pointer"); } diff --git a/userland/testbin/badcall/bad_waitpid.c b/userland/testbin/badcall/bad_waitpid.c index f9bbd0d..5e7cbe5 100644 --- a/userland/testbin/badcall/bad_waitpid.c +++ b/userland/testbin/badcall/bad_waitpid.c @@ -41,383 +41,344 @@ #include "config.h" #include "test.h" -static -void -wait_badpid(pid_t pid, const char *desc) -{ - pid_t rv; - int x; - int err; +static void wait_badpid(pid_t pid, const char *desc) { + pid_t rv; + int x; + int err; - report_begin(desc); - rv = waitpid(pid, &x, 0); - err = errno; - /* Allow ENOSYS for 0 or negative values of pid only */ - if (pid <= 0 && rv == -1 && err == ENOSYS) { - err = ESRCH; - } - else if (err == ENOSYS) { - report_saw_enosys(); - } - report_check2(rv, err, ESRCH, ECHILD); + report_begin(desc); + rv = waitpid(pid, &x, 0); + err = errno; + /* Allow ENOSYS for 0 or negative values of pid only */ + if (pid <= 0 && rv == -1 && err == ENOSYS) { + err = ESRCH; + } else if (err == ENOSYS) { + report_saw_enosys(); + } + report_check2(rv, err, ESRCH, ECHILD); } -static -void -wait_nullstatus(void) -{ - pid_t pid, rv; - int x; +static void wait_nullstatus(void) { + pid_t pid, rv; + int x; - report_begin("wait with NULL status"); + report_begin("wait with NULL status"); - pid = fork(); - if (pid<0) { - report_warn("fork failed"); - report_aborted(); - return; - } - if (pid==0) { - exit(0); - } + pid = fork(); + if (pid < 0) { + report_warn("fork failed"); + report_aborted(); + return; + } + if (pid == 0) { + exit(0); + } - /* POSIX explicitly says passing NULL for status is allowed */ - rv = waitpid(pid, NULL, 0); - report_check(rv, errno, 0); - waitpid(pid, &x, 0); + /* POSIX explicitly says passing NULL for status is allowed */ + rv = waitpid(pid, NULL, 0); + report_check(rv, errno, 0); + waitpid(pid, &x, 0); } -static -void -wait_badstatus(void *ptr, const char *desc) -{ - pid_t pid, rv; - int x; +static void wait_badstatus(void *ptr, const char *desc) { + pid_t pid, rv; + int x; - report_begin(desc); + report_begin(desc); - pid = fork(); - if (pid<0) { - report_warn("fork failed"); - report_aborted(); - return; - } - if (pid==0) { - exit(0); - } + pid = fork(); + if (pid < 0) { + report_warn("fork failed"); + report_aborted(); + return; + } + if (pid == 0) { + exit(0); + } - rv = waitpid(pid, ptr, 0); - report_check(rv, errno, EFAULT); - waitpid(pid, &x, 0); + rv = waitpid(pid, ptr, 0); + report_check(rv, errno, EFAULT); + waitpid(pid, &x, 0); } -static -void -wait_unaligned(void) -{ - pid_t pid, rv; - int x; - int status[2]; /* will have integer alignment */ - char *ptr; +static void wait_unaligned(void) { + pid_t pid, rv; + int x; + int status[2]; /* will have integer alignment */ + char *ptr; - report_begin("wait with unaligned status"); + report_begin("wait with unaligned status"); - pid = fork(); - if (pid<0) { - report_warn("fork failed"); - report_aborted(); - return; - } - if (pid==0) { - exit(0); - } + pid = fork(); + if (pid < 0) { + report_warn("fork failed"); + report_aborted(); + return; + } + if (pid == 0) { + exit(0); + } - /* start with proper integer alignment */ - ptr = (char *)(&status[0]); + /* start with proper integer alignment */ + ptr = (char *)(&status[0]); - /* generate improper alignment on platforms with restrictions */ - ptr++; + /* generate improper alignment on platforms with restrictions */ + ptr++; - rv = waitpid(pid, (int *)ptr, 0); - report_survival(rv, errno); - if (rv<0) { - waitpid(pid, &x, 0); - } + rv = waitpid(pid, (int *)ptr, 0); + report_survival(rv, errno); + if (rv < 0) { + waitpid(pid, &x, 0); + } } -static -void -wait_badflags(void) -{ - pid_t pid, rv; - int x; +static void wait_badflags(void) { + pid_t pid, rv; + int x; - report_begin("wait with bad flags"); + report_begin("wait with bad flags"); - pid = fork(); - if (pid<0) { - report_warn("fork failed"); - report_aborted(); - return; - } - if (pid==0) { - exit(0); - } + pid = fork(); + if (pid < 0) { + report_warn("fork failed"); + report_aborted(); + return; + } + if (pid == 0) { + exit(0); + } - rv = waitpid(pid, &x, 309429); - report_check(rv, errno, EINVAL); - waitpid(pid, &x, 0); + rv = waitpid(pid, &x, 309429); + report_check(rv, errno, EINVAL); + waitpid(pid, &x, 0); } -static -void -wait_self(void) -{ - pid_t rv; - int x; +static void wait_self(void) { + pid_t rv; + int x; - report_begin("wait for self"); + report_begin("wait for self"); - rv = waitpid(getpid(), &x, 0); - report_survival(rv, errno); + rv = waitpid(getpid(), &x, 0); + report_survival(rv, errno); } -static -void -wait_parent(void) -{ - pid_t mypid, childpid, rv; - int x; +static void wait_parent(void) { + pid_t mypid, childpid, rv; + int x; - report_begin("wait for parent"); - report_hassubs(); + report_begin("wait for parent"); + report_hassubs(); - mypid = getpid(); - childpid = fork(); - if (childpid<0) { - report_warn("can't fork"); - report_aborted(); - return; - } - if (childpid==0) { - /* Child. Wait for parent. */ - rv = waitpid(mypid, &x, 0); - report_beginsub("from child:"); - report_survival(rv, errno); - _exit(0); - } - rv = waitpid(childpid, &x, 0); - report_beginsub("from parent:"); - report_survival(rv, errno); + mypid = getpid(); + childpid = fork(); + if (childpid < 0) { + report_warn("can't fork"); + report_aborted(); + return; + } + if (childpid == 0) { + /* Child. Wait for parent. */ + rv = waitpid(mypid, &x, 0); + report_beginsub("from child:"); + report_survival(rv, errno); + _exit(0); + } + rv = waitpid(childpid, &x, 0); + report_beginsub("from parent:"); + report_survival(rv, errno); } //////////////////////////////////////////////////////////// -static -void -wait_siblings_child(const char *semname) -{ - pid_t pids[2], mypid, otherpid; - int rv, fd, semfd, x; - char c; +static void wait_siblings_child(const char *semname) { + pid_t pids[2], mypid, otherpid; + int rv, fd, semfd, x; + char c; - mypid = getpid(); + mypid = getpid(); - /* - * Get our own handle for the semaphore, in case naive - * file-level synchronization causes concurrent use to - * deadlock. - */ - semfd = open(semname, O_RDONLY); - if (semfd < 0) { - report_warn("child process (pid %d) can't open %s", - mypid, semname); - } - else { - if (read(semfd, &c, 1) < 0) { - report_warn("in pid %d: %s: read", mypid, semname); - } - close(semfd); - } + /* + * Get our own handle for the semaphore, in case naive + * file-level synchronization causes concurrent use to + * deadlock. + */ + semfd = open(semname, O_RDONLY); + if (semfd < 0) { + report_warn("child process (pid %d) can't open %s", mypid, semname); + } else { + if (read(semfd, &c, 1) < 0) { + report_warn("in pid %d: %s: read", mypid, semname); + } + close(semfd); + } - fd = open(TESTFILE, O_RDONLY); - if (fd<0) { - report_warn("child process (pid %d) can't open %s", - mypid, TESTFILE); - return; - } + fd = open(TESTFILE, O_RDONLY); + if (fd < 0) { + report_warn("child process (pid %d) can't open %s", mypid, TESTFILE); + return; + } - /* - * In case the semaphore above didn't work, as a backup - * busy-wait until the parent writes the pids into the - * file. If the semaphore did work, this shouldn't loop. - */ - do { - rv = lseek(fd, 0, SEEK_SET); - if (rv<0) { - report_warn("child process (pid %d) lseek error", - mypid); - return; - } - rv = read(fd, pids, sizeof(pids)); - if (rv<0) { - report_warn("child process (pid %d) read error", - mypid); - return; - } - } while (rv < (int)sizeof(pids)); + /* + * In case the semaphore above didn't work, as a backup + * busy-wait until the parent writes the pids into the + * file. If the semaphore did work, this shouldn't loop. + */ + do { + rv = lseek(fd, 0, SEEK_SET); + if (rv < 0) { + report_warn("child process (pid %d) lseek error", mypid); + return; + } + rv = read(fd, pids, sizeof(pids)); + if (rv < 0) { + report_warn("child process (pid %d) read error", mypid); + return; + } + } while (rv < (int)sizeof(pids)); - if (mypid==pids[0]) { - otherpid = pids[1]; - } - else if (mypid==pids[1]) { - otherpid = pids[0]; - } - else { - report_warn("child process (pid %d) got garbage in comm file", - mypid); - return; - } - close(fd); + if (mypid == pids[0]) { + otherpid = pids[1]; + } else if (mypid == pids[1]) { + otherpid = pids[0]; + } else { + report_warn("child process (pid %d) got garbage in comm file", mypid); + return; + } + close(fd); - rv = waitpid(otherpid, &x, 0); - report_beginsub("sibling (pid %d)", mypid); - report_survival(rv, errno); + rv = waitpid(otherpid, &x, 0); + report_beginsub("sibling (pid %d)", mypid); + report_survival(rv, errno); } -static -void -wait_siblings(void) -{ - pid_t pids[2]; - int rv, fd, semfd, x; - int bad = 0; - char semname[32]; +static void wait_siblings(void) { + pid_t pids[2]; + int rv, fd, semfd, x; + int bad = 0; + char semname[32]; - /* This test may also blow up if FS synchronization is substandard */ + /* This test may also blow up if FS synchronization is substandard */ - report_begin("siblings wait for each other"); - report_hassubs(); + report_begin("siblings wait for each other"); + report_hassubs(); - snprintf(semname, sizeof(semname), "sem:badcall.%d", (int)getpid()); - semfd = open(semname, O_WRONLY|O_CREAT|O_TRUNC, 0664); - if (semfd < 0) { - report_warn("can't make semaphore"); - report_aborted(); - return; - } + snprintf(semname, sizeof(semname), "sem:badcall.%d", (int)getpid()); + semfd = open(semname, O_WRONLY | O_CREAT | O_TRUNC, 0664); + if (semfd < 0) { + report_warn("can't make semaphore"); + report_aborted(); + return; + } - fd = open_testfile(NULL); - if (fd<0) { - report_aborted(); - close(semfd); - remove(semname); - return; - } + fd = open_testfile(NULL); + if (fd < 0) { + report_aborted(); + close(semfd); + remove(semname); + return; + } - pids[0] = fork(); - if (pids[0]<0) { - report_warn("can't fork"); - report_aborted(); - close(fd); - close(semfd); - remove(semname); - return; - } - if (pids[0]==0) { - close(fd); - close(semfd); - wait_siblings_child(semname); - _exit(0); - } + pids[0] = fork(); + if (pids[0] < 0) { + report_warn("can't fork"); + report_aborted(); + close(fd); + close(semfd); + remove(semname); + return; + } + if (pids[0] == 0) { + close(fd); + close(semfd); + wait_siblings_child(semname); + _exit(0); + } - pids[1] = fork(); - if (pids[1]<0) { - report_warn("can't fork"); - report_aborted(); - /* abandon the other child process :( */ - close(fd); - close(semfd); - remove(semname); - return; - } - if (pids[1]==0) { - close(fd); - close(semfd); - wait_siblings_child(semname); - _exit(0); - } + pids[1] = fork(); + if (pids[1] < 0) { + report_warn("can't fork"); + report_aborted(); + /* abandon the other child process :( */ + close(fd); + close(semfd); + remove(semname); + return; + } + if (pids[1] == 0) { + close(fd); + close(semfd); + wait_siblings_child(semname); + _exit(0); + } - rv = write(fd, pids, sizeof(pids)); - if (rv < 0) { - report_warn("write error on %s", TESTFILE); - report_aborted(); - /* abandon child procs :( */ - close(fd); - close(semfd); - remove(semname); - return; - } - if (rv != (int)sizeof(pids)) { - report_warnx("write error on %s: short count", TESTFILE); - report_aborted(); - /* abandon child procs :( */ - close(fd); - close(semfd); - remove(semname); - return; - } + rv = write(fd, pids, sizeof(pids)); + if (rv < 0) { + report_warn("write error on %s", TESTFILE); + report_aborted(); + /* abandon child procs :( */ + close(fd); + close(semfd); + remove(semname); + return; + } + if (rv != (int)sizeof(pids)) { + report_warnx("write error on %s: short count", TESTFILE); + report_aborted(); + /* abandon child procs :( */ + close(fd); + close(semfd); + remove(semname); + return; + } - /* gate the child procs */ - rv = write(semfd, " ", 2); - if (rv < 0) { - report_warn("%s: write", semname); - bad = 1; - } + /* gate the child procs */ + rv = write(semfd, " ", 2); + if (rv < 0) { + report_warn("%s: write", semname); + bad = 1; + } - report_beginsub("overall"); - rv = waitpid(pids[0], &x, 0); - if (rv<0) { - report_warn("error waiting for child 0 (pid %d)", pids[0]); - bad = 1; - } - rv = waitpid(pids[1], &x, 0); - if (rv<0) { - report_warn("error waiting for child 1 (pid %d)", pids[1]); - bad = 1; - } - if (bad) { - /* XXX: aborted, or failure, or what? */ - report_aborted(); - } - else { - report_passed(); - } - close(fd); - close(semfd); - remove(semname); - remove(TESTFILE); + report_beginsub("overall"); + rv = waitpid(pids[0], &x, 0); + if (rv < 0) { + report_warn("error waiting for child 0 (pid %d)", pids[0]); + bad = 1; + } + rv = waitpid(pids[1], &x, 0); + if (rv < 0) { + report_warn("error waiting for child 1 (pid %d)", pids[1]); + bad = 1; + } + if (bad) { + /* XXX: aborted, or failure, or what? */ + report_aborted(); + } else { + report_passed(); + } + close(fd); + close(semfd); + remove(semname); + remove(TESTFILE); } //////////////////////////////////////////////////////////// -void -test_waitpid(void) -{ - wait_badpid(-8, "wait for pid -8"); - wait_badpid(-1, "wait for pid -1"); - wait_badpid(0, "pid zero"); - wait_badpid(NONEXIST_PID, "nonexistent pid"); +void test_waitpid(void) { + wait_badpid(-8, "wait for pid -8"); + wait_badpid(-1, "wait for pid -1"); + wait_badpid(0, "pid zero"); + wait_badpid(NONEXIST_PID, "nonexistent pid"); - wait_nullstatus(); - wait_badstatus(INVAL_PTR, "wait with invalid pointer status"); - wait_badstatus(KERN_PTR, "wait with kernel pointer status"); + wait_nullstatus(); + wait_badstatus(INVAL_PTR, "wait with invalid pointer status"); + wait_badstatus(KERN_PTR, "wait with kernel pointer status"); - wait_unaligned(); + wait_unaligned(); - wait_badflags(); + wait_badflags(); - wait_self(); - wait_parent(); - wait_siblings(); + wait_self(); + wait_parent(); + wait_siblings(); } diff --git a/userland/testbin/badcall/bad_write.c b/userland/testbin/badcall/bad_write.c index 8a79803..5014343 100644 --- a/userland/testbin/badcall/bad_write.c +++ b/userland/testbin/badcall/bad_write.c @@ -33,9 +33,7 @@ #include "test.h" -void -test_write(void) -{ - test_write_fd(); - test_write_buf(); +void test_write(void) { + test_write_fd(); + test_write_buf(); } diff --git a/userland/testbin/badcall/common_buf.c b/userland/testbin/badcall/common_buf.c index 37f7eaa..3c439bb 100644 --- a/userland/testbin/badcall/common_buf.c +++ b/userland/testbin/badcall/common_buf.c @@ -47,169 +47,108 @@ static int buf_fd; struct buftest { - int (*setup)(void); - int (*op)(void *); - void (*cleanup)(void); - const char *name; + int (*setup)(void); + int (*op)(void *); + void (*cleanup)(void); + const char *name; }; //////////////////////////////////////////////////////////// -static -int -read_setup(void) -{ - buf_fd = open_testfile("i do not like green eggs and ham"); - if (buf_fd<0) { - return -1; - } - return 0; +static int read_setup(void) { + buf_fd = open_testfile("i do not like green eggs and ham"); + if (buf_fd < 0) { + return -1; + } + return 0; } -static -int -read_badbuf(void *buf) -{ - return read(buf_fd, buf, 128); -} +static int read_badbuf(void *buf) { return read(buf_fd, buf, 128); } -static -void -read_cleanup(void) -{ - close(buf_fd); - remove(TESTFILE); +static void read_cleanup(void) { + close(buf_fd); + remove(TESTFILE); } ////////// -static -int -write_setup(void) -{ - buf_fd = open_testfile(NULL); - if (buf_fd<0) { - return -1; - } - return 0; +static int write_setup(void) { + buf_fd = open_testfile(NULL); + if (buf_fd < 0) { + return -1; + } + return 0; } -static -int -write_badbuf(void *ptr) -{ - return write(buf_fd, ptr, 128); -} +static int write_badbuf(void *ptr) { return write(buf_fd, ptr, 128); } -static -void -write_cleanup(void) -{ - close(buf_fd); - remove(TESTFILE); +static void write_cleanup(void) { + close(buf_fd); + remove(TESTFILE); } ////////// -static -int -getdirentry_setup(void) -{ - buf_fd = open(".", O_RDONLY); - if (buf_fd < 0) { - warn("UH-OH: couldn't open ."); - return -1; - } - return 0; +static int getdirentry_setup(void) { + buf_fd = open(".", O_RDONLY); + if (buf_fd < 0) { + warn("UH-OH: couldn't open ."); + return -1; + } + return 0; } -static -int -getdirentry_badbuf(void *ptr) -{ - return getdirentry(buf_fd, ptr, 1024); +static int getdirentry_badbuf(void *ptr) { + return getdirentry(buf_fd, ptr, 1024); } -static -void -getdirentry_cleanup(void) -{ - close(buf_fd); -} +static void getdirentry_cleanup(void) { close(buf_fd); } ////////// -static -int -readlink_setup(void) -{ - return create_testlink(); -} +static int readlink_setup(void) { return create_testlink(); } -static -int -readlink_badbuf(void *buf) -{ - return readlink(TESTLINK, buf, 168); -} +static int readlink_badbuf(void *buf) { return readlink(TESTLINK, buf, 168); } -static -void -readlink_cleanup(void) -{ - remove(TESTLINK); -} +static void readlink_cleanup(void) { remove(TESTLINK); } ////////// static int getcwd_setup(void) { return 0; } static void getcwd_cleanup(void) {} -static -int -getcwd_badbuf(void *buf) -{ - return __getcwd(buf, 408); +static int getcwd_badbuf(void *buf) { return __getcwd(buf, 408); } + +//////////////////////////////////////////////////////////// + +static void common_badbuf(struct buftest *info, void *buf, + const char *bufdesc) { + int rv; + + report_begin("%s with %s buffer", info->name, bufdesc); + info->setup(); + rv = info->op(buf); + report_check(rv, errno, EFAULT); + info->cleanup(); +} + +static void any_badbuf(struct buftest *info) { + common_badbuf(info, NULL, "NULL"); + common_badbuf(info, INVAL_PTR, "invalid"); + common_badbuf(info, KERN_PTR, "kernel-space"); } //////////////////////////////////////////////////////////// -static -void -common_badbuf(struct buftest *info, void *buf, const char *bufdesc) -{ - int rv; - - - report_begin("%s with %s buffer", info->name, bufdesc); - info->setup(); - rv = info->op(buf); - report_check(rv, errno, EFAULT); - info->cleanup(); -} - -static -void -any_badbuf(struct buftest *info) -{ - common_badbuf(info, NULL, "NULL"); - common_badbuf(info, INVAL_PTR, "invalid"); - common_badbuf(info, KERN_PTR, "kernel-space"); -} - -//////////////////////////////////////////////////////////// - -#define T(call) \ - void \ - test_##call##_buf(void) \ - { \ - static struct buftest info = { \ - call##_setup, \ - call##_badbuf, \ - call##_cleanup, \ - #call, \ - }; \ - any_badbuf(&info); \ +#define T(call) \ + void test_##call##_buf(void) { \ + static struct buftest info = { \ + call##_setup, \ + call##_badbuf, \ + call##_cleanup, \ + #call, \ + }; \ + any_badbuf(&info); \ } T(read); diff --git a/userland/testbin/badcall/common_fds.c b/userland/testbin/badcall/common_fds.c index 173db73..d35a96e 100644 --- a/userland/testbin/badcall/common_fds.c +++ b/userland/testbin/badcall/common_fds.c @@ -44,182 +44,119 @@ #include "config.h" #include "test.h" - enum rwtestmodes { - RW_TEST_NONE, - RW_TEST_RDONLY, - RW_TEST_WRONLY, + RW_TEST_NONE, + RW_TEST_RDONLY, + RW_TEST_WRONLY, }; -static -int -read_badfd(int fd) -{ - char buf[128]; - return read(fd, buf, sizeof(buf)); +static int read_badfd(int fd) { + char buf[128]; + return read(fd, buf, sizeof(buf)); } -static -int -write_badfd(int fd) -{ - char buf[128]; - memset(buf, 'a', sizeof(buf)); - return write(fd, buf, sizeof(buf)); +static int write_badfd(int fd) { + char buf[128]; + memset(buf, 'a', sizeof(buf)); + return write(fd, buf, sizeof(buf)); } +static int close_badfd(int fd) { return close(fd); } -static -int -close_badfd(int fd) -{ - return close(fd); +static int ioctl_badfd(int fd) { return ioctl(fd, 0, NULL); } + +static int lseek_badfd(int fd) { return lseek(fd, 0, SEEK_SET); } + +static int fsync_badfd(int fd) { return fsync(fd); } + +static int ftruncate_badfd(int fd) { return ftruncate(fd, 60); } + +static int fstat_badfd(int fd) { + struct stat sb; + return fstat(fd, &sb); } -static -int -ioctl_badfd(int fd) -{ - return ioctl(fd, 0, NULL); +static int getdirentry_badfd(int fd) { + char buf[32]; + return getdirentry(fd, buf, sizeof(buf)); } -static -int -lseek_badfd(int fd) -{ - return lseek(fd, 0, SEEK_SET); +static int dup2_badfd(int fd) { + /* use the +1 to avoid doing dup2(CLOSED_FD, CLOSED_FD) */ + return dup2(fd, CLOSED_FD + 1); } -static -int -fsync_badfd(int fd) -{ - return fsync(fd); -} - -static -int -ftruncate_badfd(int fd) -{ - return ftruncate(fd, 60); -} - -static -int -fstat_badfd(int fd) -{ - struct stat sb; - return fstat(fd, &sb); -} - -static -int -getdirentry_badfd(int fd) -{ - char buf[32]; - return getdirentry(fd, buf, sizeof(buf)); -} - -static -int -dup2_badfd(int fd) -{ - /* use the +1 to avoid doing dup2(CLOSED_FD, CLOSED_FD) */ - return dup2(fd, CLOSED_FD+1); -} - -static -void -dup2_cleanup(void) -{ - close(CLOSED_FD+1); -} +static void dup2_cleanup(void) { close(CLOSED_FD + 1); } //////////////////////////////////////////////////////////// -static -void -any_badfd(int (*func)(int fd), void (*cleanup)(void), const char *callname, - int fd, const char *fddesc) -{ - int rv; +static void any_badfd(int (*func)(int fd), void (*cleanup)(void), + const char *callname, int fd, const char *fddesc) { + int rv; - report_begin("%s using %s", callname, fddesc); - rv = func(fd); - report_check(rv, errno, EBADF); - if (cleanup) { - cleanup(); - } + report_begin("%s using %s", callname, fddesc); + rv = func(fd); + report_check(rv, errno, EBADF); + if (cleanup) { + cleanup(); + } } -static -void -runtest(int (*func)(int fd), void (*cleanup)(void), const char *callname, - enum rwtestmodes rw) -{ - int fd; +static void runtest(int (*func)(int fd), void (*cleanup)(void), + const char *callname, enum rwtestmodes rw) { + int fd; - /* - * If adding cases, also see bad_dup2.c - */ + /* + * If adding cases, also see bad_dup2.c + */ - /* basic invalid case: fd -1 */ - any_badfd(func, cleanup, callname, -1, "fd -1"); + /* basic invalid case: fd -1 */ + any_badfd(func, cleanup, callname, -1, "fd -1"); - /* also try -5 in case -1 is special somehow */ - any_badfd(func, cleanup, callname, -5, "fd -5"); + /* also try -5 in case -1 is special somehow */ + any_badfd(func, cleanup, callname, -5, "fd -5"); - /* try a fd we know is closed */ - any_badfd(func, cleanup, callname, CLOSED_FD, "closed fd"); + /* try a fd we know is closed */ + any_badfd(func, cleanup, callname, CLOSED_FD, "closed fd"); - /* try a positive fd we know is out of range */ - any_badfd(func, cleanup, callname, IMPOSSIBLE_FD, "impossible fd"); + /* try a positive fd we know is out of range */ + any_badfd(func, cleanup, callname, IMPOSSIBLE_FD, "impossible fd"); - /* test for off-by-one errors */ + /* test for off-by-one errors */ #ifdef OPEN_MAX - any_badfd(func, cleanup, callname, OPEN_MAX, "fd OPEN_MAX"); + any_badfd(func, cleanup, callname, OPEN_MAX, "fd OPEN_MAX"); #else - warnx("Warning: OPEN_MAX not defined, test skipped"); + warnx("Warning: OPEN_MAX not defined, test skipped"); #endif - if (rw == RW_TEST_RDONLY) { - fd = reopen_testfile(O_RDONLY|O_CREAT); - if (fd < 0) { - /* already printed a message */ - } - else { - any_badfd(func, cleanup, callname, fd, - "fd opened read-only"); - } - close(fd); - } - if (rw == RW_TEST_WRONLY) { - fd = reopen_testfile(O_WRONLY|O_CREAT); - if (fd < 0) { - /* already printed a message */ - } - else { - any_badfd(func, cleanup, callname, fd, - "fd opened write-only"); - } - close(fd); - } + if (rw == RW_TEST_RDONLY) { + fd = reopen_testfile(O_RDONLY | O_CREAT); + if (fd < 0) { + /* already printed a message */ + } else { + any_badfd(func, cleanup, callname, fd, "fd opened read-only"); + } + close(fd); + } + if (rw == RW_TEST_WRONLY) { + fd = reopen_testfile(O_WRONLY | O_CREAT); + if (fd < 0) { + /* already printed a message */ + } else { + any_badfd(func, cleanup, callname, fd, "fd opened write-only"); + } + close(fd); + } } //////////////////////////////////////////////////////////// -#define T(call, rw) \ - void \ - test_##call##_fd(void) \ - { \ - runtest(call##_badfd, NULL, #call, rw); \ - } +#define T(call, rw) \ + void test_##call##_fd(void) { runtest(call##_badfd, NULL, #call, rw); } -#define TC(call, rw) \ - void \ - test_##call##_fd(void) \ - { \ - runtest(call##_badfd, call##_cleanup, #call, rw);\ +#define TC(call, rw) \ + void test_##call##_fd(void) { \ + runtest(call##_badfd, call##_cleanup, #call, rw); \ } T(read, RW_TEST_WRONLY); diff --git a/userland/testbin/badcall/common_path.c b/userland/testbin/badcall/common_path.c index 1a8ff9d..b006c19 100644 --- a/userland/testbin/badcall/common_path.c +++ b/userland/testbin/badcall/common_path.c @@ -44,151 +44,83 @@ #include "config.h" #include "test.h" -static -int -open_badpath(const char *path) -{ - return open(path, O_RDONLY); +static int open_badpath(const char *path) { return open(path, O_RDONLY); } + +static int remove_badpath(const char *path) { return remove(path); } + +static int rename_badpath1(const char *path) { return rename(path, TESTFILE); } + +static int rename_badpath2(const char *path) { return rename(TESTFILE, path); } + +static int link_badpath1(const char *path) { return link(path, TESTFILE); } + +static int link_badpath2(const char *path) { return link(TESTFILE, path); } + +static int mkdir_badpath(const char *path) { return mkdir(path, 0775); } + +static int rmdir_badpath(const char *path) { return rmdir(path); } + +static int chdir_badpath(const char *path) { return chdir(path); } + +static int symlink_badpath1(const char *path) { + return symlink(path, TESTFILE); } -static -int -remove_badpath(const char *path) -{ - return remove(path); +static int symlink_badpath2(const char *path) { + return symlink(TESTFILE, path); } -static -int -rename_badpath1(const char *path) -{ - return rename(path, TESTFILE); +static int readlink_badpath(const char *path) { + char buf[128]; + return readlink(path, buf, sizeof(buf)); } -static -int -rename_badpath2(const char *path) -{ - return rename(TESTFILE, path); +static int lstat_badpath(const char *name) { + struct stat sb; + return lstat(name, &sb); } -static -int -link_badpath1(const char *path) -{ - return link(path, TESTFILE); -} - -static -int -link_badpath2(const char *path) -{ - return link(TESTFILE, path); -} - -static -int -mkdir_badpath(const char *path) -{ - return mkdir(path, 0775); -} - -static -int -rmdir_badpath(const char *path) -{ - return rmdir(path); -} - -static -int -chdir_badpath(const char *path) -{ - return chdir(path); -} - -static -int -symlink_badpath1(const char *path) -{ - return symlink(path, TESTFILE); -} - -static -int -symlink_badpath2(const char *path) -{ - return symlink(TESTFILE, path); -} - -static -int -readlink_badpath(const char *path) -{ - char buf[128]; - return readlink(path, buf, sizeof(buf)); -} - -static -int -lstat_badpath(const char *name) -{ - struct stat sb; - return lstat(name, &sb); -} - -static -int -stat_badpath(const char *name) -{ - struct stat sb; - return stat(name, &sb); +static int stat_badpath(const char *name) { + struct stat sb; + return stat(name, &sb); } //////////////////////////////////////////////////////////// -static -void -common_badpath(int (*func)(const char *path), int mk, int rm, const char *path, - const char *call, const char *pathdesc) -{ - int rv; +static void common_badpath(int (*func)(const char *path), int mk, int rm, + const char *path, const char *call, + const char *pathdesc) { + int rv; - report_begin("%s with %s path", call, pathdesc); + report_begin("%s with %s path", call, pathdesc); - if (mk) { - if (create_testfile()<0) { - report_aborted(); - return; - } - } + if (mk) { + if (create_testfile() < 0) { + report_aborted(); + return; + } + } - rv = func(path); - report_check(rv, errno, EFAULT); + rv = func(path); + report_check(rv, errno, EFAULT); - if (mk || rm) { - remove(TESTFILE); - } + if (mk || rm) { + remove(TESTFILE); + } } -static -void -any_badpath(int (*func)(const char *path), const char *call, int mk, int rm) -{ - common_badpath(func, mk, rm, NULL, call, "NULL"); - common_badpath(func, mk, rm, INVAL_PTR, call, "invalid-pointer"); - common_badpath(func, mk, rm, KERN_PTR, call, "kernel-pointer"); +static void any_badpath(int (*func)(const char *path), const char *call, int mk, + int rm) { + common_badpath(func, mk, rm, NULL, call, "NULL"); + common_badpath(func, mk, rm, INVAL_PTR, call, "invalid-pointer"); + common_badpath(func, mk, rm, KERN_PTR, call, "kernel-pointer"); } //////////////////////////////////////////////////////////// /* functions with one pathname */ -#define T(call) \ - void \ - test_##call##_path(void) \ - { \ - any_badpath(call##_badpath, #call, 0, 0); \ - } +#define T(call) \ + void test_##call##_path(void) { any_badpath(call##_badpath, #call, 0, 0); } T(open); T(remove); @@ -200,12 +132,10 @@ T(stat); T(lstat); /* functions with two pathnames */ -#define T2(call) \ - void \ - test_##call##_paths(void) \ - { \ - any_badpath(call##_badpath1, #call "(arg1)", 0, 1); \ - any_badpath(call##_badpath2, #call "(arg2)", 1, 1); \ +#define T2(call) \ + void test_##call##_paths(void) { \ + any_badpath(call##_badpath1, #call "(arg1)", 0, 1); \ + any_badpath(call##_badpath2, #call "(arg2)", 1, 1); \ } T2(rename); diff --git a/userland/testbin/badcall/config.h b/userland/testbin/badcall/config.h index 68d9d8f..a12d9d8 100644 --- a/userland/testbin/badcall/config.h +++ b/userland/testbin/badcall/config.h @@ -35,8 +35,8 @@ */ #if defined(__mips__) -#define KERN_PTR ((void *)0x80000000) /* addr within kernel */ -#define INVAL_PTR ((void *)0x40000000) /* addr not part of program */ +#define KERN_PTR ((void *)0x80000000) /* addr within kernel */ +#define INVAL_PTR ((void *)0x40000000) /* addr not part of program */ #else #error "Please fix this" #endif @@ -45,16 +45,16 @@ * We assume CLOSED_FD is a legal fd that won't be open when we're running. * CLOSED_FD+1 should also be legal and not open. */ -#define CLOSED_FD 10 +#define CLOSED_FD 10 /* We assume IMPOSSIBLE_FD is a fd that is completely not allowed. */ -#define IMPOSSIBLE_FD 1234567890 +#define IMPOSSIBLE_FD 1234567890 /* We assume this pid won't exist while we're running. Change as needed. */ -#define NONEXIST_PID 34000 +#define NONEXIST_PID 34000 /* An arbitrary process exit code that hopefully won't occur by accident */ -#define MAGIC_STATUS 107 +#define MAGIC_STATUS 107 /* An ioctl that doesn't exist */ -#define NONEXIST_IOCTL 12345 +#define NONEXIST_IOCTL 12345 diff --git a/userland/testbin/badcall/driver.c b/userland/testbin/badcall/driver.c index 31142f0..8328ce7 100644 --- a/userland/testbin/badcall/driver.c +++ b/userland/testbin/badcall/driver.c @@ -42,74 +42,68 @@ //////////////////////////////////////////////////////////// -int -open_testfile(const char *string) -{ - int fd, rv; - size_t len; +int open_testfile(const char *string) { + int fd, rv; + size_t len; - fd = open(TESTFILE, O_RDWR|O_CREAT|O_TRUNC, 0664); - if (fd<0) { - report_warn("creating %s: failed", TESTFILE); - return -1; - } + fd = open(TESTFILE, O_RDWR | O_CREAT | O_TRUNC, 0664); + if (fd < 0) { + report_warn("creating %s: failed", TESTFILE); + return -1; + } - if (string) { - len = strlen(string); - rv = write(fd, string, len); - if (rv<0) { - report_warn("write to %s failed", TESTFILE); - close(fd); - remove(TESTFILE); - return -1; - } - if ((unsigned)rv != len) { - report_warn("write to %s got short count", TESTFILE); - close(fd); - remove(TESTFILE); - return -1; - } - rv = lseek(fd, 0, SEEK_SET); - if (rv<0) { - report_warn("rewind of %s failed", TESTFILE); - close(fd); - remove(TESTFILE); - return -1; - } - } - return fd; + if (string) { + len = strlen(string); + rv = write(fd, string, len); + if (rv < 0) { + report_warn("write to %s failed", TESTFILE); + close(fd); + remove(TESTFILE); + return -1; + } + if ((unsigned)rv != len) { + report_warn("write to %s got short count", TESTFILE); + close(fd); + remove(TESTFILE); + return -1; + } + rv = lseek(fd, 0, SEEK_SET); + if (rv < 0) { + report_warn("rewind of %s failed", TESTFILE); + close(fd); + remove(TESTFILE); + return -1; + } + } + return fd; } -int -create_testfile(void) -{ - int fd, rv; +int create_testfile(void) { + int fd, rv; - fd = open_testfile(NULL); - if (fd<0) { - return -1; - } + fd = open_testfile(NULL); + if (fd < 0) { + return -1; + } - rv = close(fd); - if (rv<0) { - report_warn("closing %s failed", TESTFILE); - return -1; - } + rv = close(fd); + if (rv < 0) { + report_warn("closing %s failed", TESTFILE); + return -1; + } - return 0; + return 0; } -int -reopen_testfile(int openflags) -{ - int fd; +int reopen_testfile(int openflags) { + int fd; - fd = open(TESTFILE, openflags, 0664); - if (fd < 0) { - report_warn("reopening %s: failed", TESTFILE); - return -1; - } - return fd; + fd = open(TESTFILE, openflags, 0664); + if (fd < 0) { + report_warn("reopening %s: failed", TESTFILE); + return -1; + } + return fd; } /* @@ -117,173 +111,155 @@ reopen_testfile(int openflags) * otherwise it has to communicate to the caller which to call and * that's a pain. */ -int -create_testdir(void) -{ - int rv; - rv = mkdir(TESTDIR, 0775); - if (rv<0) { - if (errno == ENOSYS) { - report_saw_enosys(); - report_warnx("mkdir unimplemented; cannot run test"); - report_skipped(); - } - else { - report_warn("mkdir %s failed", TESTDIR); - report_aborted(); - } - return -1; - } - return 0; +int create_testdir(void) { + int rv; + rv = mkdir(TESTDIR, 0775); + if (rv < 0) { + if (errno == ENOSYS) { + report_saw_enosys(); + report_warnx("mkdir unimplemented; cannot run test"); + report_skipped(); + } else { + report_warn("mkdir %s failed", TESTDIR); + report_aborted(); + } + return -1; + } + return 0; } -int -create_testlink(void) -{ - int rv; - rv = symlink("blahblah", TESTLINK); - if (rv<0) { - report_warn("making symlink %s failed", TESTLINK); - return -1; - } - return 0; +int create_testlink(void) { + int rv; + rv = symlink("blahblah", TESTLINK); + if (rv < 0) { + report_warn("making symlink %s failed", TESTLINK); + return -1; + } + return 0; } //////////////////////////////////////////////////////////// -static -struct { - int ch; - int asst; - const char *name; - void (*f)(void); -} ops[] = { - { 'a', 2, "execv", test_execv }, - { 'b', 2, "waitpid", test_waitpid }, - { 'c', 2, "open", test_open }, - { 'd', 2, "read", test_read }, - { 'e', 2, "write", test_write }, - { 'f', 2, "close", test_close }, - { 'g', 0, "reboot", test_reboot }, - { 'h', 3, "sbrk", test_sbrk }, - { 'i', 5, "ioctl", test_ioctl }, - { 'j', 2, "lseek", test_lseek }, - { 'k', 4, "fsync", test_fsync }, - { 'l', 4, "ftruncate", test_ftruncate }, - { 'm', 4, "fstat", test_fstat }, - { 'n', 4, "remove", test_remove }, - { 'o', 4, "rename", test_rename }, - { 'p', 5, "link", test_link }, - { 'q', 4, "mkdir", test_mkdir }, - { 'r', 4, "rmdir", test_rmdir }, - { 's', 2, "chdir", test_chdir }, - { 't', 4, "getdirentry", test_getdirentry }, - { 'u', 5, "symlink", test_symlink }, - { 'v', 5, "readlink", test_readlink }, - { 'w', 2, "dup2", test_dup2 }, - { 'x', 5, "pipe", test_pipe }, - { 'y', 5, "__time", test_time }, - { 'z', 2, "__getcwd", test_getcwd }, - { '{', 5, "stat", test_stat }, - { '|', 5, "lstat", test_lstat }, - { 0, 0, NULL, NULL } -}; +static struct { + int ch; + int asst; + const char *name; + void (*f)(void); +} ops[] = {{'a', 2, "execv", test_execv}, + {'b', 2, "waitpid", test_waitpid}, + {'c', 2, "open", test_open}, + {'d', 2, "read", test_read}, + {'e', 2, "write", test_write}, + {'f', 2, "close", test_close}, + {'g', 0, "reboot", test_reboot}, + {'h', 3, "sbrk", test_sbrk}, + {'i', 5, "ioctl", test_ioctl}, + {'j', 2, "lseek", test_lseek}, + {'k', 4, "fsync", test_fsync}, + {'l', 4, "ftruncate", test_ftruncate}, + {'m', 4, "fstat", test_fstat}, + {'n', 4, "remove", test_remove}, + {'o', 4, "rename", test_rename}, + {'p', 5, "link", test_link}, + {'q', 4, "mkdir", test_mkdir}, + {'r', 4, "rmdir", test_rmdir}, + {'s', 2, "chdir", test_chdir}, + {'t', 4, "getdirentry", test_getdirentry}, + {'u', 5, "symlink", test_symlink}, + {'v', 5, "readlink", test_readlink}, + {'w', 2, "dup2", test_dup2}, + {'x', 5, "pipe", test_pipe}, + {'y', 5, "__time", test_time}, + {'z', 2, "__getcwd", test_getcwd}, + {'{', 5, "stat", test_stat}, + {'|', 5, "lstat", test_lstat}, + {0, 0, NULL, NULL}}; -#define LOWEST 'a' +#define LOWEST 'a' #define HIGHEST '|' -static -void -menu(void) -{ - int i; - for (i=0; ops[i].name; i++) { - printf("[%c] %-24s", ops[i].ch, ops[i].name); - if (i%2==1) { - printf("\n"); - } - } - if (i%2==1) { - printf("\n"); - } - printf("[1] %-24s", "asst1"); - printf("[2] %-24s\n", "asst2"); - printf("[3] %-24s", "asst3"); - printf("[4] %-24s\n", "asst4"); - printf("[*] %-24s", "all"); - printf("[!] %-24s\n", "quit"); +static void menu(void) { + int i; + for (i = 0; ops[i].name; i++) { + printf("[%c] %-24s", ops[i].ch, ops[i].name); + if (i % 2 == 1) { + printf("\n"); + } + } + if (i % 2 == 1) { + printf("\n"); + } + printf("[1] %-24s", "asst1"); + printf("[2] %-24s\n", "asst2"); + printf("[3] %-24s", "asst3"); + printf("[4] %-24s\n", "asst4"); + printf("[*] %-24s", "all"); + printf("[!] %-24s\n", "quit"); } -static -void -runit(int op) -{ - int i, k; +static void runit(int op) { + int i, k; - if (op=='!') { - exit(0); - } + if (op == '!') { + exit(0); + } - if (op=='?') { - menu(); - return; - } + if (op == '?') { + menu(); + return; + } - if (op=='*') { - for (i=0; ops[i].name; i++) { - printf("[%s]\n", ops[i].name); - ops[i].f(); - } - return; - } + if (op == '*') { + for (i = 0; ops[i].name; i++) { + printf("[%s]\n", ops[i].name); + ops[i].f(); + } + return; + } - if (op>='1' && op <= '4') { - k = op-'0'; - for (i=0; ops[i].name; i++) { - if (ops[i].asst <= k) { - printf("[%s]\n", ops[i].name); - ops[i].f(); - } - } - return; - } + if (op >= '1' && op <= '4') { + k = op - '0'; + for (i = 0; ops[i].name; i++) { + if (ops[i].asst <= k) { + printf("[%s]\n", ops[i].name); + ops[i].f(); + } + } + return; + } - if (op < LOWEST || op > HIGHEST) { - printf("Invalid request %c\n", op); - return; - } + if (op < LOWEST || op > HIGHEST) { + printf("Invalid request %c\n", op); + return; + } - ops[op-'a'].f(); + ops[op - 'a'].f(); } -int -main(int argc, char **argv) -{ - int op, i, j; +int main(int argc, char **argv) { + int op, i, j; - printf("[%c-%c, 1-4, *, ?=menu, !=quit]\n", LOWEST, HIGHEST); + printf("[%c-%c, 1-4, *, ?=menu, !=quit]\n", LOWEST, HIGHEST); - if (argc > 1) { - for (i=1; i 1) { + for (i = 1; i < argc; i++) { + for (j = 0; argv[i][j]; j++) { + printf("Choose: %c\n", argv[i][j]); + runit(argv[i][j]); + } + } + } else { + menu(); + while (1) { + printf("Choose: "); + op = getchar(); + if (op == EOF) { + break; + } + printf("%c\n", op); + runit(op); + } + } - return 0; + return 0; } diff --git a/userland/testbin/badcall/report.c b/userland/testbin/badcall/report.c index f93c7cf..1c1f347 100644 --- a/userland/testbin/badcall/report.c +++ b/userland/testbin/badcall/report.c @@ -58,63 +58,50 @@ static size_t outbufpos; /* * Print things. */ -static -void -vsay(const char *fmt, va_list ap) -{ - size_t begin, i; +static void vsay(const char *fmt, va_list ap) { + size_t begin, i; - assert(outbufpos < sizeof(outbuf)); + assert(outbufpos < sizeof(outbuf)); - begin = outbufpos; - vsnprintf(outbuf + outbufpos, sizeof(outbuf) - outbufpos, fmt, ap); - outbufpos = strlen(outbuf); + begin = outbufpos; + vsnprintf(outbuf + outbufpos, sizeof(outbuf) - outbufpos, fmt, ap); + outbufpos = strlen(outbuf); - for (i=begin; i 4) { - name = names[random()%22]; - len = strlen(name); - if (len < buflen) { - strcpy(buf, name); - buf += len; - buflen -= len; - if (buflen > 1) { - *buf = ' '; - buf++; - buflen--; - } - } - } - while (buflen > 1) { - *buf = '.'; - buf++; - buflen--; - } - *buf = 0; + while (buflen > 4) { + name = names[random() % 22]; + len = strlen(name); + if (len < buflen) { + strcpy(buf, name); + buf += len; + buflen -= len; + if (buflen > 1) { + *buf = ' '; + buf++; + buflen--; + } + } + } + while (buflen > 1) { + *buf = '.'; + buf++; + buflen--; + } + *buf = 0; } -static -void -prepwords(void) -{ - srandom(16581); - fill(word4050, sizeof(word4050)); - fill(word16320, sizeof(word16320)); - fill(word65500, sizeof(word65500)); +static void prepwords(void) { + srandom(16581); + fill(word4050, sizeof(word4050)); + fill(word16320, sizeof(word16320)); + fill(word65500, sizeof(word65500)); } //////////////////////////////////////////////////////////// // execing/checking -static -void -try(const char *first, ...) -{ - const char *args[20]; - const char *s; - va_list ap; - int num; +static void try(const char *first, ...) { + const char *args[20]; + const char *s; + va_list ap; + int num; - assert(first != NULL); - args[0] = _PATH_MYSELF; - args[1] = first; - num = 2; + assert(first != NULL); + args[0] = _PATH_MYSELF; + args[1] = first; + num = 2; - va_start(ap, first); - while (1) { - s = va_arg(ap, const char *); - if (s == NULL) { - break; - } - assert(num < 20); - args[num++] = s; - } - assert(num < 20); - args[num] = NULL; - execv(_PATH_MYSELF, (char **)args); - err(1, "execv"); + va_start(ap, first); + while (1) { + s = va_arg(ap, const char *); + if (s == NULL) { + break; + } + assert(num < 20); + args[num++] = s; + } + assert(num < 20); + args[num] = NULL; + execv(_PATH_MYSELF, (char **)args); + err(1, "execv"); } -static -void -trymany(int num, const char *word) -{ - const char *args[num+2]; - int i; +static void trymany(int num, const char *word) { + const char *args[num + 2]; + int i; - args[0] = _PATH_MYSELF; - for (i=0; i= 65536); + assert(ARG_MAX >= 65536); - if (argv == NULL || argc == 0 || argc == 1) { - /* no args -- start the test */ - warnx("Starting."); + if (argv == NULL || argc == 0 || argc == 1) { + /* no args -- start the test */ + warnx("Starting."); - /* - * 1. Should always fit no matter what. - */ - warnx("1. Execing with one 8-letter word."); - try(word8, NULL); - } - else if (check(argc, argv, word8, NULL)) { - /* - * 2. Fits in one page. - */ - warnx("2. Execing with one 4050-letter word."); - try(word4050, NULL); - } - else if (check(argc, argv, word4050, NULL)) { - /* - * 3. Requires two pages but each word fits on a page. - */ - warnx("3. Execing with two 4050-letter words."); - try(word4050, word4050, NULL); - } - else if (check(argc, argv, word4050, word4050, NULL)) { - /* - * 4. Requires the full 64K argv buffer, in large - * chunks, with a little space for slop. Each word - * fits on a page though. With null terminators and - * 4-byte pointers the size is 4085*16 = 65360, and - * with 8-byte pointers it would become 65424. - * - * Don't forget that argv[0] will be another 21 or 25 - * bytes and some implementations may reasonably need - * to stash an ending NULL in the buffer too. - */ - warnx("4. Execing with 16 4050-letter words."); - try(word4050, word4050, word4050, word4050, - word4050, word4050, word4050, word4050, - word4050, word4050, word4050, word4050, - word4050, word4050, word4050, word4050, - NULL); - } - else if (check(argc, argv, - word4050, word4050, word4050, word4050, - word4050, word4050, word4050, word4050, - word4050, word4050, word4050, word4050, - word4050, word4050, word4050, word4050, - NULL)) { - /* - * 5. Requires more than one page for a single word. - */ - warnx("5. Execing with one 16320-letter word."); - try(word16320, NULL); - } - else if (check(argc, argv, word16320, NULL)) { - /* - * 6. Ditto but makes sure it works with two of them. - */ - warnx("6. Execing with two 16320-letter words."); - try(word16320, word16320, NULL); - } - else if (check(argc, argv, word16320, word16320, NULL)) { - /* - * 7. Requires the full 64K argv buffer. - */ - warnx("7. Execing with four 16320-letter words."); - try(word16320, word16320, word16320, word16320, - NULL); - } - else if (check(argc, argv, word16320, word16320, - word16320, word16320, NULL)) { - /* - * 8. Also requires the full 64K argv buffer, but with - * only one huge word. - */ - warnx("8. Execing with one 65500-letter word."); - try(word65500, NULL); - } - else if (check(argc, argv, word65500, NULL)) { - /* - * 9. This fits on one page. Given 4-byte pointers, - * (8+1+4)*300 = 3900. With 8-byte pointers, it - * doesn't, but we aren't doing that. (Update this if - * we ever move to a 64-bit platform.) - */ - assert((8+1+sizeof(char *))*300 < 4096); - warnx("9. Execing with 300 8-letter words."); - trymany(300, word8); - } - else if (checkmany(argc, argv, 300, word8)) { + /* + * 1. Should always fit no matter what. + */ + warnx("1. Execing with one 8-letter word."); + try(word8, NULL); + } else if (check(argc, argv, word8, NULL)) { + /* + * 2. Fits in one page. + */ + warnx("2. Execing with one 4050-letter word."); + try(word4050, NULL); + } else if (check(argc, argv, word4050, NULL)) { + /* + * 3. Requires two pages but each word fits on a page. + */ + warnx("3. Execing with two 4050-letter words."); + try(word4050, word4050, NULL); + } else if (check(argc, argv, word4050, word4050, NULL)) { + /* + * 4. Requires the full 64K argv buffer, in large + * chunks, with a little space for slop. Each word + * fits on a page though. With null terminators and + * 4-byte pointers the size is 4085*16 = 65360, and + * with 8-byte pointers it would become 65424. + * + * Don't forget that argv[0] will be another 21 or 25 + * bytes and some implementations may reasonably need + * to stash an ending NULL in the buffer too. + */ + warnx("4. Execing with 16 4050-letter words."); + try(word4050, word4050, word4050, word4050, word4050, word4050, word4050, + word4050, word4050, word4050, word4050, word4050, word4050, word4050, + word4050, word4050, NULL); + } else if (check(argc, argv, word4050, word4050, word4050, word4050, word4050, + word4050, word4050, word4050, word4050, word4050, word4050, + word4050, word4050, word4050, word4050, word4050, NULL)) { + /* + * 5. Requires more than one page for a single word. + */ + warnx("5. Execing with one 16320-letter word."); + try(word16320, NULL); + } else if (check(argc, argv, word16320, NULL)) { + /* + * 6. Ditto but makes sure it works with two of them. + */ + warnx("6. Execing with two 16320-letter words."); + try(word16320, word16320, NULL); + } else if (check(argc, argv, word16320, word16320, NULL)) { + /* + * 7. Requires the full 64K argv buffer. + */ + warnx("7. Execing with four 16320-letter words."); + try(word16320, word16320, word16320, word16320, NULL); + } else if (check(argc, argv, word16320, word16320, word16320, word16320, + NULL)) { + /* + * 8. Also requires the full 64K argv buffer, but with + * only one huge word. + */ + warnx("8. Execing with one 65500-letter word."); + try(word65500, NULL); + } else if (check(argc, argv, word65500, NULL)) { + /* + * 9. This fits on one page. Given 4-byte pointers, + * (8+1+4)*300 = 3900. With 8-byte pointers, it + * doesn't, but we aren't doing that. (Update this if + * we ever move to a 64-bit platform.) + */ + assert((8 + 1 + sizeof(char *)) * 300 < 4096); + warnx("9. Execing with 300 8-letter words."); + trymany(300, word8); + } else if (checkmany(argc, argv, 300, word8)) { #if 1 /* enforce the full size */ - /* - * 10. This requires the full 64K argv buffer. - * With 4-byte pointers, (8+1+4)*5020 = 65260. - * It also doesn't fit with 8-byte pointers. - * - * XXX for the time being, we'll allow less efficient - * implementations that use two pointers per word. - * Hence, (8+1+4+4)*3850 = 65450. - */ - assert((8+1+sizeof(char *))*5020 < 65536); - assert((8+1+2*sizeof(char *))*3850 < 65536); - warnx("10. Execing with 3850 8-letter words."); - trymany(3850, word8); - } - else if (checkmany(argc, argv, 3850, word8)) { + /* + * 10. This requires the full 64K argv buffer. + * With 4-byte pointers, (8+1+4)*5020 = 65260. + * It also doesn't fit with 8-byte pointers. + * + * XXX for the time being, we'll allow less efficient + * implementations that use two pointers per word. + * Hence, (8+1+4+4)*3850 = 65450. + */ + assert((8 + 1 + sizeof(char *)) * 5020 < 65536); + assert((8 + 1 + 2 * sizeof(char *)) * 3850 < 65536); + warnx("10. Execing with 3850 8-letter words."); + trymany(3850, word8); + } else if (checkmany(argc, argv, 3850, word8)) { #else - /* - * 10a. This requires more than one page using small - * words. With 4-byte pointers, (8+1+4)*1000 = 13000. - */ - warnx("10. Execing with 1000 8-letter words."); - trymany(1000, word8); - } - else if (checkmany(argc, argv, 1000, word8)) { + /* + * 10a. This requires more than one page using small + * words. With 4-byte pointers, (8+1+4)*1000 = 13000. + */ + warnx("10. Execing with 1000 8-letter words."); + trymany(1000, word8); + } else if (checkmany(argc, argv, 1000, word8)) { #endif - warnx("Complete."); - return 0; - } - else { - warnx("Received unknown/unexpected args:"); - dumpargs(argc, argv); - return 1; - } + warnx("Complete."); + return 0; + } else { + warnx("Received unknown/unexpected args:"); + dumpargs(argc, argv); + return 1; + } } diff --git a/userland/testbin/bigfile/bigfile.c b/userland/testbin/bigfile/bigfile.c index 6dc7b55..0cb1e7f 100644 --- a/userland/testbin/bigfile/bigfile.c +++ b/userland/testbin/bigfile/bigfile.c @@ -44,64 +44,60 @@ static char buffer[8192 + 1]; -int -main(int argc, char *argv[]) -{ - const char *filename; - char *s; - size_t i, size, chunksize, offset; - ssize_t len; - int fd; +int main(int argc, char *argv[]) { + const char *filename; + char *s; + size_t i, size, chunksize, offset; + ssize_t len; + int fd; - if (argc != 3) { - warnx("Usage: bigfile "); - errx(1, " or: bigfile /"); - } + if (argc != 3) { + warnx("Usage: bigfile "); + errx(1, " or: bigfile /"); + } - filename = argv[1]; - s = strchr(argv[2], '/'); - if (s != NULL) { - *s++ = 0; - chunksize = atoi(s); - if (chunksize >= sizeof(buffer)) { - chunksize = sizeof(buffer) - 1; - } - if (chunksize == 0) { - errx(1, "Really?"); - } - } - else { - chunksize = 10; - } - size = atoi(argv[2]); + filename = argv[1]; + s = strchr(argv[2], '/'); + if (s != NULL) { + *s++ = 0; + chunksize = atoi(s); + if (chunksize >= sizeof(buffer)) { + chunksize = sizeof(buffer) - 1; + } + if (chunksize == 0) { + errx(1, "Really?"); + } + } else { + chunksize = 10; + } + size = atoi(argv[2]); - /* round size up */ - size = ((size + chunksize - 1) / chunksize) * chunksize; + /* round size up */ + size = ((size + chunksize - 1) / chunksize) * chunksize; - printf("Creating a file of size %d in %d-byte chunks\n", - size, chunksize); + printf("Creating a file of size %d in %d-byte chunks\n", size, chunksize); - fd = open(filename, O_WRONLY|O_CREAT|O_TRUNC); - if (fd < 0) { - err(1, "%s: create", filename); - } + fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC); + if (fd < 0) { + err(1, "%s: create", filename); + } - i=0; - while (i 0) { - failures += WEXITSTATUS(status); - } - } + if (pid == -1) { + failures++; + return; + } + if (pid == 0) { + exit(failures); + } else { + if (waitpid(pid, &status, 0) < 0) { + warn("waitpid(%d)", pid); + } else if (WIFSIGNALED(status)) { + warnx("pid %d: signal %d", pid, WTERMSIG(status)); + } else if (WEXITSTATUS(status) > 0) { + failures += WEXITSTATUS(status); + } + } } -static -void -dotest(void) -{ - unsigned i, me; - pid_t pids[BRANCHES]; - int t; - char msg[128]; +static void dotest(void) { + unsigned i, me; + pid_t pids[BRANCHES]; + int t; + char msg[128]; - me = 0; - for (i=0; i 0; ) { - dowait(pids[i]); - } - if (failures > 0) { - printf("%u failures.\n", failures); - } - else { - printf("Done.\n"); - } + for (i = BRANCHES; i-- > 0;) { + dowait(pids[i]); + } + if (failures > 0) { + printf("%u failures.\n", failures); + } else { + printf("Done.\n"); + } } -int -main(void) -{ - init(); - dotest(); - return 0; +int main(void) { + init(); + dotest(); + return 0; } diff --git a/userland/testbin/bigseek/bigseek.c b/userland/testbin/bigseek/bigseek.c index aab4601..b46f074 100644 --- a/userland/testbin/bigseek/bigseek.c +++ b/userland/testbin/bigseek/bigseek.c @@ -63,208 +63,184 @@ #define TESTFILE "bigseekfile" static const char *slogans[] = { - "QUO USQUE TANDEM ABUTERE CATILINA PATENTIA NOSTRA", - "QUEM IN FINEM SESE EFFRENATA IACTABIT AUDACIA" -}; + "QUO USQUE TANDEM ABUTERE CATILINA PATENTIA NOSTRA", + "QUEM IN FINEM SESE EFFRENATA IACTABIT AUDACIA"}; -static -void -write_slogan(int fd, unsigned which, bool failok) -{ - size_t len; - ssize_t r; +static void write_slogan(int fd, unsigned which, bool failok) { + size_t len; + ssize_t r; - len = strlen(slogans[which]); - r = write(fd, slogans[which], len); - if (r < 0) { - if (failok && errno == EFBIG) { - return; - } - err(1, "write"); - } - if (failok) { - errx(1, "write: expected failure but wrote %zd bytes", r); - } - if ((size_t)r != len) { - errx(1, "write: result %zd bytes, expected %zu", r, len); - } + len = strlen(slogans[which]); + r = write(fd, slogans[which], len); + if (r < 0) { + if (failok && errno == EFBIG) { + return; + } + err(1, "write"); + } + if (failok) { + errx(1, "write: expected failure but wrote %zd bytes", r); + } + if ((size_t)r != len) { + errx(1, "write: result %zd bytes, expected %zu", r, len); + } } -static -void -check_slogan(int fd, unsigned which) -{ - char buf[256]; - size_t len; - ssize_t r; - unsigned i, wrongcount; +static void check_slogan(int fd, unsigned which) { + char buf[256]; + size_t len; + ssize_t r; + unsigned i, wrongcount; - r = read(fd, buf, sizeof(buf)); - if (r < 0) { - err(1, "read"); - } - if (r == 0) { - errx(1, "read: Unexpected EOF"); - } + r = read(fd, buf, sizeof(buf)); + if (r < 0) { + err(1, "read"); + } + if (r == 0) { + errx(1, "read: Unexpected EOF"); + } - /* we should get either a full buffer or the length of the slogan */ - len = strlen(slogans[which]); - if ((size_t)r != sizeof(buf) && (size_t)r != len) { - errx(1, "read: result %zd bytes, expected %zu or %zu", - r, sizeof(buf), len); - } + /* we should get either a full buffer or the length of the slogan */ + len = strlen(slogans[which]); + if ((size_t)r != sizeof(buf) && (size_t)r != len) { + errx(1, "read: result %zd bytes, expected %zu or %zu", r, sizeof(buf), len); + } - /* slogan should match */ - if (memcmp(buf, slogans[which], len) != 0) { - warnx("read: got wrong data"); - warnx("expected: %s", slogans[which]); - buf[sizeof(buf) - 1] = 0; - errx(1, "found: %s", buf); - } + /* slogan should match */ + if (memcmp(buf, slogans[which], len) != 0) { + warnx("read: got wrong data"); + warnx("expected: %s", slogans[which]); + buf[sizeof(buf) - 1] = 0; + errx(1, "found: %s", buf); + } - /* bytes past the slogan (if any) should be 0 */ - wrongcount = 0; - for (i=len; i<(size_t)r; i++) { - if (buf[i] != 0) { - warnx("read: buf[%zu] was 0x%x, expected 0", i, - (unsigned char)buf[i]); - wrongcount++; - } - } - if (wrongcount > 0) { - errx(1, "%u bytes of trash in file", wrongcount); - } + /* bytes past the slogan (if any) should be 0 */ + wrongcount = 0; + for (i = len; i < (size_t)r; i++) { + if (buf[i] != 0) { + warnx("read: buf[%zu] was 0x%x, expected 0", i, (unsigned char)buf[i]); + wrongcount++; + } + } + if (wrongcount > 0) { + errx(1, "%u bytes of trash in file", wrongcount); + } } -static -void -try_reading(int fd) -{ - char buf[16]; - ssize_t r; +static void try_reading(int fd) { + char buf[16]; + ssize_t r; - r = read(fd, buf, sizeof(buf)); - if (r == 0) { - /* expected EOF */ - return; - } - if (r < 0) { - err(1, "read"); - } - errx(1, "read: Expected EOF but got %zd bytes", r); + r = read(fd, buf, sizeof(buf)); + if (r == 0) { + /* expected EOF */ + return; + } + if (r < 0) { + err(1, "read"); + } + errx(1, "read: Expected EOF but got %zd bytes", r); } -static -void -try_writing(int fd) -{ - write_slogan(fd, 1, true); +static void try_writing(int fd) { write_slogan(fd, 1, true); } + +static void dolseek(int fd, off_t pos, int whence, const char *whencestr, + off_t expected) { + off_t result; + + result = lseek(fd, pos, whence); + if (result == -1) { + err(1, "lseek(fd, 0x%llx, %s)", pos, whencestr); + } + if (result != expected) { + errx(1, + "lseek(fd, 0x%llx, %s): Wrong return value" + " (got 0x%llx, expected 0x%llx)", + pos, whencestr, result, expected); + } } -static -void -dolseek(int fd, off_t pos, int whence, const char *whencestr, off_t expected) -{ - off_t result; +static void try_seeking(int fd, off_t pos, off_t cursize) { + printf("Seeking to (and near) 0x%llx\n", pos); - result = lseek(fd, pos, whence); - if (result == -1) { - err(1, "lseek(fd, 0x%llx, %s)", pos, whencestr); - } - if (result != expected) { - errx(1, "lseek(fd, 0x%llx, %s): Wrong return value" - " (got 0x%llx, expected 0x%llx)", pos, whencestr, - result, expected); - } + /* Go to the place. */ + dolseek(fd, pos, SEEK_SET, "SEEK_SET", pos); + + /* Go to where we already are. */ + dolseek(fd, 0, SEEK_CUR, "SEEK_CUR", pos); + + if (pos >= 10) { + /* Back up a little. */ + dolseek(fd, -10, SEEK_CUR, "SEEK_CUR", pos - 10); + + /* Forward a little. */ + dolseek(fd, 20, SEEK_CUR, "SEEK_CUR", pos + 10); + } else { + /* Just forward a little. */ + dolseek(fd, 10, SEEK_CUR, "SEEK_CUR", pos + 10); + } + + /* Via SEEK_END. */ + dolseek(fd, pos, SEEK_END, "SEEK_END", pos + cursize); + + /* Go back to the exact place. */ + dolseek(fd, pos, SEEK_SET, "SEEK_SET", pos); } -static -void -try_seeking(int fd, off_t pos, off_t cursize) -{ - printf("Seeking to (and near) 0x%llx\n", pos); +int main(void) { + off_t cursize; + int fd; - /* Go to the place. */ - dolseek(fd, pos, SEEK_SET, "SEEK_SET", pos); + printf("Creating file...\n"); + fd = open(TESTFILE, O_RDWR | O_CREAT | O_TRUNC, 0664); + if (fd < 0) { + err(1, "%s", TESTFILE); + } - /* Go to where we already are. */ - dolseek(fd, 0, SEEK_CUR, "SEEK_CUR", pos); + printf("Writing something at offset 0\n"); + write_slogan(fd, 0, false); + cursize = strlen(slogans[0]); - if (pos >= 10) { - /* Back up a little. */ - dolseek(fd, -10, SEEK_CUR, "SEEK_CUR", pos - 10); + try_seeking(fd, (off_t)0x1000LL, cursize); - /* Forward a little. */ - dolseek(fd, 20, SEEK_CUR, "SEEK_CUR", pos + 10); - } - else { - /* Just forward a little. */ - dolseek(fd, 10, SEEK_CUR, "SEEK_CUR", pos + 10); - } + printf("Writing something else\n"); + write_slogan(fd, 1, false); + cursize = (off_t)0x1000LL + strlen(slogans[1]); - /* Via SEEK_END. */ - dolseek(fd, pos, SEEK_END, "SEEK_END", pos + cursize); + try_seeking(fd, (off_t)0, cursize); - /* Go back to the exact place. */ - dolseek(fd, pos, SEEK_SET, "SEEK_SET", pos); -} - -int -main(void) -{ - off_t cursize; - int fd; - - printf("Creating file...\n"); - fd = open(TESTFILE, O_RDWR|O_CREAT|O_TRUNC, 0664); - if (fd < 0) { - err(1, "%s", TESTFILE); - } - - printf("Writing something at offset 0\n"); - write_slogan(fd, 0, false); - cursize = strlen(slogans[0]); - - try_seeking(fd, (off_t)0x1000LL, cursize); - - printf("Writing something else\n"); - write_slogan(fd, 1, false); - cursize = (off_t)0x1000LL + strlen(slogans[1]); - - try_seeking(fd, (off_t)0, cursize); - - /* If seek is totally bust, this will fail. */ - printf("Checking what we wrote\n"); - check_slogan(fd, 0); - - try_seeking(fd, (off_t)0x1000LL, cursize); - printf("Checking the other thing we wrote\n"); - check_slogan(fd, 1); - - try_seeking(fd, (off_t)0x20LL, cursize); - try_seeking(fd, (off_t)0x7fffffffLL, cursize); - try_seeking(fd, (off_t)0x80000000LL, cursize); - try_seeking(fd, (off_t)0x80000020LL, cursize); - try_seeking(fd, (off_t)0x100000000LL, cursize); - try_seeking(fd, (off_t)0x100000020LL, cursize); - try_seeking(fd, (off_t)0x180000000LL, cursize); - try_seeking(fd, (off_t)0x180000020LL, cursize); - - printf("Now trying to read (should get EOF)\n"); - try_reading(fd); - - printf("Now trying to write (should get EFBIG)\n"); - try_writing(fd); - - try_seeking(fd, (off_t)0x100000000LL, cursize); - - /* If seek truncates to 32 bits, this might read the slogan instead */ - printf("Trying to read again (should get EOF)\n"); - try_reading(fd); - - printf("Passed.\n"); - - close(fd); - remove(TESTFILE); - return 0; + /* If seek is totally bust, this will fail. */ + printf("Checking what we wrote\n"); + check_slogan(fd, 0); + + try_seeking(fd, (off_t)0x1000LL, cursize); + printf("Checking the other thing we wrote\n"); + check_slogan(fd, 1); + + try_seeking(fd, (off_t)0x20LL, cursize); + try_seeking(fd, (off_t)0x7fffffffLL, cursize); + try_seeking(fd, (off_t)0x80000000LL, cursize); + try_seeking(fd, (off_t)0x80000020LL, cursize); + try_seeking(fd, (off_t)0x100000000LL, cursize); + try_seeking(fd, (off_t)0x100000020LL, cursize); + try_seeking(fd, (off_t)0x180000000LL, cursize); + try_seeking(fd, (off_t)0x180000020LL, cursize); + + printf("Now trying to read (should get EOF)\n"); + try_reading(fd); + + printf("Now trying to write (should get EFBIG)\n"); + try_writing(fd); + + try_seeking(fd, (off_t)0x100000000LL, cursize); + + /* If seek truncates to 32 bits, this might read the slogan instead */ + printf("Trying to read again (should get EOF)\n"); + try_reading(fd); + + printf("Passed.\n"); + + close(fd); + remove(TESTFILE); + return 0; } diff --git a/userland/testbin/bloat/bloat.c b/userland/testbin/bloat/bloat.c index ed5aca7..a5cdb6b 100644 --- a/userland/testbin/bloat/bloat.c +++ b/userland/testbin/bloat/bloat.c @@ -32,173 +32,145 @@ static unsigned touchpages; /* when touching pages, the extent to which we favor the middle of the range */ static unsigned bias; +static void moremem(void) { + static unsigned totalpages; -static -void -moremem(void) -{ - static unsigned totalpages; + void *ptr; + unsigned i; - void *ptr; - unsigned i; - - for (i=0; i= numpages) { - mnum = numpages; - } - moffset = numpages / 2 - mnum / 2; + mnum = numpages / 100; + if (mnum < touchpages * 2) { + mnum = touchpages * 2; + } + if (mnum >= numpages) { + mnum = numpages; + } + moffset = numpages / 2 - mnum / 2; - assert(bias >= 1); - span = (mnum + bias - 1) / bias; + assert(bias >= 1); + span = (mnum + bias - 1) / bias; - do { - val = 0; - for (i=0; i= mnum); - return moffset + val; + do { + val = 0; + for (i = 0; i < bias; i++) { + val += random() % span; + } + } while (val >= mnum); + return moffset + val; } -static -void -touchmem(void) -{ - unsigned i, num; +static void touchmem(void) { + unsigned i, num; - num = (((uintptr_t)lastpage - (uintptr_t)firstpage) / PAGE_SIZE) + 1; + num = (((uintptr_t)lastpage - (uintptr_t)firstpage) / PAGE_SIZE) + 1; - if (num % 256 == 0) { - warnx("%u pages", num); - } + if (num % 256 == 0) { + warnx("%u pages", num); + } - for (i=0; i #include -int -main(void) -{ - char ch=0; - int len; +int main(void) { + char ch = 0; + int len; - while (ch!='q') { - len = read(STDIN_FILENO, &ch, 1); - if (len < 0) { - err(1, "stdin: read"); - } - if (len==0) { - /* EOF */ - break; - } - write(STDOUT_FILENO, &ch, 1); - } - return 0; + while (ch != 'q') { + len = read(STDIN_FILENO, &ch, 1); + if (len < 0) { + err(1, "stdin: read"); + } + if (len == 0) { + /* EOF */ + break; + } + write(STDOUT_FILENO, &ch, 1); + } + return 0; } diff --git a/userland/testbin/crash/crash.c b/userland/testbin/crash/crash.c index 57406aa..42bc9c1 100644 --- a/userland/testbin/crash/crash.c +++ b/userland/testbin/crash/crash.c @@ -48,341 +48,276 @@ #include #if defined(__mips__) -#define KERNEL_ADDR 0x80000000 -#define INVAL_ADDR 0x40000000 -#define INSN_TYPE uint32_t -#define INVAL_INSN 0x0000003f +#define KERNEL_ADDR 0x80000000 +#define INVAL_ADDR 0x40000000 +#define INSN_TYPE uint32_t +#define INVAL_INSN 0x0000003f #else #error "Please fix this" #endif -#define MAGIC 123456 +#define MAGIC 123456 typedef void (*func)(void); static int forking = 1; -static -void -read_from_null(void) -{ - int *null = NULL; - volatile int x; +static void read_from_null(void) { + int *null = NULL; + volatile int x; - x = *null; + x = *null; - // gcc 4.8 improperly demands this - (void)x; + // gcc 4.8 improperly demands this + (void)x; } -static -void -read_from_inval(void) -{ - int *ptr = (int *) INVAL_ADDR; - volatile int x; +static void read_from_inval(void) { + int *ptr = (int *)INVAL_ADDR; + volatile int x; - x = *ptr; + x = *ptr; - // gcc 4.8 improperly demands this - (void)x; + // gcc 4.8 improperly demands this + (void)x; } -static -void -read_from_kernel(void) -{ - int *ptr = (int *) KERNEL_ADDR; - volatile int x; +static void read_from_kernel(void) { + int *ptr = (int *)KERNEL_ADDR; + volatile int x; - x = *ptr; + x = *ptr; - // gcc 4.8 improperly demands this - (void)x; + // gcc 4.8 improperly demands this + (void)x; } -static -void -write_to_null(void) -{ - int *null = NULL; - *null = 6; +static void write_to_null(void) { + int *null = NULL; + *null = 6; } -static -void -write_to_inval(void) -{ - int *ptr = (int *) INVAL_ADDR; - *ptr = 8; +static void write_to_inval(void) { + int *ptr = (int *)INVAL_ADDR; + *ptr = 8; } -static -void -write_to_code(void) -{ - INSN_TYPE *x = (INSN_TYPE *)write_to_code; - *x = INVAL_INSN; +static void write_to_code(void) { + INSN_TYPE *x = (INSN_TYPE *)write_to_code; + *x = INVAL_INSN; } -static -void -write_to_kernel(void) -{ - int *ptr = (int *) KERNEL_ADDR; - *ptr = 8; +static void write_to_kernel(void) { + int *ptr = (int *)KERNEL_ADDR; + *ptr = 8; } -static -void -jump_to_null(void) -{ - func f = NULL; - f(); +static void jump_to_null(void) { + func f = NULL; + f(); } -static -void -jump_to_inval(void) -{ - func f = (func) INVAL_ADDR; - f(); +static void jump_to_inval(void) { + func f = (func)INVAL_ADDR; + f(); } -static -void -jump_to_kernel(void) -{ - func f = (func) KERNEL_ADDR; - f(); +static void jump_to_kernel(void) { + func f = (func)KERNEL_ADDR; + f(); } - -static -void -illegal_instruction(void) -{ +static void illegal_instruction(void) { #if defined(__mips__) - asm(".long 0x0000003f"); + asm(".long 0x0000003f"); #else #error "Please fix this" #endif } -static -void -alignment_error(void) -{ - int x; - int *ptr, *badptr; - volatile uintptr_t ptrval; - volatile int j; +static void alignment_error(void) { + int x; + int *ptr, *badptr; + volatile uintptr_t ptrval; + volatile int j; - x = 0; - ptr = &x; - /* - * Try to hide what's going on from gcc; gcc 4.8 seems to - * detect the unaligned access and issue unaligned read - * instructions for it, so then it doesn't fault. Feh. - */ - ptrval = (uintptr_t)ptr; - ptrval++; - badptr = (int *)ptrval; + x = 0; + ptr = &x; + /* + * Try to hide what's going on from gcc; gcc 4.8 seems to + * detect the unaligned access and issue unaligned read + * instructions for it, so then it doesn't fault. Feh. + */ + ptrval = (uintptr_t)ptr; + ptrval++; + badptr = (int *)ptrval; - j = *badptr; + j = *badptr; - // gcc 4.8 improperly demands this - (void)j; + // gcc 4.8 improperly demands this + (void)j; } -static -void -divide_by_zero(void) -{ - volatile int x = 6; - volatile int z = 0; - volatile int a; +static void divide_by_zero(void) { + volatile int x = 6; + volatile int z = 0; + volatile int a; - a = x/z; + a = x / z; - // gcc 4.8 improperly demands this - (void)a; + // gcc 4.8 improperly demands this + (void)a; } -static -void -mod_by_zero(void) -{ - volatile int x = 6; - volatile int z = 0; - volatile int a; +static void mod_by_zero(void) { + volatile int x = 6; + volatile int z = 0; + volatile int a; - a = x%z; + a = x % z; - // gcc 4.8 improperly demands this - (void)a; + // gcc 4.8 improperly demands this + (void)a; } -static -void -recurse_inf(void) -{ - volatile char buf[16]; +static void recurse_inf(void) { + volatile char buf[16]; - buf[0] = 0; - recurse_inf(); - buf[0] = 1; + buf[0] = 0; + recurse_inf(); + buf[0] = 1; - // gcc 4.8 improperly demands this - (void)buf; + // gcc 4.8 improperly demands this + (void)buf; } +static struct { + int ch; + const char *name; + func f; + int sig; +} ops[] = {{'a', "read from NULL", read_from_null, SIGSEGV}, + {'b', "read from invalid address", read_from_inval, SIGSEGV}, + {'c', "read from kernel address", read_from_kernel, SIGBUS}, + {'d', "write to NULL", write_to_null, SIGSEGV}, + {'e', "write to invalid address", write_to_inval, SIGSEGV}, + {'f', "write to code segment", write_to_code, SIGSEGV}, + {'g', "write to kernel address", write_to_kernel, SIGBUS}, + {'h', "jump to NULL", jump_to_null, SIGSEGV}, + {'i', "jump to invalid address", jump_to_inval, SIGSEGV}, + {'j', "jump to kernel address", jump_to_kernel, SIGBUS}, + {'k', "alignment error", alignment_error, SIGBUS}, + {'l', "illegal instruction", illegal_instruction, SIGILL}, + {'m', "divide by zero", divide_by_zero, SIGTRAP}, + {'n', "mod by zero", mod_by_zero, SIGTRAP}, + {'o', "Recurse infinitely", recurse_inf, SIGSEGV}, + {0, NULL, NULL, 0}}; -static -struct { - int ch; - const char *name; - func f; - int sig; -} ops[] = { - { 'a', "read from NULL", read_from_null, SIGSEGV }, - { 'b', "read from invalid address", read_from_inval, SIGSEGV }, - { 'c', "read from kernel address", read_from_kernel, SIGBUS }, - { 'd', "write to NULL", write_to_null, SIGSEGV }, - { 'e', "write to invalid address", write_to_inval, SIGSEGV }, - { 'f', "write to code segment", write_to_code, SIGSEGV }, - { 'g', "write to kernel address", write_to_kernel, SIGBUS }, - { 'h', "jump to NULL", jump_to_null, SIGSEGV }, - { 'i', "jump to invalid address", jump_to_inval, SIGSEGV }, - { 'j', "jump to kernel address", jump_to_kernel, SIGBUS }, - { 'k', "alignment error", alignment_error, SIGBUS }, - { 'l', "illegal instruction", illegal_instruction, SIGILL }, - { 'm', "divide by zero", divide_by_zero, SIGTRAP }, - { 'n', "mod by zero", mod_by_zero, SIGTRAP }, - { 'o', "Recurse infinitely", recurse_inf, SIGSEGV }, - { 0, NULL, NULL, 0 } -}; +static void runop(int op) { + int opindex; + pid_t pid; + int status; + int ok; -static -void -runop(int op) -{ - int opindex; - pid_t pid; - int status; - int ok; + if (op == '*') { + for (unsigned i = 0; ops[i].name; i++) { + runop(ops[i].ch); + } + return; + } else if (op == '-') { + forking = 0; + warnx("Forking disabled - next try will be the last"); + return; + } else if (op == '+') { + forking = 1; + warnx("Forking enabled."); + return; + } - if (op=='*') { - for (unsigned i=0; ops[i].name; i++) { - runop(ops[i].ch); - } - return; - } - else if (op == '-') { - forking = 0; - warnx("Forking disabled - next try will be the last"); - return; - } - else if (op == '+') { - forking = 1; - warnx("Forking enabled."); - return; - } + /* intentionally don't check if op is in bounds :) */ + opindex = op - 'a'; - /* intentionally don't check if op is in bounds :) */ - opindex = op-'a'; + printf("Running: [%c] %s\n", ops[opindex].ch, ops[opindex].name); - printf("Running: [%c] %s\n", ops[opindex].ch, ops[opindex].name); + if (forking) { + pid = fork(); + if (pid < 0) { + /* error */ + err(1, "fork"); + } else if (pid > 0) { + /* parent */ + if (waitpid(pid, &status, 0) < 0) { + err(1, "waitpid"); + } + ok = 0; + if (WIFSIGNALED(status)) { + printf("Signal %d\n", WTERMSIG(status)); + if (WTERMSIG(status) == ops[opindex].sig) { + ok = 1; + } + } else { + printf("Exit %d\n", WEXITSTATUS(status)); + if (WEXITSTATUS(status) == MAGIC) { + ok = 1; + } + } + if (ok) { + printf("Ok.\n"); + } else { + printf("FAILED: expected signal %d\n", ops[opindex].sig); + } + printf("\n"); + return; + } + } + /* child, or not forking */ - if (forking) { - pid = fork(); - if (pid < 0) { - /* error */ - err(1, "fork"); - } - else if (pid > 0) { - /* parent */ - if (waitpid(pid, &status, 0) < 0) { - err(1, "waitpid"); - } - ok = 0; - if (WIFSIGNALED(status)) { - printf("Signal %d\n", WTERMSIG(status)); - if (WTERMSIG(status) == ops[opindex].sig) { - ok = 1; - } - } - else { - printf("Exit %d\n", WEXITSTATUS(status)); - if (WEXITSTATUS(status) == MAGIC) { - ok = 1; - } - } - if (ok) { - printf("Ok.\n"); - } - else { - printf("FAILED: expected signal %d\n", - ops[opindex].sig); - } - printf("\n"); - return; - } - } - /* child, or not forking */ + ops[opindex].f(); - ops[opindex].f(); - - if (op == 'f') { - warnx(".... I guess you don't support read-only segments"); - /* use this magic signaling value so parent doesn't say FAIL */ - _exit(MAGIC); - } - errx(1, "I wasn't killed!"); + if (op == 'f') { + warnx(".... I guess you don't support read-only segments"); + /* use this magic signaling value so parent doesn't say FAIL */ + _exit(MAGIC); + } + errx(1, "I wasn't killed!"); } -static -void -ask(void) -{ - unsigned i; - int op; +static void ask(void) { + unsigned i; + int op; - while (1) { + while (1) { - for (i=0; ops[i].name; i++) { - printf("[%c] %s\n", ops[i].ch, ops[i].name); - } - printf("[-] Disable forking\n"); - printf("[+] Enable forking (default)\n"); - printf("[*] Run everything\n"); - printf("[!] Quit\n"); + for (i = 0; ops[i].name; i++) { + printf("[%c] %s\n", ops[i].ch, ops[i].name); + } + printf("[-] Disable forking\n"); + printf("[+] Enable forking (default)\n"); + printf("[*] Run everything\n"); + printf("[!] Quit\n"); - printf("Choose: "); - op = getchar(); + printf("Choose: "); + op = getchar(); - if (op == '!') { - break; - } + if (op == '!') { + break; + } - runop(op); - } + runop(op); + } } -int -main(int argc, char **argv) -{ - if (argc == 0 || argc == 1) { - /* no arguments */ - ask(); - } - else { - /* run the selected ops */ - for (int i=1; i 2) { - printf("Usage: ctest [stridesize]\n"); - printf(" stridesize should not be a multiple of 2.\n"); - return 1; - } + stride = DEFAULT; + if (argc == 2) { + stride = atoi(argv[1]); + } + if (stride <= 0 || argc > 2) { + printf("Usage: ctest [stridesize]\n"); + printf(" stridesize should not be a multiple of 2.\n"); + return 1; + } - printf("Starting ctest: stride %d\n", stride); + printf("Starting ctest: stride %d\n", stride); - /* - * Generate a huge linked list, with each entry pointing to - * the slot STRIDE entries above it. As long as STRIDE and SIZE - * are relatively prime, this will put all the entries on one - * list. Otherwise you will get multiple disjoint lists. (All - * these lists will be circular.) - */ - for (i=0; ie; - } + /* + * Traverse the list. We stop after hitting each element once. + * + * (If STRIDE was even, this will hit some elements more than + * once and others not at all.) + */ + e = &array[0]; + for (i = 0; i < SIZE; i++) { + if (i % stride == 0) { + putchar('.'); + } + e = e->e; + } - printf("\nDone!\n"); - return 0; + printf("\nDone!\n"); + return 0; } diff --git a/userland/testbin/dirconc/dirconc.c b/userland/testbin/dirconc/dirconc.c index c388006..2079535 100644 --- a/userland/testbin/dirconc/dirconc.c +++ b/userland/testbin/dirconc/dirconc.c @@ -44,40 +44,37 @@ #include #include -#define NTRIES 100 /* loop count */ -#define NPROCS 5 /* actually totals 4x this +1 processes */ +#define NTRIES 100 /* loop count */ +#define NPROCS 5 /* actually totals 4x this +1 processes */ -#define TESTDIR "dirconc" -#define NNAMES 4 -#define NAMESIZE 32 +#define TESTDIR "dirconc" +#define NNAMES 4 +#define NAMESIZE 32 //////////////////////////////////////////////////////////// static const char *const names[NNAMES] = { - "aaaa", - "bbbb", - "cccc", - "dddd", + "aaaa", + "bbbb", + "cccc", + "dddd", }; -static -void -choose_name(char *buf, size_t len) -{ - const char *a, *b, *c; +static void choose_name(char *buf, size_t len) { + const char *a, *b, *c; - a = names[random()%NNAMES]; - if (random()%2==0) { - snprintf(buf, len, "%s", a); - return; - } - b = names[random()%NNAMES]; - if (random()%2==0) { - snprintf(buf, len, "%s/%s", a, b); - return; - } - c = names[random()%NNAMES]; - snprintf(buf, len, "%s/%s/%s", a, b, c); + a = names[random() % NNAMES]; + if (random() % 2 == 0) { + snprintf(buf, len, "%s", a); + return; + } + b = names[random() % NNAMES]; + if (random() % 2 == 0) { + snprintf(buf, len, "%s/%s", a, b); + return; + } + c = names[random() % NNAMES]; + snprintf(buf, len, "%s/%s/%s", a, b, c); } //////////////////////////////////////////////////////////// @@ -86,277 +83,224 @@ choose_name(char *buf, size_t len) * The purpose of this is to be atomic. In our world, straight * printf tends not to be. */ -static -void +static void #ifdef __GNUC__ - __attribute__((__format__(__printf__, 1, 2))) + __attribute__((__format__(__printf__, 1, 2))) #endif -say(const char *fmt, ...) -{ - char buf[512]; - va_list ap; - va_start(ap, fmt); - vsnprintf(buf, sizeof(buf), fmt, ap); - va_end(ap); - write(STDOUT_FILENO, buf, strlen(buf)); + say(const char *fmt, ...) { + char buf[512]; + va_list ap; + va_start(ap, fmt); + vsnprintf(buf, sizeof(buf), fmt, ap); + va_end(ap); + write(STDOUT_FILENO, buf, strlen(buf)); } //////////////////////////////////////////////////////////// -static -void -dorename(const char *name1, const char *name2) -{ - if (rename(name1, name2) < 0) { - switch (errno) { - case ENOENT: - case ENOTEMPTY: - case EINVAL: - break; - default: - say("pid %d: rename %s -> %s: %s\n", - getpid(), name1, name2, strerror(errno)); - break; - } - } +static void dorename(const char *name1, const char *name2) { + if (rename(name1, name2) < 0) { + switch (errno) { + case ENOENT: + case ENOTEMPTY: + case EINVAL: + break; + default: + say("pid %d: rename %s -> %s: %s\n", getpid(), name1, name2, + strerror(errno)); + break; + } + } } -static -void -domkdir(const char *name) -{ - if (mkdir(name, 0775)<0) { - switch (errno) { - case ENOENT: - case EEXIST: - break; - default: - say("pid %d: mkdir %s: %s\n", - getpid(), name, strerror(errno)); - break; - } - } +static void domkdir(const char *name) { + if (mkdir(name, 0775) < 0) { + switch (errno) { + case ENOENT: + case EEXIST: + break; + default: + say("pid %d: mkdir %s: %s\n", getpid(), name, strerror(errno)); + break; + } + } } -static -void -dormdir(const char *name) -{ - if (rmdir(name)<0) { - switch (errno) { - case ENOENT: - case ENOTEMPTY: - break; - default: - say("pid %d: rmdir %s: %s\n", - getpid(), name, strerror(errno)); - break; - } - } +static void dormdir(const char *name) { + if (rmdir(name) < 0) { + switch (errno) { + case ENOENT: + case ENOTEMPTY: + break; + default: + say("pid %d: rmdir %s: %s\n", getpid(), name, strerror(errno)); + break; + } + } } -static -void -cleanup_rmdir(const char *name) -{ - if (rmdir(name)<0) { - switch (errno) { - case ENOENT: - break; - default: - say("cleanup (pid %d): rmdir %s: %s\n", - getpid(), name, strerror(errno)); - break; - } - } +static void cleanup_rmdir(const char *name) { + if (rmdir(name) < 0) { + switch (errno) { + case ENOENT: + break; + default: + say("cleanup (pid %d): rmdir %s: %s\n", getpid(), name, strerror(errno)); + break; + } + } } //////////////////////////////////////////////////////////// -static -void -rename_proc(void) -{ - char name1[NAMESIZE], name2[NAMESIZE]; - int ct; +static void rename_proc(void) { + char name1[NAMESIZE], name2[NAMESIZE]; + int ct; - for (ct=0; ct %s\n", (int)getpid(), name1, name2); - dorename(name1, name2); - } + for (ct = 0; ct < NTRIES; ct++) { + choose_name(name1, sizeof(name1)); + choose_name(name2, sizeof(name2)); + say("pid %2d: rename %s -> %s\n", (int)getpid(), name1, name2); + dorename(name1, name2); + } } -static -void -mkdir_proc(void) -{ - char name[NAMESIZE]; - int ct; +static void mkdir_proc(void) { + char name[NAMESIZE]; + int ct; - for (ct=0; ct=0) { - wp = waitpid(pids[i], &status, 0); - if (wp<0) { - say("waitpid %d: %s\n", (int) pids[i], - strerror(errno)); - } - else if (WIFSIGNALED(status)) { - say("pid %d: signal %d\n", (int) pids[i], - WTERMSIG(status)); - } - else if (WIFEXITED(status) && WEXITSTATUS(status)!=0) { - say("pid %d: exit %d\n", (int) pids[i], - WEXITSTATUS(status)); - } - } - } + for (i = 0; i < NPROCS * 4; i++) { + if (pids[i] >= 0) { + wp = waitpid(pids[i], &status, 0); + if (wp < 0) { + say("waitpid %d: %s\n", (int)pids[i], strerror(errno)); + } else if (WIFSIGNALED(status)) { + say("pid %d: signal %d\n", (int)pids[i], WTERMSIG(status)); + } else if (WIFEXITED(status) && WEXITSTATUS(status) != 0) { + say("pid %d: exit %d\n", (int)pids[i], WEXITSTATUS(status)); + } + } + } } //////////////////////////////////////////////////////////// -static -void -setup(const char *fs) -{ - if (chdir(fs)<0) { - say("chdir: %s: %s\n", fs, strerror(errno)); - exit(1); - } - if (mkdir(TESTDIR, 0775)<0) { - say("mkdir: %s: %s\n", TESTDIR, strerror(errno)); - exit(1); - } - if (chdir(TESTDIR)<0) { - say("chdir: %s: %s\n", TESTDIR, strerror(errno)); - exit(1); - } +static void setup(const char *fs) { + if (chdir(fs) < 0) { + say("chdir: %s: %s\n", fs, strerror(errno)); + exit(1); + } + if (mkdir(TESTDIR, 0775) < 0) { + say("mkdir: %s: %s\n", TESTDIR, strerror(errno)); + exit(1); + } + if (chdir(TESTDIR) < 0) { + say("chdir: %s: %s\n", TESTDIR, strerror(errno)); + exit(1); + } } -static -void -recursive_cleanup(const char *sofar, int depth) -{ - char buf[NAMESIZE*32]; - int i; +static void recursive_cleanup(const char *sofar, int depth) { + char buf[NAMESIZE * 32]; + int i; - for (i=0; i 0) { + while ((len = getdirentry(dirfd, buf, sizeof(buf) - 1)) > 0) { - if ((unsigned)len >= sizeof(buf)-1) { - errx(1, ".: entry %d: getdirentry returned " - "invalid length %d", n, len); - } - buf[len] = 0; - ix = findentry(buf); - if (ix < 0) { - errx(1, ".: entry %d: getdirentry returned " - "unexpected name %s", n, buf); - } + if ((unsigned)len >= sizeof(buf) - 1) { + errx(1, + ".: entry %d: getdirentry returned " + "invalid length %d", + n, len); + } + buf[len] = 0; + ix = findentry(buf); + if (ix < 0) { + errx(1, + ".: entry %d: getdirentry returned " + "unexpected name %s", + n, buf); + } - if (testfiles[ix].pos >= 0) { - errx(1, ".: entry %d: getdirentry returned " - "%s a second time", n, buf); - } + if (testfiles[ix].pos >= 0) { + errx(1, + ".: entry %d: getdirentry returned " + "%s a second time", + n, buf); + } - testfiles[ix].pos = pos; + testfiles[ix].pos = pos; - pos = lseek(dirfd, 0, SEEK_CUR); - if (pos < 0) { - err(1, ".: lseek(0, SEEK_CUR)"); - } - n++; - } - if (len<0) { - err(1, ".: entry %d: getdirentry", n); - } + pos = lseek(dirfd, 0, SEEK_CUR); + if (pos < 0) { + err(1, ".: lseek(0, SEEK_CUR)"); + } + n++; + } + if (len < 0) { + err(1, ".: entry %d: getdirentry", n); + } - for (i=0; testfiles[i].name; i++) { - if (testfiles[i].pos < 0) { - errx(1, ".: getdirentry failed to return %s", - testfiles[i].name); - } - } - if (i!=n) { - /* - * If all of the other checks have passed, this should not - * be able to fail. But... just in case I forgot something - * or there's a bug... - */ + for (i = 0; testfiles[i].name; i++) { + if (testfiles[i].pos < 0) { + errx(1, ".: getdirentry failed to return %s", testfiles[i].name); + } + } + if (i != n) { + /* + * If all of the other checks have passed, this should not + * be able to fail. But... just in case I forgot something + * or there's a bug... + */ - errx(1, ".: getdirentry returned %d names, not %d (huh...?)", - n, i); - } + errx(1, ".: getdirentry returned %d names, not %d (huh...?)", n, i); + } } -static -void -firstread(void) -{ - off_t pos; +static void firstread(void) { + off_t pos; - pos = lseek(dirfd, 0, SEEK_CUR); - if (pos < 0) { - err(1, ".: lseek(0, SEEK_CUR)"); - } - if (pos != 0) { - errx(1, ".: File position after open not 0"); - } + pos = lseek(dirfd, 0, SEEK_CUR); + if (pos < 0) { + err(1, ".: lseek(0, SEEK_CUR)"); + } + if (pos != 0) { + errx(1, ".: File position after open not 0"); + } - printf("Scanning directory...\n"); + printf("Scanning directory...\n"); - readit(); + readit(); } -static -void -doreadat0(void) -{ - off_t pos; +static void doreadat0(void) { + off_t pos; - printf("Rewinding directory and reading it again...\n"); + printf("Rewinding directory and reading it again...\n"); - pos = lseek(dirfd, 0, SEEK_SET); - if (pos < 0) { - err(1, ".: lseek(0, SEEK_SET)"); - } - if (pos != 0) { - errx(1, ".: lseek(0, SEEK_SET) returned %ld", (long) pos); - } + pos = lseek(dirfd, 0, SEEK_SET); + if (pos < 0) { + err(1, ".: lseek(0, SEEK_SET)"); + } + if (pos != 0) { + errx(1, ".: lseek(0, SEEK_SET) returned %ld", (long)pos); + } - readit(); + readit(); } -static -void -readone(const char *shouldbe) -{ - char buf[4096]; - int len; +static void readone(const char *shouldbe) { + char buf[4096]; + int len; - len = getdirentry(dirfd, buf, sizeof(buf)-1); - if (len < 0) { - err(1, ".: getdirentry"); - } - if ((unsigned)len >= sizeof(buf)-1) { - errx(1, ".: getdirentry returned invalid length %d", len); - } - buf[len] = 0; + len = getdirentry(dirfd, buf, sizeof(buf) - 1); + if (len < 0) { + err(1, ".: getdirentry"); + } + if ((unsigned)len >= sizeof(buf) - 1) { + errx(1, ".: getdirentry returned invalid length %d", len); + } + buf[len] = 0; - if (strcmp(buf, shouldbe)) { - errx(1, ".: getdirentry returned %s (expected %s)", - buf, shouldbe); - } + if (strcmp(buf, shouldbe)) { + errx(1, ".: getdirentry returned %s (expected %s)", buf, shouldbe); + } } -static -void -doreadone(int which) -{ - off_t pos; - pos = lseek(dirfd, testfiles[which].pos, SEEK_SET); - if (pos<0) { - err(1, ".: lseek(%ld, SEEK_SET)", (long) testfiles[which].pos); - } - if (pos != testfiles[which].pos) { - errx(1, ".: lseek(%ld, SEEK_SET) returned %ld", - (long) testfiles[which].pos, (long) pos); - } +static void doreadone(int which) { + off_t pos; + pos = lseek(dirfd, testfiles[which].pos, SEEK_SET); + if (pos < 0) { + err(1, ".: lseek(%ld, SEEK_SET)", (long)testfiles[which].pos); + } + if (pos != testfiles[which].pos) { + errx(1, ".: lseek(%ld, SEEK_SET) returned %ld", (long)testfiles[which].pos, + (long)pos); + } - readone(testfiles[which].name); + readone(testfiles[which].name); } -static -void -readallonebyone(void) -{ - int i; +static void readallonebyone(void) { + int i; - printf("Trying to read each entry again...\n"); - for (i=0; testfiles[i].name; i++) { - doreadone(i); - } + printf("Trying to read each entry again...\n"); + for (i = 0; testfiles[i].name; i++) { + doreadone(i); + } } -static -void -readallrandomly(void) -{ - int n, i, x; +static void readallrandomly(void) { + int n, i, x; - printf("Trying to read a bunch of entries randomly...\n"); + printf("Trying to read a bunch of entries randomly...\n"); - for (i=0; testfiles[i].name; i++); - n = i; + for (i = 0; testfiles[i].name; i++) + ; + n = i; - srandom(39584); - for (i=0; i<512; i++) { - x = (int)(random()%n); - doreadone(x); - } + srandom(39584); + for (i = 0; i < 512; i++) { + x = (int)(random() % n); + doreadone(x); + } } -static -void -readateof(void) -{ - char buf[4096]; - int len; +static void readateof(void) { + char buf[4096]; + int len; - len = getdirentry(dirfd, buf, sizeof(buf)-1); - if (len < 0) { - err(1, ".: at EOF: getdirentry"); - } - if (len==0) { - return; - } - if ((unsigned)len >= sizeof(buf)-1) { - errx(1, ".: at EOF: getdirentry returned " - "invalid length %d", len); - } - buf[len] = 0; - errx(1, ".: at EOF: got unexpected name %s", buf); + len = getdirentry(dirfd, buf, sizeof(buf) - 1); + if (len < 0) { + err(1, ".: at EOF: getdirentry"); + } + if (len == 0) { + return; + } + if ((unsigned)len >= sizeof(buf) - 1) { + errx(1, + ".: at EOF: getdirentry returned " + "invalid length %d", + len); + } + buf[len] = 0; + errx(1, ".: at EOF: got unexpected name %s", buf); } -static -void -doreadateof(void) -{ - off_t pos; - int i; +static void doreadateof(void) { + off_t pos; + int i; - printf("Trying to read after going to EOF...\n"); + printf("Trying to read after going to EOF...\n"); - pos = lseek(dirfd, 0, SEEK_END); - if (pos<0) { - err(1, ".: lseek(0, SEEK_END)"); - } + pos = lseek(dirfd, 0, SEEK_END); + if (pos < 0) { + err(1, ".: lseek(0, SEEK_END)"); + } - for (i=0; testfiles[i].name; i++) { - if (pos <= testfiles[i].pos) { - errx(1, ".: EOF position %ld below position %ld of %s", - pos, testfiles[i].pos, testfiles[i].name); - } - } + for (i = 0; testfiles[i].name; i++) { + if (pos <= testfiles[i].pos) { + errx(1, ".: EOF position %ld below position %ld of %s", pos, + testfiles[i].pos, testfiles[i].name); + } + } - readateof(); + readateof(); } -static -void -inval_read(void) -{ - char buf[4096]; - int len; +static void inval_read(void) { + char buf[4096]; + int len; - len = getdirentry(dirfd, buf, sizeof(buf)-1); + len = getdirentry(dirfd, buf, sizeof(buf) - 1); - /* Any result is ok, as long as the system doesn't crash */ - (void)len; + /* Any result is ok, as long as the system doesn't crash */ + (void)len; } -static -void -dobadreads(void) -{ - off_t pos, pos2, eof; - int valid, i, k=0; +static void dobadreads(void) { + off_t pos, pos2, eof; + int valid, i, k = 0; - printf("Trying some possibly invalid reads...\n"); + printf("Trying some possibly invalid reads...\n"); - eof = lseek(dirfd, 0, SEEK_END); - if (eof < 0) { - err(1, ".: lseek(0, SEEK_END)"); - } + eof = lseek(dirfd, 0, SEEK_END); + if (eof < 0) { + err(1, ".: lseek(0, SEEK_END)"); + } - for (pos=0; pos < eof; pos++) { - valid = 0; - for (i=0; testfiles[i].name; i++) { - if (pos==testfiles[i].pos) { - valid = 1; - } - } - if (valid) { - /* don't try offsets that are known to be valid */ - continue; - } + for (pos = 0; pos < eof; pos++) { + valid = 0; + for (i = 0; testfiles[i].name; i++) { + if (pos == testfiles[i].pos) { + valid = 1; + } + } + if (valid) { + /* don't try offsets that are known to be valid */ + continue; + } - pos2 = lseek(dirfd, pos, SEEK_SET); - if (pos2 < 0) { - /* this is ok */ - } - else { - inval_read(); - k++; - } - } + pos2 = lseek(dirfd, pos, SEEK_SET); + if (pos2 < 0) { + /* this is ok */ + } else { + inval_read(); + k++; + } + } - if (k>0) { - printf("Survived %d invalid reads...\n", k); - } - else { - printf("Couldn't find any invalid offsets to try...\n"); - } + if (k > 0) { + printf("Survived %d invalid reads...\n", k); + } else { + printf("Couldn't find any invalid offsets to try...\n"); + } - printf("Trying to read beyond EOF...\n"); - pos2 = lseek(dirfd, eof + 1000, SEEK_SET); - if (pos2 < 0) { - /* this is ok */ - } - else { - inval_read(); - } + printf("Trying to read beyond EOF...\n"); + pos2 = lseek(dirfd, eof + 1000, SEEK_SET); + if (pos2 < 0) { + /* this is ok */ + } else { + inval_read(); + } } -static -void -dotest(void) -{ - printf("Opening directory...\n"); - openit(); +static void dotest(void) { + printf("Opening directory...\n"); + openit(); - printf("Running tests...\n"); + printf("Running tests...\n"); - /* read the whole directory */ - firstread(); + /* read the whole directory */ + firstread(); - /* make sure eof behaves right */ - readateof(); + /* make sure eof behaves right */ + readateof(); - /* read all the filenames again by seeking */ - readallonebyone(); + /* read all the filenames again by seeking */ + readallonebyone(); - /* try reading at eof */ - doreadateof(); + /* try reading at eof */ + doreadateof(); - /* read a bunch of the filenames over and over again */ - readallrandomly(); + /* read a bunch of the filenames over and over again */ + readallrandomly(); - /* rewind and read the whole thing again, to make sure that works */ - doreadat0(); + /* rewind and read the whole thing again, to make sure that works */ + doreadat0(); - /* do invalid reads */ - dobadreads(); + /* do invalid reads */ + dobadreads(); - /* rewind again to make sure the invalid attempts didn't break it */ - doreadat0(); + /* rewind again to make sure the invalid attempts didn't break it */ + doreadat0(); - printf("Closing directory...\n"); - closeit(); + printf("Closing directory...\n"); + closeit(); } /************************************************************/ /* Setup code */ /************************************************************/ -static -void -mkfile(const char *name) -{ - int fd, i, r; - static const char message[] = "The turtle moves!\n"; - char buf[32*sizeof(message)+1]; +static void mkfile(const char *name) { + int fd, i, r; + static const char message[] = "The turtle moves!\n"; + char buf[32 * sizeof(message) + 1]; - buf[0]=0; - for (i=0; i<32; i++) { - strcat(buf, message); - } + buf[0] = 0; + for (i = 0; i < 32; i++) { + strcat(buf, message); + } - /* Use O_EXCL, because we know the file shouldn't already be there */ - fd = open(name, O_WRONLY|O_CREAT|O_EXCL, 0664); - if (fd<0) { - err(1, "%s: create", name); - } + /* Use O_EXCL, because we know the file shouldn't already be there */ + fd = open(name, O_WRONLY | O_CREAT | O_EXCL, 0664); + if (fd < 0) { + err(1, "%s: create", name); + } - r = write(fd, buf, strlen(buf)); - if (r<0) { - err(1, "%s: write", name); - } - if ((unsigned)r != strlen(buf)) { - errx(1, "%s: short write (%d bytes)", name, r); - } + r = write(fd, buf, strlen(buf)); + if (r < 0) { + err(1, "%s: write", name); + } + if ((unsigned)r != strlen(buf)) { + errx(1, "%s: short write (%d bytes)", name, r); + } - if (close(fd)<0) { - err(1, "%s: close", name); - } + if (close(fd) < 0) { + err(1, "%s: close", name); + } } -static -void -setup(void) -{ - int i; +static void setup(void) { + int i; - printf("Making directory %s...\n", TESTDIR); + printf("Making directory %s...\n", TESTDIR); - /* Create a directory */ - if (mkdir(TESTDIR, 0775)<0) { - err(1, "%s: mkdir", TESTDIR); - } + /* Create a directory */ + if (mkdir(TESTDIR, 0775) < 0) { + err(1, "%s: mkdir", TESTDIR); + } - /* Switch to it */ - if (chdir(TESTDIR)<0) { - err(1, "%s: chdir", TESTDIR); - } + /* Switch to it */ + if (chdir(TESTDIR) < 0) { + err(1, "%s: chdir", TESTDIR); + } - printf("Making some files...\n"); + printf("Making some files...\n"); - /* Populate it */ - for (i=0; testfiles[i].name; i++) { - if (testfiles[i].make_it) { - mkfile(testfiles[i].name); - } - testfiles[i].pos = -1; - } + /* Populate it */ + for (i = 0; testfiles[i].name; i++) { + if (testfiles[i].make_it) { + mkfile(testfiles[i].name); + } + testfiles[i].pos = -1; + } } -static -void -cleanup(void) -{ - int i; +static void cleanup(void) { + int i; - printf("Cleaning up...\n"); + printf("Cleaning up...\n"); - /* Remove the files */ - for (i=0; testfiles[i].name; i++) { - if (testfiles[i].make_it) { - if (remove(testfiles[i].name)<0) { - err(1, "%s: remove", testfiles[i].name); - } - } - } + /* Remove the files */ + for (i = 0; testfiles[i].name; i++) { + if (testfiles[i].make_it) { + if (remove(testfiles[i].name) < 0) { + err(1, "%s: remove", testfiles[i].name); + } + } + } - /* Leave the dir */ - if (chdir("..")<0) { - err(1, "..: chdir"); - } + /* Leave the dir */ + if (chdir("..") < 0) { + err(1, "..: chdir"); + } - /* Remove the dir */ - if (rmdir(TESTDIR)<0) { - err(1, "%s: rmdir", TESTDIR); - } + /* Remove the dir */ + if (rmdir(TESTDIR) < 0) { + err(1, "%s: rmdir", TESTDIR); + } } +int main(void) { + setup(); -int -main(void) -{ - setup(); + /* Do the whole thing twice */ + dotest(); + dotest(); - /* Do the whole thing twice */ - dotest(); - dotest(); - - cleanup(); - return 0; + cleanup(); + return 0; } diff --git a/userland/testbin/dirtest/dirtest.c b/userland/testbin/dirtest/dirtest.c index 692506d..9b517ae 100644 --- a/userland/testbin/dirtest/dirtest.c +++ b/userland/testbin/dirtest/dirtest.c @@ -46,41 +46,38 @@ #include #include -#define MAXLEVELS 5 +#define MAXLEVELS 5 -int -main(void) -{ - int i; - const char *onename = "testdir"; - char dirname[512]; +int main(void) { + int i; + const char *onename = "testdir"; + char dirname[512]; - strcpy(dirname, onename); + strcpy(dirname, onename); - for (i=0; i #include @@ -57,50 +57,45 @@ static char buffer[SectorSize + 1]; -static -void -check_buffer(void) -{ - int i; - char ch = buffer[0]; +static void check_buffer(void) { + int i; + char ch = buffer[0]; - for (i = 1; i < SectorSize + 1; i++) { - if (buffer[i] != ch) { - errx(1, "Read error: %s", buffer); - } - } + for (i = 1; i < SectorSize + 1; i++) { + if (buffer[i] != ch) { + errx(1, "Read error: %s", buffer); + } + } - putchar(ch); + putchar(ch); } -void -subproc_read(void) -{ - int fd; - int i, res; +void subproc_read(void) { + int fd; + int i, res; - printf("File Reader starting ...\n\n"); + printf("File Reader starting ...\n\n"); - fd = open(FNAME, O_RDONLY); - if (fd < 0) { - err(1, "%s: open", FNAME); - } + fd = open(FNAME, O_RDONLY); + if (fd < 0) { + err(1, "%s: open", FNAME); + } - for (i=0; i #include "f_hdr.h" -#define SECTOR_SIZE 512 +#define SECTOR_SIZE 512 - -#define BUFFER_SIZE (2 * SECTOR_SIZE + 1) +#define BUFFER_SIZE (2 * SECTOR_SIZE + 1) #define BIGFILE_SIZE (270 * BUFFER_SIZE) #define BIGFILE_NAME "large-f" @@ -60,289 +59,262 @@ char fbuffer[BUFFER_SIZE]; char ibuffer[32]; +#define DIR_DEPTH 8 +#define DIR_NAME "/t" +#define DIRFILE_NAME "a" -#define DIR_DEPTH 8 -#define DIR_NAME "/t" -#define DIRFILE_NAME "a" +#define FNAME "f-testfile" +#define TMULT 50 +#define FSIZE ((SECTOR_SIZE + 1) * TMULT) - -#define FNAME "f-testfile" -#define TMULT 50 -#define FSIZE ((SECTOR_SIZE + 1) * TMULT) - -#define READCHAR 'r' -#define WRITECHAR 'w' +#define READCHAR 'r' +#define WRITECHAR 'w' char cbuffer[SECTOR_SIZE + 1]; - /* =================================================== */ -static -pid_t -forkoff(void (*func)(void)) -{ - pid_t pid = fork(); - switch (pid) { - case -1: - warn("fork"); - return -1; - case 0: - func(); - _exit(0); - default: break; - } - return pid; +static pid_t forkoff(void (*func)(void)) { + pid_t pid = fork(); + switch (pid) { + case -1: + warn("fork"); + return -1; + case 0: + func(); + _exit(0); + default: + break; + } + return pid; } -static -void -dowait(int pid) -{ - int status; +static void dowait(int pid) { + int status; - if (waitpid(pid, &status, 0)<0) { - warn("waitpid for %d", pid); - } - else if (WIFSIGNALED(status)) { - warnx("pid %d: signal %d", pid, WTERMSIG(status)); - } - else if (WEXITSTATUS(status) != 0) { - warnx("pid %d: exit %d", pid, WEXITSTATUS(status)); - } + if (waitpid(pid, &status, 0) < 0) { + warn("waitpid for %d", pid); + } else if (WIFSIGNALED(status)) { + warnx("pid %d: signal %d", pid, WTERMSIG(status)); + } else if (WEXITSTATUS(status) != 0) { + warnx("pid %d: exit %d", pid, WEXITSTATUS(status)); + } } /* =================================================== */ -static -void -big_file(int size) -{ - int i, j, fileid; +static void big_file(int size) { + int i, j, fileid; - printf("[BIGFILE] test starting :\n"); - printf("\tCreating a file of size: %d\n", size); + printf("[BIGFILE] test starting :\n"); + printf("\tCreating a file of size: %d\n", size); - fileid = open(BIGFILE_NAME, O_WRONLY|O_CREAT|O_TRUNC, 0664); - if (fileid < 0) { - err(1, "[BIGFILE]: %s: open for write", BIGFILE_NAME); - } + fileid = open(BIGFILE_NAME, O_WRONLY | O_CREAT | O_TRUNC, 0664); + if (fileid < 0) { + err(1, "[BIGFILE]: %s: open for write", BIGFILE_NAME); + } - for(i = 0; i < BUFFER_SIZE; i++) { - fbuffer[i] = LETTER(i); - } + for (i = 0; i < BUFFER_SIZE; i++) { + fbuffer[i] = LETTER(i); + } - printf("\tWriting to file.\n"); - for (i = 0; i < size; i += BUFFER_SIZE) { - write(fileid, fbuffer, BUFFER_SIZE); + printf("\tWriting to file.\n"); + for (i = 0; i < size; i += BUFFER_SIZE) { + write(fileid, fbuffer, BUFFER_SIZE); - if (!(i % (10 * BUFFER_SIZE))) { - printf("\rBW : %d", i); - } - } + if (!(i % (10 * BUFFER_SIZE))) { + printf("\rBW : %d", i); + } + } - printf("\n\tReading from file.\n"); - close(fileid); + printf("\n\tReading from file.\n"); + close(fileid); - fileid = open(BIGFILE_NAME, O_RDONLY); - if (fileid < 0) { - err(1, "[BIGFILE]: %s: open for read", BIGFILE_NAME); - } + fileid = open(BIGFILE_NAME, O_RDONLY); + if (fileid < 0) { + err(1, "[BIGFILE]: %s: open for read", BIGFILE_NAME); + } - for (i = 0; i < size; i += BUFFER_SIZE) { - j = read(fileid, fbuffer, BUFFER_SIZE); - if (j<0) { - err(1, "[BIGFILE]: read"); - } - if (j != BUFFER_SIZE) { - errx(1, "[BIGFILE]: read: only %d bytes", j); - } - } + for (i = 0; i < size; i += BUFFER_SIZE) { + j = read(fileid, fbuffer, BUFFER_SIZE); + if (j < 0) { + err(1, "[BIGFILE]: read"); + } + if (j != BUFFER_SIZE) { + errx(1, "[BIGFILE]: read: only %d bytes", j); + } + } - if (!(i % (10 * BUFFER_SIZE))) { - printf("\rBR : %d", i); - } + if (!(i % (10 * BUFFER_SIZE))) { + printf("\rBR : %d", i); + } - /* Check to see that the data is consistent : */ - for (j = 0; j < BUFFER_SIZE; j++) { - if (fbuffer[j] != LETTER(j)) { - errx(1, "[BIGFILE] : Failed read check : " - "inconsistent data read: %d", i+j); - } - } + /* Check to see that the data is consistent : */ + for (j = 0; j < BUFFER_SIZE; j++) { + if (fbuffer[j] != LETTER(j)) { + errx(1, + "[BIGFILE] : Failed read check : " + "inconsistent data read: %d", + i + j); + } + } + close(fileid); + if (remove(BIGFILE_NAME)) { + err(1, "[BIGFILE]: %s: remove", BIGFILE_NAME); + } - close(fileid); - if (remove(BIGFILE_NAME)) { - err(1, "[BIGFILE]: %s: remove", BIGFILE_NAME); - } - - printf("\n[BIGFILE] : Success!\n"); + printf("\n[BIGFILE] : Success!\n"); } /* =================================================== */ -static -void -concur(void) -{ - int i, fd; - int r1, r2, w1; +static void concur(void) { + int i, fd; + int r1, r2, w1; - printf("Spawning 2 readers, 1 writer.\n"); + printf("Spawning 2 readers, 1 writer.\n"); + fd = open(FNAME, O_WRONLY | O_CREAT | O_TRUNC, 0664); + if (fd < 0) { + err(1, "[CONCUR]: %s: open", FNAME); + } - fd = open(FNAME, O_WRONLY|O_CREAT|O_TRUNC, 0664); - if (fd < 0) { - err(1, "[CONCUR]: %s: open", FNAME); - } + printf("Initializing test file: "); - printf("Initializing test file: "); + for (i = 0; i < SECTOR_SIZE + 1; i++) { + cbuffer[i] = READCHAR; + } - for (i = 0; i < SECTOR_SIZE + 1; i++) { - cbuffer[i] = READCHAR; - } + for (i = 0; i < TMULT; i++) { + write(fd, cbuffer, SECTOR_SIZE + 1); + } - for (i = 0; i < TMULT; i++) { - write(fd, cbuffer, SECTOR_SIZE + 1); - } + close(fd); + printf("Done initializing. Starting processes...\n"); - close(fd); + r1 = forkoff(subproc_read); + w1 = forkoff(subproc_write); + r2 = forkoff(subproc_read); - printf("Done initializing. Starting processes...\n"); + printf("Waiting for processes.\n"); - r1 = forkoff(subproc_read); - w1 = forkoff(subproc_write); - r2 = forkoff(subproc_read); + dowait(r1); + dowait(r2); + dowait(w1); - printf("Waiting for processes.\n"); + if (remove(FNAME)) { + err(1, "[CONCUR]: %s: remove", FNAME); + } - dowait(r1); - dowait(r2); - dowait(w1); - - if (remove(FNAME)) { - err(1, "[CONCUR]: %s: remove", FNAME); - } - - printf("[CONCUR] Done!\n"); + printf("[CONCUR] Done!\n"); } /* =================================================== */ -static -void -dir_test(int depth) -{ - int i, fd; - char tmp[] = DIR_NAME; - char fmp[] = DIRFILE_NAME; - char dirname[64]; +static void dir_test(int depth) { + int i, fd; + char tmp[] = DIR_NAME; + char fmp[] = DIRFILE_NAME; + char dirname[64]; - strcpy(dirname, "."); + strcpy(dirname, "."); - for (i = 0; i < depth; i++) { - strcat(dirname, tmp); + for (i = 0; i < depth; i++) { + strcat(dirname, tmp); - printf("\tCreating dir : %s\n", dirname); + printf("\tCreating dir : %s\n", dirname); - if (mkdir(dirname, 0775) < 0) { - err(1, "[DIRTEST]: %s: mkdir", dirname); - } + if (mkdir(dirname, 0775) < 0) { + err(1, "[DIRTEST]: %s: mkdir", dirname); + } - strcat(dirname, fmp); - printf("\tCreating file: %s\n", dirname); + strcat(dirname, fmp); + printf("\tCreating file: %s\n", dirname); - fd = open(dirname, O_WRONLY|O_CREAT|O_TRUNC, 0664); - if (fd<0) { - err(1, "[DIRTEST]: %s: open", dirname); - } + fd = open(dirname, O_WRONLY | O_CREAT | O_TRUNC, 0664); + if (fd < 0) { + err(1, "[DIRTEST]: %s: open", dirname); + } - dirname[strlen(dirname) - strlen(fmp)] = '\0'; - } + dirname[strlen(dirname) - strlen(fmp)] = '\0'; + } - printf("[DIRTEST] : Passed directory creation test.\n"); + printf("[DIRTEST] : Passed directory creation test.\n"); - for (i = 0; i < depth; i++) { - strcat(dirname, fmp); + for (i = 0; i < depth; i++) { + strcat(dirname, fmp); - printf("\tDeleting file: %s\n", dirname); + printf("\tDeleting file: %s\n", dirname); - if (remove(dirname)) { - err(1, "[DIRTEST]: %s: remove", dirname); - } + if (remove(dirname)) { + err(1, "[DIRTEST]: %s: remove", dirname); + } - dirname[strlen(dirname) - strlen(fmp)] = '\0'; - printf("\tRemoving dir : %s\n", dirname); + dirname[strlen(dirname) - strlen(fmp)] = '\0'; + printf("\tRemoving dir : %s\n", dirname); - if (rmdir(dirname)) { - err(1, "[DIRTEST]: %s: rmdir", dirname); - } + if (rmdir(dirname)) { + err(1, "[DIRTEST]: %s: rmdir", dirname); + } - dirname[strlen(dirname) - strlen(tmp)] = '\0'; - } + dirname[strlen(dirname) - strlen(tmp)] = '\0'; + } - printf("[DIRTEST] : Passed directory removal test.\n"); - printf("[DIRTEST] : Success!\n"); + printf("[DIRTEST] : Passed directory removal test.\n"); + printf("[DIRTEST] : Success!\n"); } /* =================================================== */ -#define RUNBIGFILE 0x1 -#define RUNDIRTEST 0x2 -#define RUNCONCUR 0x4 -#define RUNTHEMALL (RUNBIGFILE | RUNDIRTEST | RUNCONCUR) +#define RUNBIGFILE 0x1 +#define RUNDIRTEST 0x2 +#define RUNCONCUR 0x4 +#define RUNTHEMALL (RUNBIGFILE | RUNDIRTEST | RUNCONCUR) -int -main(int argc, char * argv[]) -{ - int tv = 0; +int main(int argc, char *argv[]) { + int tv = 0; - if (argc > 1) { - if (*argv[1]=='1') { - tv = RUNBIGFILE; - } - else if (*argv[1]=='2') { - tv = RUNDIRTEST; - } - else if (*argv[1]=='3') { - tv = RUNCONCUR; - } - } - else { - tv = RUNTHEMALL; - } + if (argc > 1) { + if (*argv[1] == '1') { + tv = RUNBIGFILE; + } else if (*argv[1] == '2') { + tv = RUNDIRTEST; + } else if (*argv[1] == '3') { + tv = RUNCONCUR; + } + } else { + tv = RUNTHEMALL; + } - if (tv & RUNBIGFILE) { - printf("[BIGFILE] : Run #1\n"); - big_file(BIGFILE_SIZE); - printf("[BIGFILE] : Run #2\n"); - big_file(BIGFILE_SIZE); - } + if (tv & RUNBIGFILE) { + printf("[BIGFILE] : Run #1\n"); + big_file(BIGFILE_SIZE); + printf("[BIGFILE] : Run #2\n"); + big_file(BIGFILE_SIZE); + } - if (tv & RUNDIRTEST) { - printf("[DIRTEST] : Run #1\n"); - dir_test(DIR_DEPTH); - printf("[DIRTEST] : Run #2\n"); - dir_test(DIR_DEPTH); - } + if (tv & RUNDIRTEST) { + printf("[DIRTEST] : Run #1\n"); + dir_test(DIR_DEPTH); + printf("[DIRTEST] : Run #2\n"); + dir_test(DIR_DEPTH); + } - if (tv & RUNCONCUR) { - printf("[CONCUR]\n"); - concur(); - } - return 0; + if (tv & RUNCONCUR) { + printf("[CONCUR]\n"); + concur(); + } + return 0; } - - diff --git a/userland/testbin/f_test/f_write.c b/userland/testbin/f_test/f_write.c index 8a466d8..d7a7562 100644 --- a/userland/testbin/f_test/f_write.c +++ b/userland/testbin/f_test/f_write.c @@ -41,14 +41,14 @@ * */ -#define SectorSize 512 +#define SectorSize 512 -#define TMULT 50 -#define FSIZE ((SectorSize + 1) * TMULT) +#define TMULT 50 +#define FSIZE ((SectorSize + 1) * TMULT) -#define FNAME "f-testfile" -#define READCHAR 'r' -#define WRITECHAR 'w' +#define FNAME "f-testfile" +#define READCHAR 'r' +#define WRITECHAR 'w' #include #include @@ -57,29 +57,27 @@ static char buffer[SectorSize + 1]; -void -subproc_write(void) -{ - int fd; - int i; +void subproc_write(void) { + int fd; + int i; - for (i=0; i < SectorSize + 1; i++) { - buffer[i] = WRITECHAR; - } + for (i = 0; i < SectorSize + 1; i++) { + buffer[i] = WRITECHAR; + } - printf("File Writer starting ...\n"); + printf("File Writer starting ...\n"); - fd = open(FNAME, O_WRONLY); - if (fd < 0) { - err(1, "%s: open", FNAME); - } + fd = open(FNAME, O_WRONLY); + if (fd < 0) { + err(1, "%s: open", FNAME); + } - for (i=0; i NUMSIZE) { - warnx("%s", txt); - errx(1, "Number too large"); - } - n->first = NUMSIZE - len; - strcpy(n->buf + n->first, txt); + len = strlen(txt); + if (len > NUMSIZE) { + warnx("%s", txt); + errx(1, "Number too large"); + } + n->first = NUMSIZE - len; + strcpy(n->buf + n->first, txt); #if 0 for (i=0; ifirst; i++) { n->buf[i] = '0'; } #endif - for (i=n->first; ibuf[i] < '0' || n->buf[i] > '9') { - warnx("%s", txt); - errx(1, "Number contained non-digit characters"); - } - } - assert(n->buf[NUMSIZE] == 0); - while (n->first < NUMSIZE && n->buf[n->first] == '0') { - n->first++; - } + for (i = n->first; i < NUMSIZE; i++) { + if (n->buf[i] < '0' || n->buf[i] > '9') { + warnx("%s", txt); + errx(1, "Number contained non-digit characters"); + } + } + assert(n->buf[NUMSIZE] == 0); + while (n->first < NUMSIZE && n->buf[n->first] == '0') { + n->first++; + } } -static -char * -number_get(struct number *n) -{ - size_t pos; +static char *number_get(struct number *n) { + size_t pos; - pos = n->first; - while (pos < NUMSIZE && n->buf[pos] == '0') { - pos++; - } - if (pos == NUMSIZE) { - pos--; - n->buf[pos] = '0'; - } - return &n->buf[pos]; + pos = n->first; + while (pos < NUMSIZE && n->buf[pos] == '0') { + pos++; + } + if (pos == NUMSIZE) { + pos--; + n->buf[pos] = '0'; + } + return &n->buf[pos]; } -static -void -finishcarry(struct number *r, const struct number *b, size_t pos, - unsigned carry) -{ - if (carry > 0 && b->first == 0) { - /* if b->first is 0, pos may now be 2^32-1 */ - errx(1, "Overflow"); - } - while (carry > 0) { - if (pos == 0) { - errx(1, "Overflow"); - } - r->buf[pos--] = carry % 10 + '0'; - carry = carry / 10; - } - r->first = pos + 1; +static void finishcarry(struct number *r, const struct number *b, size_t pos, + unsigned carry) { + if (carry > 0 && b->first == 0) { + /* if b->first is 0, pos may now be 2^32-1 */ + errx(1, "Overflow"); + } + while (carry > 0) { + if (pos == 0) { + errx(1, "Overflow"); + } + r->buf[pos--] = carry % 10 + '0'; + carry = carry / 10; + } + r->first = pos + 1; } -static -void -pluseq(struct number *r, const struct number *b) -{ - size_t pos; - unsigned an, bn, rn, carry; +static void pluseq(struct number *r, const struct number *b) { + size_t pos; + unsigned an, bn, rn, carry; - carry = 0; - for (pos = NUMSIZE; pos-- > b->first; ) { - an = pos < r->first ? 0 : r->buf[pos] - '0'; - bn = b->buf[pos] - '0'; - rn = an + bn + carry; - r->buf[pos] = rn % 10 + '0'; - carry = rn / 10; - } - finishcarry(r, b, pos, carry); + carry = 0; + for (pos = NUMSIZE; pos-- > b->first;) { + an = pos < r->first ? 0 : r->buf[pos] - '0'; + bn = b->buf[pos] - '0'; + rn = an + bn + carry; + r->buf[pos] = rn % 10 + '0'; + carry = rn / 10; + } + finishcarry(r, b, pos, carry); } -static -void -dec(struct number *r) -{ - size_t pos; +static void dec(struct number *r) { + size_t pos; - for (pos = NUMSIZE; pos-- > r->first; ) { - if (r->buf[pos] == '0') { - r->buf[pos] = '9'; - } - else { - r->buf[pos]--; - return; - } - } - /* This should really not happen. */ - errx(1, "Underflow"); + for (pos = NUMSIZE; pos-- > r->first;) { + if (r->buf[pos] == '0') { + r->buf[pos] = '9'; + } else { + r->buf[pos]--; + return; + } + } + /* This should really not happen. */ + errx(1, "Underflow"); } -static -void -multc(struct number *r, const struct number *a, unsigned bn, size_t offset) -{ - size_t pos; - unsigned an, rn, carry; +static void multc(struct number *r, const struct number *a, unsigned bn, + size_t offset) { + size_t pos; + unsigned an, rn, carry; - for (pos = NUMSIZE; pos-- > NUMSIZE - offset; ) { - r->buf[pos] = '0'; - } - carry = 0; - for (pos = NUMSIZE; pos-- > a->first; ) { - an = a->buf[pos] - '0'; - rn = an * bn + carry; - if (pos < offset) { - errx(1, "Overflow"); - } - r->buf[pos - offset] = rn % 10 + '0'; - carry = rn / 10; - } - if (carry > 0 && pos < offset) { - errx(1, "Overflow"); - } - finishcarry(r, a, pos - offset, carry); + for (pos = NUMSIZE; pos-- > NUMSIZE - offset;) { + r->buf[pos] = '0'; + } + carry = 0; + for (pos = NUMSIZE; pos-- > a->first;) { + an = a->buf[pos] - '0'; + rn = an * bn + carry; + if (pos < offset) { + errx(1, "Overflow"); + } + r->buf[pos - offset] = rn % 10 + '0'; + carry = rn / 10; + } + if (carry > 0 && pos < offset) { + errx(1, "Overflow"); + } + finishcarry(r, a, pos - offset, carry); } -static -void -mult(struct number *r, const struct number *a, const struct number *b) -{ - unsigned offset; - size_t apos; +static void mult(struct number *r, const struct number *a, + const struct number *b) { + unsigned offset; + size_t apos; - /* B should normally be the larger number */ - if (a->first < b->first) { - mult(r, b, a); - return; - } + /* B should normally be the larger number */ + if (a->first < b->first) { + mult(r, b, a); + return; + } - number_init(&scratch, "0"); - offset = 0; - for (apos = NUMSIZE; apos-- > a->first; ) { - multc(&scratch, b, a->buf[apos] - '0', offset); - pluseq(r, &scratch); - offset++; - } + number_init(&scratch, "0"); + offset = 0; + for (apos = NUMSIZE; apos-- > a->first;) { + multc(&scratch, b, a->buf[apos] - '0', offset); + pluseq(r, &scratch); + offset++; + } } //////////////////////////////////////////////////////////// // argv logic -static -void -self(const char *arg1, const char *arg2) -{ - const char *args[4]; +static void self(const char *arg1, const char *arg2) { + const char *args[4]; - args[0] = _PATH_SELF; - args[1] = arg1; - args[2] = arg2; - args[3] = NULL; - execv(_PATH_SELF, (char **)args); - err(1, "execv"); + args[0] = _PATH_SELF; + args[1] = arg1; + args[2] = arg2; + args[3] = NULL; + execv(_PATH_SELF, (char **)args); + err(1, "execv"); } static struct number n1, n2, multbuf; -int -main(int argc, char *argv[]) -{ - if (argc == 0) { - /* Assume we've just been run from the menu. */ - self("404", "1"); - } - else if (argc == 2) { - self(argv[1], "1"); - } - else if (argc == 3) { - if (!strcmp(argv[1], "1") || !strcmp(argv[1], "0")) { - printf("%s\n", argv[2]); - } - else { - number_init(&n1, argv[1]); - number_init(&n2, argv[2]); - number_init(&multbuf, "0"); - mult(&multbuf, &n1, &n2); - dec(&n1); - self(number_get(&n1), number_get(&multbuf)); - } - } - else { - warnx("Usage: factorial N"); - } - return 0; +int main(int argc, char *argv[]) { + if (argc == 0) { + /* Assume we've just been run from the menu. */ + self("404", "1"); + } else if (argc == 2) { + self(argv[1], "1"); + } else if (argc == 3) { + if (!strcmp(argv[1], "1") || !strcmp(argv[1], "0")) { + printf("%s\n", argv[2]); + } else { + number_init(&n1, argv[1]); + number_init(&n2, argv[2]); + number_init(&multbuf, "0"); + mult(&multbuf, &n1, &n2); + dec(&n1); + self(number_get(&n1), number_get(&multbuf)); + } + } else { + warnx("Usage: factorial N"); + } + return 0; } diff --git a/userland/testbin/farm/farm.c b/userland/testbin/farm/farm.c index e28d820..e42d37e 100644 --- a/userland/testbin/farm/farm.c +++ b/userland/testbin/farm/farm.c @@ -40,72 +40,52 @@ #include #include -static char *hargv[2] = { (char *)"hog", NULL }; -static char *cargv[3] = { (char *)"cat", (char *)"catfile", NULL }; +static char *hargv[2] = {(char *)"hog", NULL}; +static char *cargv[3] = {(char *)"cat", (char *)"catfile", NULL}; -#define MAXPROCS 6 +#define MAXPROCS 6 static int pids[MAXPROCS], npids; -static -void -spawnv(const char *prog, char **argv) -{ - int pid = fork(); - switch (pid) { - case -1: - err(1, "fork"); - case 0: - /* child */ - execv(prog, argv); - err(1, "%s", prog); - default: - /* parent */ - pids[npids++] = pid; - break; - } +static void spawnv(const char *prog, char **argv) { + int pid = fork(); + switch (pid) { + case -1: + err(1, "fork"); + case 0: + /* child */ + execv(prog, argv); + err(1, "%s", prog); + default: + /* parent */ + pids[npids++] = pid; + break; + } } -static -void -waitall(void) -{ - int i, status; - for (i=0; i -#define REALLY_BIG_ADDRESS 0x40000000 +#define REALLY_BIG_ADDRESS 0x40000000 -int -main(void) -{ - volatile int i; +int main(void) { + volatile int i; - printf("\nEntering the faulter program - I should die immediately\n"); - i = *(int *)REALLY_BIG_ADDRESS; + printf("\nEntering the faulter program - I should die immediately\n"); + i = *(int *)REALLY_BIG_ADDRESS; - // gcc 4.8 improperly demands this - (void)i; + // gcc 4.8 improperly demands this + (void)i; - printf("I didn't get killed! Program has a bug\n"); - return 0; + printf("I didn't get killed! Program has a bug\n"); + return 0; } diff --git a/userland/testbin/filetest/filetest.c b/userland/testbin/filetest/filetest.c index dc062ec..5e24529 100644 --- a/userland/testbin/filetest/filetest.c +++ b/userland/testbin/filetest/filetest.c @@ -43,66 +43,61 @@ #include #include -int -main(int argc, char *argv[]) -{ - static char writebuf[41] = "Twiddle dee dee, Twiddle dum dum.......\n"; - static char readbuf[41]; +int main(int argc, char *argv[]) { + static char writebuf[41] = "Twiddle dee dee, Twiddle dum dum.......\n"; + static char readbuf[41]; - const char *file; - int fd, rv; + const char *file; + int fd, rv; - if (argc == 0) { - warnx("No arguments - running on \"testfile\""); - file = "testfile"; - } - else if (argc == 2) { - file = argv[1]; - } - else { - errx(1, "Usage: filetest "); - } + if (argc == 0) { + warnx("No arguments - running on \"testfile\""); + file = "testfile"; + } else if (argc == 2) { + file = argv[1]; + } else { + errx(1, "Usage: filetest "); + } - fd = open(file, O_WRONLY|O_CREAT|O_TRUNC, 0664); - if (fd<0) { - err(1, "%s: open for write", file); - } + fd = open(file, O_WRONLY | O_CREAT | O_TRUNC, 0664); + if (fd < 0) { + err(1, "%s: open for write", file); + } + rv = write(fd, writebuf, 40); + if (rv < 0) { + err(1, "%s: write", file); + } - rv = write(fd, writebuf, 40); - if (rv<0) { - err(1, "%s: write", file); - } + rv = close(fd); + if (rv < 0) { + err(1, "%s: close (1st time)", file); + } - rv = close(fd); - if (rv<0) { - err(1, "%s: close (1st time)", file); - } + fd = open(file, O_RDONLY); + if (fd < 0) { + err(1, "%s: open for read", file); + } - fd = open(file, O_RDONLY); - if (fd<0) { - err(1, "%s: open for read", file); - } + rv = read(fd, readbuf, 40); + if (rv < 0) { + err(1, "%s: read", file); + } + rv = close(fd); + if (rv < 0) { + err(1, "%s: close (2nd time)", file); + } + /* ensure null termination */ + readbuf[40] = 0; - rv = read(fd, readbuf, 40); - if (rv<0) { - err(1, "%s: read", file); - } - rv = close(fd); - if (rv<0) { - err(1, "%s: close (2nd time)", file); - } - /* ensure null termination */ - readbuf[40] = 0; + if (strcmp(readbuf, writebuf)) { + errx(1, "Buffer data mismatch!"); + } - if (strcmp(readbuf, writebuf)) { - errx(1, "Buffer data mismatch!"); - } - - rv = remove(file); - if (rv<0) { - err(1, "%s: remove", file); - } - printf("Passed filetest.\n"); - return 0; + rv = remove(file); + if (rv < 0) { + err(1, "%s: remove", file); + } + printf("Passed filetest.\n"); + return 0; } diff --git a/userland/testbin/forkbomb/forkbomb.c b/userland/testbin/forkbomb/forkbomb.c index 6db265b..96e81a5 100644 --- a/userland/testbin/forkbomb/forkbomb.c +++ b/userland/testbin/forkbomb/forkbomb.c @@ -52,25 +52,24 @@ static volatile int pid; -int -main(void) -{ - int i; +int main(void) { + int i; - while (1) { - fork(); + while (1) { + fork(); - pid = getpid(); + pid = getpid(); - /* Make sure each fork has its own address space. */ - for (i=0; i<300; i++) { - volatile int seenpid; - seenpid = pid; - if (seenpid != getpid()) { - errx(1, "pid mismatch (%d, should be %d) " - "- your vm is broken!", - seenpid, getpid()); - } - } - } + /* Make sure each fork has its own address space. */ + for (i = 0; i < 300; i++) { + volatile int seenpid; + seenpid = pid; + if (seenpid != getpid()) { + errx(1, + "pid mismatch (%d, should be %d) " + "- your vm is broken!", + seenpid, getpid()); + } + } + } } diff --git a/userland/testbin/forktest/forktest.c b/userland/testbin/forktest/forktest.c index 46e5da2..a83b7a7 100644 --- a/userland/testbin/forktest/forktest.c +++ b/userland/testbin/forktest/forktest.c @@ -51,16 +51,13 @@ static volatile int mypid; /* * Helper function for fork that prints a warning on error. */ -static -int -dofork(void) -{ - int pid; - pid = fork(); - if (pid < 0) { - warn("fork"); - } - return pid; +static int dofork(void) { + int pid; + pid = fork(); + if (pid < 0) { + warn("fork"); + } + return pid; } /* @@ -68,24 +65,22 @@ dofork(void) * the pid into the data segment and read it back repeatedly, making * sure it's correct every time. */ -static -void -check(void) -{ - int i; +static void check(void) { + int i; - mypid = getpid(); + mypid = getpid(); - /* Make sure each fork has its own address space. */ - for (i=0; i<800; i++) { - volatile int seenpid; - seenpid = mypid; - if (seenpid != getpid()) { - errx(1, "pid mismatch (%d, should be %d) " - "- your vm is broken!", - seenpid, getpid()); - } - } + /* Make sure each fork has its own address space. */ + for (i = 0; i < 800; i++) { + volatile int seenpid; + seenpid = mypid; + if (seenpid != getpid()) { + errx(1, + "pid mismatch (%d, should be %d) " + "- your vm is broken!", + seenpid, getpid()); + } + } } /* @@ -97,121 +92,109 @@ check(void) * generated the current process; that means it's time to exit. Only * the parent of all the processes returns from the chain of dowaits. */ -static -void -dowait(int nowait, int pid) -{ - int x; +static void dowait(int nowait, int pid) { + int x; - if (pid<0) { - /* fork in question failed; just return */ - return; - } - if (pid==0) { - /* in the fork in question we were the child; exit */ - exit(0); - } + if (pid < 0) { + /* fork in question failed; just return */ + return; + } + if (pid == 0) { + /* in the fork in question we were the child; exit */ + exit(0); + } - if (!nowait) { - if (waitpid(pid, &x, 0)<0) { - warn("waitpid"); - } - else if (WIFSIGNALED(x)) { - warnx("pid %d: signal %d", pid, WTERMSIG(x)); - } - else if (WEXITSTATUS(x) != 0) { - warnx("pid %d: exit %d", pid, WEXITSTATUS(x)); - } - } + if (!nowait) { + if (waitpid(pid, &x, 0) < 0) { + warn("waitpid"); + } else if (WIFSIGNALED(x)) { + warnx("pid %d: signal %d", pid, WTERMSIG(x)); + } else if (WEXITSTATUS(x) != 0) { + warnx("pid %d: exit %d", pid, WEXITSTATUS(x)); + } + } } /* * Actually run the test. */ -static -void -test(int nowait) -{ - int pid0, pid1, pid2, pid3; - int depth = 0; +static void test(int nowait) { + int pid0, pid1, pid2, pid3; + int depth = 0; - /* - * Caution: This generates processes geometrically. - * - * It is unrolled to encourage gcc to registerize the pids, - * to prevent wait/exit problems if fork corrupts memory. - * - * Note: if the depth prints trigger and show that the depth - * is too small, the most likely explanation is that the fork - * child is returning from the write() inside putchar() - * instead of from fork() and thus skipping the depth++. This - * is a fairly common problem caused by races in the kernel - * fork code. - */ + /* + * Caution: This generates processes geometrically. + * + * It is unrolled to encourage gcc to registerize the pids, + * to prevent wait/exit problems if fork corrupts memory. + * + * Note: if the depth prints trigger and show that the depth + * is too small, the most likely explanation is that the fork + * child is returning from the write() inside putchar() + * instead of from fork() and thus skipping the depth++. This + * is a fairly common problem caused by races in the kernel + * fork code. + */ - pid0 = dofork(); - depth++; - putchar('A'); - if (depth != 1) { - warnx("depth %d, should be 1", depth); - } - check(); + pid0 = dofork(); + depth++; + putchar('A'); + if (depth != 1) { + warnx("depth %d, should be 1", depth); + } + check(); - pid1 = dofork(); - depth++; - putchar('B'); - if (depth != 2) { - warnx("depth %d, should be 2", depth); - } - check(); + pid1 = dofork(); + depth++; + putchar('B'); + if (depth != 2) { + warnx("depth %d, should be 2", depth); + } + check(); - pid2 = dofork(); - depth++; - putchar('C'); - if (depth != 3) { - warnx("depth %d, should be 3", depth); - } - check(); + pid2 = dofork(); + depth++; + putchar('C'); + if (depth != 3) { + warnx("depth %d, should be 3", depth); + } + check(); - pid3 = dofork(); - depth++; - putchar('D'); - if (depth != 4) { - warnx("depth %d, should be 4", depth); - } - check(); + pid3 = dofork(); + depth++; + putchar('D'); + if (depth != 4) { + warnx("depth %d, should be 4", depth); + } + check(); - /* - * These must be called in reverse order to avoid waiting - * improperly. - */ - dowait(nowait, pid3); - dowait(nowait, pid2); - dowait(nowait, pid1); - dowait(nowait, pid0); + /* + * These must be called in reverse order to avoid waiting + * improperly. + */ + dowait(nowait, pid3); + dowait(nowait, pid2); + dowait(nowait, pid1); + dowait(nowait, pid0); - putchar('\n'); + putchar('\n'); } -int -main(int argc, char *argv[]) -{ - static const char expected[] = - "|----------------------------|\n"; - int nowait=0; +int main(int argc, char *argv[]) { + static const char expected[] = "|----------------------------|\n"; + int nowait = 0; - if (argc==2 && !strcmp(argv[1], "-w")) { - nowait=1; - } - else if (argc!=1 && argc!=0) { - warnx("usage: forktest [-w]"); - return 1; - } - warnx("Starting. Expect this many:"); - write(STDERR_FILENO, expected, strlen(expected)); + if (argc == 2 && !strcmp(argv[1], "-w")) { + nowait = 1; + } else if (argc != 1 && argc != 0) { + warnx("usage: forktest [-w]"); + return 1; + } + warnx("Starting. Expect this many:"); + write(STDERR_FILENO, expected, strlen(expected)); - test(nowait); + test(nowait); - warnx("Complete."); - return 0; + warnx("Complete."); + return 0; } diff --git a/userland/testbin/frack/check.c b/userland/testbin/frack/check.c index fea6783..059a815 100644 --- a/userland/testbin/frack/check.c +++ b/userland/testbin/frack/check.c @@ -64,126 +64,126 @@ */ enum fschanges { - FC_NEWFS, /* create the volume */ - FC_TRUNCATE, /* truncate a file */ - FC_WRITE, /* write to a file */ - FC_CREAT, /* create a file */ - FC_MKDIR, /* create a directory */ - FC_RMDIR, /* remove a directory */ - FC_UNLINK, /* remove a file */ - FC_LINK, /* hardlink a file */ - FC_RENAMEFILE, /* rename a file */ - FC_RENAMEDIR, /* rename a directory */ + FC_NEWFS, /* create the volume */ + FC_TRUNCATE, /* truncate a file */ + FC_WRITE, /* write to a file */ + FC_CREAT, /* create a file */ + FC_MKDIR, /* create a directory */ + FC_RMDIR, /* remove a directory */ + FC_UNLINK, /* remove a file */ + FC_LINK, /* hardlink a file */ + FC_RENAMEFILE, /* rename a file */ + FC_RENAMEDIR, /* rename a directory */ }; struct fschange { - /* all changes are kept in order on a doubly linked list */ - struct fschange *prev; - struct fschange *next; + /* all changes are kept in order on a doubly linked list */ + struct fschange *prev; + struct fschange *next; - /* version number for this change */ - unsigned version; + /* version number for this change */ + unsigned version; - /* whether this change reflects a partially committed operation */ - int partial; + /* whether this change reflects a partially committed operation */ + int partial; - /* the change type, parameters, and metadata */ - enum fschanges type; - union { - struct { - /* object id of the root directory */ - unsigned rootdirnum; - } fc_newfs; - struct { - /* cached: previous change affecting this file */ - struct fschange *prev_thisfile; - /* truncate params: file oid and new length */ - unsigned file; - off_t len; - } fc_truncate; - struct { - /* cached: previous change affecting this file */ - struct fschange *prev_thisfile; - /* write params: file oid, position, length */ - unsigned file; - off_t pos; - off_t len; - /* size of file before the write */ - off_t oldfilesize; - /* key for generating the write contents */ - unsigned code; - unsigned seq; - } fc_write; - struct { - /* cached: previous change affecting containing dir */ - struct fschange *prev_thisdir; - /* creat params: containing dir oid, name, new oid */ - unsigned dir; - unsigned name; - unsigned newfile; - } fc_creat; - struct { - /* cached: previous change affecting containing dir */ - struct fschange *prev_thisdir; - /* mkdir params: containing dir oid, name, new oid */ - unsigned dir; - unsigned name; - unsigned newdir; - } fc_mkdir; - struct { - /* cached: previous change affecting either dir */ - struct fschange *prev_thisdir; - struct fschange *prev_victimdir; - /* rmdir params */ - unsigned dir; - unsigned name; - unsigned victimdir; - } fc_rmdir; - struct { - /* cached: previous change affecting either object */ - struct fschange *prev_thisdir; - struct fschange *prev_victimfile; - /* unlink params */ - unsigned dir; - unsigned name; - unsigned victimfile; - } fc_unlink; - struct { - /* cached: previous change affecting each object */ - struct fschange *prev_fromdir; - struct fschange *prev_todir; - struct fschange *prev_thisfile; - /* link params */ - unsigned fromdir; - unsigned fromname; - unsigned todir; - unsigned toname; - unsigned file; - } fc_link; - struct { - /* cached: previous change affecting each object */ - struct fschange *prev_fromdir; - struct fschange *prev_todir; - struct fschange *prev_movedfile; - /* rename params */ - unsigned fromdir; - unsigned fromname; - unsigned todir; - unsigned toname; - unsigned movedfile; - } fc_renamefile; - struct { - /* cached: previous change affecting each object */ - struct fschange *prev_fromdir; - struct fschange *prev_todir; - struct fschange *prev_moveddir; - /* rename params */ - unsigned fromdir; - unsigned fromname; - unsigned todir; - unsigned toname; - unsigned moveddir; - } fc_renamedir; - }; + /* the change type, parameters, and metadata */ + enum fschanges type; + union { + struct { + /* object id of the root directory */ + unsigned rootdirnum; + } fc_newfs; + struct { + /* cached: previous change affecting this file */ + struct fschange *prev_thisfile; + /* truncate params: file oid and new length */ + unsigned file; + off_t len; + } fc_truncate; + struct { + /* cached: previous change affecting this file */ + struct fschange *prev_thisfile; + /* write params: file oid, position, length */ + unsigned file; + off_t pos; + off_t len; + /* size of file before the write */ + off_t oldfilesize; + /* key for generating the write contents */ + unsigned code; + unsigned seq; + } fc_write; + struct { + /* cached: previous change affecting containing dir */ + struct fschange *prev_thisdir; + /* creat params: containing dir oid, name, new oid */ + unsigned dir; + unsigned name; + unsigned newfile; + } fc_creat; + struct { + /* cached: previous change affecting containing dir */ + struct fschange *prev_thisdir; + /* mkdir params: containing dir oid, name, new oid */ + unsigned dir; + unsigned name; + unsigned newdir; + } fc_mkdir; + struct { + /* cached: previous change affecting either dir */ + struct fschange *prev_thisdir; + struct fschange *prev_victimdir; + /* rmdir params */ + unsigned dir; + unsigned name; + unsigned victimdir; + } fc_rmdir; + struct { + /* cached: previous change affecting either object */ + struct fschange *prev_thisdir; + struct fschange *prev_victimfile; + /* unlink params */ + unsigned dir; + unsigned name; + unsigned victimfile; + } fc_unlink; + struct { + /* cached: previous change affecting each object */ + struct fschange *prev_fromdir; + struct fschange *prev_todir; + struct fschange *prev_thisfile; + /* link params */ + unsigned fromdir; + unsigned fromname; + unsigned todir; + unsigned toname; + unsigned file; + } fc_link; + struct { + /* cached: previous change affecting each object */ + struct fschange *prev_fromdir; + struct fschange *prev_todir; + struct fschange *prev_movedfile; + /* rename params */ + unsigned fromdir; + unsigned fromname; + unsigned todir; + unsigned toname; + unsigned movedfile; + } fc_renamefile; + struct { + /* cached: previous change affecting each object */ + struct fschange *prev_fromdir; + struct fschange *prev_todir; + struct fschange *prev_moveddir; + /* rename params */ + unsigned fromdir; + unsigned fromname; + unsigned todir; + unsigned toname; + unsigned moveddir; + } fc_renamedir; + }; }; /* @@ -199,25 +199,25 @@ struct fschange { */ struct fsdirent { - unsigned name; - struct fsobject *obj; - struct fsdirent *next; + unsigned name; + struct fsobject *obj; + struct fsdirent *next; }; struct fsobject { - unsigned isdir; - unsigned refcount; - union { - struct { - unsigned identity; - off_t len; - } obj_file; - struct { - unsigned identity; - struct fsdirent *entries; - struct fsobject *parent; - } obj_dir; - }; + unsigned isdir; + unsigned refcount; + union { + struct { + unsigned identity; + off_t len; + } obj_file; + struct { + unsigned identity; + struct fsdirent *entries; + struct fsobject *parent; + } obj_dir; + }; }; //////////////////////////////////////////////////////////// @@ -228,34 +228,19 @@ struct fsobject { * unnecessary lossage on kernels where malloc doesn't work. */ -#define MAXCHANGES 16384 -#define MAXOBJECTS 16384 -#define MAXDIRENTS 16384 +#define MAXCHANGES 16384 +#define MAXOBJECTS 16384 +#define MAXDIRENTS 16384 DECLPOOL(fschange, MAXCHANGES); DECLPOOL(fsobject, MAXOBJECTS); DECLPOOL(fsdirent, MAXDIRENTS); -static -struct fschange * -getchange(void) -{ - return POOLALLOC(fschange); -} +static struct fschange *getchange(void) { return POOLALLOC(fschange); } -static -struct fsobject * -getobject(void) -{ - return POOLALLOC(fsobject); -} +static struct fsobject *getobject(void) { return POOLALLOC(fsobject); } -static -struct fsdirent * -getdirent(void) -{ - return POOLALLOC(fsdirent); -} +static struct fsdirent *getdirent(void) { return POOLALLOC(fsdirent); } #if 0 static @@ -266,307 +251,251 @@ putchange(struct fschange *fc) } #endif -static -void -putobject(struct fsobject *obj) -{ - POOLFREE(fsobject, obj); -} +static void putobject(struct fsobject *obj) { POOLFREE(fsobject, obj); } -static -void -putdirent(struct fsdirent *dirent) -{ - POOLFREE(fsdirent, dirent); -} +static void putdirent(struct fsdirent *dirent) { POOLFREE(fsdirent, dirent); } //////////////////////////////////////////////////////////// // record constructors for change records -static -struct fschange * -fc_create(enum fschanges type) -{ - struct fschange *fc; +static struct fschange *fc_create(enum fschanges type) { + struct fschange *fc; - fc = getchange(); - fc->prev = fc->next = NULL; - fc->version = 0; - fc->partial = 0; - fc->type = type; - return fc; + fc = getchange(); + fc->prev = fc->next = NULL; + fc->version = 0; + fc->partial = 0; + fc->type = type; + return fc; } -static -struct fschange * -fc_create_newfs(unsigned rootdirnum) -{ - struct fschange *fc; +static struct fschange *fc_create_newfs(unsigned rootdirnum) { + struct fschange *fc; - fc = fc_create(FC_NEWFS); - fc->fc_newfs.rootdirnum = rootdirnum; - return fc; + fc = fc_create(FC_NEWFS); + fc->fc_newfs.rootdirnum = rootdirnum; + return fc; } -static -struct fschange * -fc_create_truncate(struct fschange *prev_thisfile, unsigned file, off_t len) -{ - struct fschange *fc; +static struct fschange *fc_create_truncate(struct fschange *prev_thisfile, + unsigned file, off_t len) { + struct fschange *fc; - fc = fc_create(FC_TRUNCATE); - fc->fc_truncate.prev_thisfile = prev_thisfile; - fc->fc_truncate.file = file; - fc->fc_truncate.len = len; - return fc; + fc = fc_create(FC_TRUNCATE); + fc->fc_truncate.prev_thisfile = prev_thisfile; + fc->fc_truncate.file = file; + fc->fc_truncate.len = len; + return fc; } -static -struct fschange * -fc_create_write(struct fschange *prev_thisfile, unsigned file, - off_t pos, off_t len, off_t oldfilesize, - unsigned code, unsigned seq) -{ - struct fschange *fc; +static struct fschange *fc_create_write(struct fschange *prev_thisfile, + unsigned file, off_t pos, off_t len, + off_t oldfilesize, unsigned code, + unsigned seq) { + struct fschange *fc; - fc = fc_create(FC_WRITE); - fc->fc_write.prev_thisfile = prev_thisfile; - fc->fc_write.file = file; - fc->fc_write.pos = pos; - fc->fc_write.len = len; - fc->fc_write.oldfilesize = oldfilesize; - fc->fc_write.code = code; - fc->fc_write.seq = seq; - return fc; + fc = fc_create(FC_WRITE); + fc->fc_write.prev_thisfile = prev_thisfile; + fc->fc_write.file = file; + fc->fc_write.pos = pos; + fc->fc_write.len = len; + fc->fc_write.oldfilesize = oldfilesize; + fc->fc_write.code = code; + fc->fc_write.seq = seq; + return fc; } -static -struct fschange * -fc_create_creat(struct fschange *prev_thisdir, - unsigned dir, unsigned name, unsigned newfile) -{ - struct fschange *mdc; +static struct fschange *fc_create_creat(struct fschange *prev_thisdir, + unsigned dir, unsigned name, + unsigned newfile) { + struct fschange *mdc; - mdc = fc_create(FC_CREAT); - mdc->fc_creat.prev_thisdir = prev_thisdir; - mdc->fc_creat.dir = dir; - mdc->fc_creat.name = name; - mdc->fc_creat.newfile = newfile; - return mdc; + mdc = fc_create(FC_CREAT); + mdc->fc_creat.prev_thisdir = prev_thisdir; + mdc->fc_creat.dir = dir; + mdc->fc_creat.name = name; + mdc->fc_creat.newfile = newfile; + return mdc; } -static -struct fschange * -fc_create_mkdir(struct fschange *prev_thisdir, - unsigned dir, unsigned name, unsigned newdir) -{ - struct fschange *mdc; +static struct fschange *fc_create_mkdir(struct fschange *prev_thisdir, + unsigned dir, unsigned name, + unsigned newdir) { + struct fschange *mdc; - mdc = fc_create(FC_MKDIR); - mdc->fc_mkdir.prev_thisdir = prev_thisdir; - mdc->fc_mkdir.dir = dir; - mdc->fc_mkdir.name = name; - mdc->fc_mkdir.newdir = newdir; - return mdc; + mdc = fc_create(FC_MKDIR); + mdc->fc_mkdir.prev_thisdir = prev_thisdir; + mdc->fc_mkdir.dir = dir; + mdc->fc_mkdir.name = name; + mdc->fc_mkdir.newdir = newdir; + return mdc; } -static -struct fschange * -fc_create_rmdir(struct fschange *prev_thisdir, struct fschange *prev_victimdir, - unsigned dir, unsigned name, unsigned victimdir) -{ - struct fschange *mdc; +static struct fschange *fc_create_rmdir(struct fschange *prev_thisdir, + struct fschange *prev_victimdir, + unsigned dir, unsigned name, + unsigned victimdir) { + struct fschange *mdc; - mdc = fc_create(FC_RMDIR); - mdc->fc_rmdir.prev_thisdir = prev_thisdir; - mdc->fc_rmdir.prev_victimdir = prev_victimdir; - mdc->fc_rmdir.dir = dir; - mdc->fc_rmdir.name = name; - mdc->fc_rmdir.victimdir = victimdir; - return mdc; + mdc = fc_create(FC_RMDIR); + mdc->fc_rmdir.prev_thisdir = prev_thisdir; + mdc->fc_rmdir.prev_victimdir = prev_victimdir; + mdc->fc_rmdir.dir = dir; + mdc->fc_rmdir.name = name; + mdc->fc_rmdir.victimdir = victimdir; + return mdc; } -static -struct fschange * -fc_create_unlink(struct fschange *prev_thisdir, - struct fschange *prev_victimfile, - unsigned dir, unsigned name, unsigned victimfile) -{ - struct fschange *mdc; +static struct fschange *fc_create_unlink(struct fschange *prev_thisdir, + struct fschange *prev_victimfile, + unsigned dir, unsigned name, + unsigned victimfile) { + struct fschange *mdc; - mdc = fc_create(FC_UNLINK); - mdc->fc_unlink.prev_thisdir = prev_thisdir; - mdc->fc_unlink.prev_victimfile = prev_victimfile; - mdc->fc_unlink.dir = dir; - mdc->fc_unlink.name = name; - mdc->fc_unlink.victimfile = victimfile; - return mdc; + mdc = fc_create(FC_UNLINK); + mdc->fc_unlink.prev_thisdir = prev_thisdir; + mdc->fc_unlink.prev_victimfile = prev_victimfile; + mdc->fc_unlink.dir = dir; + mdc->fc_unlink.name = name; + mdc->fc_unlink.victimfile = victimfile; + return mdc; } -static -struct fschange * -fc_create_link(struct fschange *prev_fromdir, struct fschange *prev_todir, - struct fschange *prev_thisfile, - unsigned fromdir, unsigned fromname, - unsigned todir, unsigned toname, - unsigned file) -{ - struct fschange *mdc; +static struct fschange *fc_create_link(struct fschange *prev_fromdir, + struct fschange *prev_todir, + struct fschange *prev_thisfile, + unsigned fromdir, unsigned fromname, + unsigned todir, unsigned toname, + unsigned file) { + struct fschange *mdc; - mdc = fc_create(FC_LINK); - mdc->fc_link.prev_fromdir = prev_fromdir; - mdc->fc_link.prev_todir = prev_todir; - mdc->fc_link.prev_thisfile = prev_thisfile; - mdc->fc_link.fromdir = fromdir; - mdc->fc_link.fromname = fromname; - mdc->fc_link.todir = todir; - mdc->fc_link.toname = toname; - mdc->fc_link.file = file; - return mdc; + mdc = fc_create(FC_LINK); + mdc->fc_link.prev_fromdir = prev_fromdir; + mdc->fc_link.prev_todir = prev_todir; + mdc->fc_link.prev_thisfile = prev_thisfile; + mdc->fc_link.fromdir = fromdir; + mdc->fc_link.fromname = fromname; + mdc->fc_link.todir = todir; + mdc->fc_link.toname = toname; + mdc->fc_link.file = file; + return mdc; } -static -struct fschange * -fc_create_renamefile(struct fschange *prev_fromdir, - struct fschange *prev_todir, - struct fschange *prev_movedfile, - unsigned fromdir, unsigned fromname, - unsigned todir, unsigned toname, - unsigned movedfile) -{ - struct fschange *mdc; +static struct fschange * +fc_create_renamefile(struct fschange *prev_fromdir, struct fschange *prev_todir, + struct fschange *prev_movedfile, unsigned fromdir, + unsigned fromname, unsigned todir, unsigned toname, + unsigned movedfile) { + struct fschange *mdc; - mdc = fc_create(FC_RENAMEFILE); - mdc->fc_renamefile.prev_fromdir = prev_fromdir; - mdc->fc_renamefile.prev_todir = prev_todir; - mdc->fc_renamefile.prev_movedfile = prev_movedfile; - mdc->fc_renamefile.fromdir = fromdir; - mdc->fc_renamefile.fromname = fromname; - mdc->fc_renamefile.todir = todir; - mdc->fc_renamefile.toname = toname; - mdc->fc_renamefile.movedfile = movedfile; - return mdc; + mdc = fc_create(FC_RENAMEFILE); + mdc->fc_renamefile.prev_fromdir = prev_fromdir; + mdc->fc_renamefile.prev_todir = prev_todir; + mdc->fc_renamefile.prev_movedfile = prev_movedfile; + mdc->fc_renamefile.fromdir = fromdir; + mdc->fc_renamefile.fromname = fromname; + mdc->fc_renamefile.todir = todir; + mdc->fc_renamefile.toname = toname; + mdc->fc_renamefile.movedfile = movedfile; + return mdc; } -static -struct fschange * -fc_create_renamedir(struct fschange *prev_fromdir, - struct fschange *prev_todir, - struct fschange *prev_moveddir, - unsigned fromdir, unsigned fromname, - unsigned todir, unsigned toname, - unsigned moveddir) -{ - struct fschange *fc; +static struct fschange *fc_create_renamedir(struct fschange *prev_fromdir, + struct fschange *prev_todir, + struct fschange *prev_moveddir, + unsigned fromdir, unsigned fromname, + unsigned todir, unsigned toname, + unsigned moveddir) { + struct fschange *fc; - fc = fc_create(FC_RENAMEDIR); - fc->fc_renamedir.prev_fromdir = prev_fromdir; - fc->fc_renamedir.prev_todir = prev_todir; - fc->fc_renamedir.prev_moveddir = prev_moveddir; - fc->fc_renamedir.fromdir = fromdir; - fc->fc_renamedir.fromname = fromname; - fc->fc_renamedir.todir = todir; - fc->fc_renamedir.toname = toname; - fc->fc_renamedir.moveddir = moveddir; - return fc; + fc = fc_create(FC_RENAMEDIR); + fc->fc_renamedir.prev_fromdir = prev_fromdir; + fc->fc_renamedir.prev_todir = prev_todir; + fc->fc_renamedir.prev_moveddir = prev_moveddir; + fc->fc_renamedir.fromdir = fromdir; + fc->fc_renamedir.fromname = fromname; + fc->fc_renamedir.todir = todir; + fc->fc_renamedir.toname = toname; + fc->fc_renamedir.moveddir = moveddir; + return fc; } //////////////////////////////////////////////////////////// // constructors/destructors for current state objects -static -struct fsdirent * -fsdirent_create(unsigned name, struct fsobject *obj) -{ - struct fsdirent *ret; +static struct fsdirent *fsdirent_create(unsigned name, struct fsobject *obj) { + struct fsdirent *ret; - ret = getdirent(); - ret->name = name; - ret->obj = obj; - ret->next = NULL; - return ret; + ret = getdirent(); + ret->name = name; + ret->obj = obj; + ret->next = NULL; + return ret; } -static -void -fsdirent_destroy(struct fsdirent *de) -{ - assert(de->obj == NULL); - assert(de->next == NULL); - putdirent(de); +static void fsdirent_destroy(struct fsdirent *de) { + assert(de->obj == NULL); + assert(de->next == NULL); + putdirent(de); } -static -struct fsobject * -fsobject_create_file(unsigned id) -{ - struct fsobject *ret; +static struct fsobject *fsobject_create_file(unsigned id) { + struct fsobject *ret; - ret = getobject(); - ret->isdir = 0; - ret->refcount = 1; - ret->obj_file.identity = id; - ret->obj_file.len = 0; - return ret; + ret = getobject(); + ret->isdir = 0; + ret->refcount = 1; + ret->obj_file.identity = id; + ret->obj_file.len = 0; + return ret; } -static -struct fsobject * -fsobject_create_dir(unsigned id, struct fsobject *parent) -{ - struct fsobject *ret; +static struct fsobject *fsobject_create_dir(unsigned id, + struct fsobject *parent) { + struct fsobject *ret; - ret = getobject(); - ret->isdir = 1; - ret->refcount = 1; - ret->obj_dir.identity = id; - ret->obj_dir.entries = NULL; - ret->obj_dir.parent = parent; - return ret; + ret = getobject(); + ret->isdir = 1; + ret->refcount = 1; + ret->obj_dir.identity = id; + ret->obj_dir.entries = NULL; + ret->obj_dir.parent = parent; + return ret; } -static -void -fsobject_incref(struct fsobject *obj) -{ - assert(obj->refcount > 0); - obj->refcount++; - assert(obj->refcount > 0); +static void fsobject_incref(struct fsobject *obj) { + assert(obj->refcount > 0); + obj->refcount++; + assert(obj->refcount > 0); } -static -void -fsobject_decref(struct fsobject *obj) -{ - assert(obj->refcount > 0); - obj->refcount--; - if (obj->refcount > 0) { - return; - } +static void fsobject_decref(struct fsobject *obj) { + assert(obj->refcount > 0); + obj->refcount--; + if (obj->refcount > 0) { + return; + } - if (obj->isdir) { - assert(obj->obj_dir.entries == NULL); - } - putobject(obj); + if (obj->isdir) { + assert(obj->obj_dir.entries == NULL); + } + putobject(obj); } -static -void -fsobject_destroytree(struct fsobject *obj) -{ - struct fsdirent *de; +static void fsobject_destroytree(struct fsobject *obj) { + struct fsdirent *de; - if (obj->isdir) { - while (obj->obj_dir.entries != NULL) { - de = obj->obj_dir.entries; - obj->obj_dir.entries = de->next; - de->next = NULL; - fsobject_destroytree(de->obj); - de->obj = NULL; - fsdirent_destroy(de); - } - } - fsobject_decref(obj); + if (obj->isdir) { + while (obj->obj_dir.entries != NULL) { + de = obj->obj_dir.entries; + obj->obj_dir.entries = de->next; + de->next = NULL; + fsobject_destroytree(de->obj); + de->obj = NULL; + fsdirent_destroy(de); + } + } + fsobject_decref(obj); } //////////////////////////////////////////////////////////// @@ -575,17 +504,14 @@ fsobject_destroytree(struct fsobject *obj) /* * Bail out if something's broken. */ -static -void -die(const char *fmt, ...) -{ - char buf[256]; - va_list ap; +static void die(const char *fmt, ...) { + char buf[256]; + va_list ap; - va_start(ap, fmt); - vsnprintf(buf, sizeof(buf), fmt, ap); - va_end(ap); - errx(1, "Inconsistency: %s", buf); + va_start(ap, fmt); + vsnprintf(buf, sizeof(buf), fmt, ap); + va_end(ap); + errx(1, "Inconsistency: %s", buf); } #if 0 /* not used */ @@ -606,98 +532,89 @@ fsdirent_count(struct fsdirent *de) /* * Add an entry to a directory. */ -static -void -fsdir_add_entry(struct fsobject *dir, struct fsdirent *nde) -{ - struct fsdirent *ode; +static void fsdir_add_entry(struct fsobject *dir, struct fsdirent *nde) { + struct fsdirent *ode; - assert(dir->isdir); - for (ode = dir->obj_dir.entries; ode != NULL; ode = ode->next) { - if (ode->name == nde->name) { - die("In directory %u, %s already existed", - dir->obj_dir.identity, name_get(nde->name)); - } - } - nde->next = dir->obj_dir.entries; - dir->obj_dir.entries = nde; + assert(dir->isdir); + for (ode = dir->obj_dir.entries; ode != NULL; ode = ode->next) { + if (ode->name == nde->name) { + die("In directory %u, %s already existed", dir->obj_dir.identity, + name_get(nde->name)); + } + } + nde->next = dir->obj_dir.entries; + dir->obj_dir.entries = nde; } /* * Find an entry in a directory by name. If CROAK is set, bail out if * it's not there. */ -static -struct fsdirent * -fsdir_find_entry(struct fsobject *dir, unsigned name, int croak) -{ - struct fsdirent *de; +static struct fsdirent *fsdir_find_entry(struct fsobject *dir, unsigned name, + int croak) { + struct fsdirent *de; - assert(dir->isdir); - for (de = dir->obj_dir.entries; de != NULL; de = de->next) { - if (de->name == name) { - return de; - } - } - if (croak) { - die("In directory %u, did not find %s", - dir->obj_dir.identity, name_get(name)); - } - return NULL; + assert(dir->isdir); + for (de = dir->obj_dir.entries; de != NULL; de = de->next) { + if (de->name == name) { + return de; + } + } + if (croak) { + die("In directory %u, did not find %s", dir->obj_dir.identity, + name_get(name)); + } + return NULL; } /* * Remove an entry from a directory. */ -static -struct fsdirent * -fsdir_remove_entry(struct fsobject *dir, unsigned name) -{ - struct fsdirent *de, **prevptr; +static struct fsdirent *fsdir_remove_entry(struct fsobject *dir, + unsigned name) { + struct fsdirent *de, **prevptr; - assert(dir->isdir); - prevptr = &dir->obj_dir.entries; - for (de = *prevptr; de != NULL; prevptr = &de->next, de = *prevptr) { - if (de->name == name) { - *prevptr = de->next; - de->next = NULL; - return de; - } - } - die("In directory %u, did not find %s", - dir->obj_dir.identity, name_get(name)); - return NULL; + assert(dir->isdir); + prevptr = &dir->obj_dir.entries; + for (de = *prevptr; de != NULL; prevptr = &de->next, de = *prevptr) { + if (de->name == name) { + *prevptr = de->next; + de->next = NULL; + return de; + } + } + die("In directory %u, did not find %s", dir->obj_dir.identity, + name_get(name)); + return NULL; } //////////////////////////////////////////////////////////// // apply a change record to a current state -static -struct fsobject * -findsub(struct fsobject *obj, unsigned isdir, unsigned id) -{ - struct fsobject *ret; - struct fsdirent *de; - unsigned objid; +static struct fsobject *findsub(struct fsobject *obj, unsigned isdir, + unsigned id) { + struct fsobject *ret; + struct fsdirent *de; + unsigned objid; - /* Are we on the object we're looking for? */ - objid = obj->isdir ? obj->obj_dir.identity : obj->obj_file.identity; - if (obj->isdir == isdir && objid == id) { - return obj; - } + /* Are we on the object we're looking for? */ + objid = obj->isdir ? obj->obj_dir.identity : obj->obj_file.identity; + if (obj->isdir == isdir && objid == id) { + return obj; + } - /* If the object we're on isn't a dir, can't search any further */ - if (!obj->isdir) { - return NULL; - } + /* If the object we're on isn't a dir, can't search any further */ + if (!obj->isdir) { + return NULL; + } - for (de = obj->obj_dir.entries; de != NULL; de = de->next) { - ret = findsub(de->obj, isdir, id); - if (ret != NULL) { - return ret; - } - } - return NULL; + for (de = obj->obj_dir.entries; de != NULL; de = de->next) { + ret = findsub(de->obj, isdir, id); + if (ret != NULL) { + return ret; + } + } + return NULL; } #if 0 @@ -715,191 +632,178 @@ findfile(struct fsobject *rootdir, unsigned id) } #endif -static -struct fsobject * -findfile_maybe(struct fsobject *rootdir, unsigned id) -{ - return findsub(rootdir, 0/*!isdir*/, id); +static struct fsobject *findfile_maybe(struct fsobject *rootdir, unsigned id) { + return findsub(rootdir, 0 /*!isdir*/, id); } -static -struct fsobject * -finddir(struct fsobject *rootdir, unsigned id) -{ - struct fsobject *ret; +static struct fsobject *finddir(struct fsobject *rootdir, unsigned id) { + struct fsobject *ret; - ret = findsub(rootdir, 1/*isdir*/, id); - if (ret == NULL) { - die("Directory %u not found in current state", id); - } - return ret; + ret = findsub(rootdir, 1 /*isdir*/, id); + if (ret == NULL) { + die("Directory %u not found in current state", id); + } + return ret; } /* * Apply change CHANGE to the volume state encoded in/under ROOTDIR. */ -static -void -apply_change(struct fsobject *rootdir, struct fschange *change) -{ - struct fsobject *obj1, *obj2; - struct fsdirent *de; - off_t endpos; +static void apply_change(struct fsobject *rootdir, struct fschange *change) { + struct fsobject *obj1, *obj2; + struct fsdirent *de; + off_t endpos; - assert(rootdir->isdir); + assert(rootdir->isdir); - switch (change->type) { - case FC_NEWFS: - /* - * Creating the volume; crosscheck the root directory. - */ - assert(rootdir->isdir); - assert(rootdir->refcount == 1); - assert(rootdir->obj_dir.identity == - change->fc_newfs.rootdirnum); - assert(rootdir->obj_dir.entries == NULL); - assert(rootdir->obj_dir.parent == rootdir); - break; - case FC_TRUNCATE: - /* - * Truncate a file. (Only files, not directories.) - * - * Because truncates can and do get posted after a - * file is unlinked, we have to tolerate not finding - * the file. We don't model unlinked files, because - * they aren't visible and our goal is to check the - * visible/observable state. - */ - obj1 = findfile_maybe(rootdir, change->fc_truncate.file); - if (obj1 != NULL) { - obj1->obj_file.len = change->fc_truncate.len; - } - break; - case FC_WRITE: - /* - * Write to a file. (Only files, not directories.) - * All this actually does is update the file size if - * needed. - * - * We also have to tolerate writes to unlinked files. - */ - obj1 = findfile_maybe(rootdir, change->fc_write.file); - if (obj1 != NULL) { - endpos = change->fc_write.pos + change->fc_write.len; - if (obj1->obj_file.len < endpos) { - obj1->obj_file.len = endpos; - } - } - break; - case FC_CREAT: - /* - * Create a file. This creates a new object and a - * directory entry to hold it, then inserts the - * directory entry in the containing directory. - */ - obj1 = finddir(rootdir, change->fc_creat.dir); - obj2 = fsobject_create_file(change->fc_creat.newfile); - de = fsdirent_create(change->fc_creat.name, obj2); - fsdir_add_entry(obj1, de); - break; - case FC_MKDIR: - /* - * Create a directory. The same as creating a file, - * except the new object is a directory. - */ - obj1 = finddir(rootdir, change->fc_mkdir.dir); - obj2 = fsobject_create_dir(change->fc_mkdir.newdir, obj1); - de = fsdirent_create(change->fc_mkdir.name, obj2); - fsdir_add_entry(obj1, de); - break; - case FC_RMDIR: - /* - * Remove a directory. First take out the directory - * entry (by name); then examine the object found; - * then delete everything. - * - * XXX: why do these checks use assert vs. testing and - * calling die()? - */ - obj1 = finddir(rootdir, change->fc_rmdir.dir); - de = fsdir_remove_entry(obj1, change->fc_rmdir.name); - obj2 = de->obj; - de->obj = NULL; - assert(obj2->isdir); - assert(obj2->obj_dir.entries == NULL); - assert(obj2->obj_dir.identity == change->fc_rmdir.victimdir); - assert(obj2->obj_dir.parent == obj1); - fsdirent_destroy(de); - fsobject_decref(obj2); - break; - case FC_UNLINK: - /* - * Remove a file. Much the same as removing a directory. - */ - obj1 = finddir(rootdir, change->fc_unlink.dir); - de = fsdir_remove_entry(obj1, change->fc_unlink.name); - obj2 = de->obj; - de->obj = NULL; - assert(!obj2->isdir); - assert(obj2->obj_file.identity == - change->fc_unlink.victimfile); - fsdirent_destroy(de); - fsobject_decref(obj2); - break; - case FC_LINK: - /* - * Hard-link a file. - */ - obj1 = finddir(rootdir, change->fc_link.fromdir); - de = fsdir_find_entry(obj1, change->fc_link.fromname, 1); - obj2 = de->obj; - assert(!obj2->isdir); - assert(obj2->obj_file.identity == change->fc_link.file); - obj1 = finddir(rootdir, change->fc_link.todir); - fsobject_incref(obj2); - de = fsdirent_create(change->fc_link.toname, obj2); - fsdir_add_entry(obj1, de); - break; - case FC_RENAMEFILE: - /* - * Rename a file. XXX: this appears to do the wrong - * thing if you rename one file over another. - */ - obj1 = finddir(rootdir, change->fc_renamefile.fromdir); - de = fsdir_remove_entry(obj1, change->fc_renamefile.fromname); - obj2 = de->obj; - assert(!obj2->isdir); - assert(obj2->obj_file.identity == - change->fc_renamefile.movedfile); - obj1 = finddir(rootdir, change->fc_renamefile.todir); - de->name = change->fc_renamefile.toname; - fsdir_add_entry(obj1, de); - break; - case FC_RENAMEDIR: - /* - * Rename a directory. Same as renaming a file, except - * that we update the parent of the directory being - * moved. XXX: also seems to do the wrong thing if you - * rename one directory over another. And, XXX: should - * this be updating the refcount as the parent - * changes? Shouldn't the refcount be the same as the - * on-disk linkcount, and shouldn't the on-disk - * linkcount be part of the state we examine and - * verify? - */ - obj1 = finddir(rootdir, change->fc_renamedir.fromdir); - de = fsdir_remove_entry(obj1, change->fc_renamedir.fromname); - obj2 = de->obj; - assert(obj2->isdir); - assert(obj2->obj_dir.identity == - change->fc_renamedir.moveddir); - assert(obj2->obj_dir.parent == obj1); - obj1 = finddir(rootdir, change->fc_renamedir.todir); - de->name = change->fc_renamedir.toname; - obj2->obj_dir.parent = obj1; - fsdir_add_entry(obj1, de); - break; - } + switch (change->type) { + case FC_NEWFS: + /* + * Creating the volume; crosscheck the root directory. + */ + assert(rootdir->isdir); + assert(rootdir->refcount == 1); + assert(rootdir->obj_dir.identity == change->fc_newfs.rootdirnum); + assert(rootdir->obj_dir.entries == NULL); + assert(rootdir->obj_dir.parent == rootdir); + break; + case FC_TRUNCATE: + /* + * Truncate a file. (Only files, not directories.) + * + * Because truncates can and do get posted after a + * file is unlinked, we have to tolerate not finding + * the file. We don't model unlinked files, because + * they aren't visible and our goal is to check the + * visible/observable state. + */ + obj1 = findfile_maybe(rootdir, change->fc_truncate.file); + if (obj1 != NULL) { + obj1->obj_file.len = change->fc_truncate.len; + } + break; + case FC_WRITE: + /* + * Write to a file. (Only files, not directories.) + * All this actually does is update the file size if + * needed. + * + * We also have to tolerate writes to unlinked files. + */ + obj1 = findfile_maybe(rootdir, change->fc_write.file); + if (obj1 != NULL) { + endpos = change->fc_write.pos + change->fc_write.len; + if (obj1->obj_file.len < endpos) { + obj1->obj_file.len = endpos; + } + } + break; + case FC_CREAT: + /* + * Create a file. This creates a new object and a + * directory entry to hold it, then inserts the + * directory entry in the containing directory. + */ + obj1 = finddir(rootdir, change->fc_creat.dir); + obj2 = fsobject_create_file(change->fc_creat.newfile); + de = fsdirent_create(change->fc_creat.name, obj2); + fsdir_add_entry(obj1, de); + break; + case FC_MKDIR: + /* + * Create a directory. The same as creating a file, + * except the new object is a directory. + */ + obj1 = finddir(rootdir, change->fc_mkdir.dir); + obj2 = fsobject_create_dir(change->fc_mkdir.newdir, obj1); + de = fsdirent_create(change->fc_mkdir.name, obj2); + fsdir_add_entry(obj1, de); + break; + case FC_RMDIR: + /* + * Remove a directory. First take out the directory + * entry (by name); then examine the object found; + * then delete everything. + * + * XXX: why do these checks use assert vs. testing and + * calling die()? + */ + obj1 = finddir(rootdir, change->fc_rmdir.dir); + de = fsdir_remove_entry(obj1, change->fc_rmdir.name); + obj2 = de->obj; + de->obj = NULL; + assert(obj2->isdir); + assert(obj2->obj_dir.entries == NULL); + assert(obj2->obj_dir.identity == change->fc_rmdir.victimdir); + assert(obj2->obj_dir.parent == obj1); + fsdirent_destroy(de); + fsobject_decref(obj2); + break; + case FC_UNLINK: + /* + * Remove a file. Much the same as removing a directory. + */ + obj1 = finddir(rootdir, change->fc_unlink.dir); + de = fsdir_remove_entry(obj1, change->fc_unlink.name); + obj2 = de->obj; + de->obj = NULL; + assert(!obj2->isdir); + assert(obj2->obj_file.identity == change->fc_unlink.victimfile); + fsdirent_destroy(de); + fsobject_decref(obj2); + break; + case FC_LINK: + /* + * Hard-link a file. + */ + obj1 = finddir(rootdir, change->fc_link.fromdir); + de = fsdir_find_entry(obj1, change->fc_link.fromname, 1); + obj2 = de->obj; + assert(!obj2->isdir); + assert(obj2->obj_file.identity == change->fc_link.file); + obj1 = finddir(rootdir, change->fc_link.todir); + fsobject_incref(obj2); + de = fsdirent_create(change->fc_link.toname, obj2); + fsdir_add_entry(obj1, de); + break; + case FC_RENAMEFILE: + /* + * Rename a file. XXX: this appears to do the wrong + * thing if you rename one file over another. + */ + obj1 = finddir(rootdir, change->fc_renamefile.fromdir); + de = fsdir_remove_entry(obj1, change->fc_renamefile.fromname); + obj2 = de->obj; + assert(!obj2->isdir); + assert(obj2->obj_file.identity == change->fc_renamefile.movedfile); + obj1 = finddir(rootdir, change->fc_renamefile.todir); + de->name = change->fc_renamefile.toname; + fsdir_add_entry(obj1, de); + break; + case FC_RENAMEDIR: + /* + * Rename a directory. Same as renaming a file, except + * that we update the parent of the directory being + * moved. XXX: also seems to do the wrong thing if you + * rename one directory over another. And, XXX: should + * this be updating the refcount as the parent + * changes? Shouldn't the refcount be the same as the + * on-disk linkcount, and shouldn't the on-disk + * linkcount be part of the state we examine and + * verify? + */ + obj1 = finddir(rootdir, change->fc_renamedir.fromdir); + de = fsdir_remove_entry(obj1, change->fc_renamedir.fromname); + obj2 = de->obj; + assert(obj2->isdir); + assert(obj2->obj_dir.identity == change->fc_renamedir.moveddir); + assert(obj2->obj_dir.parent == obj1); + obj1 = finddir(rootdir, change->fc_renamedir.todir); + de->name = change->fc_renamedir.toname; + obj2->obj_dir.parent = obj1; + fsdir_add_entry(obj1, de); + break; + } } //////////////////////////////////////////////////////////// @@ -935,61 +839,52 @@ static unsigned nextfilenum, nextdirnum; * * usage: fc_attach(newrecord); */ -static -void -fc_attach(struct fschange *new) -{ - struct fschange *prev; +static void fc_attach(struct fschange *new) { + struct fschange *prev; - prev = changes; + prev = changes; - assert(prev->next == NULL); - assert(new->prev == NULL); - assert(new->next == NULL); - prev->next = new; - new->prev = prev; - new->version = prev->version + 1; + assert(prev->next == NULL); + assert(new->prev == NULL); + assert(new->next == NULL); + prev->next = new; + new->prev = prev; + new->version = prev->version + 1; - changes = new; - apply_change(state, new); + changes = new; + apply_change(state, new); } /* * Rewind the volume state kept in the global STATE to the beginning. */ -static -void -rewindstate(void) -{ - /* If we already have a state, throw it away. */ - if (state != NULL) { - fsobject_destroytree(state); - } +static void rewindstate(void) { + /* If we already have a state, throw it away. */ + if (state != NULL) { + fsobject_destroytree(state); + } - assert(firstchange->type == FC_NEWFS); + assert(firstchange->type == FC_NEWFS); - state = fsobject_create_dir(firstchange->fc_newfs.rootdirnum, NULL); - /* root directory's parent is itself */ - state->obj_dir.parent = state; + state = fsobject_create_dir(firstchange->fc_newfs.rootdirnum, NULL); + /* root directory's parent is itself */ + state->obj_dir.parent = state; } /* * Roll the volume state kept in STATE forward to a specific change * entry. */ -static -void -advancestateto(struct fschange *targetchange) -{ - struct fschange *change; +static void advancestateto(struct fschange *targetchange) { + struct fschange *change; - for (change = firstchange; change != NULL; change = change->next) { - apply_change(state, change); - if (change == targetchange) { - return; - } - } - assert(0); + for (change = firstchange; change != NULL; change = change->next) { + apply_change(state, change); + if (change == targetchange) { + return; + } + } + assert(0); } //////////////////////////////////////////////////////////// @@ -1007,55 +902,52 @@ advancestateto(struct fschange *targetchange) * records, so it can always just start from the most recent end * instead of from a specific place. */ -static -struct fschange * -changes_findprevfile(unsigned filenum) -{ - struct fschange *here; +static struct fschange *changes_findprevfile(unsigned filenum) { + struct fschange *here; - for (here = changes; here != NULL; here = here->prev) { - switch (here->type) { - case FC_NEWFS: - break; - case FC_TRUNCATE: - if (here->fc_truncate.file == filenum) { - return here; - } - break; - case FC_WRITE: - if (here->fc_write.file == filenum) { - return here; - } - break; - case FC_CREAT: - if (here->fc_creat.newfile == filenum) { - return here; - } - break; - case FC_MKDIR: - case FC_RMDIR: - break; - case FC_UNLINK: - if (here->fc_unlink.victimfile == filenum) { - return here; - } - break; - case FC_LINK: - if (here->fc_link.file == filenum) { - return here; - } - break; - case FC_RENAMEFILE: - if (here->fc_renamefile.movedfile == filenum) { - return here; - } - break; - case FC_RENAMEDIR: - break; - } - } - die("No previous record for file %u", filenum); - return NULL; + for (here = changes; here != NULL; here = here->prev) { + switch (here->type) { + case FC_NEWFS: + break; + case FC_TRUNCATE: + if (here->fc_truncate.file == filenum) { + return here; + } + break; + case FC_WRITE: + if (here->fc_write.file == filenum) { + return here; + } + break; + case FC_CREAT: + if (here->fc_creat.newfile == filenum) { + return here; + } + break; + case FC_MKDIR: + case FC_RMDIR: + break; + case FC_UNLINK: + if (here->fc_unlink.victimfile == filenum) { + return here; + } + break; + case FC_LINK: + if (here->fc_link.file == filenum) { + return here; + } + break; + case FC_RENAMEFILE: + if (here->fc_renamefile.movedfile == filenum) { + return here; + } + break; + case FC_RENAMEDIR: + break; + } + } + die("No previous record for file %u", filenum); + return NULL; } /* @@ -1063,67 +955,61 @@ changes_findprevfile(unsigned filenum) * * Likewise, if there isn't one, something's wrong. */ -static -struct fschange * -changes_findprevdir(unsigned dirnum) -{ - struct fschange *here; +static struct fschange *changes_findprevdir(unsigned dirnum) { + struct fschange *here; - for (here = changes; here != NULL; here = here->prev) { - switch (here->type) { - case FC_NEWFS: - if (here->fc_newfs.rootdirnum == dirnum) { - return here; - } - break; - case FC_TRUNCATE: - case FC_WRITE: - break; - case FC_CREAT: - if (here->fc_creat.dir == dirnum) { - return here; - } - break; - case FC_MKDIR: - if (here->fc_mkdir.dir == dirnum || - here->fc_mkdir.newdir == dirnum) { - return here; - } - break; - case FC_RMDIR: - if (here->fc_rmdir.dir == dirnum || - here->fc_rmdir.victimdir == dirnum) { - return here; - } - break; - case FC_UNLINK: - if (here->fc_unlink.dir == dirnum) { - return here; - } - break; - case FC_LINK: - if (here->fc_link.fromdir == dirnum || - here->fc_link.todir == dirnum) { - return here; - } - break; - case FC_RENAMEFILE: - if (here->fc_renamefile.fromdir == dirnum || - here->fc_renamefile.todir == dirnum) { - return here; - } - break; - case FC_RENAMEDIR: - if (here->fc_renamedir.fromdir == dirnum || - here->fc_renamedir.todir == dirnum || - here->fc_renamedir.moveddir == dirnum) { - return here; - } - break; - } - } - die("No previous record for directory %u", dirnum); - return NULL; + for (here = changes; here != NULL; here = here->prev) { + switch (here->type) { + case FC_NEWFS: + if (here->fc_newfs.rootdirnum == dirnum) { + return here; + } + break; + case FC_TRUNCATE: + case FC_WRITE: + break; + case FC_CREAT: + if (here->fc_creat.dir == dirnum) { + return here; + } + break; + case FC_MKDIR: + if (here->fc_mkdir.dir == dirnum || here->fc_mkdir.newdir == dirnum) { + return here; + } + break; + case FC_RMDIR: + if (here->fc_rmdir.dir == dirnum || here->fc_rmdir.victimdir == dirnum) { + return here; + } + break; + case FC_UNLINK: + if (here->fc_unlink.dir == dirnum) { + return here; + } + break; + case FC_LINK: + if (here->fc_link.fromdir == dirnum || here->fc_link.todir == dirnum) { + return here; + } + break; + case FC_RENAMEFILE: + if (here->fc_renamefile.fromdir == dirnum || + here->fc_renamefile.todir == dirnum) { + return here; + } + break; + case FC_RENAMEDIR: + if (here->fc_renamedir.fromdir == dirnum || + here->fc_renamedir.todir == dirnum || + here->fc_renamedir.moveddir == dirnum) { + return here; + } + break; + } + } + die("No previous record for directory %u", dirnum); + return NULL; } #if 0 @@ -1468,106 +1354,86 @@ fs_findparent(unsigned dirnum) * Find a file by name and containing directory, by searching the * volume state. */ -static -unsigned -model_findfile(unsigned dirnum, unsigned name) -{ - struct fsobject *obj; - struct fsdirent *de; +static unsigned model_findfile(unsigned dirnum, unsigned name) { + struct fsobject *obj; + struct fsdirent *de; - obj = finddir(state, dirnum); - de = fsdir_find_entry(obj, name, 1); - if (de->obj->isdir) { - die("In directory %u, %s was a directory", - dirnum, name_get(name)); - } - return de->obj->obj_file.identity; + obj = finddir(state, dirnum); + de = fsdir_find_entry(obj, name, 1); + if (de->obj->isdir) { + die("In directory %u, %s was a directory", dirnum, name_get(name)); + } + return de->obj->obj_file.identity; } /* * Find a directory by name and containing directory, by searching the * volume state. */ -static -unsigned -model_finddir(unsigned dirnum, unsigned name) -{ - struct fsobject *obj; - struct fsdirent *de; +static unsigned model_finddir(unsigned dirnum, unsigned name) { + struct fsobject *obj; + struct fsdirent *de; - obj = finddir(state, dirnum); - de = fsdir_find_entry(obj, name, 1); - if (!de->obj->isdir) { - die("In directory %u, %s was not a directory", - dirnum, name_get(name)); - } - return de->obj->obj_dir.identity; + obj = finddir(state, dirnum); + de = fsdir_find_entry(obj, name, 1); + if (!de->obj->isdir) { + die("In directory %u, %s was not a directory", dirnum, name_get(name)); + } + return de->obj->obj_dir.identity; } /* * Find a directory's parent by object id, by searching the volume * state. */ -static -unsigned -model_findparent(unsigned dirnum) -{ - struct fsobject *obj; +static unsigned model_findparent(unsigned dirnum) { + struct fsobject *obj; - obj = finddir(state, dirnum); - assert(obj->isdir); - assert(obj->obj_dir.parent->isdir); - return obj->obj_dir.parent->obj_dir.identity; + obj = finddir(state, dirnum); + assert(obj->isdir); + assert(obj->obj_dir.parent->isdir); + return obj->obj_dir.parent->obj_dir.identity; } /* * Check if a name (in a specific containing directory) is a file, by * searching the volume state. */ -static -unsigned -model_isfile(unsigned dirnum, unsigned name) -{ - struct fsobject *obj; - struct fsdirent *de; +static unsigned model_isfile(unsigned dirnum, unsigned name) { + struct fsobject *obj; + struct fsdirent *de; - obj = finddir(state, dirnum); - de = fsdir_find_entry(obj, name, 0); - return de != NULL && !de->obj->isdir; + obj = finddir(state, dirnum); + de = fsdir_find_entry(obj, name, 0); + return de != NULL && !de->obj->isdir; } /* * Check if a name (in a specific containing directory) is a * directory, by searching the volume state. */ -static -unsigned -model_isdir(unsigned dirnum, unsigned name) -{ - struct fsobject *obj; - struct fsdirent *de; +static unsigned model_isdir(unsigned dirnum, unsigned name) { + struct fsobject *obj; + struct fsdirent *de; - obj = finddir(state, dirnum); - de = fsdir_find_entry(obj, name, 0); - return de != NULL && de->obj->isdir; + obj = finddir(state, dirnum); + de = fsdir_find_entry(obj, name, 0); + return de != NULL && de->obj->isdir; } /* * Get the current size of a file in the current volume state. */ -static -off_t -model_getfilesize(unsigned filenum) -{ - struct fsobject *obj; +static off_t model_getfilesize(unsigned filenum) { + struct fsobject *obj; - obj = findfile_maybe(state, filenum); - if (obj == NULL) { - /* file is unlinked */ - return 0; - } - assert(!obj->isdir); - return obj->obj_file.len; + obj = findfile_maybe(state, filenum); + if (obj == NULL) { + /* file is unlinked */ + return 0; + } + assert(!obj->isdir); + return obj->obj_file.len; } //////////////////////////////////////////////////////////// @@ -1581,62 +1447,52 @@ static unsigned cwd; * generate the newfs record, set up the volume state, initialize * the current directory. */ -void -check_setup(void) -{ - unsigned rootdir; +void check_setup(void) { + unsigned rootdir; - assert(firstchange == NULL); - assert(changes == NULL); - assert(state == NULL); - assert(nextfilenum == 0); - assert(nextdirnum == 0); + assert(firstchange == NULL); + assert(changes == NULL); + assert(state == NULL); + assert(nextfilenum == 0); + assert(nextdirnum == 0); - rootdir = nextdirnum++; - firstchange = changes = fc_create_newfs(rootdir); + rootdir = nextdirnum++; + firstchange = changes = fc_create_newfs(rootdir); - rewindstate(); + rewindstate(); - /* apply the first change (the newfs record) */ - apply_change(state, changes); + /* apply the first change (the newfs record) */ + apply_change(state, changes); - cwd = rootdir; + cwd = rootdir; } /* * Workload replay: create a file */ -int -check_createfile(unsigned name) -{ - struct fschange *prevdir; - unsigned filenum; +int check_createfile(unsigned name) { + struct fschange *prevdir; + unsigned filenum; - prevdir = changes_findprevdir(cwd); + prevdir = changes_findprevdir(cwd); - filenum = nextfilenum++; - fc_attach(fc_create_creat(prevdir, cwd, name, filenum)); - return filenum; + filenum = nextfilenum++; + fc_attach(fc_create_creat(prevdir, cwd, name, filenum)); + return filenum; } /* * Workload replay: open a file */ -int -check_openfile(unsigned name) -{ - return model_findfile(cwd, name); -} +int check_openfile(unsigned name) { return model_findfile(cwd, name); } /* * Workload replay: close a file */ -void -check_closefile(int handle, unsigned name) -{ - /* don't need to do anything */ - (void)handle; - (void)name; +void check_closefile(int handle, unsigned name) { + /* don't need to do anything */ + (void)handle; + (void)name; } /* @@ -1644,214 +1500,176 @@ check_closefile(int handle, unsigned name) * * CODE and SEQ encode the contents to be written. */ -void -check_write(int handle, unsigned name, unsigned code, unsigned seq, - off_t pos, off_t len) -{ - unsigned filenum; - struct fschange *prevfile; - off_t prevlen; +void check_write(int handle, unsigned name, unsigned code, unsigned seq, + off_t pos, off_t len) { + unsigned filenum; + struct fschange *prevfile; + off_t prevlen; - filenum = handle; - assert(filenum < nextfilenum); - (void)name; + filenum = handle; + assert(filenum < nextfilenum); + (void)name; - prevlen = model_getfilesize(filenum); + prevlen = model_getfilesize(filenum); - prevfile = changes_findprevfile(filenum); - fc_attach(fc_create_write(prevfile, filenum, pos, len, prevlen, - code, seq)); + prevfile = changes_findprevfile(filenum); + fc_attach(fc_create_write(prevfile, filenum, pos, len, prevlen, code, seq)); } /* * Workload replay: truncate a file */ -void -check_truncate(int handle, unsigned name, off_t len) -{ - unsigned filenum; - struct fschange *prevfile; +void check_truncate(int handle, unsigned name, off_t len) { + unsigned filenum; + struct fschange *prevfile; - filenum = handle; - assert(filenum < nextfilenum); - (void)name; + filenum = handle; + assert(filenum < nextfilenum); + (void)name; - prevfile = changes_findprevfile(filenum); - fc_attach(fc_create_truncate(prevfile, filenum, len)); + prevfile = changes_findprevfile(filenum); + fc_attach(fc_create_truncate(prevfile, filenum, len)); } /* * Workload replay: create a directory */ -void -check_mkdir(unsigned name) -{ - struct fschange *prevdir; - unsigned dirnum; +void check_mkdir(unsigned name) { + struct fschange *prevdir; + unsigned dirnum; - prevdir = changes_findprevdir(cwd); - dirnum = nextdirnum++; - fc_attach(fc_create_mkdir(prevdir, cwd, name, dirnum)); + prevdir = changes_findprevdir(cwd); + dirnum = nextdirnum++; + fc_attach(fc_create_mkdir(prevdir, cwd, name, dirnum)); } /* * Workload replay: remove a directory */ -void -check_rmdir(unsigned name) -{ - struct fschange *prevdir, *prevvictim; - unsigned victim; +void check_rmdir(unsigned name) { + struct fschange *prevdir, *prevvictim; + unsigned victim; - prevdir = changes_findprevdir(cwd); - victim = model_finddir(cwd, name); - prevvictim = changes_findprevdir(victim); + prevdir = changes_findprevdir(cwd); + victim = model_finddir(cwd, name); + prevvictim = changes_findprevdir(victim); - fc_attach(fc_create_rmdir(prevdir, prevvictim, cwd, name, victim)); + fc_attach(fc_create_rmdir(prevdir, prevvictim, cwd, name, victim)); } /* * Workload replay: remove a file */ -void -check_unlink(unsigned name) -{ - struct fschange *prevdir, *prevvictim; - unsigned victim; +void check_unlink(unsigned name) { + struct fschange *prevdir, *prevvictim; + unsigned victim; - prevdir = changes_findprevdir(cwd); - victim = model_findfile(cwd, name); - prevvictim = changes_findprevfile(victim); + prevdir = changes_findprevdir(cwd); + victim = model_findfile(cwd, name); + prevvictim = changes_findprevfile(victim); - fc_attach(fc_create_unlink(prevdir, prevvictim, cwd, name, victim)); + fc_attach(fc_create_unlink(prevdir, prevvictim, cwd, name, victim)); } /* * Workload replay: hard link a file */ -void -check_link(unsigned fromname, unsigned toname) -{ - struct fschange *prevdir, *prevfile; - unsigned filenum; +void check_link(unsigned fromname, unsigned toname) { + struct fschange *prevdir, *prevfile; + unsigned filenum; - prevdir = changes_findprevdir(cwd); - filenum = model_findfile(cwd, fromname); - prevfile = changes_findprevfile(filenum); + prevdir = changes_findprevdir(cwd); + filenum = model_findfile(cwd, fromname); + prevfile = changes_findprevfile(filenum); - fc_attach(fc_create_link(prevdir, prevdir, prevfile, - cwd, fromname, cwd, toname, filenum)); + fc_attach(fc_create_link(prevdir, prevdir, prevfile, cwd, fromname, cwd, + toname, filenum)); } /* * Workload replay: rename something */ -static -void -common_rename(unsigned fromdirnum, unsigned fromname, - unsigned todirnum, unsigned toname) -{ - struct fschange *prevfromdir, *prevtodir, *prevfrom, *prevto; - unsigned fromnum, tonum; - struct fschange *fc; - int isfile; +static void common_rename(unsigned fromdirnum, unsigned fromname, + unsigned todirnum, unsigned toname) { + struct fschange *prevfromdir, *prevtodir, *prevfrom, *prevto; + unsigned fromnum, tonum; + struct fschange *fc; + int isfile; - prevfromdir = changes_findprevdir(fromdirnum); - prevtodir = changes_findprevdir(todirnum); + prevfromdir = changes_findprevdir(fromdirnum); + prevtodir = changes_findprevdir(todirnum); - if (model_isfile(todirnum, toname)) { - isfile = 1; - assert(model_isfile(fromdirnum, fromname)); - tonum = model_findfile(todirnum, toname); - prevto = changes_findprevfile(tonum); - fc = fc_create_unlink(prevtodir, prevto, - todirnum, toname, tonum); - } - else if (model_isdir(todirnum, toname)) { - isfile = 0; - assert(model_isdir(fromdirnum, fromname)); - tonum = model_finddir(todirnum, toname); - prevto = changes_findprevdir(tonum); - fc = fc_create_rmdir(prevtodir, prevto, - todirnum, toname, tonum); - } - else { - isfile = model_isfile(fromdirnum, fromname); - fc = NULL; - } + if (model_isfile(todirnum, toname)) { + isfile = 1; + assert(model_isfile(fromdirnum, fromname)); + tonum = model_findfile(todirnum, toname); + prevto = changes_findprevfile(tonum); + fc = fc_create_unlink(prevtodir, prevto, todirnum, toname, tonum); + } else if (model_isdir(todirnum, toname)) { + isfile = 0; + assert(model_isdir(fromdirnum, fromname)); + tonum = model_finddir(todirnum, toname); + prevto = changes_findprevdir(tonum); + fc = fc_create_rmdir(prevtodir, prevto, todirnum, toname, tonum); + } else { + isfile = model_isfile(fromdirnum, fromname); + fc = NULL; + } - if (fc) { - fc->partial = 1; - fc_attach(fc); - } + if (fc) { + fc->partial = 1; + fc_attach(fc); + } - if (isfile) { - fromnum = model_findfile(fromdirnum, fromname); - prevfrom = changes_findprevfile(fromnum); - fc = fc_create_renamefile(prevfromdir, prevtodir, prevfrom, - fromdirnum, fromname, - todirnum, toname, fromnum); - } - else { - fromnum = model_finddir(fromdirnum, fromname); - prevfrom = changes_findprevdir(fromnum); - fc = fc_create_renamedir(prevfromdir, prevtodir, prevfrom, - fromdirnum, fromname, - todirnum, toname, fromnum); - } - fc_attach(fc); + if (isfile) { + fromnum = model_findfile(fromdirnum, fromname); + prevfrom = changes_findprevfile(fromnum); + fc = fc_create_renamefile(prevfromdir, prevtodir, prevfrom, fromdirnum, + fromname, todirnum, toname, fromnum); + } else { + fromnum = model_finddir(fromdirnum, fromname); + prevfrom = changes_findprevdir(fromnum); + fc = fc_create_renamedir(prevfromdir, prevtodir, prevfrom, fromdirnum, + fromname, todirnum, toname, fromnum); + } + fc_attach(fc); } /* * Workload replay: rename within the current directory */ -void -check_rename(unsigned from, unsigned to) -{ - common_rename(cwd, from, cwd, to); +void check_rename(unsigned from, unsigned to) { + common_rename(cwd, from, cwd, to); } /* * Workload replay: cross-directory rename */ -void -check_renamexd(unsigned fromdir, unsigned from, unsigned todir, unsigned to) -{ - unsigned fromdirnum, todirnum; +void check_renamexd(unsigned fromdir, unsigned from, unsigned todir, + unsigned to) { + unsigned fromdirnum, todirnum; - /* fromdir/todir are names in cwd */ - fromdirnum = model_finddir(cwd, fromdir); - todirnum = model_finddir(cwd, todir); + /* fromdir/todir are names in cwd */ + fromdirnum = model_finddir(cwd, fromdir); + todirnum = model_finddir(cwd, todir); - common_rename(fromdirnum, from, todirnum, to); + common_rename(fromdirnum, from, todirnum, to); } /* * Workload replay: change directory */ -void -check_chdir(unsigned name) -{ - cwd = model_finddir(cwd, name); -} +void check_chdir(unsigned name) { cwd = model_finddir(cwd, name); } /* * Workload replay: change directory to .. */ -void -check_chdirup(void) -{ - cwd = model_findparent(cwd); -} +void check_chdirup(void) { cwd = model_findparent(cwd); } /* * Workload replay: sync */ -void -check_sync(void) -{ - /* nothing */ -} +void check_sync(void) { /* nothing */ } //////////////////////////////////////////////////////////// // inspection of the fs @@ -1866,21 +1684,18 @@ static unsigned found_subdirs, found_files; * Wrapper. As of this writing OS/161 provides fstat but not stat... * grr */ -static -int -xstat(const char *path, struct stat *buf) -{ - int fd, ret, serrno; +static int xstat(const char *path, struct stat *buf) { + int fd, ret, serrno; - fd = open(path, O_RDONLY); - if (fd < 0) { - return -1; - } - ret = fstat(fd, buf); - serrno = errno; - close(fd); - errno = serrno; - return ret; + fd = open(path, O_RDONLY); + if (fd < 0) { + return -1; + } + ret = fstat(fd, buf); + serrno = errno; + close(fd); + errno = serrno; + return ret; } /* @@ -1891,136 +1706,129 @@ xstat(const char *path, struct stat *buf) * improve the error reporting, and to allow checking .., and so * forth. */ -static -struct fsobject * -inspectdir(struct fsobject *parentobj, ino_t parentino, const char *dirnamestr) -{ - char subnamestr[NAME_MAX+1]; - size_t subnamelen; - struct stat dirstat, dotstat, substat; - int dirfd; - struct fsobject *subobj, *ret; - struct fsdirent *contents, *de; +static struct fsobject *inspectdir(struct fsobject *parentobj, ino_t parentino, + const char *dirnamestr) { + char subnamestr[NAME_MAX + 1]; + size_t subnamelen; + struct stat dirstat, dotstat, substat; + int dirfd; + struct fsobject *subobj, *ret; + struct fsdirent *contents, *de; - /* - * Stat the target, and cd into it. - */ + /* + * Stat the target, and cd into it. + */ - if (xstat(dirnamestr, &dirstat)) { - err(1, "%s: stat", dirnamestr); - } + if (xstat(dirnamestr, &dirstat)) { + err(1, "%s: stat", dirnamestr); + } - assert(S_ISDIR(dirstat.st_mode)); - if (chdir(dirnamestr)) { - err(1, "%s: chdir", dirnamestr); - } + assert(S_ISDIR(dirstat.st_mode)); + if (chdir(dirnamestr)) { + err(1, "%s: chdir", dirnamestr); + } - /* - * Check that . is correct - */ + /* + * Check that . is correct + */ - if (xstat(".", &dotstat)) { - err(1, "In %s: .: stat", dirnamestr); - } - if (dotstat.st_dev != dirstat.st_dev) { - errx(1, "in %s: .: wrong volume id; found %u, expected %u", - dirnamestr, dotstat.st_dev, dirstat.st_dev); - } - if (dotstat.st_ino != dirstat.st_ino) { - errx(1, "%s/.: wrong inode number; found %u, expected %u", - dirnamestr, dotstat.st_ino, dirstat.st_ino); - } + if (xstat(".", &dotstat)) { + err(1, "In %s: .: stat", dirnamestr); + } + if (dotstat.st_dev != dirstat.st_dev) { + errx(1, "in %s: .: wrong volume id; found %u, expected %u", dirnamestr, + dotstat.st_dev, dirstat.st_dev); + } + if (dotstat.st_ino != dirstat.st_ino) { + errx(1, "%s/.: wrong inode number; found %u, expected %u", dirnamestr, + dotstat.st_ino, dirstat.st_ino); + } - /* - * Check that .. leads back - */ + /* + * Check that .. leads back + */ - if (xstat("..", &dotstat)) { - err(1, "In %s: ..: stat", dirnamestr); - } - if (dotstat.st_dev != dirstat.st_dev) { - errx(1, "In %s: ..: wrong volume id; found %u, expected %u", - dirnamestr, dotstat.st_dev, dirstat.st_dev); - } - if (dotstat.st_ino != parentino) { - errx(1, "In %s: ..: wrong inode number; found %u, expected %u", - dirnamestr, dotstat.st_ino, parentino); - } + if (xstat("..", &dotstat)) { + err(1, "In %s: ..: stat", dirnamestr); + } + if (dotstat.st_dev != dirstat.st_dev) { + errx(1, "In %s: ..: wrong volume id; found %u, expected %u", dirnamestr, + dotstat.st_dev, dirstat.st_dev); + } + if (dotstat.st_ino != parentino) { + errx(1, "In %s: ..: wrong inode number; found %u, expected %u", dirnamestr, + dotstat.st_ino, parentino); + } - /* - * Create a directory fsobject. - */ + /* + * Create a directory fsobject. + */ - dirfd = open(".", O_RDONLY); - if (dirfd < 0) { - err(1, "In %s: .: open", dirnamestr); - } + dirfd = open(".", O_RDONLY); + if (dirfd < 0) { + err(1, "In %s: .: open", dirnamestr); + } - ret = fsobject_create_dir(UNKNOWN_ID, parentobj); + ret = fsobject_create_dir(UNKNOWN_ID, parentobj); - /* - * Read the contents of the target directory and create - * directory entries for them. Recurse for ones that are - * themselves directories. - */ - contents = NULL; - while (1) { - subnamelen = getdirentry(dirfd, subnamestr, - sizeof(subnamestr)-1); - if (subnamelen == 0) { - break; - } - subnamestr[subnamelen] = 0; + /* + * Read the contents of the target directory and create + * directory entries for them. Recurse for ones that are + * themselves directories. + */ + contents = NULL; + while (1) { + subnamelen = getdirentry(dirfd, subnamestr, sizeof(subnamestr) - 1); + if (subnamelen == 0) { + break; + } + subnamestr[subnamelen] = 0; - if (!strcmp(subnamestr, ".") || !strcmp(subnamestr, "..")) { - continue; - } - if (xstat(subnamestr, &substat)) { - err(1, "In %s: %s: stat", dirnamestr, subnamestr); - } - if (S_ISDIR(substat.st_mode)) { - subobj = inspectdir(ret, dirstat.st_ino, subnamestr); - found_subdirs++; - } - else { - subobj = fsobject_create_file(UNKNOWN_ID); - subobj->obj_file.len = substat.st_size; - found_files++; - } - de = fsdirent_create(name_find(subnamestr), subobj); - de->next = contents; - contents = de; - } + if (!strcmp(subnamestr, ".") || !strcmp(subnamestr, "..")) { + continue; + } + if (xstat(subnamestr, &substat)) { + err(1, "In %s: %s: stat", dirnamestr, subnamestr); + } + if (S_ISDIR(substat.st_mode)) { + subobj = inspectdir(ret, dirstat.st_ino, subnamestr); + found_subdirs++; + } else { + subobj = fsobject_create_file(UNKNOWN_ID); + subobj->obj_file.len = substat.st_size; + found_files++; + } + de = fsdirent_create(name_find(subnamestr), subobj); + de->next = contents; + contents = de; + } - /* - * Done scanning; cd out, save the contents, and return the - * new object. - */ + /* + * Done scanning; cd out, save the contents, and return the + * new object. + */ - close(dirfd); - if (chdir("..")) { - err(1, "In %s; ..: chdir", dirnamestr); - } + close(dirfd); + if (chdir("..")) { + err(1, "In %s; ..: chdir", dirnamestr); + } - ret->obj_dir.entries = contents; + ret->obj_dir.entries = contents; - return ret; + return ret; } /* * Inspect the whole volume by starting with "." -- we assume that we * were run in the root directory. */ -static -void -inspectfs(void) -{ - struct stat st; +static void inspectfs(void) { + struct stat st; - if (xstat(".", &st)) { - err(1, ".: stat"); - } - found = inspectdir(NULL, st.st_ino, "."); + if (xstat(".", &st)) { + err(1, ".: stat"); + } + found = inspectdir(NULL, st.st_ino, "."); } //////////////////////////////////////////////////////////// @@ -2029,127 +1837,115 @@ inspectfs(void) /* * Count the number of objects at and below a particular fsobject. */ -static -unsigned -count_subtree(struct fsobject *obj) -{ - struct fsdirent *de; - unsigned ret = 1; +static unsigned count_subtree(struct fsobject *obj) { + struct fsdirent *de; + unsigned ret = 1; - if (obj->isdir) { - for (de = obj->obj_dir.entries; de != NULL; de = de->next) { - ret += count_subtree(de->obj); - } - } - return ret; + if (obj->isdir) { + for (de = obj->obj_dir.entries; de != NULL; de = de->next) { + ret += count_subtree(de->obj); + } + } + return ret; } /* * Compare two fsobjects. Return the matching score. (lower scores are * better matches) */ -static -unsigned -compare_objects(struct fsobject *obja, struct fsobject *objb) -{ - struct fsdirent *enta, *entb; - unsigned ret, found; +static unsigned compare_objects(struct fsobject *obja, struct fsobject *objb) { + struct fsdirent *enta, *entb; + unsigned ret, found; - if (obja->isdir != objb->isdir) { - /* - * One object's a file, the other's a directory. - * - * Return one point for each name in the missing - * subtree. This includes one point for the top dir, - * which is mismatched rather than missing. - */ - if (obja->isdir) { - return count_subtree(obja); - } - assert(objb->isdir); - return count_subtree(objb); - } + if (obja->isdir != objb->isdir) { + /* + * One object's a file, the other's a directory. + * + * Return one point for each name in the missing + * subtree. This includes one point for the top dir, + * which is mismatched rather than missing. + */ + if (obja->isdir) { + return count_subtree(obja); + } + assert(objb->isdir); + return count_subtree(objb); + } - if (!obja->isdir) { - /* - * Both objects are files - */ - assert(!objb->isdir); - if (obja->obj_file.len != objb->obj_file.len) { - /* one point for the size being different */ - return 1; - } - return 0; - } + if (!obja->isdir) { + /* + * Both objects are files + */ + assert(!objb->isdir); + if (obja->obj_file.len != objb->obj_file.len) { + /* one point for the size being different */ + return 1; + } + return 0; + } - /* - * Both objects are directories. Recurse on all pairs of - * entries that have the same name. Return one point for each - * name that's present (recursively) in one object but not the - * other. - * - * XXX: sort the entries first or something instead of naively - * searching 2*N^2 times. - */ - assert(obja->isdir); - assert(objb->isdir); + /* + * Both objects are directories. Recurse on all pairs of + * entries that have the same name. Return one point for each + * name that's present (recursively) in one object but not the + * other. + * + * XXX: sort the entries first or something instead of naively + * searching 2*N^2 times. + */ + assert(obja->isdir); + assert(objb->isdir); - ret = 0; - for (enta = obja->obj_dir.entries; enta != NULL; enta = enta->next) { - found = 0; - for (entb = objb->obj_dir.entries; entb != NULL; - entb = entb->next) { - if (enta->name == entb->name) { - ret += compare_objects(enta->obj, entb->obj); - found = 1; - break; - } - } - if (!found) { - if (enta->obj->isdir) { - /* whole subtree is missing */ - ret += count_subtree(enta->obj); - } - /* one file is missing */ - ret += 1; - } - } + ret = 0; + for (enta = obja->obj_dir.entries; enta != NULL; enta = enta->next) { + found = 0; + for (entb = objb->obj_dir.entries; entb != NULL; entb = entb->next) { + if (enta->name == entb->name) { + ret += compare_objects(enta->obj, entb->obj); + found = 1; + break; + } + } + if (!found) { + if (enta->obj->isdir) { + /* whole subtree is missing */ + ret += count_subtree(enta->obj); + } + /* one file is missing */ + ret += 1; + } + } + for (entb = objb->obj_dir.entries; entb != NULL; entb = entb->next) { + found = 0; + for (enta = obja->obj_dir.entries; enta != NULL; enta = enta->next) { + if (enta->name == entb->name) { + found = 1; + break; + } + } + if (!found) { + if (entb->obj->isdir) { + /* whole subtree is missing */ + ret += count_subtree(entb->obj); + } + /* one file is missing */ + ret += 1; + } + } - for (entb = objb->obj_dir.entries; entb != NULL; entb = entb->next) { - found = 0; - for (enta = obja->obj_dir.entries; enta != NULL; - enta = enta->next) { - if (enta->name == entb->name) { - found = 1; - break; - } - } - if (!found) { - if (entb->obj->isdir) { - /* whole subtree is missing */ - ret += count_subtree(entb->obj); - } - /* one file is missing */ - ret += 1; - } - } - - return ret; + return ret; } /* * Print an indentation. */ -static -void -doindent(unsigned depth) -{ - unsigned i; +static void doindent(unsigned depth) { + unsigned i; - for (i=0; iisdir); - assert(objb->isdir); + assert(obja->isdir); + assert(objb->isdir); - for (enta = obja->obj_dir.entries; enta != NULL; enta = enta->next) { - found = 0; - for (entb = objb->obj_dir.entries; entb != NULL; - entb = entb->next) { - if (enta->name == entb->name) { - doindent(indent); - printf("%s", name_get(enta->name)); - if (enta->obj->isdir && - !entb->obj->isdir) { - printf(": expected dir, found file;"); - printf(" %u names missing.\n", - count_subtree(enta->obj) - 1); - } - else if (!enta->obj->isdir && - entb->obj->isdir) { - printf(": expected file, found dir;"); - printf(" %u extra names.\n", - count_subtree(entb->obj) - 1); - } - else if (!enta->obj->isdir && - !entb->obj->isdir) { - off_t alen, blen; + for (enta = obja->obj_dir.entries; enta != NULL; enta = enta->next) { + found = 0; + for (entb = objb->obj_dir.entries; entb != NULL; entb = entb->next) { + if (enta->name == entb->name) { + doindent(indent); + printf("%s", name_get(enta->name)); + if (enta->obj->isdir && !entb->obj->isdir) { + printf(": expected dir, found file;"); + printf(" %u names missing.\n", count_subtree(enta->obj) - 1); + } else if (!enta->obj->isdir && entb->obj->isdir) { + printf(": expected file, found dir;"); + printf(" %u extra names.\n", count_subtree(entb->obj) - 1); + } else if (!enta->obj->isdir && !entb->obj->isdir) { + off_t alen, blen; - alen = enta->obj->obj_file.len; - blen = entb->obj->obj_file.len; - if (alen == blen) { - printf("\t\t%lld bytes (ok)\n", - alen); - } - else { - printf(": found %lld bytes, " - "expected %lld " - "bytes.\n", - blen, alen); - } - } - else { - printf("/\n"); - printdiffs(indent + 1, - enta->obj, entb->obj); - } - found = 1; - break; - } - } - if (!found) { - doindent(indent); - printf("%s: missing ", name_get(enta->name)); - if (enta->obj->isdir) { - printf("subtree with %u names.\n", - count_subtree(enta->obj) - 1); - } - else { - printf("file\n"); - } - } - } + alen = enta->obj->obj_file.len; + blen = entb->obj->obj_file.len; + if (alen == blen) { + printf("\t\t%lld bytes (ok)\n", alen); + } else { + printf(": found %lld bytes, " + "expected %lld " + "bytes.\n", + blen, alen); + } + } else { + printf("/\n"); + printdiffs(indent + 1, enta->obj, entb->obj); + } + found = 1; + break; + } + } + if (!found) { + doindent(indent); + printf("%s: missing ", name_get(enta->name)); + if (enta->obj->isdir) { + printf("subtree with %u names.\n", count_subtree(enta->obj) - 1); + } else { + printf("file\n"); + } + } + } - - for (entb = objb->obj_dir.entries; entb != NULL; entb = entb->next) { - found = 0; - for (enta = obja->obj_dir.entries; enta != NULL; - enta = enta->next) { - if (enta->name == entb->name) { - found = 1; - break; - } - } - if (!found) { - doindent(indent); - printf("%s: extra ", name_get(entb->name)); - if (entb->obj->isdir) { - printf("subtree with %u names.\n", - count_subtree(entb->obj) - 1); - } - else { - printf("file\n"); - } - } - } + for (entb = objb->obj_dir.entries; entb != NULL; entb = entb->next) { + found = 0; + for (enta = obja->obj_dir.entries; enta != NULL; enta = enta->next) { + if (enta->name == entb->name) { + found = 1; + break; + } + } + if (!found) { + doindent(indent); + printf("%s: extra ", name_get(entb->name)); + if (entb->obj->isdir) { + printf("subtree with %u names.\n", count_subtree(entb->obj) - 1); + } else { + printf("file\n"); + } + } + } } //////////////////////////////////////////////////////////// @@ -2258,22 +2034,19 @@ printdiffs(unsigned indent, struct fsobject *obja, struct fsobject *objb) * structure as CHANGE. This skips past truncate and write operations * that only change file sizes. */ -static -unsigned -findokversion(struct fschange *change) -{ - while (change != NULL) { - switch (change->type) { - case FC_TRUNCATE: - case FC_WRITE: - break; - default: - return change->version; - } - change = change->prev; - } - assert(0); - return 0; +static unsigned findokversion(struct fschange *change) { + while (change != NULL) { + switch (change->type) { + case FC_TRUNCATE: + case FC_WRITE: + break; + default: + return change->version; + } + change = change->prev; + } + assert(0); + return 0; } /* @@ -2283,93 +2056,87 @@ findokversion(struct fschange *change) * * Returns the current (passed-in) change if that matches. */ -static -struct fschange * -backup_for_file(struct fschange *change, unsigned filenum) -{ - while (change != NULL) { - switch (change->type) { - case FC_TRUNCATE: - if (change->fc_truncate.file == filenum) { - return change; - } - break; - case FC_WRITE: - if (change->fc_write.file == filenum) { - return change; - } - break; - case FC_CREAT: - if (change->fc_creat.newfile == filenum) { - return change; - } - break; - default: - break; - } - change = change->prev; - } - return NULL; +static struct fschange *backup_for_file(struct fschange *change, + unsigned filenum) { + while (change != NULL) { + switch (change->type) { + case FC_TRUNCATE: + if (change->fc_truncate.file == filenum) { + return change; + } + break; + case FC_WRITE: + if (change->fc_write.file == filenum) { + return change; + } + break; + case FC_CREAT: + if (change->fc_creat.newfile == filenum) { + return change; + } + break; + default: + break; + } + change = change->prev; + } + return NULL; } /* * Expect zeros in a file from START to END. The file is given by FD * and named NAMESTR. Report if we find stuff other than zeros. */ -static -void -checkfilezeros(int fd, const char *namestr, off_t start, off_t end) -{ - char buf[1024]; - size_t len, i; - ssize_t ret; - unsigned poison = 0, trash = 0; - off_t origstart = start; +static void checkfilezeros(int fd, const char *namestr, off_t start, + off_t end) { + char buf[1024]; + size_t len, i; + ssize_t ret; + unsigned poison = 0, trash = 0; + off_t origstart = start; - printf(" %lld - %lld (expecting zeros)\n", start, end); + printf(" %lld - %lld (expecting zeros)\n", start, end); - if (lseek(fd, start, SEEK_SET) == -1) { - err(1, "%s: lseek to %lld", namestr, start); - } - while (start < end) { - /* XXX this assumes end - start fits in size_t */ - len = end - start; - if (len > sizeof(buf)) { - len = sizeof(buf); - } - ret = read(fd, buf, len); - if (ret == -1) { - err(1, "%s: read %u at %lld", namestr, len, start); - } - if (ret == 0) { - errx(1, "%s: read %u at %lld: Unexpected EOF", - namestr, len, start); - } - for (i=0; i<(size_t)ret; i++) { - if ((unsigned char)buf[i] == POISON_VAL) { - poison++; - } - else if (buf[i] != 0) { - trash++; - } - } - start += ret; - } - if (poison > 0 || trash > 0) { - printf("ERROR: File %s: expected zeros from %lld to %lld; " - "found", - namestr, origstart, end); - if (poison > 0) { - printf(" %u poison bytes", poison); - if (trash > 0) { - printf(" and"); - } - } - if (trash > 0) { - printf(" %u trash bytes", trash); - } - printf("\n"); - } + if (lseek(fd, start, SEEK_SET) == -1) { + err(1, "%s: lseek to %lld", namestr, start); + } + while (start < end) { + /* XXX this assumes end - start fits in size_t */ + len = end - start; + if (len > sizeof(buf)) { + len = sizeof(buf); + } + ret = read(fd, buf, len); + if (ret == -1) { + err(1, "%s: read %u at %lld", namestr, len, start); + } + if (ret == 0) { + errx(1, "%s: read %u at %lld: Unexpected EOF", namestr, len, start); + } + for (i = 0; i < (size_t)ret; i++) { + if ((unsigned char)buf[i] == POISON_VAL) { + poison++; + } else if (buf[i] != 0) { + trash++; + } + } + start += ret; + } + if (poison > 0 || trash > 0) { + printf("ERROR: File %s: expected zeros from %lld to %lld; " + "found", + namestr, origstart, end); + if (poison > 0) { + printf(" %u poison bytes", poison); + if (trash > 0) { + printf(" and"); + } + } + if (trash > 0) { + printf(" %u trash bytes", trash); + } + printf("\n"); + } } /* @@ -2380,42 +2147,37 @@ checkfilezeros(int fd, const char *namestr, off_t start, off_t end) * range CHECKSTART..CHECKEND, which may be only part of the data.c * region. */ -static -void -readfiledata(int fd, const char *namestr, - off_t regionstart, off_t checkstart, - off_t checkend, off_t regionend) -{ - char *readbuf; - size_t bufpos, len; - ssize_t ret; +static void readfiledata(int fd, const char *namestr, off_t regionstart, + off_t checkstart, off_t checkend, off_t regionend) { + char *readbuf; + size_t bufpos, len; + ssize_t ret; - /* CHECKSTART..CHECKEND must be within REGIONSTART..REGIONEND */ - assert(regionstart <= checkstart); - assert(checkstart <= checkend); - assert(checkend <= regionend); + /* CHECKSTART..CHECKEND must be within REGIONSTART..REGIONEND */ + assert(regionstart <= checkstart); + assert(checkstart <= checkend); + assert(checkend <= regionend); - readbuf = data_mapreadbuf(regionend - regionstart); - bufpos = checkstart - regionstart; - len = checkend - checkstart; - if (lseek(fd, checkstart, SEEK_SET) == -1) { - err(1, "%s: lseek to %lld", namestr, checkstart); - } + readbuf = data_mapreadbuf(regionend - regionstart); + bufpos = checkstart - regionstart; + len = checkend - checkstart; + if (lseek(fd, checkstart, SEEK_SET) == -1) { + err(1, "%s: lseek to %lld", namestr, checkstart); + } - while (len > 0) { - ret = read(fd, readbuf + bufpos, len); - if (ret == -1) { - err(1, "%s: read %u at %lld", - namestr, len, regionstart + bufpos); - } - if (ret == 0) { - errx(1, "%s: read %u at %lld: Unexpected EOF", - namestr, len, regionstart + bufpos); - } - bufpos += ret; - assert(len >= (size_t)ret); - len -= ret; - } + while (len > 0) { + ret = read(fd, readbuf + bufpos, len); + if (ret == -1) { + err(1, "%s: read %u at %lld", namestr, len, regionstart + bufpos); + } + if (ret == 0) { + errx(1, "%s: read %u at %lld: Unexpected EOF", namestr, len, + regionstart + bufpos); + } + bufpos += ret; + assert(len >= (size_t)ret); + len -= ret; + } } /* @@ -2426,159 +2188,142 @@ readfiledata(int fd, const char *namestr, * (the portion of a write that extended a file) and the data is * generated from CODE and SEQ. */ -static -void -checkfiledata(int fd, const char *namestr, unsigned code, unsigned seq, - off_t zerostart, - off_t regionstart, off_t checkstart, - off_t checkend, off_t regionend) -{ - if (checkstart < regionstart) { - checkstart = regionstart; - } - if (checkend > regionend) { - checkend = regionend; - } +static void checkfiledata(int fd, const char *namestr, unsigned code, + unsigned seq, off_t zerostart, off_t regionstart, + off_t checkstart, off_t checkend, off_t regionend) { + if (checkstart < regionstart) { + checkstart = regionstart; + } + if (checkend > regionend) { + checkend = regionend; + } - printf(" %lld - %lld\n", checkstart, checkend); + printf(" %lld - %lld\n", checkstart, checkend); - readfiledata(fd, namestr, - regionstart, checkstart, checkend, regionend); + readfiledata(fd, namestr, regionstart, checkstart, checkend, regionend); - data_check(namestr, regionstart, - code, seq, zerostart - regionstart, regionend - regionstart, - checkstart - regionstart, checkend - checkstart); + data_check(namestr, regionstart, code, seq, zerostart - regionstart, + regionend - regionstart, checkstart - regionstart, + checkend - checkstart); } /* * Check a range of the file FD named NAMESTR, from START to END, * against the model state expected as of CHANGE. */ -static -void -checkfilerange(int fd, const char *namestr, struct fschange *change, - off_t start, off_t end) -{ - assert(start < end); - if (change->type == FC_TRUNCATE) { - off_t tlen; - struct fschange *prev; +static void checkfilerange(int fd, const char *namestr, struct fschange *change, + off_t start, off_t end) { + assert(start < end); + if (change->type == FC_TRUNCATE) { + off_t tlen; + struct fschange *prev; - /* - * The most recent change was a truncate. Anything - * beyond the truncate length should read as zeroes; - * recurse on the part before (if any) using the - * previous change affecting this file. - * - * We might be checking that a chunk of the file - * beyond the truncate length is zero (even though as - * of this change it's past EOF) if a later change - * made that region into a hole in a sparse file. - */ + /* + * The most recent change was a truncate. Anything + * beyond the truncate length should read as zeroes; + * recurse on the part before (if any) using the + * previous change affecting this file. + * + * We might be checking that a chunk of the file + * beyond the truncate length is zero (even though as + * of this change it's past EOF) if a later change + * made that region into a hole in a sparse file. + */ - tlen = change->fc_truncate.len; - prev = change->fc_truncate.prev_thisfile; + tlen = change->fc_truncate.len; + prev = change->fc_truncate.prev_thisfile; - if (tlen < start) { - checkfilezeros(fd, namestr, start, end); - } - else if (tlen < end) { - checkfilerange(fd, namestr, prev, start, tlen); - checkfilezeros(fd, namestr, tlen, end); - } - else { - checkfilerange(fd, namestr, prev, start, end); - } - } - else if (change->type == FC_WRITE) { - off_t wstart, wend; - struct fschange *prev; - unsigned code, seq; - off_t oldfilesize, zerostart; + if (tlen < start) { + checkfilezeros(fd, namestr, start, end); + } else if (tlen < end) { + checkfilerange(fd, namestr, prev, start, tlen); + checkfilezeros(fd, namestr, tlen, end); + } else { + checkfilerange(fd, namestr, prev, start, end); + } + } else if (change->type == FC_WRITE) { + off_t wstart, wend; + struct fschange *prev; + unsigned code, seq; + off_t oldfilesize, zerostart; - /* - * The most recent change was a write. - */ + /* + * The most recent change was a write. + */ - wstart = change->fc_write.pos; - wend = change->fc_write.pos + change->fc_write.len; - prev = change->fc_write.prev_thisfile; - code = change->fc_write.code; - seq = change->fc_write.seq; - oldfilesize = change->fc_write.oldfilesize; + wstart = change->fc_write.pos; + wend = change->fc_write.pos + change->fc_write.len; + prev = change->fc_write.prev_thisfile; + code = change->fc_write.code; + seq = change->fc_write.seq; + oldfilesize = change->fc_write.oldfilesize; - /* - * ZEROSTART (where we begin to allow the file to - * contain zeros) should be the point at the write - * where we began to extend the file, if any. - */ - if (oldfilesize < wstart) { - zerostart = wstart; - } - else if (oldfilesize < wend) { - zerostart = oldfilesize; - } - else { - zerostart = wend; - } + /* + * ZEROSTART (where we begin to allow the file to + * contain zeros) should be the point at the write + * where we began to extend the file, if any. + */ + if (oldfilesize < wstart) { + zerostart = wstart; + } else if (oldfilesize < wend) { + zerostart = oldfilesize; + } else { + zerostart = wend; + } - /* - * Six cases for the range overlap: - * (1) (2) (3) (4) (5) (6) - * ** *** ****** * *** ** - * *** *** *** *** *** *** - * - * We call checkfilerange recursively using the - * previous change for this file for the - * non-overlapping parts, because this write didn't - * touch those so they must reflect the previous file - * state; and checkfiledata for the overlapping parts - * that this write did touch. - */ + /* + * Six cases for the range overlap: + * (1) (2) (3) (4) (5) (6) + * ** *** ****** * *** ** + * *** *** *** *** *** *** + * + * We call checkfilerange recursively using the + * previous change for this file for the + * non-overlapping parts, because this write didn't + * touch those so they must reflect the previous file + * state; and checkfiledata for the overlapping parts + * that this write did touch. + */ - if (end <= wstart || start >= wend) { - /* cases 1 and 6 */ - checkfilerange(fd, namestr, prev, start, end); - } - else { - /* cases 2-5 */ - if (start < wstart) { - /* case 2 or 3 */ - checkfilerange(fd, namestr, prev, - start, wstart); - } - checkfiledata(fd, namestr, code, seq, zerostart, - wstart, start, end, wend); - if (end > wend) { - /* cases 3 or 5 */ - checkfilerange(fd, namestr, prev, wend, end); - } - } - } - else if (change->type == FC_RENAMEFILE) { - struct fschange *prev; + if (end <= wstart || start >= wend) { + /* cases 1 and 6 */ + checkfilerange(fd, namestr, prev, start, end); + } else { + /* cases 2-5 */ + if (start < wstart) { + /* case 2 or 3 */ + checkfilerange(fd, namestr, prev, start, wstart); + } + checkfiledata(fd, namestr, code, seq, zerostart, wstart, start, end, + wend); + if (end > wend) { + /* cases 3 or 5 */ + checkfilerange(fd, namestr, prev, wend, end); + } + } + } else if (change->type == FC_RENAMEFILE) { + struct fschange *prev; - /* - * The most recent change was a rename. As rename - * doesn't affect contents, recurse on the previous - * change affecting the file. - */ + /* + * The most recent change was a rename. As rename + * doesn't affect contents, recurse on the previous + * change affecting the file. + */ - prev = change->fc_renamefile.prev_movedfile; - checkfilerange(fd, namestr, prev, start, end); - } - else { - assert(change->type == FC_CREAT); + prev = change->fc_renamefile.prev_movedfile; + checkfilerange(fd, namestr, prev, start, end); + } else { + assert(change->type == FC_CREAT); - /* - * The most recent change was the file being created. - * Like with truncate, check that the range is zero - * even though it's past EOF, as a later write might - * have converted past-EOF space into a hole in a - * sparse file. - */ - checkfilezeros(fd, namestr, start, end); - } + /* + * The most recent change was the file being created. + * Like with truncate, check that the range is zero + * even though it's past EOF, as a later write might + * have converted past-EOF space into a hole in a + * sparse file. + */ + checkfilezeros(fd, namestr, start, end); + } } /* @@ -2589,213 +2334,200 @@ checkfilerange(int fd, const char *namestr, struct fschange *change, * all it can check is the size, so it can readily be fooled by * sequences of truncates or multiple truncates to the same length. */ -static -int -change_is_present(int fd, const char *namestr, off_t filesize, - struct fschange *change) -{ - off_t pos, len, oldfilesize, zerostart; - unsigned code, seq; +static int change_is_present(int fd, const char *namestr, off_t filesize, + struct fschange *change) { + off_t pos, len, oldfilesize, zerostart; + unsigned code, seq; - switch (change->type) { - case FC_TRUNCATE: - return filesize == change->fc_truncate.len; - case FC_WRITE: - pos = change->fc_write.pos; - len = change->fc_write.len; - code = change->fc_write.code; - seq = change->fc_write.seq; - oldfilesize = change->fc_write.oldfilesize; - if (oldfilesize < pos) { - zerostart = 0; - } - else if (oldfilesize < pos + len) { - zerostart = oldfilesize - pos; - } - else { - zerostart = len; - } - readfiledata(fd, namestr, pos, pos, pos+len, pos+len); - return data_matches(namestr, pos, - code, seq, zerostart, len, 0, len); - case FC_CREAT: - return 1; - default: - break; - } - assert(0); - return 0; + switch (change->type) { + case FC_TRUNCATE: + return filesize == change->fc_truncate.len; + case FC_WRITE: + pos = change->fc_write.pos; + len = change->fc_write.len; + code = change->fc_write.code; + seq = change->fc_write.seq; + oldfilesize = change->fc_write.oldfilesize; + if (oldfilesize < pos) { + zerostart = 0; + } else if (oldfilesize < pos + len) { + zerostart = oldfilesize - pos; + } else { + zerostart = len; + } + readfiledata(fd, namestr, pos, pos, pos + len, pos + len); + return data_matches(namestr, pos, code, seq, zerostart, len, 0, len); + case FC_CREAT: + return 1; + default: + break; + } + assert(0); + return 0; } /* * Check the contents of the file called NAMESTR, which is the model * file FILE, as of change CHANGE. */ -static -void -checkonefilecontents(const char *namestr, struct fsobject *file, - struct fschange *change) -{ - unsigned okversion; - int fd; +static void checkonefilecontents(const char *namestr, struct fsobject *file, + struct fschange *change) { + unsigned okversion; + int fd; - /* - * Open the file. - */ + /* + * Open the file. + */ - assert(!file->isdir); + assert(!file->isdir); - fd = open(namestr, O_RDONLY); - if (fd < 0) { - err(1, "%s: open", namestr); - } + fd = open(namestr, O_RDONLY); + if (fd < 0) { + err(1, "%s: open", namestr); + } - /* - * Find the oldest version that has the same directory - * structure as CHANGE, and thus reflects the earliest - * contents we can legitimately find in the file. - * - * XXX: the matching we do to pick the change to examine takes - * file sizes into account, but findokversion specifically - * doesn't stop going backwards if just the file size changes. - * This seems wrong: if we match on file size, ok versions to - * see are only those that have the same file size. - */ - okversion = findokversion(change); + /* + * Find the oldest version that has the same directory + * structure as CHANGE, and thus reflects the earliest + * contents we can legitimately find in the file. + * + * XXX: the matching we do to pick the change to examine takes + * file sizes into account, but findokversion specifically + * doesn't stop going backwards if just the file size changes. + * This seems wrong: if we match on file size, ok versions to + * see are only those that have the same file size. + */ + okversion = findokversion(change); - /* - * Find the first change (going backwards) that affects this - * file. There should always be at least the create. This - * change might be before or after OKVERSION. - */ - change = backup_for_file(change, file->obj_file.identity); - if (change == NULL) { - die("File %s was never even created?", namestr); - } + /* + * Find the first change (going backwards) that affects this + * file. There should always be at least the create. This + * change might be before or after OKVERSION. + */ + change = backup_for_file(change, file->obj_file.identity); + if (change == NULL) { + die("File %s was never even created?", namestr); + } - if (file->obj_file.len == 0) { - /* - * The model expects the length to be 0. - * - * XXX: I think the code here was written thinking - * FILE is from the inspection results; but it's not, - * it's the model from the workload replay. So these - * checks appear to be wrong. - */ - if (change->type == FC_CREAT) { - /* file was created empty and never written to */ - return; - } - if (change->type == FC_TRUNCATE) { - /* if the length is wrong we shouldn't get this far */ - assert(change->fc_truncate.len == 0); + if (file->obj_file.len == 0) { + /* + * The model expects the length to be 0. + * + * XXX: I think the code here was written thinking + * FILE is from the inspection results; but it's not, + * it's the model from the workload replay. So these + * checks appear to be wrong. + */ + if (change->type == FC_CREAT) { + /* file was created empty and never written to */ + return; + } + if (change->type == FC_TRUNCATE) { + /* if the length is wrong we shouldn't get this far */ + assert(change->fc_truncate.len == 0); - /* so, nothing to check */ - close(fd); - return; - } - assert(change->type == FC_WRITE); - printf("ERROR: File %s is zero length but was expected to " - "contain at least %lld bytes at offset %lld!\n", - namestr, change->fc_write.pos, change->fc_write.len); - close(fd); - return; - } + /* so, nothing to check */ + close(fd); + return; + } + assert(change->type == FC_WRITE); + printf("ERROR: File %s is zero length but was expected to " + "contain at least %lld bytes at offset %lld!\n", + namestr, change->fc_write.pos, change->fc_write.len); + close(fd); + return; + } - /* XXX: this check is wrong too. */ - if (change->type == FC_CREAT) { - printf("ERROR: File %s was never written to but has " - "length %lld\n", - namestr, file->obj_file.len); - close(fd); - return; - } + /* XXX: this check is wrong too. */ + if (change->type == FC_CREAT) { + printf("ERROR: File %s was never written to but has " + "length %lld\n", + namestr, file->obj_file.len); + close(fd); + return; + } - /* - * If CHANGE isn't reflected in the file, back up. If this - * causes us to back up past OKVERSION, complain that the - * change should be present. - * - * XXX: the call to change_is_present should be using the - * observed file size, not the modeled file size. - * - * XXX: More seriously, however, this logic is not really - * right. If the workload contains multiple writes that don't - * affect the file length, interspersed with truncates that - * are all to the same length, we'll stop looking back at the - * first truncate (because the length matches) regardless of - * which writes are present. None of the workloads currently - * does anything like this, but it's still wrong. - * - * I think the right thing to do (especially since the version - * matching checks file lengths) is to check only writes for - * presence and ignore truncates; and probably, rather than - * back up based on what writes appear to be present and then - * call checkfilerange, which will then complain loudly if - * parts of an older write didn't make it out, divide the file - * into ranges based on blocks and writes and figure out which - * version the data found in each such range corresponds to, - * then object only to the ones that are crazy and warn about - * ones that reflect data buffers not making it out. But this - * is a fairly big rewrite. - */ - while (!change_is_present(fd, namestr, file->obj_file.len, change)) { - if (change->version < okversion) { - printf("File %s: change for version %u is missing\n", - namestr, change->version); - } - change = backup_for_file(change->prev,file->obj_file.identity); - if (change == NULL) { - printf("File %s: no matching version found\n", - namestr); - close(fd); - return; - } - } + /* + * If CHANGE isn't reflected in the file, back up. If this + * causes us to back up past OKVERSION, complain that the + * change should be present. + * + * XXX: the call to change_is_present should be using the + * observed file size, not the modeled file size. + * + * XXX: More seriously, however, this logic is not really + * right. If the workload contains multiple writes that don't + * affect the file length, interspersed with truncates that + * are all to the same length, we'll stop looking back at the + * first truncate (because the length matches) regardless of + * which writes are present. None of the workloads currently + * does anything like this, but it's still wrong. + * + * I think the right thing to do (especially since the version + * matching checks file lengths) is to check only writes for + * presence and ignore truncates; and probably, rather than + * back up based on what writes appear to be present and then + * call checkfilerange, which will then complain loudly if + * parts of an older write didn't make it out, divide the file + * into ranges based on blocks and writes and figure out which + * version the data found in each such range corresponds to, + * then object only to the ones that are crazy and warn about + * ones that reflect data buffers not making it out. But this + * is a fairly big rewrite. + */ + while (!change_is_present(fd, namestr, file->obj_file.len, change)) { + if (change->version < okversion) { + printf("File %s: change for version %u is missing\n", namestr, + change->version); + } + change = backup_for_file(change->prev, file->obj_file.identity); + if (change == NULL) { + printf("File %s: no matching version found\n", namestr); + close(fd); + return; + } + } - /* - * Now we've found a version that we think the file contents - * should correspond to; check that it's what we actually - * have. - * - * XXX: should this use the model length or the observed - * length? - */ + /* + * Now we've found a version that we think the file contents + * should correspond to; check that it's what we actually + * have. + * + * XXX: should this use the model length or the observed + * length? + */ - checkfilerange(fd, namestr, change, 0, file->obj_file.len); - close(fd); + checkfilerange(fd, namestr, change, 0, file->obj_file.len); + close(fd); } /* * Check the contents of all files under DIR with respect to the * change CHANGE. Recurses on subdirectories. */ -static -void -checkallfilecontents(struct fsobject *dir, struct fschange *change) -{ - struct fsdirent *de; - const char *namestr; +static void checkallfilecontents(struct fsobject *dir, + struct fschange *change) { + struct fsdirent *de; + const char *namestr; - assert(dir->isdir); - for (de = dir->obj_dir.entries; de != NULL; de = de->next) { - namestr = name_get(de->name); - if (de->obj->isdir) { - printf(" >>> Entering %s\n", namestr); - if (chdir(namestr)) { - err(1, "%s: chdir", namestr); - } - checkallfilecontents(de->obj, change); - printf(" <<< Leaving %s\n", namestr); - if (chdir("..")) { - err(1, "..: chdir"); - } - } - else { - printf("%s...\n", namestr); - checkonefilecontents(namestr, de->obj, change); - } - } + assert(dir->isdir); + for (de = dir->obj_dir.entries; de != NULL; de = de->next) { + namestr = name_get(de->name); + if (de->obj->isdir) { + printf(" >>> Entering %s\n", namestr); + if (chdir(namestr)) { + err(1, "%s: chdir", namestr); + } + checkallfilecontents(de->obj, change); + printf(" <<< Leaving %s\n", namestr); + if (chdir("..")) { + err(1, "..: chdir"); + } + } else { + printf("%s...\n", namestr); + checkonefilecontents(namestr, de->obj, change); + } + } } //////////////////////////////////////////////////////////// @@ -2804,108 +2536,105 @@ checkallfilecontents(struct fsobject *dir, struct fschange *change) /* * Compare the on-disk state we see to the model we've built. */ -void -checkfs(void) -{ - struct fschange *change, *best; - unsigned score, bestscore; +void checkfs(void) { + struct fschange *change, *best; + unsigned score, bestscore; - /* - * We just built the model; talk about it. - */ - printf("Established %u versions across %u directories and %u files\n", - changes->version + 1, nextdirnum, nextfilenum); + /* + * We just built the model; talk about it. + */ + printf("Established %u versions across %u directories and %u files\n", + changes->version + 1, nextdirnum, nextfilenum); - /* - * Inspect the volume state we've got. Initializes the global - * FOUND holding the found volume state. - */ - inspectfs(); - printf("Found %u subdirs and %u files on the volume\n", - found_subdirs, found_files); + /* + * Inspect the volume state we've got. Initializes the global + * FOUND holding the found volume state. + */ + inspectfs(); + printf("Found %u subdirs and %u files on the volume\n", found_subdirs, + found_files); - /* - * Rewind the model state to the beginning. - */ - rewindstate(); + /* + * Rewind the model state to the beginning. + */ + rewindstate(); - /* - * Loop through all the changes; apply each one to the model - * state, and score the model state against the found state. - * Keep track of the best matching version. - * - * XXX: there might be several versions with the same score, - * in which case we'll blindly take the most recent one. If - * there are several versions that match exactly (which can - * easily happen for workloads that don't explicitly avoid it) - * we'll also blindly take the most recent one, and then the - * matching of file contents can blow up. We should collect - * all the versions with the same score, and score each one - * on file contents too. Or something like that. - */ + /* + * Loop through all the changes; apply each one to the model + * state, and score the model state against the found state. + * Keep track of the best matching version. + * + * XXX: there might be several versions with the same score, + * in which case we'll blindly take the most recent one. If + * there are several versions that match exactly (which can + * easily happen for workloads that don't explicitly avoid it) + * we'll also blindly take the most recent one, and then the + * matching of file contents can blow up. We should collect + * all the versions with the same score, and score each one + * on file contents too. Or something like that. + */ - change = firstchange; - assert(change->type == FC_NEWFS); - best = NULL; - bestscore = 0; + change = firstchange; + assert(change->type == FC_NEWFS); + best = NULL; + bestscore = 0; - while (change != NULL) { - apply_change(state, change); - score = compare_objects(state, found); - if (best == NULL || score <= bestscore) { - best = change; - bestscore = score; - } - //printf("version %u score %u\n", change->version, score); - change = change->next; - } - assert(best != NULL); + while (change != NULL) { + apply_change(state, change); + score = compare_objects(state, found); + if (best == NULL || score <= bestscore) { + best = change; + bestscore = score; + } + // printf("version %u score %u\n", change->version, score); + change = change->next; + } + assert(best != NULL); - /* - * Set the model state to the best matching state we found. - */ + /* + * Set the model state to the best matching state we found. + */ - rewindstate(); - advancestateto(best); + rewindstate(); + advancestateto(best); - if (bestscore > 0) { - /* - * We didn't get an exact match, so print how the - * differences. XXX: this results in not checking file - * data... - */ - printf("FAILURE: Directory tree does not match on any " - "version.\n"); - printf("Best version is %u; describing differences:\n", - best->version); - printdiffs(1, state, found); - return; - } + if (bestscore > 0) { + /* + * We didn't get an exact match, so print how the + * differences. XXX: this results in not checking file + * data... + */ + printf("FAILURE: Directory tree does not match on any " + "version.\n"); + printf("Best version is %u; describing differences:\n", best->version); + printdiffs(1, state, found); + return; + } - /* - * Ok, we did get an exact match. Print it. - */ + /* + * Ok, we did get an exact match. Print it. + */ - printf("Directory tree matched in version %u.\n", best->version); - if (best->partial) { - printf("WARNING: this is a version from a partially committed " - "operation.\n"); - } + printf("Directory tree matched in version %u.\n", best->version); + if (best->partial) { + printf("WARNING: this is a version from a partially committed " + "operation.\n"); + } - /* - * XXX we should check hard links here; that is, that all the - * files that are supposed to be hard links of each other are, - * and that no other files are randomly hardlinked. - * - * However, if things are wrong it should result in bad - * contents. It would be very unlikely for even a very broken - * filesystem to, on its own, copy files that are supposed to - * be hardlinked. - */ + /* + * XXX we should check hard links here; that is, that all the + * files that are supposed to be hard links of each other are, + * and that no other files are randomly hardlinked. + * + * However, if things are wrong it should result in bad + * contents. It would be very unlikely for even a very broken + * filesystem to, on its own, copy files that are supposed to + * be hardlinked. + */ - /* now check the file contents */ + /* now check the file contents */ - printf("Checking file contents...\n"); - checkallfilecontents(state, best); - printf("Done.\n"); + printf("Checking file contents...\n"); + checkallfilecontents(state, best); + printf("Done.\n"); } diff --git a/userland/testbin/frack/check.h b/userland/testbin/frack/check.h index c429180..850cb71 100644 --- a/userland/testbin/frack/check.h +++ b/userland/testbin/frack/check.h @@ -28,24 +28,22 @@ * SUCH DAMAGE. */ - int check_createfile(unsigned name); int check_openfile(unsigned name); void check_closefile(int handle, unsigned name); void check_write(int handle, unsigned name, unsigned code, unsigned seq, - off_t pos, off_t len); + off_t pos, off_t len); void check_truncate(int handle, unsigned name, off_t len); void check_mkdir(unsigned name); void check_rmdir(unsigned name); void check_unlink(unsigned name); void check_link(unsigned from, unsigned to); void check_rename(unsigned from, unsigned to); -void check_renamexd(unsigned fromdir, unsigned from, - unsigned todir, unsigned to); +void check_renamexd(unsigned fromdir, unsigned from, unsigned todir, + unsigned to); void check_chdir(unsigned name); void check_chdirup(void); void check_sync(void); - void check_setup(void); void checkfs(void); diff --git a/userland/testbin/frack/data.c b/userland/testbin/frack/data.c index dbaa26f..7ca019b 100644 --- a/userland/testbin/frack/data.c +++ b/userland/testbin/frack/data.c @@ -43,68 +43,51 @@ static char databuf[DATA_MAXSIZE]; static char readbuf[DATA_MAXSIZE]; -static -void -prepdata(unsigned code, unsigned seq, char *buf, off_t len) -{ - char smallbuf[32]; - char letter; - size_t slen; +static void prepdata(unsigned code, unsigned seq, char *buf, off_t len) { + char smallbuf[32]; + char letter; + size_t slen; - snprintf(smallbuf, sizeof(smallbuf), "%u@%u\n", seq, code); - slen = strlen(smallbuf); + snprintf(smallbuf, sizeof(smallbuf), "%u@%u\n", seq, code); + slen = strlen(smallbuf); - while (len >= slen) { - memcpy(buf, smallbuf, slen); - buf += slen; - len -= slen; - } - if (len > 1) { - letter = 'A' + (code + seq) % 26; - memset(buf, letter, len - 1); - buf += len - 1; - } - if (len > 0) { - *buf = '\n'; - } + while (len >= slen) { + memcpy(buf, smallbuf, slen); + buf += slen; + len -= slen; + } + if (len > 1) { + letter = 'A' + (code + seq) % 26; + memset(buf, letter, len - 1); + buf += len - 1; + } + if (len > 0) { + *buf = '\n'; + } } -static -int -matches_at(size_t start, size_t len) -{ - if (!memcmp(databuf + start, readbuf + start, len)) { - return 1; - } - return 0; +static int matches_at(size_t start, size_t len) { + if (!memcmp(databuf + start, readbuf + start, len)) { + return 1; + } + return 0; } -static -int -byte_at(size_t start, size_t len, unsigned char val) -{ - size_t i; +static int byte_at(size_t start, size_t len, unsigned char val) { + size_t i; - for (i=0; i 0); - assert(checklen <= len); - assert(checkstart >= 0 && checkstart < len); - assert(checkstart + checklen <= len); - assert(zerostart >= 0); - assert(zerostart <= len); + assert(len <= DATA_MAXSIZE); + assert(checklen > 0); + assert(checklen <= len); + assert(checkstart >= 0 && checkstart < len); + assert(checkstart + checklen <= len); + assert(zerostart >= 0); + assert(zerostart <= len); - prepdata(code, seq, databuf, len); + prepdata(code, seq, databuf, len); - ret = 1; - while (checklen > 0) { - /* check one block at a time */ - where = checkstart; - howmuch = BLOCKSIZE; - /* no more than is left to do */ - if (howmuch > checklen) { - howmuch = checklen; - } - /* if we stick over a block boundary, stop there */ - absend = regionoffset + where + howmuch; - slop = absend % BLOCKSIZE; - if (slop != 0 && slop < howmuch) { - howmuch -= slop; - } - /* if we go past the zerostart point, stop there */ - if (where < zerostart && where + howmuch > zerostart) { - howmuch = zerostart - where; - } - assert(howmuch > 0); + ret = 1; + while (checklen > 0) { + /* check one block at a time */ + where = checkstart; + howmuch = BLOCKSIZE; + /* no more than is left to do */ + if (howmuch > checklen) { + howmuch = checklen; + } + /* if we stick over a block boundary, stop there */ + absend = regionoffset + where + howmuch; + slop = absend % BLOCKSIZE; + if (slop != 0 && slop < howmuch) { + howmuch -= slop; + } + /* if we go past the zerostart point, stop there */ + if (where < zerostart && where + howmuch > zerostart) { + howmuch = zerostart - where; + } + assert(howmuch > 0); - if (matches_at(where, howmuch)) { - /* nothing */ - } - else if (zero_at(where, howmuch)) { - if (where >= zerostart) { - printf("WARNING: file %s range %lld-%lld is " - "zeroed\n", - namestr, regionoffset + where, - regionoffset + where + howmuch); - } - else { - ret = 0; - } - } - else if (poison_at(where, howmuch)) { - if (where >= zerostart) { - printf("ERROR: file %s range %lld-%lld is " - "poisoned\n", - namestr, regionoffset + where, - regionoffset + where + howmuch); - } - else { - ret = 0; - } - } - else { - ret = 0; - } + if (matches_at(where, howmuch)) { + /* nothing */ + } else if (zero_at(where, howmuch)) { + if (where >= zerostart) { + printf("WARNING: file %s range %lld-%lld is " + "zeroed\n", + namestr, regionoffset + where, regionoffset + where + howmuch); + } else { + ret = 0; + } + } else if (poison_at(where, howmuch)) { + if (where >= zerostart) { + printf("ERROR: file %s range %lld-%lld is " + "poisoned\n", + namestr, regionoffset + where, regionoffset + where + howmuch); + } else { + ret = 0; + } + } else { + ret = 0; + } - checkstart += howmuch; - checklen -= howmuch; - } - return ret; + checkstart += howmuch; + checklen -= howmuch; + } + return ret; } -void -data_check(const char *namestr, off_t regionoffset, - unsigned code, unsigned seq, off_t zerostart, off_t len, - off_t checkstart, off_t checklen) -{ - assert(zerostart >= 0); - assert(zerostart <= len); +void data_check(const char *namestr, off_t regionoffset, unsigned code, + unsigned seq, off_t zerostart, off_t len, off_t checkstart, + off_t checklen) { + assert(zerostart >= 0); + assert(zerostart <= len); - if (!data_matches(namestr, regionoffset, - code, seq, zerostart, len, checkstart, checklen)) { - printf("ERROR: file %s range %lld-%lld contains garbage\n", - namestr, regionoffset + checkstart, - regionoffset + checkstart + checklen); - } + if (!data_matches(namestr, regionoffset, code, seq, zerostart, len, + checkstart, checklen)) { + printf("ERROR: file %s range %lld-%lld contains garbage\n", namestr, + regionoffset + checkstart, regionoffset + checkstart + checklen); + } } -void * -data_map(unsigned code, unsigned seq, off_t len) -{ - assert(len <= DATA_MAXSIZE); - prepdata(code, seq, databuf, len); - return databuf; +void *data_map(unsigned code, unsigned seq, off_t len) { + assert(len <= DATA_MAXSIZE); + prepdata(code, seq, databuf, len); + return databuf; } -void * -data_mapreadbuf(off_t len) -{ - assert(len <= DATA_MAXSIZE); - return readbuf; +void *data_mapreadbuf(off_t len) { + assert(len <= DATA_MAXSIZE); + return readbuf; } diff --git a/userland/testbin/frack/data.h b/userland/testbin/frack/data.h index 6d5c15e..f49ea56 100644 --- a/userland/testbin/frack/data.h +++ b/userland/testbin/frack/data.h @@ -30,12 +30,12 @@ void *data_map(unsigned code, unsigned seq, off_t len); void *data_mapreadbuf(off_t len); -int data_matches(const char *namestr, off_t regionoffset, - unsigned code, unsigned seq, off_t zerostart, off_t len, - off_t checkstart, off_t checklen); -void data_check(const char *namestr, off_t regionoffset, - unsigned code, unsigned seq, off_t zerostart, off_t len, - off_t checkstart, off_t checklen); +int data_matches(const char *namestr, off_t regionoffset, unsigned code, + unsigned seq, off_t zerostart, off_t len, off_t checkstart, + off_t checklen); +void data_check(const char *namestr, off_t regionoffset, unsigned code, + unsigned seq, off_t zerostart, off_t len, off_t checkstart, + off_t checklen); #define DATA_MAXSIZE 65536 #define POISON_VAL 0xa9 diff --git a/userland/testbin/frack/do.c b/userland/testbin/frack/do.c index 059cf2c..8e7457c 100644 --- a/userland/testbin/frack/do.c +++ b/userland/testbin/frack/do.c @@ -39,213 +39,180 @@ #include "name.h" #include "do.h" -int -do_opendir(unsigned name) -{ - const char *namestr; - int fd; +int do_opendir(unsigned name) { + const char *namestr; + int fd; - namestr = name_get(name); - fd = open(namestr, O_RDONLY); - if (fd < 0) { - err(1, "%s: opendir", namestr); - } - return fd; + namestr = name_get(name); + fd = open(namestr, O_RDONLY); + if (fd < 0) { + err(1, "%s: opendir", namestr); + } + return fd; } -void -do_closedir(int fd, unsigned name) -{ - if (close(fd)) { - warn("%s: closedir", name_get(name)); - } +void do_closedir(int fd, unsigned name) { + if (close(fd)) { + warn("%s: closedir", name_get(name)); + } } -int -do_createfile(unsigned name) -{ - const char *namestr; - int fd; +int do_createfile(unsigned name) { + const char *namestr; + int fd; - namestr = name_get(name); - fd = open(namestr, O_WRONLY|O_CREAT|O_EXCL, 0664); - if (fd < 0) { - err(1, "%s: create", namestr); - } - printf("create %s\n", namestr); - return fd; + namestr = name_get(name); + fd = open(namestr, O_WRONLY | O_CREAT | O_EXCL, 0664); + if (fd < 0) { + err(1, "%s: create", namestr); + } + printf("create %s\n", namestr); + return fd; } -int -do_openfile(unsigned name, int dotrunc) -{ - const char *namestr; - int fd; +int do_openfile(unsigned name, int dotrunc) { + const char *namestr; + int fd; - namestr = name_get(name); - fd = open(namestr, O_WRONLY | (dotrunc ? O_TRUNC : 0), 0664); - if (fd < 0) { - err(1, "%s: open", namestr); - } - return fd; + namestr = name_get(name); + fd = open(namestr, O_WRONLY | (dotrunc ? O_TRUNC : 0), 0664); + if (fd < 0) { + err(1, "%s: open", namestr); + } + return fd; } -void -do_closefile(int fd, unsigned name) -{ - if (close(fd)) { - warn("%s: close", name_get(name)); - } +void do_closefile(int fd, unsigned name) { + if (close(fd)) { + warn("%s: close", name_get(name)); + } } -void -do_write(int fd, unsigned name, unsigned code, unsigned seq, - off_t pos, off_t len) -{ - off_t done = 0; - ssize_t ret; - char *buf; - const char *namestr; +void do_write(int fd, unsigned name, unsigned code, unsigned seq, off_t pos, + off_t len) { + off_t done = 0; + ssize_t ret; + char *buf; + const char *namestr; - namestr = name_get(name); - buf = data_map(code, seq, len); - if (lseek(fd, pos, SEEK_SET) == -1) { - err(1, "%s: lseek to %lld", name_get(name), pos); - } + namestr = name_get(name); + buf = data_map(code, seq, len); + if (lseek(fd, pos, SEEK_SET) == -1) { + err(1, "%s: lseek to %lld", name_get(name), pos); + } - while (done < len) { - ret = write(fd, buf + done, len - done); - if (ret == -1) { - err(1, "%s: write %lld at %lld", name_get(name), - len, pos); - } - done += ret; - } + while (done < len) { + ret = write(fd, buf + done, len - done); + if (ret == -1) { + err(1, "%s: write %lld at %lld", name_get(name), len, pos); + } + done += ret; + } - printf("write %s: %lld at %lld\n", namestr, len, pos); + printf("write %s: %lld at %lld\n", namestr, len, pos); } -void -do_truncate(int fd, unsigned name, off_t len) -{ - const char *namestr; +void do_truncate(int fd, unsigned name, off_t len) { + const char *namestr; - namestr = name_get(name); - if (ftruncate(fd, len) == -1) { - err(1, "%s: truncate to %lld", namestr, len); - } - printf("truncate %s: to %lld\n", namestr, len); + namestr = name_get(name); + if (ftruncate(fd, len) == -1) { + err(1, "%s: truncate to %lld", namestr, len); + } + printf("truncate %s: to %lld\n", namestr, len); } -void -do_mkdir(unsigned name) -{ - const char *namestr; +void do_mkdir(unsigned name) { + const char *namestr; - namestr = name_get(name); - if (mkdir(namestr, 0775) == -1) { - err(1, "%s: mkdir", namestr); - } - printf("mkdir %s\n", namestr); + namestr = name_get(name); + if (mkdir(namestr, 0775) == -1) { + err(1, "%s: mkdir", namestr); + } + printf("mkdir %s\n", namestr); } -void -do_rmdir(unsigned name) -{ - const char *namestr; +void do_rmdir(unsigned name) { + const char *namestr; - namestr = name_get(name); - if (rmdir(namestr) == -1) { - err(1, "%s: rmdir", namestr); - } - printf("rmdir %s\n", namestr); + namestr = name_get(name); + if (rmdir(namestr) == -1) { + err(1, "%s: rmdir", namestr); + } + printf("rmdir %s\n", namestr); } -void -do_unlink(unsigned name) -{ - const char *namestr; +void do_unlink(unsigned name) { + const char *namestr; - namestr = name_get(name); - if (remove(namestr) == -1) { - err(1, "%s: remove", namestr); - } - printf("remove %s\n", namestr); + namestr = name_get(name); + if (remove(namestr) == -1) { + err(1, "%s: remove", namestr); + } + printf("remove %s\n", namestr); } -void -do_link(unsigned from, unsigned to) -{ - const char *fromstr, *tostr; +void do_link(unsigned from, unsigned to) { + const char *fromstr, *tostr; - fromstr = name_get(from); - tostr = name_get(to); - if (link(fromstr, tostr) == -1) { - err(1, "link %s to %s", fromstr, tostr); - } - printf("link %s %s\n", fromstr, tostr); + fromstr = name_get(from); + tostr = name_get(to); + if (link(fromstr, tostr) == -1) { + err(1, "link %s to %s", fromstr, tostr); + } + printf("link %s %s\n", fromstr, tostr); } -void -do_rename(unsigned from, unsigned to) -{ - const char *fromstr, *tostr; +void do_rename(unsigned from, unsigned to) { + const char *fromstr, *tostr; - fromstr = name_get(from); - tostr = name_get(to); - if (rename(fromstr, tostr) == -1) { - err(1, "rename %s to %s", fromstr, tostr); - } - printf("rename %s %s\n", fromstr, tostr); + fromstr = name_get(from); + tostr = name_get(to); + if (rename(fromstr, tostr) == -1) { + err(1, "rename %s to %s", fromstr, tostr); + } + printf("rename %s %s\n", fromstr, tostr); } -void -do_renamexd(unsigned fromdir, unsigned from, unsigned todir, unsigned to) -{ - char frombuf[64]; - char tobuf[64]; +void do_renamexd(unsigned fromdir, unsigned from, unsigned todir, unsigned to) { + char frombuf[64]; + char tobuf[64]; - strcpy(frombuf, name_get(fromdir)); - strcat(frombuf, "/"); - strcat(frombuf, name_get(from)); + strcpy(frombuf, name_get(fromdir)); + strcat(frombuf, "/"); + strcat(frombuf, name_get(from)); - strcpy(tobuf, name_get(todir)); - strcat(tobuf, "/"); - strcat(tobuf, name_get(to)); + strcpy(tobuf, name_get(todir)); + strcat(tobuf, "/"); + strcat(tobuf, name_get(to)); - if (rename(frombuf, tobuf) == -1) { - err(1, "rename %s to %s", frombuf, tobuf); - } - printf("rename %s %s\n", frombuf, tobuf); + if (rename(frombuf, tobuf) == -1) { + err(1, "rename %s to %s", frombuf, tobuf); + } + printf("rename %s %s\n", frombuf, tobuf); } -void -do_chdir(unsigned name) -{ - const char *namestr; +void do_chdir(unsigned name) { + const char *namestr; - namestr = name_get(name); - if (chdir(namestr) == -1) { - err(1, "chdir: %s", namestr); - } - printf("chdir %s\n", namestr); + namestr = name_get(name); + if (chdir(namestr) == -1) { + err(1, "chdir: %s", namestr); + } + printf("chdir %s\n", namestr); } -void -do_chdirup(void) -{ - if (chdir("..") == -1) { - err(1, "chdir: .."); - } - printf("chdir ..\n"); +void do_chdirup(void) { + if (chdir("..") == -1) { + err(1, "chdir: .."); + } + printf("chdir ..\n"); } -void -do_sync(void) -{ - if (sync()) { - warn("sync"); - } - printf("sync\n"); - printf("----------------------------------------\n"); +void do_sync(void) { + if (sync()) { + warn("sync"); + } + printf("sync\n"); + printf("----------------------------------------\n"); } diff --git a/userland/testbin/frack/do.h b/userland/testbin/frack/do.h index 7726815..95e2682 100644 --- a/userland/testbin/frack/do.h +++ b/userland/testbin/frack/do.h @@ -28,14 +28,13 @@ * SUCH DAMAGE. */ - int do_opendir(unsigned name); void do_closedir(int handle, unsigned name); int do_createfile(unsigned name); int do_openfile(unsigned name, int dotrunc); void do_closefile(int handle, unsigned name); -void do_write(int handle, unsigned name, unsigned code, unsigned seq, - off_t pos, off_t len); +void do_write(int handle, unsigned name, unsigned code, unsigned seq, off_t pos, + off_t len); void do_truncate(int handle, unsigned name, off_t len); void do_mkdir(unsigned name); void do_rmdir(unsigned name); diff --git a/userland/testbin/frack/main.c b/userland/testbin/frack/main.c index 1a0c7e8..f051ebd 100644 --- a/userland/testbin/frack/main.c +++ b/userland/testbin/frack/main.c @@ -37,160 +37,148 @@ #include "main.h" struct workload { - const char *name; - const char *argname; - union { - void (*witharg)(const char *); - void (*noarg)(void); - } run; + const char *name; + const char *argname; + union { + void (*witharg)(const char *); + void (*noarg)(void); + } run; }; -#define WL(n) { .name = #n, .argname = NULL, .run.noarg = wl_##n } -#define WLA(n,a) { .name = #n, .argname = #a, .run.witharg = wl_##n } +#define WL(n) {.name = #n, .argname = NULL, .run.noarg = wl_##n} +#define WLA(n, a) {.name = #n, .argname = #a, .run.witharg = wl_##n} static const struct workload workloads[] = { - WLA(createwrite, size), - WLA(rewrite, size), - WLA(randupdate, size), - WLA(truncwrite, size), - WLA(makehole, size), - WLA(fillhole, size), - WLA(truncfill, size), - WLA(append, size), - WLA(trunczero, size), - WLA(trunconeblock, size), - WLA(truncsmallersize, size), - WLA(trunclargersize, size), - WLA(appendandtrunczero, size), - WLA(appendandtruncpartly, size), - WL(mkfile), - WL(mkdir), - WL(mkmanyfile), - WL(mkmanydir), - WL(mktree), - WLA(mkrandtree, seed), - WL(rmfile), - WL(rmdir), - WL(rmfiledelayed), - WL(rmfiledelayedappend), - WL(rmdirdelayed), - WL(rmmanyfile), - WL(rmmanyfiledelayed), - WL(rmmanyfiledelayedandappend), - WL(rmmanydir), - WL(rmmanydirdelayed), - WL(rmtree), - WLA(rmrandtree, seed), - WL(linkfile), - WL(linkmanyfile), - WL(unlinkfile), - WL(unlinkmanyfile), - WL(linkunlinkfile), - WL(renamefile), - WL(renamedir), - WL(renamesubtree), - WL(renamexdfile), - WL(renamexddir), - WL(renamexdsubtree), - WL(renamemanyfile), - WL(renamemanydir), - WL(renamemanysubtree), - WL(copyandrename), - WL(untar), - WL(compile), - WL(cvsupdate), - WLA(writefileseq, seed), - WLA(writetruncseq, seed), - WLA(mkrmseq, seed), - WLA(linkunlinkseq, seed), - WLA(renameseq, seed), - WLA(diropseq, seed), - WLA(genseq, seed), + WLA(createwrite, size), + WLA(rewrite, size), + WLA(randupdate, size), + WLA(truncwrite, size), + WLA(makehole, size), + WLA(fillhole, size), + WLA(truncfill, size), + WLA(append, size), + WLA(trunczero, size), + WLA(trunconeblock, size), + WLA(truncsmallersize, size), + WLA(trunclargersize, size), + WLA(appendandtrunczero, size), + WLA(appendandtruncpartly, size), + WL(mkfile), + WL(mkdir), + WL(mkmanyfile), + WL(mkmanydir), + WL(mktree), + WLA(mkrandtree, seed), + WL(rmfile), + WL(rmdir), + WL(rmfiledelayed), + WL(rmfiledelayedappend), + WL(rmdirdelayed), + WL(rmmanyfile), + WL(rmmanyfiledelayed), + WL(rmmanyfiledelayedandappend), + WL(rmmanydir), + WL(rmmanydirdelayed), + WL(rmtree), + WLA(rmrandtree, seed), + WL(linkfile), + WL(linkmanyfile), + WL(unlinkfile), + WL(unlinkmanyfile), + WL(linkunlinkfile), + WL(renamefile), + WL(renamedir), + WL(renamesubtree), + WL(renamexdfile), + WL(renamexddir), + WL(renamexdsubtree), + WL(renamemanyfile), + WL(renamemanydir), + WL(renamemanysubtree), + WL(copyandrename), + WL(untar), + WL(compile), + WL(cvsupdate), + WLA(writefileseq, seed), + WLA(writetruncseq, seed), + WLA(mkrmseq, seed), + WLA(linkunlinkseq, seed), + WLA(renameseq, seed), + WLA(diropseq, seed), + WLA(genseq, seed), }; static const unsigned numworkloads = sizeof(workloads) / sizeof(workloads[0]); #undef WL #undef WLA -static -const struct workload * -findworkload(const char *name) -{ - unsigned i; +static const struct workload *findworkload(const char *name) { + unsigned i; - for (i=0; iargname) { - if (argc != 4) { - errx(1, "%s requires argument %s\n", - workloadname, workload->argname); - } - workload->run.witharg(argv[3]); - } - else { - if (argc != 3) { - errx(1, "Stray argument for workload %s",workloadname); - } - workload->run.noarg(); - } - complete(); - return 0; + workloadname = argv[2]; + workload = findworkload(workloadname); + if (workload == NULL) { + errx(1, "Unknown workload %s\n", workloadname); + printworkloads(); + exit(1); + } + setcheckmode(checkmode); + if (workload->argname) { + if (argc != 4) { + errx(1, "%s requires argument %s\n", workloadname, workload->argname); + } + workload->run.witharg(argv[3]); + } else { + if (argc != 3) { + errx(1, "Stray argument for workload %s", workloadname); + } + workload->run.noarg(); + } + complete(); + return 0; } diff --git a/userland/testbin/frack/name.c b/userland/testbin/frack/name.c index 88eff09..335bbd7 100644 --- a/userland/testbin/frack/name.c +++ b/userland/testbin/frack/name.c @@ -37,57 +37,28 @@ #define MAXNAMES 32 static const char *const names[MAXNAMES] = { - "allspice", - "anise", - "basil", - "cardamom", - "cayenne", - "cilantro", - "cinnamon", - "cloves", - "coriander", - "cumin", - "dill", - "fennel", - "fenugreek", - "galangal", - "ginger", - "horseradish", - "lemongrass", - "licorice", - "mace", - "marjoram", - "mustard", - "nutmeg", - "oregano", - "parsley", - "paprika", - "pepper", - "saffron", - "sage", - "rosemary", - "thyme", - "turmeric", - "wasabi", + "allspice", "anise", "basil", "cardamom", "cayenne", + "cilantro", "cinnamon", "cloves", "coriander", "cumin", + "dill", "fennel", "fenugreek", "galangal", "ginger", + "horseradish", "lemongrass", "licorice", "mace", "marjoram", + "mustard", "nutmeg", "oregano", "parsley", "paprika", + "pepper", "saffron", "sage", "rosemary", "thyme", + "turmeric", "wasabi", }; -const char * -name_get(unsigned name) -{ - assert(name < MAXNAMES); - return names[name]; +const char *name_get(unsigned name) { + assert(name < MAXNAMES); + return names[name]; } -unsigned -name_find(const char *namestr) -{ - unsigned i; +unsigned name_find(const char *namestr) { + unsigned i; - for (i=0; iname = name; - if (checkmode) { - ret->handle = -1; - } - else { - ret->handle = do_opendir(name); - } - return ret; + ret = POOLALLOC(dir); + ret->name = name; + if (checkmode) { + ret->handle = -1; + } else { + ret->handle = do_opendir(name); + } + return ret; } -void -op_closedir(struct dir *d) -{ - if (checkmode) { - /* nothing */ - (void)d; - } - else { - do_closedir(d->handle, d->name); - } - POOLFREE(dir, d); +void op_closedir(struct dir *d) { + if (checkmode) { + /* nothing */ + (void)d; + } else { + do_closedir(d->handle, d->name); + } + POOLFREE(dir, d); } //////////////////////////////////////////////////////////// @@ -104,212 +96,166 @@ op_closedir(struct dir *d) #define MAXFILES 32 DECLPOOL(file, MAXFILES); -struct file * -op_open(unsigned testcode, unsigned name, unsigned openflags) -{ - struct file *ret; - int dotrunc; +struct file *op_open(unsigned testcode, unsigned name, unsigned openflags) { + struct file *ret; + int dotrunc; - if (openflags == O_TRUNC) { - openflags = 0; - dotrunc = 1; - } - else { - dotrunc = 0; - } + if (openflags == O_TRUNC) { + openflags = 0; + dotrunc = 1; + } else { + dotrunc = 0; + } - assert(openflags == 0 || openflags == (O_CREAT|O_EXCL)); + assert(openflags == 0 || openflags == (O_CREAT | O_EXCL)); - ret = POOLALLOC(file); - ret->name = name; - ret->testcode = testcode; - ret->seq = 0; - if (checkmode) { - if (openflags) { - ret->handle = check_createfile(name); - } - else { - ret->handle = check_openfile(name); - } - } - else { - if (openflags) { - assert(dotrunc == 0); - ret->handle = do_createfile(name); - } - else { - /* - * XXX: as of 2013 OS/161 doesn't provide a - * truncate call - neither truncate() nor - * ftruncate()! You can only O_TRUNC. Oops... - */ - ret->handle = do_openfile(name, dotrunc); - dotrunc = 0; - } - } - if (dotrunc) { - op_truncate(ret, 0); - } - return ret; + ret = POOLALLOC(file); + ret->name = name; + ret->testcode = testcode; + ret->seq = 0; + if (checkmode) { + if (openflags) { + ret->handle = check_createfile(name); + } else { + ret->handle = check_openfile(name); + } + } else { + if (openflags) { + assert(dotrunc == 0); + ret->handle = do_createfile(name); + } else { + /* + * XXX: as of 2013 OS/161 doesn't provide a + * truncate call - neither truncate() nor + * ftruncate()! You can only O_TRUNC. Oops... + */ + ret->handle = do_openfile(name, dotrunc); + dotrunc = 0; + } + } + if (dotrunc) { + op_truncate(ret, 0); + } + return ret; } -void -op_close(struct file *f) -{ - if (checkmode) { - check_closefile(f->handle, f->name); - } - else { - do_closefile(f->handle, f->name); - } - POOLFREE(file, f); +void op_close(struct file *f) { + if (checkmode) { + check_closefile(f->handle, f->name); + } else { + do_closefile(f->handle, f->name); + } + POOLFREE(file, f); } -void -op_write(struct file *f, off_t pos, off_t len) -{ - off_t amount; +void op_write(struct file *f, off_t pos, off_t len) { + off_t amount; - while (len > 0) { - amount = len; - if (amount > DATA_MAXSIZE) { - amount = DATA_MAXSIZE; - } + while (len > 0) { + amount = len; + if (amount > DATA_MAXSIZE) { + amount = DATA_MAXSIZE; + } - if (checkmode) { - check_write(f->handle, f->name, f->testcode, f->seq, - pos, amount); - } - else { - do_write(f->handle, f->name, f->testcode, f->seq, - pos, amount); - } - f->seq++; - pos += amount; - len -= amount; - } + if (checkmode) { + check_write(f->handle, f->name, f->testcode, f->seq, pos, amount); + } else { + do_write(f->handle, f->name, f->testcode, f->seq, pos, amount); + } + f->seq++; + pos += amount; + len -= amount; + } } -void -op_truncate(struct file *f, off_t len) -{ - if (checkmode) { - check_truncate(f->handle, f->name, len); - } - else { - do_truncate(f->handle, f->name, len); - } +void op_truncate(struct file *f, off_t len) { + if (checkmode) { + check_truncate(f->handle, f->name, len); + } else { + do_truncate(f->handle, f->name, len); + } } //////////////////////////////////////////////////////////// // dirops -void -op_mkdir(unsigned name) -{ - if (checkmode) { - check_mkdir(name); - } - else { - do_mkdir(name); - } +void op_mkdir(unsigned name) { + if (checkmode) { + check_mkdir(name); + } else { + do_mkdir(name); + } } -void -op_rmdir(unsigned name) -{ - if (checkmode) { - check_rmdir(name); - } - else { - do_rmdir(name); - } +void op_rmdir(unsigned name) { + if (checkmode) { + check_rmdir(name); + } else { + do_rmdir(name); + } } -void -op_unlink(unsigned name) -{ - if (checkmode) { - check_unlink(name); - } - else { - do_unlink(name); - } +void op_unlink(unsigned name) { + if (checkmode) { + check_unlink(name); + } else { + do_unlink(name); + } } -void -op_link(unsigned from, unsigned to) -{ - if (checkmode) { - check_link(from, to); - } - else { - do_link(from, to); - } +void op_link(unsigned from, unsigned to) { + if (checkmode) { + check_link(from, to); + } else { + do_link(from, to); + } } -void -op_rename(unsigned from, unsigned to) -{ - if (checkmode) { - check_rename(from, to); - } - else { - do_rename(from, to); - } +void op_rename(unsigned from, unsigned to) { + if (checkmode) { + check_rename(from, to); + } else { + do_rename(from, to); + } } -void -op_renamexd(unsigned fromdir, unsigned from, unsigned todir, unsigned to) -{ - if (checkmode) { - check_renamexd(fromdir, from, todir, to); - } - else { - do_renamexd(fromdir, from, todir, to); - } +void op_renamexd(unsigned fromdir, unsigned from, unsigned todir, unsigned to) { + if (checkmode) { + check_renamexd(fromdir, from, todir, to); + } else { + do_renamexd(fromdir, from, todir, to); + } } -void -op_chdir(unsigned name) -{ - if (checkmode) { - check_chdir(name); - } - else { - do_chdir(name); - } +void op_chdir(unsigned name) { + if (checkmode) { + check_chdir(name); + } else { + do_chdir(name); + } } -void -op_chdirup(void) -{ - if (checkmode) { - check_chdirup(); - } - else { - do_chdirup(); - } +void op_chdirup(void) { + if (checkmode) { + check_chdirup(); + } else { + do_chdirup(); + } } //////////////////////////////////////////////////////////// // other -void -op_sync(void) -{ - if (checkmode) { - check_sync(); - } - else { - do_sync(); - } +void op_sync(void) { + if (checkmode) { + check_sync(); + } else { + do_sync(); + } } -void -complete(void) -{ - if (checkmode) { - checkfs(); - } +void complete(void) { + if (checkmode) { + checkfs(); + } } diff --git a/userland/testbin/frack/pool.c b/userland/testbin/frack/pool.c index ceda9c3..5f6231a 100644 --- a/userland/testbin/frack/pool.c +++ b/userland/testbin/frack/pool.c @@ -34,37 +34,33 @@ #include "pool.h" -unsigned -poolalloc(struct poolctl *pool) -{ - uint32_t mask; - unsigned j, i; +unsigned poolalloc(struct poolctl *pool) { + uint32_t mask; + unsigned j, i; - assert(pool->max % 32 == 0); - for (j=0; jmax/32; j++) { - for (mask=1, i=0; i<32; mask<<=1, i++) { - if ((pool->inuse[j] & mask) == 0) { - pool->inuse[j] |= mask; - return j*32 + i; - } - } - } - errx(1, "Too many %s -- increase %s in %s", - pool->itemtype, pool->maxname, pool->file); - return 0; + assert(pool->max % 32 == 0); + for (j = 0; j < pool->max / 32; j++) { + for (mask = 1, i = 0; i < 32; mask <<= 1, i++) { + if ((pool->inuse[j] & mask) == 0) { + pool->inuse[j] |= mask; + return j * 32 + i; + } + } + } + errx(1, "Too many %s -- increase %s in %s", pool->itemtype, pool->maxname, + pool->file); + return 0; } -void -poolfree(struct poolctl *pool, unsigned num) -{ - uint32_t mask; - unsigned pos; +void poolfree(struct poolctl *pool, unsigned num) { + uint32_t mask; + unsigned pos; - assert(num < pool->max); + assert(num < pool->max); - pos = num / 32; - mask = 1 << (num % 32); + pos = num / 32; + mask = 1 << (num % 32); - assert(pool->inuse[pos] & mask); - pool->inuse[pos] &= ~(uint32_t)mask; + assert(pool->inuse[pos] & mask); + pool->inuse[pos] &= ~(uint32_t)mask; } diff --git a/userland/testbin/frack/pool.h b/userland/testbin/frack/pool.h index f24347f..aa6cad0 100644 --- a/userland/testbin/frack/pool.h +++ b/userland/testbin/frack/pool.h @@ -29,26 +29,24 @@ */ struct poolctl { - uint32_t *inuse; - unsigned max; - const char *itemtype; - const char *maxname; - const char *file; + uint32_t *inuse; + unsigned max; + const char *itemtype; + const char *maxname; + const char *file; }; -#define DIVROUNDUP(a, b) (((a) + (b) - 1) / (b)) -#define ROUNDUP(a, b) (DIVROUNDUP(a, b) * (b)) +#define DIVROUNDUP(a, b) (((a) + (b) - 1) / (b)) +#define ROUNDUP(a, b) (DIVROUNDUP(a, b) * (b)) -#define DECLPOOL(T, MAX) \ - static struct T pool_space_##T[ROUNDUP(MAX, 32)]; \ - static uint32_t pool_inuse_##T[DIVROUNDUP(MAX, 32)]; \ - static struct poolctl pool_##T = { \ - .inuse = pool_inuse_##T, \ - .max = ROUNDUP(MAX, 32), \ - .itemtype = "struct " #T, \ - .maxname = #MAX, \ - .file = __FILE__ \ - } +#define DECLPOOL(T, MAX) \ + static struct T pool_space_##T[ROUNDUP(MAX, 32)]; \ + static uint32_t pool_inuse_##T[DIVROUNDUP(MAX, 32)]; \ + static struct poolctl pool_##T = {.inuse = pool_inuse_##T, \ + .max = ROUNDUP(MAX, 32), \ + .itemtype = "struct " #T, \ + .maxname = #MAX, \ + .file = __FILE__} #define POOLALLOC(T) (&pool_space_##T[poolalloc(&pool_##T)]) #define POOLFREE(T, x) (poolfree(&pool_##T, (x) - pool_space_##T)) diff --git a/userland/testbin/frack/workloads.c b/userland/testbin/frack/workloads.c index e7b33d3..864de54 100644 --- a/userland/testbin/frack/workloads.c +++ b/userland/testbin/frack/workloads.c @@ -49,10 +49,7 @@ typedef unsigned bool; //////////////////////////////////////////////////////////// // support code -static -unsigned long -getnum(const char *str) -{ +static unsigned long getnum(const char *str) { #if 0 /* sigh */ unsigned long val; char *x; @@ -67,7 +64,7 @@ getnum(const char *str) } return val; #else - return atoi(str); + return atoi(str); #endif } @@ -75,249 +72,209 @@ getnum(const char *str) // standard sizes enum sizes { - SIZE_ONE, - SIZE_SMALL, - SIZE_MEDIUM, - SIZE_LARGE, - SIZE_LARGEPLUS, + SIZE_ONE, + SIZE_SMALL, + SIZE_MEDIUM, + SIZE_LARGE, + SIZE_LARGEPLUS, }; /* * This only returns the sizes that can be selected from the command * line. */ -static -enum sizes -strtosize(const char *word) -{ - if (!strcmp(word, "small")) { - return SIZE_SMALL; - } - if (!strcmp(word, "medium")) { - return SIZE_MEDIUM; - } - if (!strcmp(word, "large")) { - return SIZE_LARGE; - } - errx(1, "Invalid size %s (try small, medium, or large)", word); - /* XXX errx should be declared noreturn */ - return SIZE_SMALL; +static enum sizes strtosize(const char *word) { + if (!strcmp(word, "small")) { + return SIZE_SMALL; + } + if (!strcmp(word, "medium")) { + return SIZE_MEDIUM; + } + if (!strcmp(word, "large")) { + return SIZE_LARGE; + } + errx(1, "Invalid size %s (try small, medium, or large)", word); + /* XXX errx should be declared noreturn */ + return SIZE_SMALL; } -static -enum sizes -randsize(void) -{ - switch (random() % 7) { - case 0: - return SIZE_ONE; - case 1: - case 2: - case 3: - return SIZE_SMALL; - case 4: - case 5: - return SIZE_MEDIUM; - case 6: +static enum sizes randsize(void) { + switch (random() % 7) { + case 0: + return SIZE_ONE; + case 1: + case 2: + case 3: + return SIZE_SMALL; + case 4: + case 5: + return SIZE_MEDIUM; + case 6: #if 0 /* too annoying */ return SIZE_LARGE; #else - return SIZE_MEDIUM; + return SIZE_MEDIUM; #endif - } - return SIZE_ONE; + } + return SIZE_ONE; } -static -enum sizes -nextsmallersize(enum sizes sz) -{ - switch (sz) { - case SIZE_ONE: - break; - case SIZE_SMALL: - return SIZE_ONE; - case SIZE_MEDIUM: - return SIZE_SMALL; - case SIZE_LARGE: - return SIZE_MEDIUM; - case SIZE_LARGEPLUS: - return SIZE_LARGE; - } - assert(0); - return SIZE_ONE; +static enum sizes nextsmallersize(enum sizes sz) { + switch (sz) { + case SIZE_ONE: + break; + case SIZE_SMALL: + return SIZE_ONE; + case SIZE_MEDIUM: + return SIZE_SMALL; + case SIZE_LARGE: + return SIZE_MEDIUM; + case SIZE_LARGEPLUS: + return SIZE_LARGE; + } + assert(0); + return SIZE_ONE; } -static -enum sizes -nextlargersize(enum sizes sz) -{ - switch (sz) { - case SIZE_ONE: - return SIZE_SMALL; - case SIZE_SMALL: - return SIZE_MEDIUM; - case SIZE_MEDIUM: - return SIZE_LARGE; - case SIZE_LARGE: - return SIZE_LARGEPLUS; - case SIZE_LARGEPLUS: - break; - } - assert(0); - return SIZE_LARGEPLUS; +static enum sizes nextlargersize(enum sizes sz) { + switch (sz) { + case SIZE_ONE: + return SIZE_SMALL; + case SIZE_SMALL: + return SIZE_MEDIUM; + case SIZE_MEDIUM: + return SIZE_LARGE; + case SIZE_LARGE: + return SIZE_LARGEPLUS; + case SIZE_LARGEPLUS: + break; + } + assert(0); + return SIZE_LARGEPLUS; } -static -unsigned -sizeblocks(enum sizes sz) -{ - /* - * XXX for now hardwire things we know about SFS - */ +static unsigned sizeblocks(enum sizes sz) { + /* + * XXX for now hardwire things we know about SFS + */ #define BLOCKSIZE /*SFS_BLOCKSIZE*/ 512 - static const unsigned ndb = /*SFS_NDIRECT*/ 15; - static const unsigned dbperidb = /*SFS_DBPERIDB*/ 128; + static const unsigned ndb = /*SFS_NDIRECT*/ 15; + static const unsigned dbperidb = /*SFS_DBPERIDB*/ 128; - switch (sz) { - case SIZE_ONE: - /* one block; 512 bytes */ - return 1; - case SIZE_SMALL: - /* fits in direct blocks only; 7.5K */ - return ndb; - case SIZE_MEDIUM: - /* uses an indirect block; ~40K */ - return ndb + dbperidb / 2; - case SIZE_LARGE: - /* uses a double-indirect block; 4.2M */ - return ndb + dbperidb + dbperidb * dbperidb / 2; - case SIZE_LARGEPLUS: - /* requires a triple-indirect block; 8.5M */ - return ndb + dbperidb + dbperidb * dbperidb + dbperidb / 2; - } - assert(0); - return 12; + switch (sz) { + case SIZE_ONE: + /* one block; 512 bytes */ + return 1; + case SIZE_SMALL: + /* fits in direct blocks only; 7.5K */ + return ndb; + case SIZE_MEDIUM: + /* uses an indirect block; ~40K */ + return ndb + dbperidb / 2; + case SIZE_LARGE: + /* uses a double-indirect block; 4.2M */ + return ndb + dbperidb + dbperidb * dbperidb / 2; + case SIZE_LARGEPLUS: + /* requires a triple-indirect block; 8.5M */ + return ndb + dbperidb + dbperidb * dbperidb + dbperidb / 2; + } + assert(0); + return 12; } -static -unsigned -sizebytes(enum sizes sz) -{ - return BLOCKSIZE * sizeblocks(sz); -} +static unsigned sizebytes(enum sizes sz) { return BLOCKSIZE * sizeblocks(sz); } //////////////////////////////////////////////////////////// // common suboperations -static -void -file_randomwrite(struct file *f, enum sizes sz, - unsigned startskip, unsigned endskip) -{ - unsigned nblocks, nwrites, i; - unsigned blocknum; - off_t pos; +static void file_randomwrite(struct file *f, enum sizes sz, unsigned startskip, + unsigned endskip) { + unsigned nblocks, nwrites, i; + unsigned blocknum; + off_t pos; - nblocks = sizeblocks(sz); - assert(nblocks > startskip + endskip); + nblocks = sizeblocks(sz); + assert(nblocks > startskip + endskip); - nwrites = nblocks/6; - if (nwrites < 2) { - nwrites = 2; - } + nwrites = nblocks / 6; + if (nwrites < 2) { + nwrites = 2; + } - nblocks -= startskip + endskip; - for (i=0; i -static -void -wl_mktree_sub(unsigned testcode, unsigned depth) -{ - unsigned i, numthings = 4; +static void wl_mktree_sub(unsigned testcode, unsigned depth) { + unsigned i, numthings = 4; - for (i=0; i 0) { - return; - } - break; - case 2: - case 3: - writenewfile(testcode, numhere/*filenum*/, SIZE_ONE); - (*ct)++; - numhere++; - break; - } - } + numhere = 0; + while (*ct < numthings) { + switch (random() % 4) { + case 0: + (*ct)++; + op_mkdir(numhere /*filenum*/); + op_chdir(numhere /*filenum*/); + mkrandtree_sub(testcode, depth + 1, ct, numthings); + op_chdirup(); + numhere++; + break; + case 1: + if (depth > 0) { + return; + } + break; + case 2: + case 3: + writenewfile(testcode, numhere /*filenum*/, SIZE_ONE); + (*ct)++; + numhere++; + break; + } + } } -static -void -rmrandtree_sub(unsigned depth, unsigned *ct, unsigned numthings) -{ - unsigned numhere; +static void rmrandtree_sub(unsigned depth, unsigned *ct, unsigned numthings) { + unsigned numhere; - numhere = 0; - while (*ct < numthings) { - switch (random() % 4) { - case 0: - (*ct)++; - op_chdir(numhere/*filenum*/); - rmrandtree_sub(depth + 1, ct, numthings); - op_chdirup(); - op_rmdir(numhere/*filenum*/); - numhere++; - break; - case 1: - if (depth > 0) { - return; - } - break; - case 2: - case 3: - op_unlink(numhere/*filenum*/); - (*ct)++; - numhere++; - break; - } - } + numhere = 0; + while (*ct < numthings) { + switch (random() % 4) { + case 0: + (*ct)++; + op_chdir(numhere /*filenum*/); + rmrandtree_sub(depth + 1, ct, numthings); + op_chdirup(); + op_rmdir(numhere /*filenum*/); + numhere++; + break; + case 1: + if (depth > 0) { + return; + } + break; + case 2: + case 3: + op_unlink(numhere /*filenum*/); + (*ct)++; + numhere++; + break; + } + } } -void -wl_mkrandtree(const char *seed) -{ - unsigned testcode = 103; - unsigned numthings, count; - unsigned long seednum = getnum(seed); +void wl_mkrandtree(const char *seed) { + unsigned testcode = 103; + unsigned numthings, count; + unsigned long seednum = getnum(seed); - srandom(seednum); - numthings = random() % 44 + 12; - count = 0; + srandom(seednum); + numthings = random() % 44 + 12; + count = 0; - mkrandtree_sub(testcode, 0, &count, numthings); + mkrandtree_sub(testcode, 0, &count, numthings); } //////////////////////////////////////////////////////////// @@ -785,27 +686,23 @@ wl_mkrandtree(const char *seed) /* * Delete a file. (We have to create the file first and sync it.) */ -void -wl_rmfile(void) -{ - unsigned testcode = 150; +void wl_rmfile(void) { + unsigned testcode = 150; - writenewfile(testcode, 0/*filenum*/, SIZE_ONE); - writeemptyfile(1/*filenum*/); - op_sync(); - op_unlink(0/*filenum*/); + writenewfile(testcode, 0 /*filenum*/, SIZE_ONE); + writeemptyfile(1 /*filenum*/); + op_sync(); + op_unlink(0 /*filenum*/); } /* * Delete a directory. (We have to mkdir first and sync it.) */ -void -wl_rmdir(void) -{ - op_mkdir(0/*filenum*/); - writeemptyfile(1/*filenum*/); - op_sync(); - op_rmdir(0/*filenum*/); +void wl_rmdir(void) { + op_mkdir(0 /*filenum*/); + writeemptyfile(1 /*filenum*/); + op_sync(); + op_rmdir(0 /*filenum*/); } /* @@ -814,101 +711,91 @@ wl_rmdir(void) * (Should there be a form of this that syncs after unlinking but * before closing?) */ -void -wl_rmfiledelayed(void) -{ - unsigned testcode = 151; - struct file *f; +void wl_rmfiledelayed(void) { + unsigned testcode = 151; + struct file *f; - writenewfile(testcode, 0/*filenum*/, SIZE_ONE); - writeemptyfile(1/*filenum*/); - op_sync(); - f = op_open(testcode, 0/*filenum*/, 0); - op_unlink(0/*filenum*/); - op_close(f); + writenewfile(testcode, 0 /*filenum*/, SIZE_ONE); + writeemptyfile(1 /*filenum*/); + op_sync(); + f = op_open(testcode, 0 /*filenum*/, 0); + op_unlink(0 /*filenum*/); + op_close(f); } /* * Delete a file, with delayed reclaim, and append to the file before * reclaiming. */ -void -wl_rmfiledelayedappend(void) -{ - unsigned testcode = 152; - struct file *f; - enum sizes sz = SIZE_SMALL; +void wl_rmfiledelayedappend(void) { + unsigned testcode = 152; + struct file *f; + enum sizes sz = SIZE_SMALL; - writenewfile(testcode, 0/*filenum*/, sz); - writeemptyfile(1/*filenum*/); - op_sync(); - f = op_open(testcode, 0/*filenum*/, 0); - op_unlink(0/*filenum*/); - op_write(f, sizebytes(sz), 6 * BLOCKSIZE); - op_close(f); + writenewfile(testcode, 0 /*filenum*/, sz); + writeemptyfile(1 /*filenum*/); + op_sync(); + f = op_open(testcode, 0 /*filenum*/, 0); + op_unlink(0 /*filenum*/); + op_write(f, sizebytes(sz), 6 * BLOCKSIZE); + op_close(f); } /* * Delete a directory, with delayed reclaim. */ -void -wl_rmdirdelayed(void) -{ - struct dir *d; +void wl_rmdirdelayed(void) { + struct dir *d; - op_mkdir(0/*filenum*/); - writeemptyfile(1/*filenum*/); - op_sync(); - d = op_opendir(0/*filenum*/); - op_rmdir(0/*filenum*/); - op_closedir(d); + op_mkdir(0 /*filenum*/); + writeemptyfile(1 /*filenum*/); + op_sync(); + d = op_opendir(0 /*filenum*/); + op_rmdir(0 /*filenum*/); + op_closedir(d); } /* * Delete many files. */ -void -wl_rmmanyfile(void) -{ - unsigned testcode = 153; - unsigned numfiles = 27; - unsigned i; +void wl_rmmanyfile(void) { + unsigned testcode = 153; + unsigned numfiles = 27; + unsigned i; - for (i=0; i #include -#define PageSize 4096 -#define NumPages 512 +#define PageSize 4096 +#define NumPages 512 -int sparse[NumPages][PageSize]; /* use only the first element in the row */ +int sparse[NumPages][PageSize]; /* use only the first element in the row */ -int -main(void) -{ - int i,j; +int main(void) { + int i, j; - printf("Entering the huge program - I will stress test your VM\n"); + printf("Entering the huge program - I will stress test your VM\n"); - /* move number in so that sparse[i][0]=i */ - for (i=0; i=0; i--) { - if (sparse[i][0]!=i+5) { - printf("BAD NEWS!!! - your VM mechanism has a bug!\n"); - exit(1); - } - } + /* check if the numbers are sane */ + for (i = NumPages - 1; i >= 0; i--) { + if (sparse[i][0] != i + 5) { + printf("BAD NEWS!!! - your VM mechanism has a bug!\n"); + exit(1); + } + } - printf("You passed!\n"); + printf("You passed!\n"); - return 0; + return 0; } - diff --git a/userland/testbin/malloctest/malloctest.c b/userland/testbin/malloctest/malloctest.c index 5f3d4bf..5187c96 100644 --- a/userland/testbin/malloctest/malloctest.c +++ b/userland/testbin/malloctest/malloctest.c @@ -49,52 +49,45 @@ #include #include +#define _PATH_RANDOM "random:" -#define _PATH_RANDOM "random:" - -#define SMALLSIZE 72 -#define MEDIUMSIZE 896 -#define BIGSIZE 16384 -#define HUGESIZE (1024 * 1024 * 1024) +#define SMALLSIZE 72 +#define MEDIUMSIZE 896 +#define BIGSIZE 16384 +#define HUGESIZE (1024 * 1024 * 1024) /* Maximum amount of space per block we allow for indexing structures */ -#define OVERHEAD 32 +#define OVERHEAD 32 /* Point past which we assume something else is going on */ -#define ABSURD_OVERHEAD 256 +#define ABSURD_OVERHEAD 256 -static -int -geti(void) -{ - int val=0; - int ch, digits=0; +static int geti(void) { + int val = 0; + int ch, digits = 0; - while (1) { - ch = getchar(); - if (ch=='\n' || ch=='\r') { - putchar('\n'); - break; - } - else if ((ch=='\b' || ch==127) && digits>0) { - printf("\b \b"); - val = val/10; - digits--; - } - else if (ch>='0' && ch<='9') { - putchar(ch); - val = val*10 + (ch-'0'); - digits++; - } - else { - putchar('\a'); - } - } + while (1) { + ch = getchar(); + if (ch == '\n' || ch == '\r') { + putchar('\n'); + break; + } else if ((ch == '\b' || ch == 127) && digits > 0) { + printf("\b \b"); + val = val / 10; + digits--; + } else if (ch >= '0' && ch <= '9') { + putchar(ch); + val = val * 10 + (ch - '0'); + digits++; + } else { + putchar('\a'); + } + } - if (digits==0) { - return -1; - } - return val; + if (digits == 0) { + return -1; + } + return val; } //////////////////////////////////////////////////////////// @@ -102,65 +95,60 @@ geti(void) /* * Fill a block of memory with a test pattern. */ -static -void -markblock(volatile void *ptr, size_t size, unsigned bias, int doprint) -{ - size_t n, i; - unsigned long *pl; - unsigned long val; +static void markblock(volatile void *ptr, size_t size, unsigned bias, + int doprint) { + size_t n, i; + unsigned long *pl; + unsigned long val; - pl = (unsigned long *)ptr; - n = size / sizeof(unsigned long); + pl = (unsigned long *)ptr; + n = size / sizeof(unsigned long); - for (i=0; inext = list; - list = tmp; + assert(tmp != list); + tmp->next = list; + list = tmp; - tot += sizeof(struct test3); + tot += sizeof(struct test3); - markblock(list->junk, sizeof(list->junk), (uintptr_t)list, 0); + markblock(list->junk, sizeof(list->junk), (uintptr_t)list, 0); - ct++; - if (ct%128==0) { - printf("."); - } - } + ct++; + if (ct % 128 == 0) { + printf("."); + } + } - printf("Allocated %lu bytes\n", (unsigned long) tot); + printf("Allocated %lu bytes\n", (unsigned long)tot); - printf("Trying some more allocations which I expect to fail...\n"); + printf("Trying some more allocations which I expect to fail...\n"); - x = malloc(SMALLSIZE); - if (x != NULL) { - printf("FAILED: malloc(%u) succeeded\n", SMALLSIZE); - return; - } + x = malloc(SMALLSIZE); + if (x != NULL) { + printf("FAILED: malloc(%u) succeeded\n", SMALLSIZE); + return; + } - x = malloc(MEDIUMSIZE); - if (x != NULL) { - printf("FAILED: malloc(%u) succeeded\n", MEDIUMSIZE); - return; - } + x = malloc(MEDIUMSIZE); + if (x != NULL) { + printf("FAILED: malloc(%u) succeeded\n", MEDIUMSIZE); + return; + } - x = malloc(BIGSIZE); - if (x != NULL) { - printf("FAILED: malloc(%u) succeeded\n", BIGSIZE); - return; - } + x = malloc(BIGSIZE); + if (x != NULL) { + printf("FAILED: malloc(%u) succeeded\n", BIGSIZE); + return; + } - printf("Ok, now I'm going to free everything...\n"); + printf("Ok, now I'm going to free everything...\n"); - while (list != NULL) { - tmp = list->next; + while (list != NULL) { + tmp = list->next; - if (checkblock(list->junk, sizeof(list->junk), - (uintptr_t)list, 0)) { - failed = 1; - } + if (checkblock(list->junk, sizeof(list->junk), (uintptr_t)list, 0)) { + failed = 1; + } - free(list); - list = tmp; - } + free(list); + list = tmp; + } - if (failed) { - printf("FAILED: data corruption\n"); - return; - } + if (failed) { + printf("FAILED: data corruption\n"); + return; + } - printf("Let me see if I can allocate some more now...\n"); + printf("Let me see if I can allocate some more now...\n"); - x = malloc(MEDIUMSIZE); - if (x == NULL) { - printf("FAIL: Nope, I couldn't.\n"); - return; - } - free(x); + x = malloc(MEDIUMSIZE); + if (x == NULL) { + printf("FAIL: Nope, I couldn't.\n"); + return; + } + free(x); - printf("Passed malloc test 3\n"); + printf("Passed malloc test 3\n"); } //////////////////////////////////////////////////////////// @@ -390,121 +365,117 @@ test3(void) * next-fit/best-fit algorithm is used. */ -static -void -test4(void) -{ - void *x, *y, *z; - unsigned long lx, ly, lz, overhead, zsize; +static void test4(void) { + void *x, *y, *z; + unsigned long lx, ly, lz, overhead, zsize; - printf("Entering malloc test 4.\n"); - printf("This test is intended for first/best-fit based mallocs.\n"); - printf("This test may not work correctly if run after other tests.\n"); + printf("Entering malloc test 4.\n"); + printf("This test is intended for first/best-fit based mallocs.\n"); + printf("This test may not work correctly if run after other tests.\n"); - printf("Testing free list coalescing:\n"); + printf("Testing free list coalescing:\n"); - x = malloc(SMALLSIZE); - if (x==NULL) { - printf("FAILED: malloc(%u) failed\n", SMALLSIZE); - return; - } + x = malloc(SMALLSIZE); + if (x == NULL) { + printf("FAILED: malloc(%u) failed\n", SMALLSIZE); + return; + } - y = malloc(MEDIUMSIZE); - if (y==NULL) { - printf("FAILED: malloc(%u) failed\n", MEDIUMSIZE); - return; - } + y = malloc(MEDIUMSIZE); + if (y == NULL) { + printf("FAILED: malloc(%u) failed\n", MEDIUMSIZE); + return; + } - if (sizeof(unsigned long) < sizeof(void *)) { - printf("Buh? I can't fit a void * in an unsigned long\n"); - printf("ENVIRONMENT FAILED...\n"); - return; - } + if (sizeof(unsigned long) < sizeof(void *)) { + printf("Buh? I can't fit a void * in an unsigned long\n"); + printf("ENVIRONMENT FAILED...\n"); + return; + } - lx = (unsigned long)x; - ly = (unsigned long)y; + lx = (unsigned long)x; + ly = (unsigned long)y; - printf("x is 0x%lx; y is 0x%lx\n", lx, ly); + printf("x is 0x%lx; y is 0x%lx\n", lx, ly); - /* - * The memory should look something like this: - * - * OXXXOYYYYYYYYYYY - * - * where O are optional overhead (indexing) blocks. - */ + /* + * The memory should look something like this: + * + * OXXXOYYYYYYYYYYY + * + * where O are optional overhead (indexing) blocks. + */ - /* This is obviously wrong. */ - if (lx == ly) { - printf("FAIL: x == y\n"); - return; - } + /* This is obviously wrong. */ + if (lx == ly) { + printf("FAIL: x == y\n"); + return; + } - /* - * Check for overlap. It is sufficient to check if the start - * of each block is within the other block. (If the end of a - * block is within the other block, either the start is too, - * or the other block's start is within the first block.) - */ - if (lx < ly && lx + SMALLSIZE > ly) { - printf("FAIL: y starts within x\n"); - return; - } - if (ly < lx && ly + MEDIUMSIZE > lx) { - printf("FAIL: x starts within y\n"); - return; - } + /* + * Check for overlap. It is sufficient to check if the start + * of each block is within the other block. (If the end of a + * block is within the other block, either the start is too, + * or the other block's start is within the first block.) + */ + if (lx < ly && lx + SMALLSIZE > ly) { + printf("FAIL: y starts within x\n"); + return; + } + if (ly < lx && ly + MEDIUMSIZE > lx) { + printf("FAIL: x starts within y\n"); + return; + } - /* - * If y is lower than x, some memory scheme we don't - * understand is in use, or else there's already stuff on the - * free list. - */ - if (ly < lx) { - printf("TEST UNSUITABLE: y is below x\n"); - return; - } + /* + * If y is lower than x, some memory scheme we don't + * understand is in use, or else there's already stuff on the + * free list. + */ + if (ly < lx) { + printf("TEST UNSUITABLE: y is below x\n"); + return; + } - /* - * Compute the space used by index structures. - */ - overhead = ly - (lx + SMALLSIZE); - printf("Apparent block overhead: %lu\n", overhead); + /* + * Compute the space used by index structures. + */ + overhead = ly - (lx + SMALLSIZE); + printf("Apparent block overhead: %lu\n", overhead); - if (overhead > ABSURD_OVERHEAD) { - printf("TEST UNSUITABLE: block overhead absurdly large.\n"); - return; - } - if (overhead > OVERHEAD) { - printf("FAIL: block overhead is too large.\n"); - return; - } + if (overhead > ABSURD_OVERHEAD) { + printf("TEST UNSUITABLE: block overhead absurdly large.\n"); + return; + } + if (overhead > OVERHEAD) { + printf("FAIL: block overhead is too large.\n"); + return; + } - printf("Freeing blocks...\n"); - free(x); - free(y); + printf("Freeing blocks...\n"); + free(x); + free(y); - zsize = SMALLSIZE + MEDIUMSIZE + overhead; + zsize = SMALLSIZE + MEDIUMSIZE + overhead; - printf("Now allocating %lu bytes... should reuse the space.\n", zsize); - z = malloc(zsize); - if (z == NULL) { - printf("FAIL: Allocation failed...\n"); - return; - } + printf("Now allocating %lu bytes... should reuse the space.\n", zsize); + z = malloc(zsize); + if (z == NULL) { + printf("FAIL: Allocation failed...\n"); + return; + } - lz = (unsigned long) z; + lz = (unsigned long)z; - printf("z is 0x%lx (x was 0x%lx, y 0x%lx)\n", lz, lx, ly); + printf("z is 0x%lx (x was 0x%lx, y 0x%lx)\n", lz, lx, ly); - if (lz==lx) { - printf("Passed.\n"); - } - else { - printf("Failed.\n"); - } + if (lz == lx) { + printf("Passed.\n"); + } else { + printf("Failed.\n"); + } - free(z); + free(z); } //////////////////////////////////////////////////////////// @@ -519,176 +490,152 @@ test4(void) * Test 7 asks for a seed. */ -static -void -test567(int testno, unsigned long seed) -{ - static const int sizes[8] = { 13, 17, 69, 176, 433, 871, 1150, 6060 }; +static void test567(int testno, unsigned long seed) { + static const int sizes[8] = {13, 17, 69, 176, 433, 871, 1150, 6060}; - void *ptrs[32]; - int psizes[32]; - int i, n, size, failed=0; + void *ptrs[32]; + int psizes[32]; + int i, n, size, failed = 0; - srandom(seed); - printf("Seeded random number generator with %lu.\n", seed); + srandom(seed); + printf("Seeded random number generator with %lu.\n", seed); - for (i=0; i<32; i++) { - ptrs[i] = NULL; - psizes[i] = 0; - } + for (i = 0; i < 32; i++) { + ptrs[i] = NULL; + psizes[i] = 0; + } - for (i=0; i<100000; i++) { - n = random()%32; - if (ptrs[n] == NULL) { - size = sizes[random()%8]; - ptrs[n] = malloc(size); - psizes[n] = size; - if (ptrs[n] == NULL) { - printf("\nmalloc %u failed\n", size); - failed = 1; - break; - } - markblock(ptrs[n], size, n, 0); - } - else { - size = psizes[n]; - if (checkblock(ptrs[n], size, n, 0)) { - failed = 1; - break; - } - free(ptrs[n]); - ptrs[n] = NULL; - psizes[n] = 0; - } - if (i%256==0) { - printf("."); - } - } - printf("\n"); + for (i = 0; i < 100000; i++) { + n = random() % 32; + if (ptrs[n] == NULL) { + size = sizes[random() % 8]; + ptrs[n] = malloc(size); + psizes[n] = size; + if (ptrs[n] == NULL) { + printf("\nmalloc %u failed\n", size); + failed = 1; + break; + } + markblock(ptrs[n], size, n, 0); + } else { + size = psizes[n]; + if (checkblock(ptrs[n], size, n, 0)) { + failed = 1; + break; + } + free(ptrs[n]); + ptrs[n] = NULL; + psizes[n] = 0; + } + if (i % 256 == 0) { + printf("."); + } + } + printf("\n"); - for (i=0; i<32; i++) { - if (ptrs[i] != NULL) { - free(ptrs[i]); - } - } + for (i = 0; i < 32; i++) { + if (ptrs[i] != NULL) { + free(ptrs[i]); + } + } - if (failed) { - printf("FAILED malloc test %d\n", testno); - } - else { - printf("Passed malloc test %d\n", testno); - } + if (failed) { + printf("FAILED malloc test %d\n", testno); + } else { + printf("Passed malloc test %d\n", testno); + } } -static -void -test5(void) -{ - printf("Beginning malloc test 5\n"); - test567(5, 0); +static void test5(void) { + printf("Beginning malloc test 5\n"); + test567(5, 0); } -static -void -test6(void) -{ - int fd, len; - unsigned long seed; +static void test6(void) { + int fd, len; + unsigned long seed; - printf("Beginning malloc test 6\n"); + printf("Beginning malloc test 6\n"); - fd = open(_PATH_RANDOM, O_RDONLY); - if (fd < 0) { - err(1, "%s", _PATH_RANDOM); - } - len = read(fd, &seed, sizeof(seed)); - if (len < 0) { - err(1, "%s", _PATH_RANDOM); - } - else if (len < (int)sizeof(seed)) { - errx(1, "%s: Short read", _PATH_RANDOM); - } - close(fd); + fd = open(_PATH_RANDOM, O_RDONLY); + if (fd < 0) { + err(1, "%s", _PATH_RANDOM); + } + len = read(fd, &seed, sizeof(seed)); + if (len < 0) { + err(1, "%s", _PATH_RANDOM); + } else if (len < (int)sizeof(seed)) { + errx(1, "%s: Short read", _PATH_RANDOM); + } + close(fd); - test567(6, seed); + test567(6, seed); } -static -void -test7(void) -{ - unsigned long seed; +static void test7(void) { + unsigned long seed; - printf("Beginning malloc test 7\n"); + printf("Beginning malloc test 7\n"); - printf("Enter random seed: "); - seed = geti(); + printf("Enter random seed: "); + seed = geti(); - test567(7, seed); + test567(7, seed); } //////////////////////////////////////////////////////////// static struct { - int num; - const char *desc; - void (*func)(void); -} tests[] = { - { 1, "Simple allocation test", test1 }, - { 2, "Allocate all memory in a big chunk", test2 }, - { 3, "Allocate all memory in small chunks", test3 }, - { 4, "Free list coalescing test (first/next/best-fit only)", test4 }, - { 5, "Stress test", test5 }, - { 6, "Randomized stress test", test6 }, - { 7, "Stress test with particular seed", test7 }, - { -1, NULL, NULL } -}; + int num; + const char *desc; + void (*func)(void); +} tests[] = {{1, "Simple allocation test", test1}, + {2, "Allocate all memory in a big chunk", test2}, + {3, "Allocate all memory in small chunks", test3}, + {4, "Free list coalescing test (first/next/best-fit only)", test4}, + {5, "Stress test", test5}, + {6, "Randomized stress test", test6}, + {7, "Stress test with particular seed", test7}, + {-1, NULL, NULL}}; -static -int -dotest(int tn) -{ - int i; - for (i=0; tests[i].num>=0; i++) { - if (tests[i].num == tn) { - tests[i].func(); - return 0; - } - } - return -1; +static int dotest(int tn) { + int i; + for (i = 0; tests[i].num >= 0; i++) { + if (tests[i].num == tn) { + tests[i].func(); + return 0; + } + } + return -1; } -int -main(int argc, char *argv[]) -{ - int i, tn, menu=1; +int main(int argc, char *argv[]) { + int i, tn, menu = 1; - if (argc > 1) { - for (i=1; i 1) { + for (i = 1; i < argc; i++) { + dotest(atoi(argv[i])); + } + return 0; + } - while (1) { - if (menu) { - for (i=0; tests[i].num>=0; i++) { - printf(" %2d %s\n", tests[i].num, - tests[i].desc); - } - menu = 0; - } - printf("malloctest: "); - tn = geti(); - if (tn < 0) { - break; - } + while (1) { + if (menu) { + for (i = 0; tests[i].num >= 0; i++) { + printf(" %2d %s\n", tests[i].num, tests[i].desc); + } + menu = 0; + } + printf("malloctest: "); + tn = geti(); + if (tn < 0) { + break; + } - if (dotest(tn)) { - menu = 1; - } - } + if (dotest(tn)) { + menu = 1; + } + } - return 0; + return 0; } - diff --git a/userland/testbin/matmult/matmult-orig.c b/userland/testbin/matmult/matmult-orig.c index b707347..0f45a7e 100644 --- a/userland/testbin/matmult/matmult-orig.c +++ b/userland/testbin/matmult/matmult-orig.c @@ -48,41 +48,39 @@ #include #include -#define Dim 360 /* sum total of the arrays doesn't fit in - * physical memory - */ +#define Dim \ + 360 /* sum total of the arrays doesn't fit in \ + * physical memory \ + */ -#define RIGHT 46397160 /* correct answer */ +#define RIGHT 46397160 /* correct answer */ int A[Dim][Dim]; int B[Dim][Dim]; int C[Dim][Dim]; -int -main(void) -{ - int i, j, k, r; +int main(void) { + int i, j, k, r; - for (i = 0; i < Dim; i++) /* first initialize the matrices */ - for (j = 0; j < Dim; j++) { - A[i][j] = i; - B[i][j] = j; - C[i][j] = 0; - } - - for (i = 0; i < Dim; i++) /* then multiply them together */ - for (j = 0; j < Dim; j++) - for (k = 0; k < Dim; k++) - C[i][j] += A[i][k] * B[k][j]; - - printf("matmult-orig finished.\n"); - r = C[Dim-1][Dim-1]; - printf("answer is: %d (should be %d)\n", r, RIGHT); - if (r != RIGHT) { - printf("FAILED\n"); + for (i = 0; i < Dim; i++) /* first initialize the matrices */ + for (j = 0; j < Dim; j++) { + A[i][j] = i; + B[i][j] = j; + C[i][j] = 0; } - else { - printf("Passed.\n"); - } - return 0; + + for (i = 0; i < Dim; i++) /* then multiply them together */ + for (j = 0; j < Dim; j++) + for (k = 0; k < Dim; k++) + C[i][j] += A[i][k] * B[k][j]; + + printf("matmult-orig finished.\n"); + r = C[Dim - 1][Dim - 1]; + printf("answer is: %d (should be %d)\n", r, RIGHT); + if (r != RIGHT) { + printf("FAILED\n"); + } else { + printf("Passed.\n"); + } + return 0; } diff --git a/userland/testbin/matmult/matmult.c b/userland/testbin/matmult/matmult.c index 6dd99a3..260dc64 100644 --- a/userland/testbin/matmult/matmult.c +++ b/userland/testbin/matmult/matmult.c @@ -42,49 +42,48 @@ #include #include -#define Dim 72 /* sum total of the arrays doesn't fit in - * physical memory - */ +#define Dim \ + 72 /* sum total of the arrays doesn't fit in \ + * physical memory \ + */ -#define RIGHT 8772192 /* correct answer */ +#define RIGHT 8772192 /* correct answer */ int A[Dim][Dim]; int B[Dim][Dim]; int C[Dim][Dim]; int T[Dim][Dim][Dim]; -int -main(void) -{ - int i, j, k, r; +int main(void) { + int i, j, k, r; - for (i = 0; i < Dim; i++) /* first initialize the matrices */ - for (j = 0; j < Dim; j++) { - A[i][j] = i; - B[i][j] = j; - C[i][j] = 0; - } - - for (i = 0; i < Dim; i++) /* then multiply them together */ - for (j = 0; j < Dim; j++) - for (k = 0; k < Dim; k++) - T[i][j][k] = A[i][k] * B[k][j]; - - for (i = 0; i < Dim; i++) - for (j = 0; j < Dim; j++) - for (k = 0; k < Dim; k++) - C[i][j] += T[i][j][k]; - - r = 0; - for (i = 0; i < Dim; i++) - r += C[i][i]; - - printf("matmult finished.\n"); - printf("answer is: %d (should be %d)\n", r, RIGHT); - if (r != RIGHT) { - printf("FAILED\n"); - return 1; + for (i = 0; i < Dim; i++) /* first initialize the matrices */ + for (j = 0; j < Dim; j++) { + A[i][j] = i; + B[i][j] = j; + C[i][j] = 0; } - printf("Passed.\n"); - return 0; + + for (i = 0; i < Dim; i++) /* then multiply them together */ + for (j = 0; j < Dim; j++) + for (k = 0; k < Dim; k++) + T[i][j][k] = A[i][k] * B[k][j]; + + for (i = 0; i < Dim; i++) + for (j = 0; j < Dim; j++) + for (k = 0; k < Dim; k++) + C[i][j] += T[i][j][k]; + + r = 0; + for (i = 0; i < Dim; i++) + r += C[i][i]; + + printf("matmult finished.\n"); + printf("answer is: %d (should be %d)\n", r, RIGHT); + if (r != RIGHT) { + printf("FAILED\n"); + return 1; + } + printf("Passed.\n"); + return 0; } diff --git a/userland/testbin/multiexec/multiexec.c b/userland/testbin/multiexec/multiexec.c index b6f157d..0335905 100644 --- a/userland/testbin/multiexec/multiexec.c +++ b/userland/testbin/multiexec/multiexec.c @@ -81,74 +81,52 @@ */ struct usem { - char name[32]; - int fd; + char name[32]; + int fd; }; -static -void -semcreate(const char *tag, struct usem *sem) -{ - int fd; +static void semcreate(const char *tag, struct usem *sem) { + int fd; - snprintf(sem->name, sizeof(sem->name), "sem:multiexec.%s.%d", - tag, (int)getpid()); + snprintf(sem->name, sizeof(sem->name), "sem:multiexec.%s.%d", tag, + (int)getpid()); - fd = open(sem->name, O_WRONLY|O_CREAT|O_TRUNC, 0664); - if (fd < 0) { - err(1, "%s: create", sem->name); - } - close(fd); + fd = open(sem->name, O_WRONLY | O_CREAT | O_TRUNC, 0664); + if (fd < 0) { + err(1, "%s: create", sem->name); + } + close(fd); } -static -void -semopen(struct usem *sem) -{ - sem->fd = open(sem->name, O_RDWR, 0664); - if (sem->fd < 0) { - err(1, "%s: open", sem->name); - } +static void semopen(struct usem *sem) { + sem->fd = open(sem->name, O_RDWR, 0664); + if (sem->fd < 0) { + err(1, "%s: open", sem->name); + } } -static -void -semclose(struct usem *sem) -{ - close(sem->fd); +static void semclose(struct usem *sem) { close(sem->fd); } + +static void semdestroy(struct usem *sem) { remove(sem->name); } + +static void semP(struct usem *sem, size_t num) { + char c[num]; + + if (read(sem->fd, c, num) < 0) { + err(1, "%s: read", sem->name); + } + (void)c; } -static -void -semdestroy(struct usem *sem) -{ - remove(sem->name); -} +static void semV(struct usem *sem, size_t num) { + char c[num]; -static -void -semP(struct usem *sem, size_t num) -{ - char c[num]; + /* semfs does not use these values, but be conservative */ + memset(c, 0, num); - if (read(sem->fd, c, num) < 0) { - err(1, "%s: read", sem->name); - } - (void)c; -} - -static -void -semV(struct usem *sem, size_t num) -{ - char c[num]; - - /* semfs does not use these values, but be conservative */ - memset(c, 0, num); - - if (write(sem->fd, c, num) < 0) { - err(1, "%s: write", sem->name); - } + if (write(sem->fd, c, num) < 0) { + err(1, "%s: write", sem->name); + } } //////////////////////////////////////////////////////////// @@ -158,115 +136,105 @@ semV(struct usem *sem, size_t num) static char *subargv[SUBARGC_MAX]; static int subargc = 0; -static -void -spawn(int njobs) -{ - struct usem s1, s2; - pid_t pids[njobs]; - int failed, status; - int i; +static void spawn(int njobs) { + struct usem s1, s2; + pid_t pids[njobs]; + int failed, status; + int i; - semcreate("1", &s1); - semcreate("2", &s2); + semcreate("1", &s1); + semcreate("2", &s2); - printf("Forking %d child processes...\n", njobs); + printf("Forking %d child processes...\n", njobs); - for (i=0; i 0) { - warnx("%d children failed", failed); - } - else { - printf("Succeeded\n"); - } + failed = 0; + for (i = 0; i < njobs; i++) { + if (waitpid(pids[i], &status, 0) < 0) { + warn("waitpid"); + failed++; + } else if (WIFSIGNALED(status)) { + warnx("pid %d (child %d): Signal %d", (int)pids[i], i, WTERMSIG(status)); + failed++; + } else if (WIFEXITED(status) && WEXITSTATUS(status) != 0) { + warnx("pid %d (child %d): Exit %d", (int)pids[i], i, WEXITSTATUS(status)); + failed++; + } + } + if (failed > 0) { + warnx("%d children failed", failed); + } else { + printf("Succeeded\n"); + } - semclose(&s1); - semclose(&s2); - semdestroy(&s1); - semdestroy(&s2); + semclose(&s1); + semclose(&s2); + semdestroy(&s1); + semdestroy(&s2); } -int -main(int argc, char *argv[]) -{ - static char default_prog[] = "/bin/pwd"; +int main(int argc, char *argv[]) { + static char default_prog[] = "/bin/pwd"; - int njobs = 12; - int i; + int njobs = 12; + int i; - for (i=1; i= SUBARGC_MAX) { - errx(1, "Too many arguments"); - } - } - } + else { + subargv[subargc++] = argv[i]; + if (subargc >= SUBARGC_MAX) { + errx(1, "Too many arguments"); + } + } + } - if (subargc == 0) { - subargv[subargc++] = default_prog; - } - subargv[subargc] = NULL; + if (subargc == 0) { + subargv[subargc++] = default_prog; + } + subargv[subargc] = NULL; - spawn(njobs); + spawn(njobs); - return 0; + return 0; } diff --git a/userland/testbin/palin/palin.c b/userland/testbin/palin/palin.c index 6bc476c..7c7f682 100644 --- a/userland/testbin/palin/palin.c +++ b/userland/testbin/palin/palin.c @@ -29,19 +29,19 @@ /* - Test suite. + Test suite. - This program takes the palindrome below and checks if it's - a palindrome or not. It will hopefully exhibit an interesting - page fault pattern. + This program takes the palindrome below and checks if it's + a palindrome or not. It will hopefully exhibit an interesting + page fault pattern. - The palindrome was taken from + The palindrome was taken from - http://www.cs.brown.edu/people/nfp/palindrome.html + http://www.cs.brown.edu/people/nfp/palindrome.html - This is not large enough to really stress the VM system, but - might be useful for testing in the early stages of the VM - assignment. + This is not large enough to really stress the VM system, but + might be useful for testing in the early stages of the VM + assignment. */ /* @@ -85,114 +85,112 @@ a canal - Panama! #include char palindrome[8000] = -"amanaplanacaretabanamyriadasumalacaliarahoopapintacatalpaagasanoil" -"abirdayellavatacawapaxawagataxanayaramacapayamagayatsarawalla" -"caralugerawardabinawomanavassalawolfatunaanitapallafretawattabaya" -"daubatanacabadatumagallahatafagazapasayajawalayawetagallopatuga" -"trotatrapatramatorracaperatopatonkatollaballafairasaxaminimatenora" -"bassapasseracapitalarutanamenatedacabalatangasunanassamawasaga" -"jamadamasubasaltanaxonasailanadawadiaradianaroomaroodaripatada" -"pariaharevelareelareedapoolaplugapinapeekaparabolaadogapatacudanua" -"fanapalarumanodanetaalaganeelabatikamugamotanapamaximamooda" -"leekagrubagobageladrabacitadelatotalacedaratapagagaratamanorabara" -"galacolaapapayawatabarajagabanagapaganabagajarabatawayapapaa" -"localagarabaronamataragagapataradecalatotaledaticabardalegaboga" -"burgakeeladoomamixamapanatomagumakitabaleenagalaatenadonamurala" -"panafaunaducatapagodaalobarapakeepanipagulpaloopadeeraleeralevera" -"hairapadatapiradooramooranaidaraidawadanaliasanoxanatlasabusamadam" -"ajagasawamassananusagnatalabacadetanemanaturalatipacaressapassa" -"baronetaminimaxasariafallaballotaknotapotarepacarrotamartapartatorta" -"gutapollagatewayalawajayasapazagafatahallagamutadabacanatabuaday" -"abattawaterfallapatinaanutaflowalassavanamowanibadrawaregularacalla" -"warastayagamayapacamarayanaxatagawaxapawacatavalleyadribaliona" -"sagaaplatacatnipapooharailacalamusadairymanabateracanalpanama" -"amanaplanacaretabanamyriadasumalacaliarahoopapintacatalpaagasanoil" -"abirdayellavatacawapaxawagataxanayaramacapayamagayatsarawalla" -"caralugerawardabinawomanavassalawolfatunaanitapallafretawattabaya" -"daubatanacabadatumagallahatafagazapasayajawalayawetagallopatuga" -"trotatrapatramatorracaperatopatonkatollaballafairasaxaminimatenora" -"bassapasseracapitalarutanamenatedacabalatangasunanassamawasaga" -"jamadamasubasaltanaxonasailanadawadiaradianaroomaroodaripatada" -"pariaharevelareelareedapoolaplugapinapeekaparabolaadogapatacudanua" -"fanapalarumanodanetaalaganeelabatikamugamotanapamaximamooda" -"leekagrubagobageladrabacitadelatotalacedaratapagagaratamanorabara" -"galacolaapapayawatabarajagabanagapaganabagajarabatawayapapaa" -"localagarabaronamataragagapataradecalatotaledaticabardalegaboga" -"burgakeeladoomamixamapanatomagumakitabaleenagalaatenadonamurala" -"panafaunaducatapagodaalobarapakeepanipagulpaloopadeeraleeralevera" -"hairapadatapiradooramooranaidaraidawadanaliasanoxanatlasabusamadam" -"ajagasawamassananusagnatalabacadetanemanaturalatipacaressapassa" -"baronetaminimaxasariafallaballotaknotapotarepacarrotamartapartatorta" -"gutapollagatewayalawajayasapazagafatahallagamutadabacanatabuaday" -"abattawaterfallapatinaanutaflowalassavanamowanibadrawaregularacalla" -"warastayagamayapacamarayanaxatagawaxapawacatavalleyadribaliona" -"sagaaplatacatnipapooharailacalamusadairymanabateracanalpanama" -"amanaplanacaretabanamyriadasumalacaliarahoopapintacatalpaagasanoil" -"abirdayellavatacawapaxawagataxanayaramacapayamagayatsarawalla" -"caralugerawardabinawomanavassalawolfatunaanitapallafretawattabaya" -"daubatanacabadatumagallahatafagazapasayajawalayawetagallopatuga" -"trotatrapatramatorracaperatopatonkatollaballafairasaxaminimatenora" -"bassapasseracapitalarutanamenatedacabalatangasunanassamawasaga" -"jamadamasubasaltanaxonasailanadawadiaradianaroomaroodaripatada" -"pariaharevelareelareedapoolaplugapinapeekaparabolaadogapatacudanua" -"fanapalarumanodanetaalaganeelabatikamugamotanapamaximamooda" -"leekagrubagobageladrabacitadelatotalacedaratapagagaratamanorabara" -"galacolaapapayawatabarajagabanagapaganabagajarabatawayapapaa" -"localagarabaronamataragagapataradecalatotaledaticabardalegaboga" -"burgakeeladoomamixamapanatomagumakitabaleenagalaatenadonamurala" -"panafaunaducatapagodaalobarapakeepanipagulpaloopadeeraleeralevera" -"hairapadatapiradooramooranaidaraidawadanaliasanoxanatlasabusamadam" -"ajagasawamassananusagnatalabacadetanemanaturalatipacaressapassa" -"baronetaminimaxasariafallaballotaknotapotarepacarrotamartapartatorta" -"gutapollagatewayalawajayasapazagafatahallagamutadabacanatabuaday" -"abattawaterfallapatinaanutaflowalassavanamowanibadrawaregularacalla" -"warastayagamayapacamarayanaxatagawaxapawacatavalleyadribaliona" -"sagaaplatacatnipapooharailacalamusadairymanabateracanalpanama" -"amanaplanacaretabanamyriadasumalacaliarahoopapintacatalpaagasanoil" -"abirdayellavatacawapaxawagataxanayaramacapayamagayatsarawalla" -"caralugerawardabinawomanavassalawolfatunaanitapallafretawattabaya" -"daubatanacabadatumagallahatafagazapasayajawalayawetagallopatuga" -"trotatrapatramatorracaperatopatonkatollaballafairasaxaminimatenora" -"bassapasseracapitalarutanamenatedacabalatangasunanassamawasaga" -"jamadamasubasaltanaxonasailanadawadiaradianaroomaroodaripatada" -"pariaharevelareelareedapoolaplugapinapeekaparabolaadogapatacudanua" -"fanapalarumanodanetaalaganeelabatikamugamotanapamaximamooda" -"leekagrubagobageladrabacitadelatotalacedaratapagagaratamanorabara" -"galacolaapapayawatabarajagabanagapaganabagajarabatawayapapaa" -"localagarabaronamataragagapataradecalatotaledaticabardalegaboga" -"burgakeeladoomamixamapanatomagumakitabaleenagalaatenadonamurala" -"panafaunaducatapagodaalobarapakeepanipagulpaloopadeeraleeralevera" -"hairapadatapiradooramooranaidaraidawadanaliasanoxanatlasabusamadam" -"ajagasawamassananusagnatalabacadetanemanaturalatipacaressapassa" -"baronetaminimaxasariafallaballotaknotapotarepacarrotamartapartatorta" -"gutapollagatewayalawajayasapazagafatahallagamutadabacanatabuaday" -"abattawaterfallapatinaanutaflowalassavanamowanibadrawaregularacalla" -"warastayagamayapacamarayanaxatagawaxapawacatavalleyadribaliona" -"sagaaplatacatnipapooharailacalamusadairymanabateracanalpanama"; + "amanaplanacaretabanamyriadasumalacaliarahoopapintacatalpaagasanoil" + "abirdayellavatacawapaxawagataxanayaramacapayamagayatsarawalla" + "caralugerawardabinawomanavassalawolfatunaanitapallafretawattabaya" + "daubatanacabadatumagallahatafagazapasayajawalayawetagallopatuga" + "trotatrapatramatorracaperatopatonkatollaballafairasaxaminimatenora" + "bassapasseracapitalarutanamenatedacabalatangasunanassamawasaga" + "jamadamasubasaltanaxonasailanadawadiaradianaroomaroodaripatada" + "pariaharevelareelareedapoolaplugapinapeekaparabolaadogapatacudanua" + "fanapalarumanodanetaalaganeelabatikamugamotanapamaximamooda" + "leekagrubagobageladrabacitadelatotalacedaratapagagaratamanorabara" + "galacolaapapayawatabarajagabanagapaganabagajarabatawayapapaa" + "localagarabaronamataragagapataradecalatotaledaticabardalegaboga" + "burgakeeladoomamixamapanatomagumakitabaleenagalaatenadonamurala" + "panafaunaducatapagodaalobarapakeepanipagulpaloopadeeraleeralevera" + "hairapadatapiradooramooranaidaraidawadanaliasanoxanatlasabusamadam" + "ajagasawamassananusagnatalabacadetanemanaturalatipacaressapassa" + "baronetaminimaxasariafallaballotaknotapotarepacarrotamartapartatorta" + "gutapollagatewayalawajayasapazagafatahallagamutadabacanatabuaday" + "abattawaterfallapatinaanutaflowalassavanamowanibadrawaregularacalla" + "warastayagamayapacamarayanaxatagawaxapawacatavalleyadribaliona" + "sagaaplatacatnipapooharailacalamusadairymanabateracanalpanama" + "amanaplanacaretabanamyriadasumalacaliarahoopapintacatalpaagasanoil" + "abirdayellavatacawapaxawagataxanayaramacapayamagayatsarawalla" + "caralugerawardabinawomanavassalawolfatunaanitapallafretawattabaya" + "daubatanacabadatumagallahatafagazapasayajawalayawetagallopatuga" + "trotatrapatramatorracaperatopatonkatollaballafairasaxaminimatenora" + "bassapasseracapitalarutanamenatedacabalatangasunanassamawasaga" + "jamadamasubasaltanaxonasailanadawadiaradianaroomaroodaripatada" + "pariaharevelareelareedapoolaplugapinapeekaparabolaadogapatacudanua" + "fanapalarumanodanetaalaganeelabatikamugamotanapamaximamooda" + "leekagrubagobageladrabacitadelatotalacedaratapagagaratamanorabara" + "galacolaapapayawatabarajagabanagapaganabagajarabatawayapapaa" + "localagarabaronamataragagapataradecalatotaledaticabardalegaboga" + "burgakeeladoomamixamapanatomagumakitabaleenagalaatenadonamurala" + "panafaunaducatapagodaalobarapakeepanipagulpaloopadeeraleeralevera" + "hairapadatapiradooramooranaidaraidawadanaliasanoxanatlasabusamadam" + "ajagasawamassananusagnatalabacadetanemanaturalatipacaressapassa" + "baronetaminimaxasariafallaballotaknotapotarepacarrotamartapartatorta" + "gutapollagatewayalawajayasapazagafatahallagamutadabacanatabuaday" + "abattawaterfallapatinaanutaflowalassavanamowanibadrawaregularacalla" + "warastayagamayapacamarayanaxatagawaxapawacatavalleyadribaliona" + "sagaaplatacatnipapooharailacalamusadairymanabateracanalpanama" + "amanaplanacaretabanamyriadasumalacaliarahoopapintacatalpaagasanoil" + "abirdayellavatacawapaxawagataxanayaramacapayamagayatsarawalla" + "caralugerawardabinawomanavassalawolfatunaanitapallafretawattabaya" + "daubatanacabadatumagallahatafagazapasayajawalayawetagallopatuga" + "trotatrapatramatorracaperatopatonkatollaballafairasaxaminimatenora" + "bassapasseracapitalarutanamenatedacabalatangasunanassamawasaga" + "jamadamasubasaltanaxonasailanadawadiaradianaroomaroodaripatada" + "pariaharevelareelareedapoolaplugapinapeekaparabolaadogapatacudanua" + "fanapalarumanodanetaalaganeelabatikamugamotanapamaximamooda" + "leekagrubagobageladrabacitadelatotalacedaratapagagaratamanorabara" + "galacolaapapayawatabarajagabanagapaganabagajarabatawayapapaa" + "localagarabaronamataragagapataradecalatotaledaticabardalegaboga" + "burgakeeladoomamixamapanatomagumakitabaleenagalaatenadonamurala" + "panafaunaducatapagodaalobarapakeepanipagulpaloopadeeraleeralevera" + "hairapadatapiradooramooranaidaraidawadanaliasanoxanatlasabusamadam" + "ajagasawamassananusagnatalabacadetanemanaturalatipacaressapassa" + "baronetaminimaxasariafallaballotaknotapotarepacarrotamartapartatorta" + "gutapollagatewayalawajayasapazagafatahallagamutadabacanatabuaday" + "abattawaterfallapatinaanutaflowalassavanamowanibadrawaregularacalla" + "warastayagamayapacamarayanaxatagawaxapawacatavalleyadribaliona" + "sagaaplatacatnipapooharailacalamusadairymanabateracanalpanama" + "amanaplanacaretabanamyriadasumalacaliarahoopapintacatalpaagasanoil" + "abirdayellavatacawapaxawagataxanayaramacapayamagayatsarawalla" + "caralugerawardabinawomanavassalawolfatunaanitapallafretawattabaya" + "daubatanacabadatumagallahatafagazapasayajawalayawetagallopatuga" + "trotatrapatramatorracaperatopatonkatollaballafairasaxaminimatenora" + "bassapasseracapitalarutanamenatedacabalatangasunanassamawasaga" + "jamadamasubasaltanaxonasailanadawadiaradianaroomaroodaripatada" + "pariaharevelareelareedapoolaplugapinapeekaparabolaadogapatacudanua" + "fanapalarumanodanetaalaganeelabatikamugamotanapamaximamooda" + "leekagrubagobageladrabacitadelatotalacedaratapagagaratamanorabara" + "galacolaapapayawatabarajagabanagapaganabagajarabatawayapapaa" + "localagarabaronamataragagapataradecalatotaledaticabardalegaboga" + "burgakeeladoomamixamapanatomagumakitabaleenagalaatenadonamurala" + "panafaunaducatapagodaalobarapakeepanipagulpaloopadeeraleeralevera" + "hairapadatapiradooramooranaidaraidawadanaliasanoxanatlasabusamadam" + "ajagasawamassananusagnatalabacadetanemanaturalatipacaressapassa" + "baronetaminimaxasariafallaballotaknotapotarepacarrotamartapartatorta" + "gutapollagatewayalawajayasapazagafatahallagamutadabacanatabuaday" + "abattawaterfallapatinaanutaflowalassavanamowanibadrawaregularacalla" + "warastayagamayapacamarayanaxatagawaxapawacatavalleyadribaliona" + "sagaaplatacatnipapooharailacalamusadairymanabateracanalpanama"; -int -main(void) -{ - char *start, *end; +int main(void) { + char *start, *end; - printf("Welcome to the palindrome tester!\n"); - printf("I will take a large palindrome and test it.\n"); - printf("Here it is:\n"); - printf("%s\n", palindrome); + printf("Welcome to the palindrome tester!\n"); + printf("I will take a large palindrome and test it.\n"); + printf("Here it is:\n"); + printf("%s\n", palindrome); - printf("Testing..."); - /* skip to end */ - end = palindrome+strlen(palindrome); - end--; + printf("Testing..."); + /* skip to end */ + end = palindrome + strlen(palindrome); + end--; - for (start = palindrome; start <= end; start++, end--) { - putchar('.'); - if (*start != *end) { - printf("NOT a palindrome\n"); - return 0; - } - } + for (start = palindrome; start <= end; start++, end--) { + putchar('.'); + if (*start != *end) { + printf("NOT a palindrome\n"); + return 0; + } + } - printf("IS a palindrome\n"); - return 0; + printf("IS a palindrome\n"); + return 0; } diff --git a/userland/testbin/parallelvm/parallelvm.c b/userland/testbin/parallelvm/parallelvm.c index 953764a..6b8dc3f 100644 --- a/userland/testbin/parallelvm/parallelvm.c +++ b/userland/testbin/parallelvm/parallelvm.c @@ -46,43 +46,23 @@ #include #include -#define NJOBS 24 +#define NJOBS 24 -#define DIM 35 -#define NMATS 11 -#define JOBSIZE ((NMATS+1)*DIM*DIM*sizeof(int)) +#define DIM 35 +#define NMATS 11 +#define JOBSIZE ((NMATS + 1) * DIM * DIM * sizeof(int)) static const int right_answers[NJOBS] = { - -1337312809, - 356204544, - -537881911, - -65406976, - 1952063315, - -843894784, - 1597000869, - -993925120, - 838840559, - -1616928768, - -182386335, - -364554240, - 251084843, - -61403136, - 295326333, - 1488013312, - 1901440647, - 0, - -1901440647, - -1488013312, - -295326333, - 61403136, - -251084843, - 364554240, + -1337312809, 356204544, -537881911, -65406976, 1952063315, -843894784, + 1597000869, -993925120, 838840559, -1616928768, -182386335, -364554240, + 251084843, -61403136, 295326333, 1488013312, 1901440647, 0, + -1901440647, -1488013312, -295326333, 61403136, -251084843, 364554240, }; //////////////////////////////////////////////////////////// struct matrix { - int m_data[DIM][DIM]; + int m_data[DIM][DIM]; }; //////////////////////////////////////////////////////////// @@ -91,129 +71,100 @@ struct matrix { * Use this instead of just calling printf so we know each printout * is atomic; this prevents the lines from getting intermingled. */ -static -void -say(const char *fmt, ...) -{ - char buf[256]; - va_list ap; - va_start(ap, fmt); - vsnprintf(buf, sizeof(buf), fmt, ap); - va_end(ap); - write(STDOUT_FILENO, buf, strlen(buf)); +static void say(const char *fmt, ...) { + char buf[256]; + va_list ap; + va_start(ap, fmt); + vsnprintf(buf, sizeof(buf), fmt, ap); + va_end(ap); + write(STDOUT_FILENO, buf, strlen(buf)); } //////////////////////////////////////////////////////////// -static -void -multiply(struct matrix *res, const struct matrix *m1, const struct matrix *m2) -{ - int i, j, k; +static void multiply(struct matrix *res, const struct matrix *m1, + const struct matrix *m2) { + int i, j, k; - for (i=0; im_data[i][k]*m2->m_data[k][j]; - } - res->m_data[i][j] = val; - } - } + for (i = 0; i < DIM; i++) { + for (j = 0; j < DIM; j++) { + int val = 0; + for (k = 0; k < DIM; k++) { + val += m1->m_data[i][k] * m2->m_data[k][j]; + } + res->m_data[i][j] = val; + } + } } -static -void -addeq(struct matrix *m1, const struct matrix *m2) -{ - int i, j; - for (i=0; im_data[i][j] += m2->m_data[i][j]; - } - } +static void addeq(struct matrix *m1, const struct matrix *m2) { + int i, j; + for (i = 0; i < DIM; i++) { + for (j = 0; j < DIM; j++) { + m1->m_data[i][j] += m2->m_data[i][j]; + } + } } -static -int -trace(const struct matrix *m1) -{ - int i, t=0; - for (i=0; im_data[i][i]; - } - return t; +static int trace(const struct matrix *m1) { + int i, t = 0; + for (i = 0; i < DIM; i++) { + t += m1->m_data[i][i]; + } + return t; } //////////////////////////////////////////////////////////// static struct matrix mats[NMATS]; -static -void -populate_initial_matrixes(int mynum) -{ - int i,j; - struct matrix *m = &mats[0]; - for (i=0; im_data[i][j] = mynum+i-2*j; - } - } +static void populate_initial_matrixes(int mynum) { + int i, j; + struct matrix *m = &mats[0]; + for (i = 0; i < DIM; i++) { + for (j = 0; j < DIM; j++) { + m->m_data[i][j] = mynum + i - 2 * j; + } + } - multiply(&mats[1], &mats[0], &mats[0]); + multiply(&mats[1], &mats[0], &mats[0]); } -static -void -compute(int n) -{ - struct matrix tmp; - int i, j; +static void compute(int n) { + struct matrix tmp; + int i, j; - for (i=0,j=n-1; iname, sizeof(sem->name), "sem:parallelvm.%s.%d", - tag, (int)getpid()); + snprintf(sem->name, sizeof(sem->name), "sem:parallelvm.%s.%d", tag, + (int)getpid()); - fd = open(sem->name, O_WRONLY|O_CREAT|O_TRUNC, 0664); - if (fd < 0) { - err(1, "%s: create", sem->name); - } - close(fd); + fd = open(sem->name, O_WRONLY | O_CREAT | O_TRUNC, 0664); + if (fd < 0) { + err(1, "%s: create", sem->name); + } + close(fd); } -static -void -semopen(struct usem *sem) -{ - sem->fd = open(sem->name, O_RDWR, 0664); - if (sem->fd < 0) { - err(1, "%s: open", sem->name); - } +static void semopen(struct usem *sem) { + sem->fd = open(sem->name, O_RDWR, 0664); + if (sem->fd < 0) { + err(1, "%s: open", sem->name); + } } -static -void -semclose(struct usem *sem) -{ - close(sem->fd); +static void semclose(struct usem *sem) { close(sem->fd); } + +static void semdestroy(struct usem *sem) { remove(sem->name); } + +static void semP(struct usem *sem, size_t num) { + char c[num]; + + if (read(sem->fd, c, num) < 0) { + err(1, "%s: read", sem->name); + } + (void)c; } -static -void -semdestroy(struct usem *sem) -{ - remove(sem->name); -} +static void semV(struct usem *sem, size_t num) { + char c[num]; -static -void -semP(struct usem *sem, size_t num) -{ - char c[num]; + /* semfs does not use these values, but be conservative */ + memset(c, 0, num); - if (read(sem->fd, c, num) < 0) { - err(1, "%s: read", sem->name); - } - (void)c; -} - -static -void -semV(struct usem *sem, size_t num) -{ - char c[num]; - - /* semfs does not use these values, but be conservative */ - memset(c, 0, num); - - if (write(sem->fd, c, num) < 0) { - err(1, "%s: write", sem->name); - } + if (write(sem->fd, c, num) < 0) { + err(1, "%s: write", sem->name); + } } //////////////////////////////////////////////////////////// // driver -static -int -status_is_failure(int status) -{ - /* Proper interpretation of Unix exit status */ - if (WIFSIGNALED(status)) { - return 1; - } - if (!WIFEXITED(status)) { - /* ? */ - return 1; - } - status = WEXITSTATUS(status); - return status != 0; +static int status_is_failure(int status) { + /* Proper interpretation of Unix exit status */ + if (WIFSIGNALED(status)) { + return 1; + } + if (!WIFEXITED(status)) { + /* ? */ + return 1; + } + status = WEXITSTATUS(status); + return status != 0; } -static -void -makeprocs(bool dowait) -{ - int i, status, failcount; - struct usem s1, s2; - pid_t pids[NJOBS]; +static void makeprocs(bool dowait) { + int i, status, failcount; + struct usem s1, s2; + pid_t pids[NJOBS]; - if (dowait) { - semcreate("1", &s1); - semcreate("2", &s2); - } + if (dowait) { + semcreate("1", &s1); + semcreate("2", &s2); + } - printf("Job size approximately %lu bytes\n", (unsigned long) JOBSIZE); - printf("Forking %d jobs; total load %luk\n", NJOBS, - (unsigned long) (NJOBS * JOBSIZE)/1024); + printf("Job size approximately %lu bytes\n", (unsigned long)JOBSIZE); + printf("Forking %d jobs; total load %luk\n", NJOBS, + (unsigned long)(NJOBS * JOBSIZE) / 1024); - for (i=0; i0) { - printf("%d subprocesses failed\n", failcount); - exit(1); - } - printf("Test complete\n"); + if (failcount > 0) { + printf("%d subprocesses failed\n", failcount); + exit(1); + } + printf("Test complete\n"); - semclose(&s1); - semclose(&s2); - semdestroy(&s1); - semdestroy(&s2); + semclose(&s1); + semclose(&s2); + semdestroy(&s1); + semdestroy(&s2); } -int -main(int argc, char *argv[]) -{ - bool dowait = false; +int main(int argc, char *argv[]) { + bool dowait = false; - if (argc == 0) { - /* broken/unimplemented argv handling; do nothing */ - } - else if (argc == 1) { - /* nothing */ - } - else if (argc == 2 && !strcmp(argv[1], "-w")) { - dowait = true; - } - else { - printf("Usage: parallelvm [-w]\n"); - return 1; - } - makeprocs(dowait); - return 0; + if (argc == 0) { + /* broken/unimplemented argv handling; do nothing */ + } else if (argc == 1) { + /* nothing */ + } else if (argc == 2 && !strcmp(argv[1], "-w")) { + dowait = true; + } else { + printf("Usage: parallelvm [-w]\n"); + return 1; + } + makeprocs(dowait); + return 0; } diff --git a/userland/testbin/poisondisk/poisondisk.c b/userland/testbin/poisondisk/poisondisk.c index e329f91..ce22799 100644 --- a/userland/testbin/poisondisk/poisondisk.c +++ b/userland/testbin/poisondisk/poisondisk.c @@ -46,29 +46,24 @@ #define POISON_BYTE 0xa9 #define BLOCKSIZE 512 -static -void -poison(void) -{ - char buf[BLOCKSIZE]; - off_t sectors, i; +static void poison(void) { + char buf[BLOCKSIZE]; + off_t sectors, i; - memset(buf, POISON_BYTE, sizeof(buf)); + memset(buf, POISON_BYTE, sizeof(buf)); - sectors = diskblocks(); - for (i=0; i= 0) { - snprintf(buf, len, "%s: proc %d: ", progname, me); - } - else { - snprintf(buf, len, "%s: ", progname); - } - pos = strlen(buf); + if (me >= 0) { + snprintf(buf, len, "%s: proc %d: ", progname, me); + } else { + snprintf(buf, len, "%s: ", progname); + } + pos = strlen(buf); - vsnprintf(buf+pos, len-pos, fmt, ap); - pos = strlen(buf); + vsnprintf(buf + pos, len - pos, fmt, ap); + pos = strlen(buf); - if (err >= 0) { - snprintf(buf+pos, len-pos, ": %s\n", strerror(err)); - } - else { - snprintf(buf+pos, len-pos, "\n"); - } + if (err >= 0) { + snprintf(buf + pos, len - pos, ": %s\n", strerror(err)); + } else { + snprintf(buf + pos, len - pos, "\n"); + } } -static -void -complainx(const char *fmt, ...) -{ - char buf[256]; - va_list ap; - ssize_t junk; +static void complainx(const char *fmt, ...) { + char buf[256]; + va_list ap; + ssize_t junk; - va_start(ap, fmt); - vscomplain(buf, sizeof(buf), fmt, ap, -1); - va_end(ap); + va_start(ap, fmt); + vscomplain(buf, sizeof(buf), fmt, ap, -1); + va_end(ap); - /* Write the message in one go so it's atomic */ - junk = write(STDERR_FILENO, buf, strlen(buf)); + /* Write the message in one go so it's atomic */ + junk = write(STDERR_FILENO, buf, strlen(buf)); - /* - * This variable must be assigned and then ignored with some - * (broken) Linux C libraries. Ah, Linux... - */ - (void)junk; + /* + * This variable must be assigned and then ignored with some + * (broken) Linux C libraries. Ah, Linux... + */ + (void)junk; } -static -void -complain(const char *fmt, ...) -{ - char buf[256]; - va_list ap; - ssize_t junk; - int err = errno; +static void complain(const char *fmt, ...) { + char buf[256]; + va_list ap; + ssize_t junk; + int err = errno; - va_start(ap, fmt); - vscomplain(buf, sizeof(buf), fmt, ap, err); - va_end(ap); + va_start(ap, fmt); + vscomplain(buf, sizeof(buf), fmt, ap, err); + va_end(ap); - /* Write the message in one go so it's atomic */ - junk = write(STDERR_FILENO, buf, strlen(buf)); + /* Write the message in one go so it's atomic */ + junk = write(STDERR_FILENO, buf, strlen(buf)); - /* - * This variable must be assigned and then ignored with some - * (broken) Linux C libraries. Ah, Linux... - */ - (void)junk; + /* + * This variable must be assigned and then ignored with some + * (broken) Linux C libraries. Ah, Linux... + */ + (void)junk; } //////////////////////////////////////////////////////////// -static -int -doopen(const char *path, int flags, int mode) -{ - int fd; +static int doopen(const char *path, int flags, int mode) { + int fd; - fd = open(path, flags, mode); - if (fd<0) { - complain("%s", path); - exit(1); - } - return fd; + fd = open(path, flags, mode); + if (fd < 0) { + complain("%s", path); + exit(1); + } + return fd; } -static -void -doclose(const char *path, int fd) -{ - if (close(fd)) { - complain("%s: close", path); - exit(1); - } +static void doclose(const char *path, int fd) { + if (close(fd)) { + complain("%s: close", path); + exit(1); + } } -static -void -docreate(const char *path) -{ - int fd; +static void docreate(const char *path) { + int fd; - fd = doopen(path, O_WRONLY|O_CREAT|O_TRUNC, 0664); - doclose(path, fd); + fd = doopen(path, O_WRONLY | O_CREAT | O_TRUNC, 0664); + doclose(path, fd); } -static -void -doremove(const char *path) -{ - static int noremove; +static void doremove(const char *path) { + static int noremove; - if (noremove) { - return; - } + if (noremove) { + return; + } - if (remove(path) < 0) { - if (errno == ENOSYS) { - /* Complain (and try) only once. */ - noremove = 1; - } - complain("%s: remove", path); - } + if (remove(path) < 0) { + if (errno == ENOSYS) { + /* Complain (and try) only once. */ + noremove = 1; + } + complain("%s: remove", path); + } } -static -off_t -getsize(const char *path) -{ - struct stat buf; - int fd; - static int no_stat, no_fstat; +static off_t getsize(const char *path) { + struct stat buf; + int fd; + static int no_stat, no_fstat; - if (!no_stat) { - if (stat(path, &buf) == 0) { - return buf.st_size; - } - if (errno != ENOSYS) { - complain("%s: stat", path); - exit(1); - } - /* Avoid further "Unknown syscall 81" messages */ - no_stat = 1; - } + if (!no_stat) { + if (stat(path, &buf) == 0) { + return buf.st_size; + } + if (errno != ENOSYS) { + complain("%s: stat", path); + exit(1); + } + /* Avoid further "Unknown syscall 81" messages */ + no_stat = 1; + } - fd = doopen(path, O_RDONLY, 0); - if (!no_fstat) { - if (fstat(fd, &buf) == 0) { - close(fd); - return buf.st_size; - } - if (errno != ENOSYS) { - complain("%s: stat", path); - exit(1); - } - /* Avoid further "Unknown syscall 82" messages */ - no_fstat = 1; - } + fd = doopen(path, O_RDONLY, 0); + if (!no_fstat) { + if (fstat(fd, &buf) == 0) { + close(fd); + return buf.st_size; + } + if (errno != ENOSYS) { + complain("%s: stat", path); + exit(1); + } + /* Avoid further "Unknown syscall 82" messages */ + no_fstat = 1; + } - /* otherwise, lseek */ - if (lseek(fd, 0, SEEK_END) >= 0) { - buf.st_size = lseek(fd, 0, SEEK_CUR); - if (buf.st_size >= 0) { - return buf.st_size; - } - } - complain("%s: getting file size with lseek", path); - close(fd); - exit(1); + /* otherwise, lseek */ + if (lseek(fd, 0, SEEK_END) >= 0) { + buf.st_size = lseek(fd, 0, SEEK_CUR); + if (buf.st_size >= 0) { + return buf.st_size; + } + } + complain("%s: getting file size with lseek", path); + close(fd); + exit(1); } -static -size_t -doread(const char *path, int fd, void *buf, size_t len) -{ - int result; +static size_t doread(const char *path, int fd, void *buf, size_t len) { + int result; - result = read(fd, buf, len); - if (result < 0) { - complain("%s: read", path); - exit(1); - } - return (size_t) result; + result = read(fd, buf, len); + if (result < 0) { + complain("%s: read", path); + exit(1); + } + return (size_t)result; } -static -void -doexactread(const char *path, int fd, void *buf, size_t len) -{ - size_t result; +static void doexactread(const char *path, int fd, void *buf, size_t len) { + size_t result; - result = doread(path, fd, buf, len); - if (result != len) { - complainx("%s: read: short count", path); - exit(1); - } + result = doread(path, fd, buf, len); + if (result != len) { + complainx("%s: read: short count", path); + exit(1); + } } -static -void -dowrite(const char *path, int fd, const void *buf, size_t len) -{ - int result; +static void dowrite(const char *path, int fd, const void *buf, size_t len) { + int result; - result = write(fd, buf, len); - if (result < 0) { - complain("%s: write", path); - exit(1); - } - if ((size_t) result != len) { - complainx("%s: write: short count", path); - exit(1); - } + result = write(fd, buf, len); + if (result < 0) { + complain("%s: write", path); + exit(1); + } + if ((size_t)result != len) { + complainx("%s: write: short count", path); + exit(1); + } } -static -void -dolseek(const char *name, int fd, off_t offset, int whence) -{ - if (lseek(fd, offset, whence) < 0) { - complain("%s: lseek", name); - exit(1); - } +static void dolseek(const char *name, int fd, off_t offset, int whence) { + if (lseek(fd, offset, whence) < 0) { + complain("%s: lseek", name); + exit(1); + } } -#if 0 /* let's not require subdirs */ +#if 0 /* let's not require subdirs */ static void dochdir(const char *path) @@ -444,688 +397,607 @@ domkdir(const char *path, int mode) } #endif /* 0 */ -static -pid_t -dofork(void) -{ - pid_t pid; +static pid_t dofork(void) { + pid_t pid; - pid = fork(); - if (pid < 0) { - complain("fork"); - /* but don't exit */ - } + pid = fork(); + if (pid < 0) { + complain("fork"); + /* but don't exit */ + } - return pid; + return pid; } //////////////////////////////////////////////////////////// -static -int -dowait(int guy, pid_t pid) -{ - int status, result; +static int dowait(int guy, pid_t pid) { + int status, result; - result = waitpid(pid, &status, 0); - if (result < 0) { - complain("waitpid"); - return -1; - } - if (WIFSIGNALED(status)) { - complainx("proc %d: signal %d", guy, WTERMSIG(status)); - return -1; - } - assert(WIFEXITED(status)); - status = WEXITSTATUS(status); - if (status) { - complainx("proc %d: exit %d", guy, status); - return -1; - } - return 0; + result = waitpid(pid, &status, 0); + if (result < 0) { + complain("waitpid"); + return -1; + } + if (WIFSIGNALED(status)) { + complainx("proc %d: signal %d", guy, WTERMSIG(status)); + return -1; + } + assert(WIFEXITED(status)); + status = WEXITSTATUS(status); + if (status) { + complainx("proc %d: exit %d", guy, status); + return -1; + } + return 0; } -static -void -doforkall(const char *phasename, void (*func)(void)) -{ - int i, bad = 0; - pid_t pids[numprocs]; +static void doforkall(const char *phasename, void (*func)(void)) { + int i, bad = 0; + pid_t pids[numprocs]; - for (i=0; i 0 && dowait(i, pids[i])) { - bad = 1; - } - } + for (i = 0; i < numprocs; i++) { + if (pids[i] > 0 && dowait(i, pids[i])) { + bad = 1; + } + } - if (bad) { - complainx("%s failed.", phasename); - exit(1); - } + if (bad) { + complainx("%s failed.", phasename); + exit(1); + } } -static -void -seekmyplace(const char *name, int fd) -{ - int keys_per, myfirst; - off_t offset; +static void seekmyplace(const char *name, int fd) { + int keys_per, myfirst; + off_t offset; - keys_per = numkeys / numprocs; - myfirst = me*keys_per; - offset = myfirst * sizeof(int); + keys_per = numkeys / numprocs; + myfirst = me * keys_per; + offset = myfirst * sizeof(int); - dolseek(name, fd, offset, SEEK_SET); + dolseek(name, fd, offset, SEEK_SET); } -static -int -getmykeys(void) -{ - int keys_per, myfirst, mykeys; +static int getmykeys(void) { + int keys_per, myfirst, mykeys; - keys_per = numkeys / numprocs; - myfirst = me*keys_per; - mykeys = (me < numprocs-1) ? keys_per : numkeys - myfirst; + keys_per = numkeys / numprocs; + myfirst = me * keys_per; + mykeys = (me < numprocs - 1) ? keys_per : numkeys - myfirst; - return mykeys; + return mykeys; } //////////////////////////////////////////////////////////// -static -unsigned long -checksum_file(const char *path) -{ - int fd; - char buf[512]; - size_t count, i; - unsigned long sum = 0; +static unsigned long checksum_file(const char *path) { + int fd; + char buf[512]; + size_t count, i; + unsigned long sum = 0; - fd = doopen(path, O_RDONLY, 0); + fd = doopen(path, O_RDONLY, 0); - while ((count = doread(path, fd, buf, sizeof(buf))) > 0) { - for (i=0; i 0) { + for (i = 0; i < count; i++) { + sum += (unsigned char)buf[i]; + } + } - doclose(path, fd); + doclose(path, fd); - return sum; + return sum; } //////////////////////////////////////////////////////////// static long *seeds; -static -void -genkeys_sub(void) -{ - int fd, i, mykeys, keys_done, keys_to_do, value; +static void genkeys_sub(void) { + int fd, i, mykeys, keys_done, keys_to_do, value; - fd = doopen(PATH_KEYS, O_WRONLY, 0); + fd = doopen(PATH_KEYS, O_WRONLY, 0); - mykeys = getmykeys(); - seekmyplace(PATH_KEYS, fd); + mykeys = getmykeys(); + seekmyplace(PATH_KEYS, fd); - srandom(seeds[me]); - keys_done = 0; - while (keys_done < mykeys) { - keys_to_do = mykeys - keys_done; - if (keys_to_do > WORKNUM) { - keys_to_do = WORKNUM; - } + srandom(seeds[me]); + keys_done = 0; + while (keys_done < mykeys) { + keys_to_do = mykeys - keys_done; + if (keys_to_do > WORKNUM) { + keys_to_do = WORKNUM; + } - for (i=0; i= 0); - assert(value <= RANDOM_MAX); + // check bounds of value + assert(value >= 0); + assert(value <= RANDOM_MAX); - // do not allow the value to be zero or RANDOM_MAX - while (value == 0 || value == RANDOM_MAX) { - value = random(); - } + // do not allow the value to be zero or RANDOM_MAX + while (value == 0 || value == RANDOM_MAX) { + value = random(); + } - workspace[i] = value; - } + workspace[i] = value; + } - dowrite(PATH_KEYS, fd, workspace, keys_to_do*sizeof(int)); - keys_done += keys_to_do; - } + dowrite(PATH_KEYS, fd, workspace, keys_to_do * sizeof(int)); + keys_done += keys_to_do; + } - doclose(PATH_KEYS, fd); + doclose(PATH_KEYS, fd); } -static -void -genkeys(void) -{ - long seedspace[numprocs]; - int i; +static void genkeys(void) { + long seedspace[numprocs]; + int i; - /* Create the file. */ - docreate(PATH_KEYS); + /* Create the file. */ + docreate(PATH_KEYS); - /* Generate random seeds for each subprocess. */ - srandom(randomseed); - for (i=0; i WORKNUM) { - keys_to_do = WORKNUM; - } + keys_done = 0; + while (keys_done < mykeys) { + keys_to_do = mykeys - keys_done; + if (keys_to_do > WORKNUM) { + keys_to_do = WORKNUM; + } - doexactread(PATH_KEYS, infd, workspace, - keys_to_do * sizeof(int)); + doexactread(PATH_KEYS, infd, workspace, keys_to_do * sizeof(int)); - for (i=0; i= 0); - assert(binnum < numprocs); - dowrite("bin", outfds[binnum], &key, sizeof(key)); - } + binnum = key / pivot; + if (key <= 0) { + complainx("proc %d: garbage key %d", me, key); + key = 0; + } + assert(binnum >= 0); + assert(binnum < numprocs); + dowrite("bin", outfds[binnum], &key, sizeof(key)); + } - keys_done += keys_to_do; - } - doclose(PATH_KEYS, infd); + keys_done += keys_to_do; + } + doclose(PATH_KEYS, infd); - for (i=0; i (off_t) sizeof(workspace)) { - complainx("proc %d: %s: bin too large", me, name); - exit(1); - } + for (i = 0; i < numprocs; i++) { + name = binname(me, i); + binsize = getsize(name); + if (binsize % sizeof(int) != 0) { + complainx("%s: bin size %ld no good", name, (long)binsize); + exit(1); + } + if (binsize > (off_t)sizeof(workspace)) { + complainx("proc %d: %s: bin too large", me, name); + exit(1); + } - fd = doopen(name, O_RDWR, 0); - doexactread(name, fd, workspace, binsize); + fd = doopen(name, O_RDWR, 0); + doexactread(name, fd, workspace, binsize); - sortints(workspace, binsize/sizeof(int)); + sortints(workspace, binsize / sizeof(int)); - dolseek(name, fd, 0, SEEK_SET); - dowrite(name, fd, workspace, binsize); - doclose(name, fd); - } + dolseek(name, fd, 0, SEEK_SET); + dowrite(name, fd, workspace, binsize); + doclose(name, fd); + } } -static -void -mergebins(void) -{ - int infds[numprocs], outfd; - int values[numprocs], ready[numprocs]; - const char *name, *outname; - int i, result; - int numready, place, val, worknum; +static void mergebins(void) { + int infds[numprocs], outfd; + int values[numprocs], ready[numprocs]; + const char *name, *outname; + int i, result; + int numready, place, val, worknum; - outname = mergedname(me); - outfd = doopen(outname, O_WRONLY|O_CREAT|O_TRUNC, 0664); + outname = mergedname(me); + outfd = doopen(outname, O_WRONLY | O_CREAT | O_TRUNC, 0664); - for (i=0; i= 0); + /* find the smallest */ + place = -1; + for (i = 0; i < numprocs; i++) { + if (!ready[i]) { + continue; + } + if (place < 0 || values[i] < val) { + val = values[i]; + place = i; + } + } + assert(place >= 0); - workspace[worknum++] = val; - if (worknum >= WORKNUM) { - assert(worknum == WORKNUM); - dowrite(outname, outfd, workspace, - worknum * sizeof(int)); - worknum = 0; - } - ready[place] = 0; - } + workspace[worknum++] = val; + if (worknum >= WORKNUM) { + assert(worknum == WORKNUM); + dowrite(outname, outfd, workspace, worknum * sizeof(int)); + worknum = 0; + } + ready[place] = 0; + } - dowrite(outname, outfd, workspace, worknum * sizeof(int)); - doclose(outname, outfd); + dowrite(outname, outfd, workspace, worknum * sizeof(int)); + doclose(outname, outfd); - for (i=0; i WORKNUM) { - keys_to_do = WORKNUM; - } + keys_done = 0; + while (keys_done < mykeys) { + keys_to_do = mykeys - keys_done; + if (keys_to_do > WORKNUM) { + keys_to_do = WORKNUM; + } - doexactread(name, fd, workspace, keys_to_do * sizeof(int)); + doexactread(name, fd, workspace, keys_to_do * sizeof(int)); - for (i=0; i= RANDOM_MAX) { - complain("%s: found too-large key", name); - exit(1); - } + if (key < 0) { + complain("%s: found negative key", name); + exit(1); + } + if (key == 0) { + complain("%s: found zero key", name); + exit(1); + } + if (key >= RANDOM_MAX) { + complain("%s: found too-large key", name); + exit(1); + } - if (key < smallest) { - smallest = key; - } - if (key > largest) { - largest = key; - } - } + if (key < smallest) { + smallest = key; + } + if (key > largest) { + largest = key; + } + } - keys_done += keys_to_do; - } - doclose(name, fd); + keys_done += keys_to_do; + } + doclose(name, fd); - name = validname(me); - fd = doopen(name, O_WRONLY|O_CREAT|O_TRUNC, 0664); - dowrite(name, fd, &smallest, sizeof(smallest)); - dowrite(name, fd, &largest, sizeof(largest)); - doclose(name, fd); + name = validname(me); + fd = doopen(name, O_WRONLY | O_CREAT | O_TRUNC, 0664); + dowrite(name, fd, &smallest, sizeof(smallest)); + dowrite(name, fd, &largest, sizeof(largest)); + doclose(name, fd); } -static -void -validate(void) -{ - int smallest, largest, prev_largest; - int i, fd; - const char *name; +static void validate(void) { + int smallest, largest, prev_largest; + int i, fd; + const char *name; - complainx("Validating the sorted data using %d procs", numprocs); - doforkall("Validation", dovalidate); - checksize_valid(); + complainx("Validating the sorted data using %d procs", numprocs); + doforkall("Validation", dovalidate); + checksize_valid(); - prev_largest = 1; + prev_largest = 1; - for (i=0; i= RANDOM_MAX) { - complainx("Validation: block %d: bad LARGEST", i); - exit(1); - } - if (smallest > largest) { - complainx("Validation: block %d: SMALLEST > LARGEST", - i); - exit(1); - } + if (smallest < 1) { + complainx("Validation: block %d: bad SMALLEST", i); + exit(1); + } + if (largest >= RANDOM_MAX) { + complainx("Validation: block %d: bad LARGEST", i); + exit(1); + } + if (smallest > largest) { + complainx("Validation: block %d: SMALLEST > LARGEST", i); + exit(1); + } - if (smallest < prev_largest) { - complain("Validation: block %d smallest key %d", - i, smallest); - complain("Validation: previous block largest key %d", - prev_largest); - complain("Validation failed"); - exit(1); - } - } + if (smallest < prev_largest) { + complain("Validation: block %d smallest key %d", i, smallest); + complain("Validation: previous block largest key %d", prev_largest); + complain("Validation failed"); + exit(1); + } + } - - for (i=0; i 0 ? argv[0] : NULL); +int main(int argc, char *argv[]) { + initprogname(argc > 0 ? argv[0] : NULL); - doargs(argc, argv); - correctsize = (off_t) (numkeys*sizeof(int)); + doargs(argc, argv); + correctsize = (off_t)(numkeys * sizeof(int)); - setdir(); + setdir(); - genkeys(); - sort(); - validate(); - complainx("Succeeded."); + genkeys(); + sort(); + validate(); + complainx("Succeeded."); - unsetdir(); + unsetdir(); - return 0; + return 0; } diff --git a/userland/testbin/randcall/main.c b/userland/testbin/randcall/main.c index 1b87a73..2e68512 100644 --- a/userland/testbin/randcall/main.c +++ b/userland/testbin/randcall/main.c @@ -33,134 +33,110 @@ #include "extern.h" -static -void -randchar(char *c) -{ +static void randchar(char *c) { #if RAND_MAX != 0x7fffffff #error "This code assumes RAND_MAX is 0x7fffffff" #endif - static long lbits = 0; - static long lnum = 0; + static long lbits = 0; + static long lnum = 0; - long bit; - int ct = 0; + long bit; + int ct = 0; - *c = 0; + *c = 0; - while (ct < CHAR_BIT) { - if (lnum==0) { - lbits = random(); - lnum = 31; - } + while (ct < CHAR_BIT) { + if (lnum == 0) { + lbits = random(); + lnum = 31; + } - bit = lbits & 1; - if (bit) { - (*c) |= 1; - } - (*c) <<= 1; - ct++; - lbits >>= 1; - lnum--; - } + bit = lbits & 1; + if (bit) { + (*c) |= 1; + } + (*c) <<= 1; + ct++; + lbits >>= 1; + lnum--; + } } -static -void -fillrand(void *p, size_t len) -{ - size_t i; - char *cp = p; - for (i=0; i 4) { - usage(); - } - } + if (!strcmp(argv[i], "all")) { + an = 5; + } else { + an = atoi(argv[i]); + if (an < 2 || an > 4) { + usage(); + } + } - printf("Seed: %d Count: %d\n", seed, count); + printf("Seed: %d Count: %d\n", seed, count); - srandom(seed); - trycalls(an, dofork, count); + srandom(seed); + trycalls(an, dofork, count); - return 0; + return 0; } diff --git a/userland/testbin/redirect/redirect.c b/userland/testbin/redirect/redirect.c index cca3f49..f07204d 100644 --- a/userland/testbin/redirect/redirect.c +++ b/userland/testbin/redirect/redirect.c @@ -50,148 +50,128 @@ static const char slogan[] = "CECIDI, ET NON SURGERE POSSUM!\n"; -static -int -doopen(const char *path, int openflags) -{ - int fd; +static int doopen(const char *path, int openflags) { + int fd; - fd = open(path, openflags, 0664); - if (fd < 0) { - err(1, "%s", path); - } - return fd; + fd = open(path, openflags, 0664); + if (fd < 0) { + err(1, "%s", path); + } + return fd; } -static -void -dodup2(int ofd, int nfd, const char *file) -{ - int r; +static void dodup2(int ofd, int nfd, const char *file) { + int r; - r = dup2(ofd, nfd); - if (r < 0) { - err(1, "%s: dup2", file); - } - if (r != nfd) { - errx(1, "%s: dup2: Expected %d, got %d", nfd, r); - } + r = dup2(ofd, nfd); + if (r < 0) { + err(1, "%s: dup2", file); + } + if (r != nfd) { + errx(1, "%s: dup2: Expected %d, got %d", nfd, r); + } } -static -void -doclose(int fd, const char *file) -{ - if (close(fd)) { - warnx("%s: close", file); - } +static void doclose(int fd, const char *file) { + if (close(fd)) { + warnx("%s: close", file); + } } -static -void -mkfile(void) -{ - int fd; - ssize_t r; +static void mkfile(void) { + int fd; + ssize_t r; - fd = doopen(INFILE, O_WRONLY|O_CREAT|O_TRUNC); + fd = doopen(INFILE, O_WRONLY | O_CREAT | O_TRUNC); - r = write(fd, slogan, strlen(slogan)); - if (r < 0) { - err(1, "%s: write", INFILE); - } - if ((size_t)r != strlen(slogan)) { - errx(1, "%s: write: Short count (got %zd, expected %zu)", - INFILE, r, strlen(slogan)); - } + r = write(fd, slogan, strlen(slogan)); + if (r < 0) { + err(1, "%s: write", INFILE); + } + if ((size_t)r != strlen(slogan)) { + errx(1, "%s: write: Short count (got %zd, expected %zu)", INFILE, r, + strlen(slogan)); + } - doclose(fd, INFILE); + doclose(fd, INFILE); } -static -void -chkfile(void) -{ - char buf[256]; - ssize_t r; - int fd; +static void chkfile(void) { + char buf[256]; + ssize_t r; + int fd; - fd = doopen(OUTFILE, O_RDONLY); + fd = doopen(OUTFILE, O_RDONLY); - r = read(fd, buf, sizeof(buf)); - if (r < 0) { - err(1, "%s: read", OUTFILE); - } - if (r == 0) { - errx(1, "%s: read: Unexpected EOF", OUTFILE); - } - if ((size_t)r != strlen(slogan)) { - errx(1, "%s: read: Short count (got %zd, expected %zu)", - OUTFILE, r, strlen(slogan)); - } + r = read(fd, buf, sizeof(buf)); + if (r < 0) { + err(1, "%s: read", OUTFILE); + } + if (r == 0) { + errx(1, "%s: read: Unexpected EOF", OUTFILE); + } + if ((size_t)r != strlen(slogan)) { + errx(1, "%s: read: Short count (got %zd, expected %zu)", OUTFILE, r, + strlen(slogan)); + } - doclose(fd, OUTFILE); + doclose(fd, OUTFILE); } -static -void -cat(void) -{ - pid_t pid; - int rfd, wfd, result, status; - const char *args[2]; +static void cat(void) { + pid_t pid; + int rfd, wfd, result, status; + const char *args[2]; - rfd = doopen(INFILE, O_RDONLY); - wfd = doopen(OUTFILE, O_WRONLY|O_CREAT|O_TRUNC); + rfd = doopen(INFILE, O_RDONLY); + wfd = doopen(OUTFILE, O_WRONLY | O_CREAT | O_TRUNC); - pid = fork(); - if (pid < 0) { - err(1, "fork"); - } + pid = fork(); + if (pid < 0) { + err(1, "fork"); + } - if (pid == 0) { - /* child */ - dodup2(rfd, STDIN_FILENO, INFILE); - dodup2(wfd, STDOUT_FILENO, OUTFILE); - doclose(rfd, INFILE); - doclose(wfd, OUTFILE); - args[0] = "cat"; - args[1] = NULL; - execv(PATH_CAT, (char **)args); - warn("%s: execv", PATH_CAT); - _exit(1); - } + if (pid == 0) { + /* child */ + dodup2(rfd, STDIN_FILENO, INFILE); + dodup2(wfd, STDOUT_FILENO, OUTFILE); + doclose(rfd, INFILE); + doclose(wfd, OUTFILE); + args[0] = "cat"; + args[1] = NULL; + execv(PATH_CAT, (char **)args); + warn("%s: execv", PATH_CAT); + _exit(1); + } - /* parent */ - doclose(rfd, INFILE); - doclose(wfd, OUTFILE); + /* parent */ + doclose(rfd, INFILE); + doclose(wfd, OUTFILE); - result = waitpid(pid, &status, 0); - if (result == -1) { - err(1, "waitpid"); - } - if (WIFSIGNALED(status)) { - errx(1, "pid %d: Signal %d", (int)pid, WTERMSIG(status)); - } - if (WIFEXITED(status) && WEXITSTATUS(status) != 0) { - errx(1, "pid %d: Exit %d", (int)pid, WEXITSTATUS(status)); - } + result = waitpid(pid, &status, 0); + if (result == -1) { + err(1, "waitpid"); + } + if (WIFSIGNALED(status)) { + errx(1, "pid %d: Signal %d", (int)pid, WTERMSIG(status)); + } + if (WIFEXITED(status) && WEXITSTATUS(status) != 0) { + errx(1, "pid %d: Exit %d", (int)pid, WEXITSTATUS(status)); + } } -int -main(void) -{ - printf("Creating %s...\n", INFILE); - mkfile(); +int main(void) { + printf("Creating %s...\n", INFILE); + mkfile(); - printf("Running cat < %s > %s\n", INFILE, OUTFILE); - cat(); + printf("Running cat < %s > %s\n", INFILE, OUTFILE); + cat(); - printf("Checking %s...\n", OUTFILE); - chkfile(); + printf("Checking %s...\n", OUTFILE); + chkfile(); - printf("Passed.\n"); - (void)remove(INFILE); - (void)remove(OUTFILE); - return 0; + printf("Passed.\n"); + (void)remove(INFILE); + (void)remove(OUTFILE); + return 0; } diff --git a/userland/testbin/rmdirtest/rmdirtest.c b/userland/testbin/rmdirtest/rmdirtest.c index a244f67..a38490e 100644 --- a/userland/testbin/rmdirtest/rmdirtest.c +++ b/userland/testbin/rmdirtest/rmdirtest.c @@ -46,7 +46,6 @@ #include #include - static const char testdir[] = "testdir"; static char startpoint[PATH_MAX - sizeof(testdir)]; @@ -55,21 +54,18 @@ static char startpoint[PATH_MAX - sizeof(testdir)]; * where we came from. */ -static -void -startup(void) -{ - if (getcwd(startpoint, sizeof(startpoint))==NULL) { - err(1, "getcwd (not in test dir)"); - } +static void startup(void) { + if (getcwd(startpoint, sizeof(startpoint)) == NULL) { + err(1, "getcwd (not in test dir)"); + } - if (mkdir(testdir, 0775) < 0) { - err(1, "%s: mkdir", testdir); - } + if (mkdir(testdir, 0775) < 0) { + err(1, "%s: mkdir", testdir); + } - if (chdir(testdir) < 0) { - err(1, "%s: chdir", testdir); - } + if (chdir(testdir) < 0) { + err(1, "%s: chdir", testdir); + } } /* @@ -80,16 +76,13 @@ startup(void) * from the current directory, which is justifiably prohibited. */ -static -void -killdir(void) -{ - char tmp[PATH_MAX]; +static void killdir(void) { + char tmp[PATH_MAX]; - snprintf(tmp, sizeof(tmp), "%s/%s", startpoint, testdir); - if (rmdir(tmp)<0) { - err(1, "%s: rmdir", tmp); - } + snprintf(tmp, sizeof(tmp), "%s/%s", startpoint, testdir); + if (rmdir(tmp) < 0) { + err(1, "%s: rmdir", tmp); + } } /* @@ -97,13 +90,10 @@ killdir(void) * can try again. */ -static -void -finish(void) -{ - if (chdir(startpoint)<0) { - err(1, "%s: chdir", startpoint); - } +static void finish(void) { + if (chdir(startpoint) < 0) { + err(1, "%s: chdir", startpoint); + } } /*************************************************************/ @@ -112,293 +102,262 @@ finish(void) * Basic test - just try removing the directory without doing anything * evil. */ -static -void -test1(void) -{ - printf("Making %s\n", testdir); - startup(); +static void test1(void) { + printf("Making %s\n", testdir); + startup(); - printf("Removing %s while in it\n", testdir); - killdir(); + printf("Removing %s while in it\n", testdir); + killdir(); - printf("Leaving the test directory\n"); - finish(); + printf("Leaving the test directory\n"); + finish(); } /* * Now do it while we also have the directory open. */ -static -void -test2(void) -{ - int fd; +static void test2(void) { + int fd; - printf("Now trying with the directory open...\n"); - startup(); - fd = open(".", O_RDONLY); - if (fd<0) { - err(1, ".: open"); - } - killdir(); - finish(); + printf("Now trying with the directory open...\n"); + startup(); + fd = open(".", O_RDONLY); + if (fd < 0) { + err(1, ".: open"); + } + killdir(); + finish(); - /* close *after* leaving, just for excitement */ - if (close(fd)<0) { - err(1, "removed %s: close", testdir); - } + /* close *after* leaving, just for excitement */ + if (close(fd) < 0) { + err(1, "removed %s: close", testdir); + } } /* * Now see if . and .. work after rmdir. */ -static -void -test3(void) -{ - char buf[PATH_MAX]; - int fd; +static void test3(void) { + char buf[PATH_MAX]; + int fd; - printf("Checking if . exists after rmdir\n"); - startup(); - killdir(); + printf("Checking if . exists after rmdir\n"); + startup(); + killdir(); - fd = open(".", O_RDONLY); - if (fd<0) { - switch (errno) { - case EINVAL: - case EIO: - case ENOENT: - break; - default: - err(1, "."); - break; - } - } - else { - close(fd); - } + fd = open(".", O_RDONLY); + if (fd < 0) { + switch (errno) { + case EINVAL: + case EIO: + case ENOENT: + break; + default: + err(1, "."); + break; + } + } else { + close(fd); + } - fd = open("..", O_RDONLY); - if (fd<0) { - switch (errno) { - case EINVAL: - case EIO: - case ENOENT: - break; - default: - err(1, ".."); - break; - } - } - else { - warnx("..: openable after rmdir - might be bad"); - close(fd); - } + fd = open("..", O_RDONLY); + if (fd < 0) { + switch (errno) { + case EINVAL: + case EIO: + case ENOENT: + break; + default: + err(1, ".."); + break; + } + } else { + warnx("..: openable after rmdir - might be bad"); + close(fd); + } - snprintf(buf, sizeof(buf), "../%s", testdir); - fd = open(buf, O_RDONLY); - if (fd<0) { - switch (errno) { - case EINVAL: - case EIO: - case ENOENT: - break; - default: - err(1, "%s", buf); - break; - } - } - else { - errx(1, "%s: works after rmdir", buf); - } + snprintf(buf, sizeof(buf), "../%s", testdir); + fd = open(buf, O_RDONLY); + if (fd < 0) { + switch (errno) { + case EINVAL: + case EIO: + case ENOENT: + break; + default: + err(1, "%s", buf); + break; + } + } else { + errx(1, "%s: works after rmdir", buf); + } - finish(); + finish(); } /* * Now try to create files. */ -static -void -test4(void) -{ - char buf[4096]; - int fd; +static void test4(void) { + char buf[4096]; + int fd; - printf("Checking if creating files works after rmdir...\n"); - startup(); - killdir(); + printf("Checking if creating files works after rmdir...\n"); + startup(); + killdir(); - fd = open("newfile", O_WRONLY|O_CREAT|O_TRUNC, 0664); - if (fd<0) { - switch (errno) { - case EINVAL: - case EIO: - case ENOENT: - break; - default: - err(1, "%s", buf); - break; - } - } - else { - warnx("newfile: creating files after rmdir works"); - warnx("(this is only ok if the space gets reclaimed)"); + fd = open("newfile", O_WRONLY | O_CREAT | O_TRUNC, 0664); + if (fd < 0) { + switch (errno) { + case EINVAL: + case EIO: + case ENOENT: + break; + default: + err(1, "%s", buf); + break; + } + } else { + warnx("newfile: creating files after rmdir works"); + warnx("(this is only ok if the space gets reclaimed)"); - /* - * Waste a bunch of space so we'll be able to tell - */ - memset(buf, 'J', sizeof(buf)); - write(fd, buf, sizeof(buf)); - write(fd, buf, sizeof(buf)); - write(fd, buf, sizeof(buf)); - write(fd, buf, sizeof(buf)); - close(fd); - } + /* + * Waste a bunch of space so we'll be able to tell + */ + memset(buf, 'J', sizeof(buf)); + write(fd, buf, sizeof(buf)); + write(fd, buf, sizeof(buf)); + write(fd, buf, sizeof(buf)); + write(fd, buf, sizeof(buf)); + close(fd); + } - finish(); + finish(); } /* * Now try to create directories. */ -static -void -test5(void) -{ - printf("Checking if creating subdirs works after rmdir...\n"); - startup(); - killdir(); +static void test5(void) { + printf("Checking if creating subdirs works after rmdir...\n"); + startup(); + killdir(); - if (mkdir("newdir", 0775)<0) { - switch (errno) { - case EINVAL: - case EIO: - case ENOENT: - break; - default: - err(1, "mkdir in removed dir"); - break; - } - } - else { - warnx("newfile: creating directories after rmdir works"); - warnx("(this is only ok if the space gets reclaimed)"); + if (mkdir("newdir", 0775) < 0) { + switch (errno) { + case EINVAL: + case EIO: + case ENOENT: + break; + default: + err(1, "mkdir in removed dir"); + break; + } + } else { + warnx("newfile: creating directories after rmdir works"); + warnx("(this is only ok if the space gets reclaimed)"); - /* - * Waste a bunch of space so we'll be able to tell - */ - mkdir("newdir/t0", 0775); - mkdir("newdir/t1", 0775); - mkdir("newdir/t2", 0775); - mkdir("newdir/t3", 0775); - mkdir("newdir/t4", 0775); - mkdir("newdir/t5", 0775); - } + /* + * Waste a bunch of space so we'll be able to tell + */ + mkdir("newdir/t0", 0775); + mkdir("newdir/t1", 0775); + mkdir("newdir/t2", 0775); + mkdir("newdir/t3", 0775); + mkdir("newdir/t4", 0775); + mkdir("newdir/t5", 0775); + } - finish(); + finish(); } /* * Now try listing the directory. */ -static -void -test6(void) -{ - char buf[PATH_MAX]; - int fd, len; +static void test6(void) { + char buf[PATH_MAX]; + int fd, len; - printf("Now trying to list the directory...\n"); - startup(); - fd = open(".", O_RDONLY); - if (fd<0) { - err(1, ".: open"); - } - killdir(); + printf("Now trying to list the directory...\n"); + startup(); + fd = open(".", O_RDONLY); + if (fd < 0) { + err(1, ".: open"); + } + killdir(); - while ((len = getdirentry(fd, buf, sizeof(buf)-1))>0) { - if ((unsigned)len >= sizeof(buf)-1) { - errx(1, ".: getdirentry: returned invalid length"); - } - buf[len] = 0; - if (!strcmp(buf, ".") || !strcmp(buf, "..")) { - /* these are allowed to appear */ - continue; - } - errx(1, ".: getdirentry: returned unexpected name %s", buf); - } - if (len==0) { - /* EOF - ok */ - } - else { /* len < 0 */ - switch (errno) { - case EINVAL: - case EIO: - break; - default: - err(1, ".: getdirentry"); - break; - } - } + while ((len = getdirentry(fd, buf, sizeof(buf) - 1)) > 0) { + if ((unsigned)len >= sizeof(buf) - 1) { + errx(1, ".: getdirentry: returned invalid length"); + } + buf[len] = 0; + if (!strcmp(buf, ".") || !strcmp(buf, "..")) { + /* these are allowed to appear */ + continue; + } + errx(1, ".: getdirentry: returned unexpected name %s", buf); + } + if (len == 0) { + /* EOF - ok */ + } else { /* len < 0 */ + switch (errno) { + case EINVAL: + case EIO: + break; + default: + err(1, ".: getdirentry"); + break; + } + } - finish(); + finish(); - /* close *after* leaving, just for excitement */ - if (close(fd)<0) { - err(1, "removed %s: close", testdir); - } + /* close *after* leaving, just for excitement */ + if (close(fd) < 0) { + err(1, "removed %s: close", testdir); + } } /* * Try getcwd. */ -static -void -test7(void) -{ - char buf[PATH_MAX]; +static void test7(void) { + char buf[PATH_MAX]; - startup(); - killdir(); - if (getcwd(buf, sizeof(buf))==NULL) { - switch (errno) { - case EINVAL: - case EIO: - case ENOENT: - break; - default: - err(1, "getcwd after removing %s", testdir); - break; - } - } - else { - errx(1, "getcwd after removing %s: succeeded (got %s)", - testdir, buf); - } + startup(); + killdir(); + if (getcwd(buf, sizeof(buf)) == NULL) { + switch (errno) { + case EINVAL: + case EIO: + case ENOENT: + break; + default: + err(1, "getcwd after removing %s", testdir); + break; + } + } else { + errx(1, "getcwd after removing %s: succeeded (got %s)", testdir, buf); + } - finish(); + finish(); } /**************************************************************/ -int -main(void) -{ - test1(); - test2(); - test3(); - test4(); - test5(); - test6(); - test7(); +int main(void) { + test1(); + test2(); + test3(); + test4(); + test5(); + test6(); + test7(); - printf("Whew... survived.\n"); - return 0; + printf("Whew... survived.\n"); + return 0; } diff --git a/userland/testbin/rmtest/rmtest.c b/userland/testbin/rmtest/rmtest.c index 376236c..f3ad5b3 100644 --- a/userland/testbin/rmtest/rmtest.c +++ b/userland/testbin/rmtest/rmtest.c @@ -43,121 +43,110 @@ #include #include -#define TEST "rmdata" -#define TESTDATA "I wish I was a headlight. -- Jerry Garcia" -#define TESTLEN (sizeof(TESTDATA)-1) +#define TEST "rmdata" +#define TESTDATA "I wish I was a headlight. -- Jerry Garcia" +#define TESTLEN (sizeof(TESTDATA) - 1) -static -void -dorm(int fd) -{ - /* - * This used to spawn a copy of /bin/rm, but that's silly. - * However, we will do the remove() from a subprocess, so - * that various kinds of improper hacks to make this test - * run won't work. - * - * Close the file in the subprocess, for similar reasons. - */ +static void dorm(int fd) { + /* + * This used to spawn a copy of /bin/rm, but that's silly. + * However, we will do the remove() from a subprocess, so + * that various kinds of improper hacks to make this test + * run won't work. + * + * Close the file in the subprocess, for similar reasons. + */ - pid_t pid; - int status; + pid_t pid; + int status; - pid = fork(); - if (pid<0) { - err(1, "fork"); - } - if (pid==0) { - /* child process */ - close(fd); - if (remove(TEST)) { - err(1, "%s: remove", TEST); - } - _exit(0); - } - /* parent process */ - if (waitpid(pid, &status, 0)<0) { - err(1, "waitpid"); - } - else if (WIFSIGNALED(status)) { - warn("child process exited with signal %d", WTERMSIG(status)); - } - else if (WEXITSTATUS(status) != 0) { - warnx("child process exited with code %d",WEXITSTATUS(status)); - } + pid = fork(); + if (pid < 0) { + err(1, "fork"); + } + if (pid == 0) { + /* child process */ + close(fd); + if (remove(TEST)) { + err(1, "%s: remove", TEST); + } + _exit(0); + } + /* parent process */ + if (waitpid(pid, &status, 0) < 0) { + err(1, "waitpid"); + } else if (WIFSIGNALED(status)) { + warn("child process exited with signal %d", WTERMSIG(status)); + } else if (WEXITSTATUS(status) != 0) { + warnx("child process exited with code %d", WEXITSTATUS(status)); + } } -static -int -same(const char *a, const char *b, int len) -{ - while (len-- > 0) { - if (*a++ != *b++) return 0; - } - return 1; +static int same(const char *a, const char *b, int len) { + while (len-- > 0) { + if (*a++ != *b++) + return 0; + } + return 1; } -int -main(void) -{ - int file, len; - char buf[TESTLEN]; +int main(void) { + int file, len; + char buf[TESTLEN]; - /* create test data file */ - file = open(TEST, O_WRONLY | O_CREAT | O_TRUNC, 0664); - write(file, TESTDATA, TESTLEN); - close(file); + /* create test data file */ + file = open(TEST, O_WRONLY | O_CREAT | O_TRUNC, 0664); + write(file, TESTDATA, TESTLEN); + close(file); - /* make sure the data is there */ - file = open(TEST, O_RDONLY); - len = read(file, buf, TESTLEN); - if (len < 0) { - warn("read: before deletion"); - } - else if (len < (int)TESTLEN) { - warnx("read: before deletion: short count %d", len); - } - if (!same(buf, TESTDATA, TESTLEN)) { - errx(1, "Failed: data read back was not the same"); - } + /* make sure the data is there */ + file = open(TEST, O_RDONLY); + len = read(file, buf, TESTLEN); + if (len < 0) { + warn("read: before deletion"); + } else if (len < (int)TESTLEN) { + warnx("read: before deletion: short count %d", len); + } + if (!same(buf, TESTDATA, TESTLEN)) { + errx(1, "Failed: data read back was not the same"); + } - /* rewind the file */ - if (lseek(file, 0, SEEK_SET)) { - err(1, "lseek"); - } + /* rewind the file */ + if (lseek(file, 0, SEEK_SET)) { + err(1, "lseek"); + } - /* now spawn our killer and wait for it to do its work */ - dorm(file); + /* now spawn our killer and wait for it to do its work */ + dorm(file); - /* we should be still able to read the data */ - memset(buf, '\0', TESTLEN); - len = read(file, buf, TESTLEN); - if (len < 0) { - warn("read: after deletion"); - } - else if (len < (int)TESTLEN) { - warnx("read: after deletion: short count %d", len); - } + /* we should be still able to read the data */ + memset(buf, '\0', TESTLEN); + len = read(file, buf, TESTLEN); + if (len < 0) { + warn("read: after deletion"); + } else if (len < (int)TESTLEN) { + warnx("read: after deletion: short count %d", len); + } - if (!same(buf, TESTDATA, TESTLEN)) { - errx(1, "Failed: data read after deletion was not the same"); - } + if (!same(buf, TESTDATA, TESTLEN)) { + errx(1, "Failed: data read after deletion was not the same"); + } - /* ok, close the file and it should go away */ - close(file); + /* ok, close the file and it should go away */ + close(file); - /* try to open it again */ - file = open(TEST, O_RDONLY); - if (file >= 0) { - close(file); - errx(1, "Failed: the file could still be opened"); - } + /* try to open it again */ + file = open(TEST, O_RDONLY); + if (file >= 0) { + close(file); + errx(1, "Failed: the file could still be opened"); + } - if (errno!=ENOENT) { - err(1, "Unexpected error reopening the file"); - } + if (errno != ENOENT) { + err(1, "Unexpected error reopening the file"); + } - printf("Succeeded!\n"); + printf("Succeeded!\n"); - return 0; + return 0; } diff --git a/userland/testbin/sbrktest/sbrktest.c b/userland/testbin/sbrktest/sbrktest.c index b4a626b..fd2dda9 100644 --- a/userland/testbin/sbrktest/sbrktest.c +++ b/userland/testbin/sbrktest/sbrktest.c @@ -36,7 +36,7 @@ #include #include -#define _PATH_RANDOM "random:" +#define _PATH_RANDOM "random:" /* * Caution: OS/161 doesn't provide any way to get this properly from @@ -48,101 +48,82 @@ //////////////////////////////////////////////////////////// // support code -static -int -geti(void) -{ - int val=0; - int ch, digits=0; +static int geti(void) { + int val = 0; + int ch, digits = 0; - while (1) { - ch = getchar(); - if (ch=='\n' || ch=='\r') { - putchar('\n'); - break; - } - else if ((ch=='\b' || ch==127) && digits>0) { - printf("\b \b"); - val = val/10; - digits--; - } - else if (ch>='0' && ch<='9') { - putchar(ch); - val = val*10 + (ch-'0'); - digits++; - } - else { - putchar('\a'); - } - } + while (1) { + ch = getchar(); + if (ch == '\n' || ch == '\r') { + putchar('\n'); + break; + } else if ((ch == '\b' || ch == 127) && digits > 0) { + printf("\b \b"); + val = val / 10; + digits--; + } else if (ch >= '0' && ch <= '9') { + putchar(ch); + val = val * 10 + (ch - '0'); + digits++; + } else { + putchar('\a'); + } + } - if (digits==0) { - return -1; - } - return val; + if (digits == 0) { + return -1; + } + return val; } -static -unsigned long -getseed(void) -{ - int fd, len; - unsigned long seed; +static unsigned long getseed(void) { + int fd, len; + unsigned long seed; - fd = open(_PATH_RANDOM, O_RDONLY); - if (fd < 0) { - err(1, "%s", _PATH_RANDOM); - } - len = read(fd, &seed, sizeof(seed)); - if (len < 0) { - err(1, "%s", _PATH_RANDOM); - } - else if (len < (int)sizeof(seed)) { - errx(1, "%s: Short read", _PATH_RANDOM); - } - close(fd); + fd = open(_PATH_RANDOM, O_RDONLY); + if (fd < 0) { + err(1, "%s", _PATH_RANDOM); + } + len = read(fd, &seed, sizeof(seed)); + if (len < 0) { + err(1, "%s", _PATH_RANDOM); + } else if (len < (int)sizeof(seed)) { + errx(1, "%s: Short read", _PATH_RANDOM); + } + close(fd); - return seed; + return seed; } -static -pid_t -dofork(void) -{ - pid_t pid; +static pid_t dofork(void) { + pid_t pid; - pid = fork(); - if (pid < 0) { - err(1, "fork"); - } - return pid; + pid = fork(); + if (pid < 0) { + err(1, "fork"); + } + return pid; } -static -void -dowait(pid_t pid) -{ - int status; - int result; +static void dowait(pid_t pid) { + int status; + int result; - result = waitpid(pid, &status, 0); - if (result == -1) { - err(1, "waitpid"); - } - if (WIFSIGNALED(status)) { - errx(1, "child: Signal %d", WTERMSIG(status)); - } - if (WIFEXITED(status) && WEXITSTATUS(status) != 0) { - errx(1, "child: Exit %d", WEXITSTATUS(status)); - } + result = waitpid(pid, &status, 0); + if (result == -1) { + err(1, "waitpid"); + } + if (WIFSIGNALED(status)) { + errx(1, "child: Signal %d", WTERMSIG(status)); + } + if (WIFEXITED(status) && WEXITSTATUS(status) != 0) { + errx(1, "child: Exit %d", WEXITSTATUS(status)); + } } -static -void -say(const char *msg) -{ - /* Use one write so it's atomic (printf usually won't be) */ - write(STDOUT_FILENO, msg, strlen(msg)); +static void say(const char *msg) { + /* Use one write so it's atomic (printf usually won't be) */ + write(STDOUT_FILENO, msg, strlen(msg)); } //////////////////////////////////////////////////////////// @@ -151,158 +132,138 @@ say(const char *msg) /* * Fill a page of memory with a test pattern. */ -static -void -markpage(volatile void *baseptr, unsigned pageoffset) -{ - volatile char *pageptr; - size_t n, i; - volatile unsigned long *pl; - unsigned long val; +static void markpage(volatile void *baseptr, unsigned pageoffset) { + volatile char *pageptr; + size_t n, i; + volatile unsigned long *pl; + unsigned long val; - pageptr = baseptr; - pageptr += (size_t)PAGE_SIZE * pageoffset; + pageptr = baseptr; + pageptr += (size_t)PAGE_SIZE * pageoffset; - pl = (volatile unsigned long *)pageptr; - n = PAGE_SIZE / sizeof(unsigned long); + pl = (volatile unsigned long *)pageptr; + n = PAGE_SIZE / sizeof(unsigned long); - for (i=0; i 0; ) { - (void)dosbrk(-PAGE_SIZE); - for (j=0; j 0;) { + (void)dosbrk(-PAGE_SIZE); + for (j = 0; j < i; j++) { + if (checkpage(p, j, false)) { + warnx("FAILED: data corrupt on page %u " + "after freeing %u pages", + j, i); + bad = true; + } + } + } + if (bad) { + exit(1); + } - q = dosbrk(0); - if (q != op) { - errx(1, "FAILED: sbrk shrink didn't restore the heap " - "(got %p, expected %p", q, op); - } + q = dosbrk(0); + if (q != op) { + errx(1, + "FAILED: sbrk shrink didn't restore the heap " + "(got %p, expected %p", + q, op); + } - printf("Passed sbrk test 4.\n"); + printf("Passed sbrk test 4.\n"); } //////////////////////////////////////////////////////////// @@ -485,51 +451,42 @@ test4(void) * Checks that the page past end of the heap as we got it is not * valid. (Crashes when successful.) */ -static -void -test5(void) -{ - void *p; +static void test5(void) { + void *p; - p = dosbrk(0); - printf("This should produce fatal signal 11 (SIGSEGV).\n"); - ((long *)p)[10] = 0; - errx(1, "FAILED: I didn't crash"); + p = dosbrk(0); + printf("This should produce fatal signal 11 (SIGSEGV).\n"); + ((long *)p)[10] = 0; + errx(1, "FAILED: I didn't crash"); } /* * Allocates a page and checks that the next page past it is not * valid. (Crashes when successful.) */ -static -void -test6(void) -{ - void *p; +static void test6(void) { + void *p; - (void)dosbrk(PAGE_SIZE); - p = dosbrk(0); - printf("This should produce fatal signal 11 (SIGSEGV).\n"); - ((long *)p)[10] = 0; - errx(1, "FAILED: I didn't crash"); + (void)dosbrk(PAGE_SIZE); + p = dosbrk(0); + printf("This should produce fatal signal 11 (SIGSEGV).\n"); + ((long *)p)[10] = 0; + errx(1, "FAILED: I didn't crash"); } /* * Allocates and frees a page and checks that the page freed is no * longer valid. (Crashes when successful.) */ -static -void -test7(void) -{ - void *p; +static void test7(void) { + void *p; - (void)dosbrk(PAGE_SIZE); - (void)dosbrk(-PAGE_SIZE); - p = dosbrk(0); - printf("This should produce fatal signal 11 (SIGSEGV).\n"); - ((long *)p)[10] = 0; - errx(1, "FAILED: I didn't crash"); + (void)dosbrk(PAGE_SIZE); + (void)dosbrk(-PAGE_SIZE); + p = dosbrk(0); + printf("This should produce fatal signal 11 (SIGSEGV).\n"); + ((long *)p)[10] = 0; + errx(1, "FAILED: I didn't crash"); } /* @@ -537,18 +494,15 @@ test7(void) * past the new end of the heap is no longer valid. (Crashes when * successful.) */ -static -void -test8(void) -{ - void *p; +static void test8(void) { + void *p; - (void)dosbrk(PAGE_SIZE * 12); - (void)dosbrk(-PAGE_SIZE * 6); - p = dosbrk(0); - printf("This should produce fatal signal 11 (SIGSEGV).\n"); - ((long *)p)[10] = 0; - errx(1, "FAILED: I didn't crash"); + (void)dosbrk(PAGE_SIZE * 12); + (void)dosbrk(-PAGE_SIZE * 6); + p = dosbrk(0); + printf("This should produce fatal signal 11 (SIGSEGV).\n"); + ((long *)p)[10] = 0; + errx(1, "FAILED: I didn't crash"); } //////////////////////////////////////////////////////////// @@ -577,167 +531,157 @@ test8(void) * that you end up needing a huge swap disk even to run relatively * small workloads, and then this test takes forever to run. */ -static -void -test9(void) -{ - size_t size; - unsigned i, pages, dot; - void *p; - bool bad; +static void test9(void) { + size_t size; + unsigned i, pages, dot; + void *p; + bool bad; -#define HUGESIZE (1024 * 1024 * 1024) /* 1G */ +#define HUGESIZE (1024 * 1024 * 1024) /* 1G */ - printf("Checking how much memory we can allocate:\n"); - for (size = HUGESIZE; (p = sbrk(size)) == (void *)-1; size = size/2) { - printf(" %9lu bytes: failed\n", (unsigned long) size); - } - printf(" %9lu bytes: succeeded\n", (unsigned long) size); - printf("Passed sbrk test 9 (part 1/5)\n"); + printf("Checking how much memory we can allocate:\n"); + for (size = HUGESIZE; (p = sbrk(size)) == (void *)-1; size = size / 2) { + printf(" %9lu bytes: failed\n", (unsigned long)size); + } + printf(" %9lu bytes: succeeded\n", (unsigned long)size); + printf("Passed sbrk test 9 (part 1/5)\n"); - printf("Touching each page.\n"); - pages = size / PAGE_SIZE; - dot = pages / 64; - for (i=0; i 0 && i % dot == 0) { - printf("."); - } - } - if (dot > 0) { - printf("\n"); - } + printf("Touching each page.\n"); + pages = size / PAGE_SIZE; + dot = pages / 64; + for (i = 0; i < pages; i++) { + markpagelight(p, i); + if (dot > 0 && i % dot == 0) { + printf("."); + } + } + if (dot > 0) { + printf("\n"); + } - printf("Testing each page.\n"); - bad = false; - for (i=0; i 0)) { - if (dot > 0) { - printf("\n"); - } - warnx("FAILED: data corrupt"); - bad = true; - } - if (dot > 0 && i % dot == 0) { - printf("."); - } - } - if (dot > 0) { - printf("\n"); - } - if (bad) { - exit(1); - } - printf("Passed sbrk test 9 (part 2/5)\n"); + printf("Testing each page.\n"); + bad = false; + for (i = 0; i < pages; i++) { + if (checkpagelight(p, i, dot > 0)) { + if (dot > 0) { + printf("\n"); + } + warnx("FAILED: data corrupt"); + bad = true; + } + if (dot > 0 && i % dot == 0) { + printf("."); + } + } + if (dot > 0) { + printf("\n"); + } + if (bad) { + exit(1); + } + printf("Passed sbrk test 9 (part 2/5)\n"); - printf("Freeing the memory.\n"); - (void)dosbrk(-size); - printf("Passed sbrk test 9 (part 3/5)\n"); + printf("Freeing the memory.\n"); + (void)dosbrk(-size); + printf("Passed sbrk test 9 (part 3/5)\n"); - printf("Allocating the memory again.\n"); - (void)dosbrk(size); - printf("Passed sbrk test 9 (part 4/5)\n"); + printf("Allocating the memory again.\n"); + (void)dosbrk(size); + printf("Passed sbrk test 9 (part 4/5)\n"); - printf("And really freeing it.\n"); - (void)dosbrk(-size); - printf("Passed sbrk test 9 (all)\n"); + printf("And really freeing it.\n"); + (void)dosbrk(-size); + printf("Passed sbrk test 9 (all)\n"); } /* * Allocate all of memory one page at a time. The same restrictions * and considerations apply as above. */ -static -void -test10(void) -{ - void *p, *op; - unsigned i, n; - bool bad; +static void test10(void) { + void *p, *op; + unsigned i, n; + bool bad; - printf("Allocating all of memory one page at a time:\n"); - op = dosbrk(0); - n = 0; - while ((p = sbrk(PAGE_SIZE)) != (void *)-1) { - markpagelight(op, n); - n++; - } - printf("Got %u pages (%zu bytes).\n", n, (size_t)PAGE_SIZE * n); + printf("Allocating all of memory one page at a time:\n"); + op = dosbrk(0); + n = 0; + while ((p = sbrk(PAGE_SIZE)) != (void *)-1) { + markpagelight(op, n); + n++; + } + printf("Got %u pages (%zu bytes).\n", n, (size_t)PAGE_SIZE * n); - printf("Now freeing them.\n"); - bad = false; - for (i=0; i (large ? 128 : 32)) { - neg = 1; - } - if (neg) { - dosbrk(-(pages * PAGE_SIZE)); - num -= pages; - } - else { - dosbrk(pages * PAGE_SIZE); - for (j=0; j (large ? 128 : 32)) { + neg = 1; + } + if (neg) { + dosbrk(-(pages * PAGE_SIZE)); + num -= pages; + } else { + dosbrk(pages * PAGE_SIZE); + for (j = 0; j < pages; j++) { + markpagelight(op, num + j); + } + num += pages; + } + for (j = 0; j < num; j++) { + if (checkpagelight(op, j, true)) { + printf("\n"); + warnx("FAILED: data corrupt on page %u", j); + bad = true; + } + } + if (i % dot == 0) { + printf("."); + } + } + printf("\n"); + if (bad) { + warnx("FAILED"); + exit(1); + } - dosbrk(-(num * PAGE_SIZE)); - printf("Passed sbrk %s stress test.\n", large ? "large" : "small"); + dosbrk(-(num * PAGE_SIZE)); + printf("Passed sbrk %s stress test.\n", large ? "large" : "small"); } -static -void -test16(void) -{ - stresstest(0, false); +static void test16(void) { stresstest(0, false); } + +static void test17(void) { stresstest(getseed(), false); } + +static void test18(void) { + printf("Enter random seed: "); + stresstest(geti(), false); } -static -void -test17(void) -{ - stresstest(getseed(), false); -} +static void test19(void) { stresstest(0, true); } -static -void -test18(void) -{ - printf("Enter random seed: "); - stresstest(geti(), false); -} +static void test20(void) { stresstest(getseed(), true); } -static -void -test19(void) -{ - stresstest(0, true); -} - -static -void -test20(void) -{ - stresstest(getseed(), true); -} - -static -void -test21(void) -{ - printf("Enter random seed: "); - stresstest(geti(), true); +static void test21(void) { + printf("Enter random seed: "); + stresstest(geti(), true); } //////////////////////////////////////////////////////////// // main static const struct { - int num; - const char *desc; - void (*func)(void); + int num; + const char *desc; + void (*func)(void); } tests[] = { - { 1, "Allocate one page", test1 }, - { 2, "Allocate and free one page", test2 }, - { 3, "Allocate and free several pages", test3 }, - { 4, "Allocate several pages and free them one at a time", test4 }, - { 5, "Check the heap end (crashes)", test5 }, - { 6, "Allocate and check the heap end (crashes)", test6 }, - { 7, "Allocate and free and check the heap end (crashes)", test7 }, - { 8, "Allocate several, free some, check heap end (crashes)", test8 }, - { 9, "Allocate all memory in a big chunk", test9 }, - { 10, "Allocate all memory a page at a time", test10 }, - { 11, "Allocate a lot and intentionally leak it", test11 }, - { 12, "Fork and then allocate", test12 }, - { 13, "Allocate and then fork", test13 }, - { 14, "Allocate and then fork and free", test14 }, - { 15, "Allocate, fork, allocate more, and free (and spam)", test15 }, - { 16, "Small stress test", test16 }, - { 17, "Randomized small stress test", test17 }, - { 18, "Small stress test with particular seed", test18 }, - { 19, "Large stress test", test19 }, - { 20, "Randomized large stress test", test20 }, - { 21, "Large stress test with particular seed", test21 }, + {1, "Allocate one page", test1}, + {2, "Allocate and free one page", test2}, + {3, "Allocate and free several pages", test3}, + {4, "Allocate several pages and free them one at a time", test4}, + {5, "Check the heap end (crashes)", test5}, + {6, "Allocate and check the heap end (crashes)", test6}, + {7, "Allocate and free and check the heap end (crashes)", test7}, + {8, "Allocate several, free some, check heap end (crashes)", test8}, + {9, "Allocate all memory in a big chunk", test9}, + {10, "Allocate all memory a page at a time", test10}, + {11, "Allocate a lot and intentionally leak it", test11}, + {12, "Fork and then allocate", test12}, + {13, "Allocate and then fork", test13}, + {14, "Allocate and then fork and free", test14}, + {15, "Allocate, fork, allocate more, and free (and spam)", test15}, + {16, "Small stress test", test16}, + {17, "Randomized small stress test", test17}, + {18, "Small stress test with particular seed", test18}, + {19, "Large stress test", test19}, + {20, "Randomized large stress test", test20}, + {21, "Large stress test with particular seed", test21}, }; static const unsigned numtests = sizeof(tests) / sizeof(tests[0]); -static -int -dotest(int tn) -{ - unsigned i; +static int dotest(int tn) { + unsigned i; - for (i=0; i 1) { - for (i=1; i 1) { + for (i = 1; i < argc; i++) { + dotest(atoi(argv[i])); + } + return 0; + } - while (1) { - if (menu) { - for (j=0; j b) { - return 1; - } - return 0; + if (a < b) { + return -1; + } + if (a > b) { + return 1; + } + return 0; } -static -int -altcmp(const void *av, const void *bv) -{ - unsigned a = *(const unsigned *)av; - unsigned b = *(const unsigned *)bv; - unsigned ax = (a & 0xffff0000) >> 16; - unsigned ay = a & 0xffff; - unsigned bx = (b & 0xffff0000) >> 16; - unsigned by = b & 0xffff; +static int altcmp(const void *av, const void *bv) { + unsigned a = *(const unsigned *)av; + unsigned b = *(const unsigned *)bv; + unsigned ax = (a & 0xffff0000) >> 16; + unsigned ay = a & 0xffff; + unsigned bx = (b & 0xffff0000) >> 16; + unsigned by = b & 0xffff; - if (ax < bx) { - return 1; - } - if (ax > bx) { - return -1; - } - if (ay < by) { - return -1; - } - if (ay > by) { - return 1; - } - return 0; + if (ax < bx) { + return 1; + } + if (ax > bx) { + return -1; + } + if (ay < by) { + return -1; + } + if (ay > by) { + return 1; + } + return 0; } #if 0 @@ -104,35 +98,29 @@ shuffle(unsigned *p, unsigned n) /* * Compute first differences. */ -static -void -diffs(unsigned *p, unsigned n) -{ - unsigned p0; - unsigned i; +static void diffs(unsigned *p, unsigned n) { + unsigned p0; + unsigned i; - p0 = p[0]; + p0 = p[0]; - for (i=0; i 0) { - calcresult(0, startsecs, startnsecs, buf, sizeof(buf)); - printf("Thinkers: %s\n", buf); - } + printf("--- Timings ---\n"); + if (numthinkers > 0) { + calcresult(0, startsecs, startnsecs, buf, sizeof(buf)); + printf("Thinkers: %s\n", buf); + } - if (numgrinders > 0) { - calcresult(1, startsecs, startnsecs, buf, sizeof(buf)); - printf("Grinders: %s\n", buf); - } + if (numgrinders > 0) { + calcresult(1, startsecs, startnsecs, buf, sizeof(buf)); + printf("Grinders: %s\n", buf); + } - for (i=0; i MAXCOUNT) { - err(1, "pong: too many pongers -- recompile pong.c"); - } - for (i=0; i MAXCOUNT) { + err(1, "pong: too many pongers -- recompile pong.c"); + } + for (i = 0; i < count; i++) { + usem_init(&sems[i], "sem:pong-%u-%u", groupid, i); + } + nsems = count; } -void -pong_cleanup(unsigned groupid, unsigned count) -{ - unsigned i; +void pong_cleanup(unsigned groupid, unsigned count) { + unsigned i; - assert(nsems == count); - (void)groupid; - - for (i=0; i 0 || id > 0) { - P(&sems[id]); - } + nextid = (id + 1) % nsems; + for (i = 0; i < PONGLOOPS; i++) { + if (i > 0 || id > 0) { + P(&sems[id]); + } #ifdef VERBOSE_PONG - printf(" %u", id); + printf(" %u", id); #else - if (nextid == 0 && i % 16 == 0) { - putchar('.'); - } + if (nextid == 0 && i % 16 == 0) { + putchar('.'); + } #endif - V(&sems[nextid]); - } - if (id == 0) { - P(&sems[id]); - } + V(&sems[nextid]); + } + if (id == 0) { + P(&sems[id]); + } #ifdef VERBOSE_PONG - putchar('\n'); + putchar('\n'); #else - if (nextid == 0) { - putchar('\n'); - } + if (nextid == 0) { + putchar('\n'); + } #endif } @@ -124,88 +117,80 @@ pong_cyclic(unsigned id) * Pong back and forth. This runs the tasks with middle numbers more * often. */ -static -void -pong_reciprocating(unsigned id) -{ - unsigned i, n; - unsigned nextfwd, nextback; - unsigned gofwd = 1; +static void pong_reciprocating(unsigned id) { + unsigned i, n; + unsigned nextfwd, nextback; + unsigned gofwd = 1; - if (id == 0) { - nextfwd = nextback = 1; - n = PONGLOOPS; - } - else if (id == nsems - 1) { - nextfwd = nextback = nsems - 2; - n = PONGLOOPS; - } - else { - nextfwd = id + 1; - nextback = id - 1; - n = PONGLOOPS * 2; - } + if (id == 0) { + nextfwd = nextback = 1; + n = PONGLOOPS; + } else if (id == nsems - 1) { + nextfwd = nextback = nsems - 2; + n = PONGLOOPS; + } else { + nextfwd = id + 1; + nextback = id - 1; + n = PONGLOOPS * 2; + } - for (i=0; i 0 || id > 0) { - P(&sems[id]); - } + for (i = 0; i < n; i++) { + if (i > 0 || id > 0) { + P(&sems[id]); + } #ifdef VERBOSE_PONG - printf(" %u", id); + printf(" %u", id); #else - if (id == 0 && i % 16 == 0) { - putchar('.'); - } + if (id == 0 && i % 16 == 0) { + putchar('.'); + } #endif - if (gofwd) { - V(&sems[nextfwd]); - gofwd = 0; - } - else { - V(&sems[nextback]); - gofwd = 1; - } - } - if (id == 0) { - P(&sems[id]); - } + if (gofwd) { + V(&sems[nextfwd]); + gofwd = 0; + } else { + V(&sems[nextback]); + gofwd = 1; + } + } + if (id == 0) { + P(&sems[id]); + } #ifdef VERBOSE_PONG - putchar('\n'); + putchar('\n'); #else - if (id == 0) { - putchar('\n'); - } + if (id == 0) { + putchar('\n'); + } #endif } /* * Do the pong thing. */ -void -pong(unsigned groupid, unsigned id) -{ - unsigned idfwd, idback; +void pong(unsigned groupid, unsigned id) { + unsigned idfwd, idback; - (void)groupid; + (void)groupid; - idfwd = (id + 1) % nsems; - idback = (id + nsems - 1) % nsems; - usem_open(&sems[id]); - usem_open(&sems[idfwd]); - usem_open(&sems[idback]); + idfwd = (id + 1) % nsems; + idback = (id + nsems - 1) % nsems; + usem_open(&sems[id]); + usem_open(&sems[idfwd]); + usem_open(&sems[idback]); - waitstart(); - pong_cyclic(id); + waitstart(); + pong_cyclic(id); #ifdef VERBOSE_PONG - printf("--------------------------------\n"); + printf("--------------------------------\n"); #endif - pong_reciprocating(id); + pong_reciprocating(id); #ifdef VERBOSE_PONG - printf("--------------------------------\n"); + printf("--------------------------------\n"); #endif - pong_cyclic(id); + pong_cyclic(id); - usem_close(&sems[id]); - usem_close(&sems[idfwd]); - usem_close(&sems[idback]); + usem_close(&sems[id]); + usem_close(&sems[idfwd]); + usem_close(&sems[idback]); } diff --git a/userland/testbin/schedpong/results.c b/userland/testbin/schedpong/results.c index bffd491..b08154b 100644 --- a/userland/testbin/schedpong/results.c +++ b/userland/testbin/schedpong/results.c @@ -44,34 +44,30 @@ static int resultsfile = -1; * Create the file that the timing results are written to. * This is done first, in the main process. */ -void -createresultsfile(void) -{ - int fd; +void createresultsfile(void) { + int fd; - assert(resultsfile == -1); + assert(resultsfile == -1); - fd = open(RESULTSFILE, O_RDWR|O_CREAT|O_TRUNC, 0664); - if (fd < 0) { - err(1, "%s", RESULTSFILE); - } - if (close(fd) == -1) { - warn("%s: close", RESULTSFILE); - } + fd = open(RESULTSFILE, O_RDWR | O_CREAT | O_TRUNC, 0664); + if (fd < 0) { + err(1, "%s", RESULTSFILE); + } + if (close(fd) == -1) { + warn("%s: close", RESULTSFILE); + } } /* * Remove the timing results file. * This is done last, in the main process. */ -void -destroyresultsfile(void) -{ - if (remove(RESULTSFILE) == -1) { - if (errno != ENOSYS) { - warn("%s: remove", RESULTSFILE); - } - } +void destroyresultsfile(void) { + if (remove(RESULTSFILE) == -1) { + if (errno != ENOSYS) { + warn("%s: remove", RESULTSFILE); + } + } } /* @@ -80,90 +76,82 @@ destroyresultsfile(void) * then require extra semaphoring to coordinate...) and afterwards * done for reading in the main process. */ -void -openresultsfile(int openflags) -{ - assert(openflags == O_RDONLY || openflags == O_WRONLY); - assert(resultsfile == -1); +void openresultsfile(int openflags) { + assert(openflags == O_RDONLY || openflags == O_WRONLY); + assert(resultsfile == -1); - resultsfile = open(RESULTSFILE, openflags, 0); - if (resultsfile < 0) { - err(1, "%s", RESULTSFILE); - } + resultsfile = open(RESULTSFILE, openflags, 0); + if (resultsfile < 0) { + err(1, "%s", RESULTSFILE); + } } /* * Close the timing results file. */ -void -closeresultsfile(void) -{ - assert(resultsfile >= 0); +void closeresultsfile(void) { + assert(resultsfile >= 0); - if (close(resultsfile) == -1) { - warn("%s: close", RESULTSFILE); - } - resultsfile = -1; + if (close(resultsfile) == -1) { + warn("%s: close", RESULTSFILE); + } + resultsfile = -1; } /* * Write a result into the timing results file. */ -void -putresult(unsigned groupid, time_t secs, unsigned long nsecs) -{ - off_t pos; - ssize_t r; +void putresult(unsigned groupid, time_t secs, unsigned long nsecs) { + off_t pos; + ssize_t r; - assert(resultsfile >= 0); + assert(resultsfile >= 0); - pos = groupid * (sizeof(secs) + sizeof(nsecs)); - if (lseek(resultsfile, pos, SEEK_SET) == -1) { - err(1, "%s: lseek", RESULTSFILE); - } - r = write(resultsfile, &secs, sizeof(secs)); - if (r < 0) { - err(1, "%s: write (seconds)", RESULTSFILE); - } - if ((size_t)r < sizeof(secs)) { - errx(1, "%s: write (seconds): Short write", RESULTSFILE); - } - r = write(resultsfile, &nsecs, sizeof(nsecs)); - if (r < 0) { - err(1, "%s: write (nsecs)", RESULTSFILE); - } - if ((size_t)r < sizeof(nsecs)) { - errx(1, "%s: write (nsecs): Short write", RESULTSFILE); - } + pos = groupid * (sizeof(secs) + sizeof(nsecs)); + if (lseek(resultsfile, pos, SEEK_SET) == -1) { + err(1, "%s: lseek", RESULTSFILE); + } + r = write(resultsfile, &secs, sizeof(secs)); + if (r < 0) { + err(1, "%s: write (seconds)", RESULTSFILE); + } + if ((size_t)r < sizeof(secs)) { + errx(1, "%s: write (seconds): Short write", RESULTSFILE); + } + r = write(resultsfile, &nsecs, sizeof(nsecs)); + if (r < 0) { + err(1, "%s: write (nsecs)", RESULTSFILE); + } + if ((size_t)r < sizeof(nsecs)) { + errx(1, "%s: write (nsecs): Short write", RESULTSFILE); + } } /* * Read a result from the timing results file. */ -void -getresult(unsigned groupid, time_t *secs, unsigned long *nsecs) -{ - off_t pos; - ssize_t r; +void getresult(unsigned groupid, time_t *secs, unsigned long *nsecs) { + off_t pos; + ssize_t r; - assert(resultsfile >= 0); + assert(resultsfile >= 0); - pos = groupid * (sizeof(*secs) + sizeof(*nsecs)); - if (lseek(resultsfile, pos, SEEK_SET) == -1) { - err(1, "%s: lseek", RESULTSFILE); - } - r = read(resultsfile, secs, sizeof(*secs)); - if (r < 0) { - err(1, "%s: read (seconds)", RESULTSFILE); - } - if ((size_t)r < sizeof(*secs)) { - errx(1, "%s: read (seconds): Unexpected EOF", RESULTSFILE); - } - r = read(resultsfile, nsecs, sizeof(*nsecs)); - if (r < 0) { - err(1, "%s: read (nsecs)", RESULTSFILE); - } - if ((size_t)r < sizeof(*nsecs)) { - errx(1, "%s: read (nsecs): Unexpected EOF", RESULTSFILE); - } + pos = groupid * (sizeof(*secs) + sizeof(*nsecs)); + if (lseek(resultsfile, pos, SEEK_SET) == -1) { + err(1, "%s: lseek", RESULTSFILE); + } + r = read(resultsfile, secs, sizeof(*secs)); + if (r < 0) { + err(1, "%s: read (seconds)", RESULTSFILE); + } + if ((size_t)r < sizeof(*secs)) { + errx(1, "%s: read (seconds): Unexpected EOF", RESULTSFILE); + } + r = read(resultsfile, nsecs, sizeof(*nsecs)); + if (r < 0) { + err(1, "%s: read (nsecs)", RESULTSFILE); + } + if ((size_t)r < sizeof(*nsecs)) { + errx(1, "%s: read (nsecs): Unexpected EOF", RESULTSFILE); + } } diff --git a/userland/testbin/schedpong/think.c b/userland/testbin/schedpong/think.c index a5188f5..099d0b7 100644 --- a/userland/testbin/schedpong/think.c +++ b/userland/testbin/schedpong/think.c @@ -35,21 +35,19 @@ * * All we do is loop. */ -void -think(unsigned groupid, unsigned id) -{ - volatile unsigned long k, m; - volatile unsigned i; +void think(unsigned groupid, unsigned id) { + volatile unsigned long k, m; + volatile unsigned i; - (void)groupid; - (void)id; + (void)groupid; + (void)id; - waitstart(); + waitstart(); - k = 15; - m = 7; + k = 15; + m = 7; #define LOOPCOUNT 35000000 - for (i=0; iname, sizeof(sem->name), namefmt, ap); - va_end(ap); + va_start(ap, namefmt); + vsnprintf(sem->name, sizeof(sem->name), namefmt, ap); + va_end(ap); - sem->fd = open(sem->name, O_RDWR|O_CREAT|O_TRUNC, 0664); - if (sem->fd < 0) { - err(1, "%s: create", sem->name); - } - close(sem->fd); - sem->fd = -1; + sem->fd = open(sem->name, O_RDWR | O_CREAT | O_TRUNC, 0664); + if (sem->fd < 0) { + err(1, "%s: create", sem->name); + } + close(sem->fd); + sem->fd = -1; } -void -usem_open(struct usem *sem) -{ - sem->fd = open(sem->name, O_RDWR); - if (sem->fd < 0) { - err(1, "%s: open", sem->name); - } +void usem_open(struct usem *sem) { + sem->fd = open(sem->name, O_RDWR); + if (sem->fd < 0) { + err(1, "%s: open", sem->name); + } } -void -usem_close(struct usem *sem) -{ - if (close(sem->fd) == -1) { - warn("%s: close", sem->name); - } +void usem_close(struct usem *sem) { + if (close(sem->fd) == -1) { + warn("%s: close", sem->name); + } } -void -usem_cleanup(struct usem *sem) -{ - (void)remove(sem->name); +void usem_cleanup(struct usem *sem) { (void)remove(sem->name); } + +void Pn(struct usem *sem, unsigned count) { + ssize_t r; + char c[count]; + + r = read(sem->fd, c, count); + if (r < 0) { + err(1, "%s: read", sem->name); + } + if ((size_t)r < count) { + errx(1, "%s: read: unexpected EOF", sem->name); + } } -void -Pn(struct usem *sem, unsigned count) -{ - ssize_t r; - char c[count]; +void P(struct usem *sem) { Pn(sem, 1); } - r = read(sem->fd, c, count); - if (r < 0) { - err(1, "%s: read", sem->name); - } - if ((size_t)r < count) { - errx(1, "%s: read: unexpected EOF", sem->name); - } +void Vn(struct usem *sem, unsigned count) { + ssize_t r; + char c[count]; + + /* semfs does not use these values, but be conservative */ + memset(c, 0, count); + + r = write(sem->fd, c, count); + if (r < 0) { + err(1, "%s: write", sem->name); + } + if ((size_t)r < count) { + errx(1, "%s: write: Short count", sem->name); + } } -void -P(struct usem *sem) -{ - Pn(sem, 1); -} - -void -Vn(struct usem *sem, unsigned count) -{ - ssize_t r; - char c[count]; - - /* semfs does not use these values, but be conservative */ - memset(c, 0, count); - - r = write(sem->fd, c, count); - if (r < 0) { - err(1, "%s: write", sem->name); - } - if ((size_t)r < count) { - errx(1, "%s: write: Short count", sem->name); - } -} - -void -V(struct usem *sem) -{ - Vn(sem, 1); -} +void V(struct usem *sem) { Vn(sem, 1); } diff --git a/userland/testbin/schedpong/usem.h b/userland/testbin/schedpong/usem.h index 8646ee2..5463f94 100644 --- a/userland/testbin/schedpong/usem.h +++ b/userland/testbin/schedpong/usem.h @@ -32,8 +32,8 @@ * Semaphore structure. */ struct usem { - char name[32]; - int fd; + char name[32]; + int fd; }; /* XXX this should be in sys/cdefs.h */ diff --git a/userland/testbin/sort/sort.c b/userland/testbin/sort/sort.c index 6f90c4f..6eaa658 100644 --- a/userland/testbin/sort/sort.c +++ b/userland/testbin/sort/sort.c @@ -41,8 +41,7 @@ #include /* Larger than physical memory */ -#define SIZE (144*1024) - +#define SIZE (144 * 1024) /* * Quicksort. @@ -54,82 +53,69 @@ * Also, quicksort has somewhat more interesting memory usage patterns. */ -static -void -sort(int *arr, int size) -{ - static int tmp[SIZE]; - int pivot, i, j, k; +static void sort(int *arr, int size) { + static int tmp[SIZE]; + int pivot, i, j, k; - if (size<2) { - return; - } + if (size < 2) { + return; + } - pivot = size/2; - sort(arr, pivot); - sort(&arr[pivot], size-pivot); + pivot = size / 2; + sort(arr, pivot); + sort(&arr[pivot], size - pivot); - i = 0; - j = pivot; - k = 0; - while (i A[i+1]) { - errx(1, "Failed: A[%d] is %d, A[%d] is %d", - i, A[i], i+1, A[i+1]); - } - } - warnx("Passed."); + for (i = 0; i < SIZE - 1; i++) { + if (A[i] > A[i + 1]) { + errx(1, "Failed: A[%d] is %d, A[%d] is %d", i, A[i], i + 1, A[i + 1]); + } + } + warnx("Passed."); } -int -main(void) -{ - initarray(); - sort(A, SIZE); - check(); - return 0; +int main(void) { + initarray(); + sort(A, SIZE); + check(); + return 0; } diff --git a/userland/testbin/sparsefile/sparsefile.c b/userland/testbin/sparsefile/sparsefile.c index 93cd5bf..b701c58 100644 --- a/userland/testbin/sparsefile/sparsefile.c +++ b/userland/testbin/sparsefile/sparsefile.c @@ -42,46 +42,43 @@ #include #include -int -main(int argc, char *argv[]) -{ - const char *filename; - int size; - int fd; - int r; - char byte; +int main(int argc, char *argv[]) { + const char *filename; + int size; + int fd; + int r; + char byte; - if (argc != 3) { - errx(1, "Usage: sparsefile "); - } + if (argc != 3) { + errx(1, "Usage: sparsefile "); + } - filename = argv[1]; - size = atoi(argv[2]); - byte = '\n'; + filename = argv[1]; + size = atoi(argv[2]); + byte = '\n'; - if (size == 0) { - err(1, "Sparse files of length zero are not meaningful"); - } + if (size == 0) { + err(1, "Sparse files of length zero are not meaningful"); + } - printf("Creating a sparse file of size %d\n", size); + printf("Creating a sparse file of size %d\n", size); - fd = open(filename, O_WRONLY|O_CREAT|O_TRUNC); - if (fd < 0) { - err(1, "%s: create", filename); - } + fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC); + if (fd < 0) { + err(1, "%s: create", filename); + } - if (lseek(fd, size-1, SEEK_SET) == -1) { - err(1, "%s: lseek", filename); - } - r = write(fd, &byte, 1); - if (r < 0) { - err(1, "%s: write", filename); - } - else if (r != 1) { - errx(1, "%s: write: Unexpected result count %d", filename, r); - } + if (lseek(fd, size - 1, SEEK_SET) == -1) { + err(1, "%s: lseek", filename); + } + r = write(fd, &byte, 1); + if (r < 0) { + err(1, "%s: write", filename); + } else if (r != 1) { + errx(1, "%s: write: Unexpected result count %d", filename, r); + } - close(fd); + close(fd); - return 0; + return 0; } diff --git a/userland/testbin/tail/tail.c b/userland/testbin/tail/tail.c index 6c2b693..139e4cd 100644 --- a/userland/testbin/tail/tail.c +++ b/userland/testbin/tail/tail.c @@ -47,35 +47,29 @@ char buffer[BUFSIZE]; -static -void -tail(int file, off_t where, const char *filename) -{ - int len; +static void tail(int file, off_t where, const char *filename) { + int len; - if (lseek(file, where, SEEK_SET)<0) { - err(1, "%s", filename); - } + if (lseek(file, where, SEEK_SET) < 0) { + err(1, "%s", filename); + } - while ((len = read(file, buffer, sizeof(buffer))) > 0) { - write(STDOUT_FILENO, buffer, len); - } + while ((len = read(file, buffer, sizeof(buffer))) > 0) { + write(STDOUT_FILENO, buffer, len); + } } -int -main(int argc, char **argv) -{ - int file; +int main(int argc, char **argv) { + int file; - if (argc < 3) { - errx(1, "Usage: tail "); - } - file = open(argv[1], O_RDONLY); - if (file < 0) { - err(1, "%s", argv[1]); - } - tail(file, atoi(argv[2]), argv[1]); - close(file); - return 0; + if (argc < 3) { + errx(1, "Usage: tail "); + } + file = open(argv[1], O_RDONLY); + if (file < 0) { + err(1, "%s", argv[1]); + } + tail(file, atoi(argv[2]), argv[1]); + close(file); + return 0; } - diff --git a/userland/testbin/tictac/tictac.c b/userland/testbin/tictac/tictac.c index d65ec27..3750c1e 100644 --- a/userland/testbin/tictac/tictac.c +++ b/userland/testbin/tictac/tictac.c @@ -42,14 +42,14 @@ #include #define NEWLINE 012 -#define EMPTY 0 -#define X_PLAYER 1 -#define O_PLAYER 2 -#define X_MARKER 1 -#define O_MARKER 2 -#define DIM 3 -#define DIMCHAR "2" -#define MAXSTRING 100 +#define EMPTY 0 +#define X_PLAYER 1 +#define O_PLAYER 2 +#define X_MARKER 1 +#define O_MARKER 2 +#define DIM 3 +#define DIMCHAR "2" +#define MAXSTRING 100 typedef enum { FALSE, TRUE } bool; @@ -58,7 +58,7 @@ bool ask_yesno(const char *msg); bool do_move(int player); void initialize_board(void); bool is_win(int x, int y); -int read_string(char *buf, int length); +int read_string(char *buf, int length); void print_board(void); void print_instructions(void); bool win_column(int y, int marker); @@ -67,7 +67,6 @@ bool win_diag_right(int x, int y, int marker); bool win_row(int x, int marker); bool Strcmp(const char *a, const char *b); - /* * The board is gloabally defined. */ @@ -75,37 +74,35 @@ int board[DIM][DIM]; /* Console I/O routines */ -int -main(void) -{ - bool win = FALSE; - int move, max_moves; - int player; +int main(void) { + bool win = FALSE; + int move, max_moves; + int player; - print_instructions(); - max_moves = DIM * DIM; /* Maximum number of moves in a game */ + print_instructions(); + max_moves = DIM * DIM; /* Maximum number of moves in a game */ - while (TRUE) { - initialize_board(); - for (move = 1; move <= max_moves; move++) { - player = move % 2 == 0 ? 2 : 1; - win = do_move(player); - print_board(); - if (win) { - printf("Player %d, you WON!\n\n", player); - break; /* out of for loop */ - } - } - /* - * If we got here by falling through the loop, then it is a - * tie game. - */ - if (!win) - printf("Tie Game!\n\n"); - if (!ask_yesno("Do you wish to play again?")) - break; /* out of while loop */ - } - return 0; + while (TRUE) { + initialize_board(); + for (move = 1; move <= max_moves; move++) { + player = move % 2 == 0 ? 2 : 1; + win = do_move(player); + print_board(); + if (win) { + printf("Player %d, you WON!\n\n", player); + break; /* out of for loop */ + } + } + /* + * If we got here by falling through the loop, then it is a + * tie game. + */ + if (!win) + printf("Tie Game!\n\n"); + if (!ask_yesno("Do you wish to play again?")) + break; /* out of while loop */ + } + return 0; } /* @@ -118,12 +115,10 @@ main(void) * Error * None */ -void -print_instructions(void) -{ - printf("Welcome to tic-tac-toe!\n"); - printf("Player 1 always plays X and player 2 always play O\n"); - printf("Good luck!\n\n\n"); +void print_instructions(void) { + printf("Welcome to tic-tac-toe!\n"); + printf("Player 1 always plays X and player 2 always play O\n"); + printf("Good luck!\n\n\n"); } void @@ -139,25 +134,33 @@ void */ print_board(void) { - int i, j; + int i, j; - /* Print labels across the top */ - printf("\n 0 1 2\n"); + /* Print labels across the top */ + printf("\n 0 1 2\n"); - for (i = 0; i < DIM; i++) { - /* Print row labels */ - printf(" %d ", i); - for (j = 0; j < DIM; j++) { - switch (board[i][j]) { - case EMPTY: printf(" "); break; - case X_MARKER: printf(" X "); break; - case O_MARKER: printf(" O "); break; - default: printf("???"); break; - } - } - printf("\n"); - } - printf("\n"); + for (i = 0; i < DIM; i++) { + /* Print row labels */ + printf(" %d ", i); + for (j = 0; j < DIM; j++) { + switch (board[i][j]) { + case EMPTY: + printf(" "); + break; + case X_MARKER: + printf(" X "); + break; + case O_MARKER: + printf(" O "); + break; + default: + printf("???"); + break; + } + } + printf("\n"); + } + printf("\n"); } /* @@ -175,22 +178,20 @@ print_board(void) * Error * None */ -bool -ask_yesno(const char *msg) -{ - char answer[MAXSTRING]; +bool ask_yesno(const char *msg) { + char answer[MAXSTRING]; - while (TRUE) { - printf("%s [yes/no] ", msg); - if (read_string(answer, MAXSTRING) < 0) - return(FALSE); - if (Strcmp(answer, "yes")) - return(TRUE); - else if (Strcmp(answer, "no")) - return(FALSE); - else - printf("Please answer either yes or no\n"); - } + while (TRUE) { + printf("%s [yes/no] ", msg); + if (read_string(answer, MAXSTRING) < 0) + return (FALSE); + if (Strcmp(answer, "yes")) + return (TRUE); + else if (Strcmp(answer, "no")) + return (FALSE); + else + printf("Please answer either yes or no\n"); + } } /* @@ -209,47 +210,42 @@ ask_yesno(const char *msg) * Error * None */ -bool -do_move(int player) -{ - int x, y; - char answer[MAXSTRING]; - char cx; +bool do_move(int player) { + int x, y; + char answer[MAXSTRING]; + char cx; - printf("Player %d (%c), your move\n", player, - player == X_PLAYER ? 'X' : 'O'); + printf("Player %d (%c), your move\n", player, player == X_PLAYER ? 'X' : 'O'); - while (TRUE) { - printf("Which row [0-%d]: ", DIM-1); - if (read_string(answer, MAXSTRING) < 0) - return(FALSE); - cx = answer[0]; - x = cx - '0'; - if (x < 0 || x >= DIM) { - printf("Invalid row; must be >= 0 and < %d\n", DIM-1); - continue; - } - printf("Which column [0-%d]: ", DIM-1); - if (read_string(answer, MAXSTRING) < 0) - return(FALSE); - cx = answer[0]; - y = cx - '0'; - if (y < 0 || y >= DIM) { - printf("Invalid column; must be >= 0 and < %d\n", - DIM-1); - continue; - } + while (TRUE) { + printf("Which row [0-%d]: ", DIM - 1); + if (read_string(answer, MAXSTRING) < 0) + return (FALSE); + cx = answer[0]; + x = cx - '0'; + if (x < 0 || x >= DIM) { + printf("Invalid row; must be >= 0 and < %d\n", DIM - 1); + continue; + } + printf("Which column [0-%d]: ", DIM - 1); + if (read_string(answer, MAXSTRING) < 0) + return (FALSE); + cx = answer[0]; + y = cx - '0'; + if (y < 0 || y >= DIM) { + printf("Invalid column; must be >= 0 and < %d\n", DIM - 1); + continue; + } - if (board[x][y] != EMPTY) { - printf("That location is occupied; please try again\n"); - print_board(); - } else - break; - } - board[x][y] = player == X_PLAYER ? X_MARKER : O_MARKER; - - return(is_win(x, y)); + if (board[x][y] != EMPTY) { + printf("That location is occupied; please try again\n"); + print_board(); + } else + break; + } + board[x][y] = player == X_PLAYER ? X_MARKER : O_MARKER; + return (is_win(x, y)); } /* @@ -274,124 +270,106 @@ do_move(int player) * TRUE if player won * FALSE otherwise */ -bool -is_win(int x, int y) -{ - int marker; +bool is_win(int x, int y) { + int marker; - marker = board[x][y]; + marker = board[x][y]; - /* - * Note that C "short circuit evaluation". As soon as any one - * of these functions returns TRUE, we know that the expression - * is true. Therefore, we can return TRUE without executing - * any of the other routines. - */ - return(win_row(x, marker) || win_column(y, marker) || - win_diag_left(x, y, marker) || win_diag_right(x, y, marker)); + /* + * Note that C "short circuit evaluation". As soon as any one + * of these functions returns TRUE, we know that the expression + * is true. Therefore, we can return TRUE without executing + * any of the other routines. + */ + return (win_row(x, marker) || win_column(y, marker) || + win_diag_left(x, y, marker) || win_diag_right(x, y, marker)); } /* * Four helper functions for determining a win. */ -bool -win_column(int y, int marker) -{ - int i; - for (i = 0; i < DIM; i++) - if (board[i][y] != marker) - return(FALSE); - return(TRUE); +bool win_column(int y, int marker) { + int i; + for (i = 0; i < DIM; i++) + if (board[i][y] != marker) + return (FALSE); + return (TRUE); } -bool -win_row(int x, int marker) -{ - int i; - for (i = 0; i < DIM; i++) - if (board[x][i] != marker) - return(FALSE); - return(TRUE); +bool win_row(int x, int marker) { + int i; + for (i = 0; i < DIM; i++) + if (board[x][i] != marker) + return (FALSE); + return (TRUE); } -bool -win_diag_left(int x, int y, int marker) -{ - int i; +bool win_diag_left(int x, int y, int marker) { + int i; - /* Check that move is on the diagonal */ - if (x != y) - return(FALSE); + /* Check that move is on the diagonal */ + if (x != y) + return (FALSE); - for (i = 0; i < DIM; i++) - if (board[i][i] != marker) - return(FALSE); - return(TRUE); + for (i = 0; i < DIM; i++) + if (board[i][i] != marker) + return (FALSE); + return (TRUE); } -bool -win_diag_right(int x, int y, int marker) -{ - int i; +bool win_diag_right(int x, int y, int marker) { + int i; - /* Check that move is on the diagonal */ - if (x + y != DIM - 1) - return(FALSE); - for (i = 0; i < DIM; i++) - if (board[i][DIM - 1 - i] != marker) - return(FALSE); - return(TRUE); + /* Check that move is on the diagonal */ + if (x + y != DIM - 1) + return (FALSE); + for (i = 0; i < DIM; i++) + if (board[i][DIM - 1 - i] != marker) + return (FALSE); + return (TRUE); } -void -initialize_board(void) -{ - int i, j; +void initialize_board(void) { + int i, j; - for (i = 0; i < DIM; i++) - for (j = 0; j < DIM; j++) - board[i][j] = EMPTY; + for (i = 0; i < DIM; i++) + for (j = 0; j < DIM; j++) + board[i][j] = EMPTY; } -int -read_string(char *buf, int length) -{ - int char_read; - int i; +int read_string(char *buf, int length) { + int char_read; + int i; - i = 0; - while ((char_read = getchar()) != EOF && char_read != NEWLINE && - i < length) { - buf[i] = (char) char_read; - i++; - putchar(char_read); - } + i = 0; + while ((char_read = getchar()) != EOF && char_read != NEWLINE && i < length) { + buf[i] = (char)char_read; + i++; + putchar(char_read); + } - if (char_read == EOF) - return(-1); + if (char_read == EOF) + return (-1); - /* - * If the input overflows the buffer, just cut it short - * at length - 1 characters. - */ - if (i >= length) - i--; - buf[i] = 0; - return(i); + /* + * If the input overflows the buffer, just cut it short + * at length - 1 characters. + */ + if (i >= length) + i--; + buf[i] = 0; + return (i); } -bool -Strcmp(const char *a, const char *b) -{ - if (a == NULL) - return(b == NULL); - if (b == NULL) - return(FALSE); +bool Strcmp(const char *a, const char *b) { + if (a == NULL) + return (b == NULL); + if (b == NULL) + return (FALSE); - while (*a && *b) - if (*a++ != *b++) - return(FALSE); - - return(*a == *b); + while (*a && *b) + if (*a++ != *b++) + return (FALSE); + return (*a == *b); } diff --git a/userland/testbin/triplehuge/triplehuge.c b/userland/testbin/triplehuge/triplehuge.c index af457f8..abcb9aa 100644 --- a/userland/testbin/triplehuge/triplehuge.c +++ b/userland/testbin/triplehuge/triplehuge.c @@ -37,9 +37,7 @@ #include -int -main(void) -{ - triple("/testbin/huge"); - return 0; +int main(void) { + triple("/testbin/huge"); + return 0; } diff --git a/userland/testbin/triplemat/triplemat.c b/userland/testbin/triplemat/triplemat.c index 7c5a9ed..93fc33e 100644 --- a/userland/testbin/triplemat/triplemat.c +++ b/userland/testbin/triplemat/triplemat.c @@ -37,9 +37,7 @@ #include -int -main(void) -{ - triple("/testbin/matmult"); - return 0; +int main(void) { + triple("/testbin/matmult"); + return 0; } diff --git a/userland/testbin/triplesort/triplesort.c b/userland/testbin/triplesort/triplesort.c index b93ba3a..7d39f67 100644 --- a/userland/testbin/triplesort/triplesort.c +++ b/userland/testbin/triplesort/triplesort.c @@ -37,9 +37,7 @@ #include -int -main(void) -{ - triple("/testbin/sort"); - return 0; +int main(void) { + triple("/testbin/sort"); + return 0; } diff --git a/userland/testbin/usemtest/usemtest.c b/userland/testbin/usemtest/usemtest.c index e812e86..0240782 100644 --- a/userland/testbin/usemtest/usemtest.c +++ b/userland/testbin/usemtest/usemtest.c @@ -45,25 +45,22 @@ #include #include -#define ONCELOOPS 3 -#define TWICELOOPS 2 +#define ONCELOOPS 3 +#define TWICELOOPS 2 #define THRICELOOPS 1 -#define LOOPS (ONCELOOPS + 2*TWICELOOPS + 3*THRICELOOPS) +#define LOOPS (ONCELOOPS + 2 * TWICELOOPS + 3 * THRICELOOPS) #define NUMJOBS 4 /* * Print to the console, one character at a time to encourage * interleaving if the semaphores aren't working. */ -static -void -say(const char *str) -{ - size_t i; +static void say(const char *str) { + size_t i; - for (i=0; str[i]; i++) { - putchar(str[i]); - } + for (i = 0; str[i]; i++) { + putchar(str[i]); + } } #if 0 /* not used */ @@ -85,26 +82,21 @@ sayf(const char *str, ...) /* * This should probably be in libtest. */ -static -void -dowait(pid_t pid, unsigned num) -{ - pid_t r; - int status; +static void dowait(pid_t pid, unsigned num) { + pid_t r; + int status; - r = waitpid(pid, &status, 0); - if (r < 0) { - warn("waitpid"); - return; - } - if (WIFSIGNALED(status)) { - warnx("pid %d (subprocess %u): Signal %d", (int)pid, - num, WTERMSIG(status)); - } - else if (WIFEXITED(status) && WEXITSTATUS(status) != 0) { - warnx("pid %d (subprocess %u): Exit %d", (int)pid, - num, WEXITSTATUS(status)); - } + r = waitpid(pid, &status, 0); + if (r < 0) { + warn("waitpid"); + return; + } + if (WIFSIGNALED(status)) { + warnx("pid %d (subprocess %u): Signal %d", (int)pid, num, WTERMSIG(status)); + } else if (WIFEXITED(status) && WEXITSTATUS(status) != 0) { + warnx("pid %d (subprocess %u): Exit %d", (int)pid, num, + WEXITSTATUS(status)); + } } //////////////////////////////////////////////////////////// @@ -114,276 +106,238 @@ dowait(pid_t pid, unsigned num) * Semaphore structure. */ struct usem { - char name[32]; - int fd; + char name[32]; + int fd; }; -static -void -usem_init(struct usem *sem, const char *tag, unsigned num) -{ - snprintf(sem->name, sizeof(sem->name), "sem:usemtest.%s%u", tag, num); - sem->fd = open(sem->name, O_RDWR|O_CREAT|O_TRUNC, 0664); - if (sem->fd < 0) { - err(1, "%s: create", sem->name); - } - close(sem->fd); - sem->fd = -1; +static void usem_init(struct usem *sem, const char *tag, unsigned num) { + snprintf(sem->name, sizeof(sem->name), "sem:usemtest.%s%u", tag, num); + sem->fd = open(sem->name, O_RDWR | O_CREAT | O_TRUNC, 0664); + if (sem->fd < 0) { + err(1, "%s: create", sem->name); + } + close(sem->fd); + sem->fd = -1; } -static -void -usem_open(struct usem *sem) -{ - sem->fd = open(sem->name, O_RDWR); - if (sem->fd < 0) { - err(1, "%s: open", sem->name); - } +static void usem_open(struct usem *sem) { + sem->fd = open(sem->name, O_RDWR); + if (sem->fd < 0) { + err(1, "%s: open", sem->name); + } } -static -void -usem_close(struct usem *sem) -{ - if (close(sem->fd) == -1) { - warn("%s: close", sem->name); - } +static void usem_close(struct usem *sem) { + if (close(sem->fd) == -1) { + warn("%s: close", sem->name); + } } -static -void -usem_cleanup(struct usem *sem) -{ - (void)remove(sem->name); +static void usem_cleanup(struct usem *sem) { (void)remove(sem->name); } + +static void P(struct usem *sem) { + ssize_t r; + char c; + + r = read(sem->fd, &c, 1); + if (r < 0) { + err(1, "%s: read", sem->name); + } + if (r == 0) { + errx(1, "%s: read: unexpected EOF", sem->name); + } } -static -void -P(struct usem *sem) -{ - ssize_t r; - char c; +static void V(struct usem *sem) { + ssize_t r; + char c; - r = read(sem->fd, &c, 1); - if (r < 0) { - err(1, "%s: read", sem->name); - } - if (r == 0) { - errx(1, "%s: read: unexpected EOF", sem->name); - } -} - -static -void -V(struct usem *sem) -{ - ssize_t r; - char c; - - r = write(sem->fd, &c, 1); - if (r < 0) { - err(1, "%s: write", sem->name); - } - if (r == 0) { - errx(1, "%s: write: short count", sem->name); - } + r = write(sem->fd, &c, 1); + if (r < 0) { + err(1, "%s: write", sem->name); + } + if (r == 0) { + errx(1, "%s: write: short count", sem->name); + } } //////////////////////////////////////////////////////////// // test components -static -void -child_plain(struct usem *gosem, struct usem *waitsem, unsigned num) -{ - static const char *const strings[NUMJOBS] = { - "Nitwit!", - "Blubber!", - "Oddment!", - "Tweak!", - }; +static void child_plain(struct usem *gosem, struct usem *waitsem, + unsigned num) { + static const char *const strings[NUMJOBS] = { + "Nitwit!", + "Blubber!", + "Oddment!", + "Tweak!", + }; - const char *string; - unsigned i; + const char *string; + unsigned i; - string = strings[num]; - for (i=0; i #include -#define NTHREADS 3 -#define MAX 1<<25 +#define NTHREADS 3 +#define MAX 1 << 25 /* counter for the loop in the threads: This variable is shared and incremented by each @@ -64,23 +63,21 @@ volatile int count = 0; void ThreadRunner(void); void BladeRunner(void); -int -main(int argc, char *argv[]) -{ - int i; +int main(int argc, char *argv[]) { + int i; - (void)argc; - (void)argv; + (void)argc; + (void)argv; - for (i=0; i