1 #include <u.h> 2 #include <libc.h> 3 4 int ulcmp(ulong*, ulong*); 5 void swapem(ulong*, long); 6 7 #define Wormsize 546000 8 int wflag; 9 10 void 11 main(int argc, char *argv[]) 12 { 13 long i, l, x, lobits, hibits, tot; 14 int f, j; 15 char *file; 16 ulong *b, a, lo, hi; 17 18 ARGBEGIN { 19 default: 20 print("usage: exsort [-w] [file]\n"); 21 exits("usage"); 22 case 'w': 23 wflag++; 24 break; 25 } ARGEND; 26 27 file = "/adm/cache"; 28 if(argc > 0) 29 file = argv[0]; 30 31 if(wflag) 32 f = open(file, ORDWR); 33 else 34 f = open(file, OREAD); 35 if(f < 0) { 36 print("cant open %s: %r\n", file); 37 exits("open"); 38 } 39 l = seek(f, 0, 2) / sizeof(long); 40 41 b = malloc(l*sizeof(long)); 42 if(b == 0) { 43 print("cant malloc %s: %r\n", file); 44 exits("malloc"); 45 } 46 seek(f, 0, 0); 47 if(read(f, b, l*sizeof(long)) != l*sizeof(long)) { 48 print("short read %s: %r\n", file); 49 exits("read"); 50 } 51 52 lobits = 0; 53 hibits = 0; 54 for(i=0; i<l; i++) { 55 a = b[i]; 56 if(a & (1L<<7)) 57 lobits++; 58 if(a & (1L<<31)) 59 hibits++; 60 } 61 62 print("lobits = %6ld\n", lobits); 63 print("hibits = %6ld\n", hibits); 64 65 if(hibits > lobits) { 66 print("swapping\n"); 67 swapem(b, l); 68 } 69 70 qsort(b, l, sizeof(ulong), ulcmp); 71 72 tot = 0; 73 for(j=0; j<100; j++) { 74 lo = j*Wormsize; 75 hi = lo + Wormsize; 76 77 x = 0; 78 for(i=0; i<l; i++) { 79 a = b[i]; 80 if(a >= lo && a < hi) 81 x++; 82 } 83 if(x) { 84 print("disk %2d %6ld blocks\n", j, x); 85 tot += x; 86 } 87 } 88 print("total %6ld blocks\n", tot); 89 90 91 if(wflag) { 92 if(hibits > lobits) 93 swapem(b, l); 94 seek(f, 0, 0); 95 if(write(f, b, l*sizeof(long)) != l*sizeof(long)) { 96 print("short write %s\n", file); 97 exits("write"); 98 } 99 } 100 101 exits(0); 102 } 103 104 int 105 ulcmp(ulong *a, ulong *b) 106 { 107 if(*a > *b) 108 return 1; 109 if(*a < *b) 110 return -1; 111 return 0; 112 } 113 114 void 115 swapem(ulong *b, long l) 116 { 117 long i; 118 ulong x, a; 119 120 for(i=0; i<l; i++, b++) { 121 a = *b; 122 x = (((a>>0) & 0xff) << 24) | 123 (((a>>8) & 0xff) << 16) | 124 (((a>>16) & 0xff) << 8) | 125 (((a>>24) & 0xff) << 0); 126 *b = x; 127 } 128 } 129