rcache.c revision 1.15 1 /* $NetBSD: rcache.c,v 1.15 2003/02/04 08:11:50 enami Exp $ */
2
3 /*-
4 * Copyright (c) 1999 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Martin J. Laubach <mjl (at) emsi.priv.at> and
9 * Manuel Bouyer <Manuel.Bouyer (at) lip6.fr>.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. All advertising materials mentioning features or use of this software
20 * must display the following acknowledgement:
21 * This product includes software developed by the NetBSD
22 * Foundation, Inc. and its contributors.
23 * 4. Neither the name of The NetBSD Foundation nor the names of its
24 * contributors may be used to endorse or promote products derived
25 * from this software without specific prior written permission.
26 *
27 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
28 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
29 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
30 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
31 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
32 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
33 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
34 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
35 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
36 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
37 * POSSIBILITY OF SUCH DAMAGE.
38 */
39
40 #include <sys/cdefs.h>
41 #ifndef lint
42 __RCSID("$NetBSD: rcache.c,v 1.15 2003/02/04 08:11:50 enami Exp $");
43 #endif /* not lint */
44
45 #include <sys/types.h>
46 #include <sys/uio.h>
47 #include <sys/mman.h>
48 #include <sys/param.h>
49 #include <sys/sysctl.h>
50 #include <ufs/ufs/dinode.h>
51
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <unistd.h>
55 #include <fcntl.h>
56 #include <errno.h>
57 #include <string.h>
58
59 #include "dump.h"
60
61 /*-----------------------------------------------------------------------*/
62 #define MAXCACHEBUFS 512 /* max 512 buffers */
63 #define MAXMEMPART 6 /* max 15% of the user mem */
64
65 /*-----------------------------------------------------------------------*/
66 union cdesc {
67 volatile size_t cd_count;
68 struct {
69 volatile daddr_t blkstart;
70 volatile daddr_t blkend; /* start + nblksread */
71 volatile daddr_t blocksRead;
72 volatile size_t time;
73 #ifdef DIAGNOSTICS
74 volatile pid_t owner;
75 #endif
76 } desc;
77 #define cd_blkstart desc.blkstart
78 #define cd_blkend desc.blkend
79 #define cd_blocksRead desc.blocksRead
80 #define cd_time desc.time
81 #define cd_owner desc.owner
82 };
83
84 static int findlru(void);
85
86 static void *shareBuffer = NULL;
87 static union cdesc *cheader;
88 static union cdesc *cdesc;
89 static char *cdata;
90 static int cachebufs;
91 static int nblksread;
92
93 #ifdef STATS
94 static int nreads;
95 static int nphysread;
96 static int64_t readsize;
97 static int64_t physreadsize;
98 #endif
99
100 #define CDATA(i) (cdata + ((i) * nblksread * dev_bsize))
101
102 void
103 initcache(int cachesize, int readblksize)
104 {
105 size_t len;
106 size_t sharedSize;
107
108 /* Convert read block size in terms of filesystem block size */
109 nblksread = howmany(readblksize, ufsib->ufs_bsize);
110
111 /* Then, convert it in terms of device block size */
112 nblksread <<= ufsib->ufs_bshift - dev_bshift;
113
114 if (cachesize == -1) { /* Compute from memory available */
115 int usermem;
116 int mib[2] = { CTL_HW, HW_USERMEM };
117
118 len = sizeof(usermem);
119 if (sysctl(mib, 2, &usermem, &len, NULL, 0) < 0) {
120 msg("sysctl(hw.usermem) failed: %s\n",
121 strerror(errno));
122 return;
123 }
124 cachebufs = (usermem / MAXMEMPART) / (nblksread * dev_bsize);
125 } else { /* User specified */
126 cachebufs = cachesize;
127 }
128
129 if (cachebufs) { /* Don't allocate if zero --> no caching */
130 if (cachebufs > MAXCACHEBUFS)
131 cachebufs = MAXCACHEBUFS;
132
133 sharedSize = sizeof(union cdesc) +
134 sizeof(union cdesc) * cachebufs +
135 nblksread * cachebufs * dev_bsize;
136 #ifdef STATS
137 fprintf(stderr, "Using %d buffers (%d bytes)\n", cachebufs,
138 sharedSize);
139 #endif
140 shareBuffer = mmap(NULL, sharedSize, PROT_READ | PROT_WRITE,
141 MAP_ANON | MAP_SHARED, -1, 0);
142 if (shareBuffer == MAP_FAILED) {
143 msg("can't mmap shared memory for buffer: %s\n",
144 strerror(errno));
145 return;
146 }
147 cheader = shareBuffer;
148 cdesc = (union cdesc *) (((char *) shareBuffer) +
149 sizeof(union cdesc));
150 cdata = ((char *) shareBuffer) + sizeof(union cdesc) +
151 sizeof(union cdesc) * cachebufs;
152
153 memset(shareBuffer, '\0', sharedSize);
154 }
155 }
156
157 /*
158 * Find the cache buffer descriptor that shows the minimal access time
159 */
160 static int
161 findlru(void)
162 {
163 int i;
164 size_t minTime = cdesc[0].cd_time;
165 int minIdx = 0;
166
167 for (i = 0; i < cachebufs; i++) {
168 if (cdesc[i].cd_time < minTime) {
169 minIdx = i;
170 minTime = cdesc[i].cd_time;
171 }
172 }
173
174 return minIdx;
175 }
176
177 /*
178 * Read data directly from disk, with smart error handling.
179 * Try to recover from hard errors by reading in sector sized pieces.
180 * Error recovery is attempted at most BREADEMAX times before seeking
181 * consent from the operator to continue.
182 */
183
184 static int breaderrors = 0;
185 #define BREADEMAX 32
186
187 void
188 rawread(daddr_t blkno, char *buf, int size)
189 {
190 int cnt, i;
191
192 #ifdef STATS
193 nphysread++;
194 physreadsize += size;
195 #endif
196
197 loop:
198 if (lseek(diskfd, ((off_t) blkno << dev_bshift), SEEK_SET) < 0) {
199 msg("rawread: lseek fails\n");
200 goto err;
201 }
202 if ((cnt = read(diskfd, buf, size)) == size)
203 return;
204 if (blkno + (size / dev_bsize) > ufsib->ufs_dsize) {
205 /*
206 * Trying to read the final fragment.
207 *
208 * NB - dump only works in TP_BSIZE blocks, hence
209 * rounds `dev_bsize' fragments up to TP_BSIZE pieces.
210 * It should be smarter about not actually trying to
211 * read more than it can get, but for the time being
212 * we punt and scale back the read only when it gets
213 * us into trouble. (mkm 9/25/83)
214 */
215 size -= dev_bsize;
216 goto loop;
217 }
218 if (cnt == -1)
219 msg("read error from %s: %s: [block %lld]: count=%d\n",
220 disk, strerror(errno), (long long)blkno, size);
221 else
222 msg("short read error from %s: [block %lld]: "
223 "count=%d, got=%d\n",
224 disk, (long long)blkno, size, cnt);
225 err:
226 if (++breaderrors > BREADEMAX) {
227 msg("More than %d block read errors from %s\n",
228 BREADEMAX, disk);
229 broadcast("DUMP IS AILING!\n");
230 msg("This is an unrecoverable error.\n");
231 if (!query("Do you want to attempt to continue?")) {
232 dumpabort(0);
233 /*NOTREACHED*/
234 } else
235 breaderrors = 0;
236 }
237 /*
238 * Zero buffer, then try to read each sector of buffer separately.
239 */
240 memset(buf, 0, size);
241 for (i = 0; i < size; i += dev_bsize, buf += dev_bsize, blkno++) {
242 if (lseek(diskfd, ((off_t)blkno << dev_bshift),
243 SEEK_SET) < 0) {
244 msg("rawread: lseek2 fails: %s!\n",
245 strerror(errno));
246 continue;
247 }
248 if ((cnt = read(diskfd, buf, (int)dev_bsize)) == dev_bsize)
249 continue;
250 if (cnt == -1) {
251 msg("read error from %s: %s: [sector %lld]: "
252 "count=%ld: %s\n", disk, strerror(errno),
253 (long long)blkno,
254 dev_bsize, strerror(errno));
255 continue;
256 }
257 msg("short read error from %s: [sector %lld]: "
258 "count=%ld, got=%d\n",
259 disk, (long long)blkno, dev_bsize, cnt);
260 }
261 }
262
263 void
264 bread(daddr_t blkno, char *buf, int size)
265 {
266 int osize = size;
267 daddr_t oblkno = blkno;
268 char *obuf = buf;
269 daddr_t numBlocks = howmany(size, dev_bsize);
270
271 #ifdef STATS
272 nreads++;
273 readsize += size;
274 #endif
275
276 if (!shareBuffer) {
277 rawread(blkno, buf, size);
278 return;
279 }
280
281 if (flock(diskfd, LOCK_EX)) {
282 msg("flock(LOCK_EX) failed: %s\n",
283 strerror(errno));
284 rawread(blkno, buf, size);
285 return;
286 }
287
288 retry:
289 while(size > 0) {
290 int i;
291
292 for (i = 0; i < cachebufs; i++) {
293 union cdesc *curr = &cdesc[i];
294
295 #ifdef DIAGNOSTICS
296 if (curr->cd_owner) {
297 fprintf(stderr, "Owner is set (%d, me=%d), can"
298 "not happen.\n", curr->cd_owner, getpid());
299 }
300 #endif
301
302 if (curr->cd_blkend == 0)
303 continue;
304 /*
305 * If we find a bit of the read in the buffers,
306 * now compute how many blocks we can copy,
307 * copy them out, adjust blkno, buf and size,
308 * and restart
309 */
310 if (curr->cd_blkstart <= blkno &&
311 blkno < curr->cd_blkend) {
312 /* Number of data blocks to be copied */
313 int toCopy = MIN(size,
314 (curr->cd_blkend - blkno) * dev_bsize);
315 #ifdef DIAGNOSTICS
316 if (toCopy <= 0 ||
317 toCopy > nblksread * dev_bsize) {
318 fprintf(stderr, "toCopy %d !\n",
319 toCopy);
320 dumpabort(0);
321 }
322 if (CDATA(i) + (blkno - curr->cd_blkstart) *
323 dev_bsize < CDATA(i) ||
324 CDATA(i) + (blkno - curr->cd_blkstart) *
325 dev_bsize >
326 CDATA(i) + nblksread * dev_bsize) {
327 fprintf(stderr, "%p < %p !!!\n",
328 CDATA(i) + (blkno -
329 curr->cd_blkstart) * dev_bsize,
330 CDATA(i));
331 fprintf(stderr, "cdesc[i].cd_blkstart %d "
332 "blkno %d dev_bsize %ld\n",
333 curr->cd_blkstart, blkno, dev_bsize);
334 dumpabort(0);
335 }
336 #endif
337 memcpy(buf, CDATA(i) +
338 (blkno - curr->cd_blkstart) * dev_bsize,
339 toCopy);
340
341 buf += toCopy;
342 size -= toCopy;
343 blkno += howmany(toCopy, dev_bsize);
344 numBlocks -= howmany(toCopy, dev_bsize);
345
346 curr->cd_time = cheader->cd_count++;
347
348 /*
349 * If all data of a cache block have been
350 * read, chances are good no more reads
351 * will occur, so expire the cache immediately
352 */
353
354 curr->cd_blocksRead +=
355 howmany(toCopy, dev_bsize);
356 if (curr->cd_blocksRead >= nblksread)
357 curr->cd_time = 0;
358
359 goto retry;
360 }
361 }
362
363 /* No more to do? */
364 if (size == 0)
365 break;
366
367 /*
368 * This does actually not happen if fs blocks are not greater
369 * than nblksread.
370 */
371 if (numBlocks > nblksread || blkno >= ufsib->ufs_dsize) {
372 rawread(oblkno, obuf, osize);
373 break;
374 } else {
375 int idx;
376 ssize_t rsize;
377 daddr_t blockBlkNo;
378
379 blockBlkNo = (blkno / nblksread) * nblksread;
380 idx = findlru();
381 rsize = MIN(nblksread,
382 ufsib->ufs_dsize - blockBlkNo) *
383 dev_bsize;
384
385 #ifdef DIAGNOSTICS
386 if (cdesc[idx].cd_owner)
387 fprintf(stderr, "Owner is set (%d, me=%d), can"
388 "not happen(2).\n", cdesc[idx].cd_owner,
389 getpid());
390 cdesc[idx].cd_owner = getpid();
391 #endif
392 cdesc[idx].cd_time = cheader->cd_count++;
393 cdesc[idx].cd_blkstart = blockBlkNo;
394 cdesc[idx].cd_blocksRead = 0;
395
396 if (lseek(diskfd, ((off_t) blockBlkNo << dev_bshift),
397 SEEK_SET) < 0) {
398 msg("readBlocks: lseek fails: %s\n",
399 strerror(errno));
400 rsize = -1;
401 } else {
402 rsize = read(diskfd, CDATA(idx), rsize);
403 if (rsize < 0) {
404 msg("readBlocks: read fails: %s\n",
405 strerror(errno));
406 }
407 }
408
409 /* On errors, panic, punt, try to read without
410 * cache and let raw read routine do the rest.
411 */
412
413 if (rsize <= 0) {
414 rawread(oblkno, obuf, osize);
415 #ifdef DIAGNOSTICS
416 if (cdesc[idx].cd_owner != getpid())
417 fprintf(stderr, "Owner changed from "
418 "%d to %d, can't happen\n",
419 getpid(), cdesc[idx].cd_owner);
420 cdesc[idx].cd_owner = 0;
421 #endif
422 break;
423 }
424
425 /* On short read, just note the fact and go on */
426 cdesc[idx].cd_blkend = blockBlkNo + rsize / dev_bsize;
427
428 #ifdef STATS
429 nphysread++;
430 physreadsize += rsize;
431 #endif
432 #ifdef DIAGNOSTICS
433 if (cdesc[idx].cd_owner != getpid())
434 fprintf(stderr, "Owner changed from "
435 "%d to %d, can't happen\n",
436 getpid(), cdesc[idx].cd_owner);
437 cdesc[idx].cd_owner = 0;
438 #endif
439 /*
440 * We swapped some of data in, let the loop fetch
441 * them from cache
442 */
443 }
444 }
445
446 if (flock(diskfd, LOCK_UN))
447 msg("flock(LOCK_UN) failed: %s\n",
448 strerror(errno));
449 }
450
451 void
452 printcachestats(void)
453 {
454
455 #ifdef STATS
456 fprintf(stderr, "Pid %d: %d reads (%u bytes) "
457 "%d physical reads (%u bytes) %d%% hits, %d%% overhead\n",
458 getpid(), nreads, (u_int) readsize, nphysread,
459 (u_int) physreadsize, (nreads - nphysread) * 100 / nreads,
460 (int) (((physreadsize - readsize) * 100) / readsize));
461 #endif
462 }
463