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