+ va_start(ap, what);
+ progress_clear(&progress);
+ printf(";; recovery buffer (");
+ vprintf(what, ap);
+ printf("): "
+ "(%"PRIuSEC") ..%"PRIuSEC".. "
+ "[%"PRIuSEC" ..%"PRIuSEC".. %"PRIuSEC"] "
+ "..%"PRIuSEC".. (%"PRIuSEC")\n",
+ r->pos, r->start,
+ r->pos + r->start, r->end - r->start, r->pos + r->end,
+ r->sz - r->end, r->pos + r->sz);
+ va_end(ap);
+ assert(r->start <= r->end);
+ assert(r->end <= r->sz);
+}
+#endif
+
+static ssize_t recovery_read_sectors(struct recoverybuf *r,
+ secaddr pos, secaddr off, secaddr want)
+ /* Try to read WANT sectors starting at sector address POS from the
+ * current file into R's buffer, at offset OFF sectors from the start
+ * of the buffer. Return the number of sectors read, zero if at end
+ * of file, or -1 in the event of a system error.
+ *
+ * This is a trivial wrapper around `read_sectors' with some
+ * additional range checking, used only by `recovery_read_buffer'
+ * below.
+ */
+{
+ ssize_t n;
+
+ assert(off <= r->sz); assert(want <= r->sz - off);
+ assert(pos == r->pos + off);
+ n = read_sectors(pos, r->buf + off*SECTORSZ, want);
+ return (n);
+}
+
+static ssize_t recovery_read_buffer(struct recoverybuf *r,
+ secaddr pos, secaddr want)
+ /* Try to read WANT sectors, starting at sector address POS, from the
+ * current file into the buffer R, returning a count of the number of
+ * sectors read, or 0 if at end of file, or -1 in the case of a
+ * system error, as for `read_sectors'. The data will end up
+ * /somewhere/ in the buffer, but not necessarily at the start.
+ */
+{
+ secaddr diff, pp, nn;
+ ssize_t n;
+
+ /* This is the main piece of the short-range tracking machinery. It's
+ * rather complicated, so hold on tight. (It's much simpler -- and less
+ * broken -- than earlier versions were, though.)
+ */
+
+#ifdef DEBUG
+ progress_clear(&progress);
+ show_recovery_buffer_map(r, "begin(%"PRIuSEC", %"PRIuSEC")", pos, want);
+#endif
+
+ /* The first order of business is to make space in the buffer for this new
+ * data. We therefore start with a case analysis.
+ */
+ if (pos < r->pos) {
+ /* The new position is before the current start of the buffer, so we have
+ * no choice but to decrease the buffer position, which will involve
+ * shifting the existing material upwards.
+ */
+
+ /* Determine how far up we'll need to shift. */
+ diff = r->pos - pos;
+
+ if (r->start + diff >= r->sz) {
+ /* The material that's currently in the buffer would be completely
+ * shifted off the end, so we have no choice but to discard it
+ * completely.
+ */
+
+ r->pos = pos; r->start = r->end = 0;
+#ifdef DEBUG
+ show_recovery_buffer_map(r, "cleared; shift up by %"PRIuSEC"", diff);
+#endif
+ } else {
+ /* Some of the material in the buffer will still be there. We might
+ * lose some stuff off the end: start by throwing that away, and then
+ * whatever's left can be moved easily.
+ */
+
+ if (r->end + diff > r->sz) r->end = r->sz - diff;
+ rearrange_sectors(r, r->start + diff, r->start, r->end - r->start);
+ r->pos -= diff; r->start += diff; r->end += diff;
+#ifdef DEBUG
+ show_recovery_buffer_map(r, "shifted up by %"PRIuSEC"", diff);
+#endif
+ }
+ } else if (pos > r->pos + r->end) {
+ /* The new position is strictly beyond the old region. We /could/ maybe
+ * keep this material, but it turns out to be better not to. To keep it,
+ * we'd have to also read the stuff that's in between the end of the old
+ * region and the start of the new one, and that might contain bad
+ * sectors which the caller is specifically trying to skip. We just
+ * discard the entire region here so as not to subvert the caller's
+ * optimizations.
+ */
+
+ r->pos = pos; r->start = r->end = 0;
+#ifdef DEBUG
+ show_recovery_buffer_map(r, "cleared; beyond previous region");
+#endif
+ } else if (pos + want > r->pos + r->sz) {
+ /* The requested range of sectors extends beyond the region currently
+ * covered by the buffer. We must therefore increase the buffer position
+ * which will involve shifting the existing material downwards.
+ */
+
+ /* Determine how far down we'll need to shift. */
+ diff = (pos + want) - (r->pos + r->sz);
+
+ if (r->end <= diff) {
+ /* The material that's currently in the buffer would be completely
+ * shifted off the beginning, so we have no choice but to discard it
+ * completely.
+ */
+
+ r->pos = pos; r->start = r->end = 0;
+#ifdef DEBUG
+ show_recovery_buffer_map(r, "cleared; shift down by %"PRIuSEC"", diff);
+#endif
+ } else {
+ /* Some of the material in the buffer will still be there. We might
+ * lose some stuff off the beginning: start by throwing that away, and
+ * then whatever's left can be moved easily.
+ */
+
+ if (r->start < diff) r->start = diff;
+ rearrange_sectors(r, r->start - diff, r->start, r->end - r->start);
+ r->pos += diff; r->start -= diff; r->end -= diff;
+#ifdef DEBUG
+ show_recovery_buffer_map(r, "shifted down by %"PRIuSEC"", diff);
+#endif
+ }
+ }
+
+ /* We now have space in the buffer in which to put the new material.
+ * However, the buffer already contains some stuff. We may need to read
+ * some data from the input file into an area before the existing
+ * material, or into an area following the existing stuff, or both, or
+ * (possibly) neither.
+ */
+
+ if (pos < r->pos + r->start) {
+ /* The requested position is before the current good material, so we'll
+ * need to read some stuff there.
+ */
+
+ /* Determine the place in the buffer where this data will be placed, and
+ * how long it will need to be. Try to extend it all the way to the
+ * existing region even if this is more than the caller wants, because it
+ * will mean that we can join it onto the existing region rather than
+ * having to decide which of two disconnected parts to throw away.
+ */
+ pp = pos - r->pos; nn = r->start - pp;
+
+ /* Read the data. */
+#ifdef DEBUG
+ printf(";; read low (%"PRIuSEC"@%"PRIuSEC", %"PRIuSEC")", pos, pp, nn);
+ fflush(stdout);
+#endif
+ n = recovery_read_sectors(r, pos, pp, nn);
+#ifdef DEBUG
+ printf(" -> %zd\n", n);
+#endif
+
+ /* See whether it worked. */
+ if (n != nn) {
+ /* We didn't get everything we wanted. */
+
+ /* If we got more than the caller asked for then technically this is
+ * good; but there must be some problem lurking up ahead, and the
+ * caller will want to skip past that. So we don't update the tracking
+ * information to reflect our new data; even though this /looks/ like a
+ * success, it isn't really.
+ */
+ if (n >= 0 && n > want) n = want;
+
+ /* We're done. */
+ goto end;
+ }
+
+ /* Extend the region to include the new piece. */
+ r->start = pp;
+#ifdef DEBUG
+ show_recovery_buffer_map(r, "joined new region");
+#endif
+ }
+
+ if (pos + want > r->pos + r->end) {
+ /* The requested region extends beyond the current region, so we'll need
+ * to read some stuff there.
+ */
+
+ /* Determine the place in the buffer where this data will be placed, and
+ * how long it will need to be. Note that pos <= r->pos + r->end, so
+ * there won't be a gap between the old good region and the material
+ * we're trying to read.
+ */
+ pp = r->end; nn = (pos + want) - (r->pos + r->end);
+
+ /* Read the data. */
+#ifdef DEBUG
+ printf(";; read high (%"PRIuSEC"@%"PRIuSEC", %"PRIuSEC")",
+ r->pos + pp, pp, nn);
+ fflush(stdout);
+#endif
+ n = recovery_read_sectors(r, r->pos + pp, pp, nn);
+#ifdef DEBUG
+ printf(" -> %zd\n", n);
+#endif
+
+ /* See whether it worked. */
+ if (n > 0) {
+ /* We read something, so add it onto the existing region. */
+
+ r->end += n;
+#ifdef DEBUG
+ show_recovery_buffer_map(r, "joined new region");
+#endif
+ }
+ }
+
+ /* Work out the return value to pass back to the caller. The newly read
+ * material has been merged with the existing region (the case where we
+ * didn't manage to join the two together has been handled already), so we
+ * can easily work out how much stuff is available by looking at the
+ * tracking information. It only remains to bound the region size by the
+ * requested length.
+ */
+ n = r->pos + r->end - pos;
+ if (!n && want) n = -1;
+ else if (n > want) n = want;
+
+end:
+ /* Done. */
+#ifdef DEBUG
+ show_recovery_buffer_map(r, "done; return %zd", n);
+#endif
+ return (n);
+}
+
+static ssize_t recovery_read_multiple(struct recoverybuf *r,
+ secaddr pos, secaddr want)
+ /* Try to read WANT sectors, starting at sector address POS, from the
+ * current file, returning a count of the number of sectors read, or
+ * 0 if at end of file, or -1 in the case of a system error, as for
+ * `read_sectors'. Some data might end up in R's buffer, but if WANT
+ * is larger than R->sz then a lot will be just thrown away.
+ *
+ * This is only used by `recovery_read' below.
+ */
+{
+ ssize_t n;
+ secaddr skip, want0 = want;
+
+ /* If the request is larger than the buffer, then we start at the /end/ and
+ * work backwards. If we encounter a bad sector while we're doing this,
+ * then we report a short read as far as the bad sector: the idea is to
+ * find the /latest/ bad sector we can. The caller will want to skip past
+ * the bad sector, so the fact that we implicitly lied about the earlier
+ * data as being `good' won't matter.
+ */
+
+ while (want > r->sz) {
+ /* There's (strictly!) more than a buffer's worth. Fill the buffer with
+ * stuff and reduce the requested size.
+ */
+
+ skip = want - r->sz;
+ n = recovery_read_buffer(r, pos + skip, r->sz);
+
+ /* If it failed, then we always return a positive result, because we're
+ * pretending we managed to read all of the (nonempty) preceding
+ * material.
+ */
+ if (n < r->sz) return (skip + (n >= 0 ? n : 0));
+
+ /* Cross off a buffer's worth and go around again. */
+ want -= r->sz;
+ }
+
+ /* Read the last piece. If it fails or comes up short, then we don't need
+ * to mess with the return code this time.
+ */
+ n = recovery_read_buffer(r, pos, want);
+ if (n < 0 || n < want) return (n);
+
+ /* It all worked. Return the full original amount requested. */
+ return (want0);
+}
+
+static ssize_t recovery_read(struct recoverybuf *r,
+ secaddr pos, secaddr want)
+ /* Try to read WANT sectors, starting at sector address POS, from the
+ * current file, returning a count of the number of
+ * sectors read, or 0 if at end of file, or -1 in the case of a
+ * system error, as for `read_sectors'. Some data might end up in
+ * R's buffer, but if WANT is larger than R->sz then a lot will be
+ * just thrown away.
+ */
+{
+ secaddr lo = pos, hi = pos + want, span; /* calculate the request bounds */
+ ssize_t n;
+
+ /* This is the main piece of the long-range tracking machinery.
+ * Fortunately, it's much simpler than the short-range stuff that we've
+ * just dealt with.
+ */
+
+ if (hi < r->good_lo || lo > r->good_hi) {
+ /* The requested region doesn't abut or overlap with the existing good
+ * region, so it's no good to us. Just read the requested region; if it
+ * worked at all, then replace the current known-good region with the
+ * region that was successfully read.
+ */
+
+ n = recovery_read_multiple(r, lo, hi - lo);
+ if (n > 0) { r->good_lo = lo; r->good_hi = lo + n; }
+ return (n);
+ }
+
+ if (hi > r->good_hi) {
+ /* The requested region ends later than the current known-good region.
+ * Read the missing piece. We're doing this first so that we find later
+ * bad sectors.
+ */
+
+ span = hi - r->good_hi;
+ n = recovery_read_multiple(r, r->good_hi, span);
+
+ /* If we read anything at all, then extend the known-good region. */
+ if (n > 0) r->good_hi += n;
+
+ /* If we didn't read everything we wanted, then report this as a short
+ * read (so including some nonempty portion of the known-good region).
+ */
+ if (n < 0 || n < span) return (r->good_hi - lo);
+ }
+
+ if (lo < r->good_lo) {
+ /* The requested region begins earlier than the known-good region. */
+
+ span = r->good_lo - lo;
+ n = recovery_read_multiple(r, lo, span);
+
+ /* If we read everything we wanted, then extend the known-good region.
+ * Otherwise, we're better off keeping the stuff after the bad block.
+ */
+ if (n == span) r->good_lo = lo;
+ else return (n);
+ }
+
+ /* Everything read OK, and we've extended the known-good region to cover
+ * the requested region. So return an appropriate code by consulting the
+ * new known-good region.
+ */
+ n = r->good_hi - pos; if (n > want) n = want;
+ if (!n) { errno = EIO; n = -1; }
+ return (n);
+}
+
+/*----- Skipping past regions of bad sectors ------------------------------*/
+
+static double clear_factor = 0.5; /* proportion of clear sectors needed */
+static secaddr clear_min = 1, clear_max = SECLIMIT; /* absolute bounds */
+static double step_factor = 2.0; /* factor for how far to look ahead */
+static secaddr step_min = 1, step_max = 0; /* and absolute bounds */
+
+static void recovered(secaddr bad_lo, secaddr bad_hi)
+ /* Do all of the things that are necessary when a region of bad
+ * sectors has been found between BAD_LO (inclusive) and BAD_HI
+ * (exclusive).
+ */
+{
+ char fn[MAXFNSZ];
+
+ /* Remove the progress display temporarily. */
+ progress_clear(&progress);
+
+ /* Print a message into the permanent output log. */
+ if (!file || id_kind(file->id) == RAW)
+ moan("skipping %"PRIuSEC" bad sectors (%"PRIuSEC" .. %"PRIuSEC")",
+ bad_hi - bad_lo, bad_lo, bad_hi);
+ else {
+ store_filename(fn, file->id);
+ moan("skipping %"PRIuSEC" bad sectors (%"PRIuSEC" .. %"PRIuSEC"; "
+ "`%s' %"PRIuSEC" .. %"PRIuSEC" of %"PRIuSEC")",
+ bad_hi - bad_lo, bad_lo, bad_hi,
+ fn, bad_lo - file->start, bad_hi - file->start,
+ file->end - file->start);
+ }
+
+ if (mapfile) {
+ /* The user requested a map of the skipped regions, so write an entry. */
+
+ /* Open the file, if it's not open already. */
+ open_file_on_demand(mapfile, &mapfp, "bad-sector region map");
+
+ /* Write the sector range. */
+ fprintf(mapfp, "%"PRIuSEC" %"PRIuSEC" # %"PRIuSEC" sectors",
+ bad_lo, bad_hi, bad_hi - bad_lo);
+
+ /* If we're currently reading from a file then note down the position in
+ * the file in the comment. (Intentional bad sectors are frequently at
+ * the start and end of titles, so this helps a reader to decide how
+ * concerned to be.)
+ */
+ if (file && id_kind(file->id) != RAW)
+ fprintf(mapfp, "; `%s' %"PRIuSEC" .. %"PRIuSEC" of %"PRIuSEC"",
+ fn, bad_lo - file->start, bad_hi - file->start,
+ file->end - file->start);
+
+ /* Done. Flush the output to the file so that we don't lose it if we
+ * crash!
+ */
+ fputc('\n', mapfp);
+ check_write(mapfp, "bad-sector region map");
+ }
+
+ /* Adjust the position in our output file to skip past the bad region.
+ * (This avoids overwriting anything that was there already, which is
+ * almost certainly less wrong than anything we could come up with here.)
+ */
+ if (lseek(outfd, (off_t)(bad_hi - bad_lo)*SECTORSZ, SEEK_CUR) < 0)
+ bail_syserr(errno, "failed to seek past bad sectors");
+
+ /* Remove our notice now that we're no longer messing about with bad
+ * sectors, and reinstate the progress display.
+ */
+ progress_removeitem(&progress, &badblock_progress);
+ progress_update(&progress);
+}
+
+static secaddr run_length_wanted(secaddr pos, secaddr badlen, secaddr end)
+ /* Return the number of good sectors that we want to see before
+ * we're happy, given that we're about to try to read sector POS,
+ * which is BADLEN sectors beyond where we found the first bad
+ * sector, and the current region ends at sector END (i.e., this is
+ * where the next event occurs).
+ */
+{
+ secaddr want;
+
+ /* Apply the factor to BADLEN to get an initial length. */
+ want = ceil(clear_factor*badlen);
+
+ /* Apply the user-configurable lower bound. */
+ if (want < clear_min) want = clear_min;
+
+ /* Cap this with the end of the region. */
+ if (want > end - pos) want = end - pos;
+
+ /* And apply the user-configurable upper bound. */
+ if (clear_max && want > clear_max) want = clear_max;