]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/block.c
Implement repositioning code + misc
[bacula/bacula] / bacula / src / stored / block.c
1 /*
2  *
3  *   block.c -- tape block handling functions
4  *
5  *              Kern Sibbald, March MMI
6  *                 added BB02 format October MMII
7  *
8  *   Version $Id$
9  *
10  */
11 /*
12    Copyright (C) 2000-2003 Kern Sibbald and John Walker
13
14    This program is free software; you can redistribute it and/or
15    modify it under the terms of the GNU General Public License as
16    published by the Free Software Foundation; either version 2 of
17    the License, or (at your option) any later version.
18
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22    General Public License for more details.
23
24    You should have received a copy of the GNU General Public
25    License along with this program; if not, write to the Free
26    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
27    MA 02111-1307, USA.
28
29  */
30
31
32 #include "bacula.h"
33 #include "stored.h"
34
35 extern int debug_level;
36
37 /*
38  * Dump the block header, then walk through
39  * the block printing out the record headers.
40  */
41 void dump_block(DEV_BLOCK *b, char *msg)
42 {
43    ser_declare;
44    char *p;
45    char Id[BLKHDR_ID_LENGTH+1];
46    uint32_t CheckSum, BlockCheckSum;
47    uint32_t block_len;
48    uint32_t BlockNumber;
49    uint32_t VolSessionId, VolSessionTime, data_len;
50    int32_t  FileIndex;
51    int32_t  Stream;
52    int bhl, rhl;
53
54    unser_begin(b->buf, BLKHDR1_LENGTH);
55    unser_uint32(CheckSum);
56    unser_uint32(block_len);
57    unser_uint32(BlockNumber);
58    unser_bytes(Id, BLKHDR_ID_LENGTH);
59    ASSERT(unser_length(b->buf) == BLKHDR1_LENGTH);
60    Id[BLKHDR_ID_LENGTH] = 0;
61    if (Id[3] == '2') {
62       unser_uint32(VolSessionId);
63       unser_uint32(VolSessionTime);
64       bhl = BLKHDR2_LENGTH;
65       rhl = RECHDR2_LENGTH;
66    } else {
67       VolSessionId = VolSessionTime = 0;
68       bhl = BLKHDR1_LENGTH;
69       rhl = RECHDR1_LENGTH;
70    }
71
72    if (block_len > 100000) {
73       Dmsg3(20, "Dump block %s 0x%x blocksize too big %u\n", msg, b, block_len);
74       return;
75    }
76
77    BlockCheckSum = bcrc32((uint8_t *)b->buf+BLKHDR_CS_LENGTH,
78                          block_len-BLKHDR_CS_LENGTH);
79    Pmsg6(000, "Dump block %s %x: size=%d BlkNum=%d\n\
80                Hdrcksum=%x cksum=%x\n",
81       msg, b, block_len, BlockNumber, CheckSum, BlockCheckSum);
82    p = b->buf + bhl;
83    while (p < (b->buf + block_len+WRITE_RECHDR_LENGTH)) { 
84       unser_begin(p, WRITE_RECHDR_LENGTH);
85       if (rhl == RECHDR1_LENGTH) {
86          unser_uint32(VolSessionId);
87          unser_uint32(VolSessionTime);
88       }
89       unser_int32(FileIndex);
90       unser_int32(Stream);
91       unser_uint32(data_len);
92       Pmsg6(000, "   Rec: VId=%u VT=%u FI=%s Strm=%s len=%d p=%x\n",
93            VolSessionId, VolSessionTime, FI_to_ascii(FileIndex), 
94            stream_to_ascii(Stream, FileIndex), data_len, p);
95       p += data_len + rhl;
96   }
97 }
98     
99 /*
100  * Create a new block structure.                           
101  * We pass device so that the block can inherit the
102  * min and max block sizes.
103  */
104 DEV_BLOCK *new_block(DEVICE *dev)
105 {
106    DEV_BLOCK *block = (DEV_BLOCK *)get_memory(sizeof(DEV_BLOCK));
107
108    memset(block, 0, sizeof(DEV_BLOCK));
109
110    /* If the user has specified a max_block_size, use it as the default */
111    if (dev->max_block_size == 0) {
112       block->buf_len = DEFAULT_BLOCK_SIZE;
113    } else {
114       block->buf_len = dev->max_block_size;
115    }
116    block->dev = dev;
117    block->block_len = block->buf_len;  /* default block size */
118    block->buf = get_memory(block->buf_len); 
119    if (block->buf == NULL) {
120       Mmsg0(&dev->errmsg, _("Unable to malloc block buffer.\n"));
121       Emsg0(M_FATAL, 0, dev->errmsg);
122       return NULL;
123    }
124    empty_block(block);
125    block->BlockVer = BLOCK_VER;       /* default write version */
126    Dmsg1(90, "Returning new block=%x\n", block);
127    return block;
128 }
129
130 /*
131  * Free block 
132  */
133 void free_block(DEV_BLOCK *block)
134 {
135    Dmsg1(199, "free_block buffer %x\n", block->buf);
136    free_memory(block->buf);
137    Dmsg1(199, "free_block block %x\n", block);
138    free_memory((POOLMEM *)block);
139 }
140
141 /* Empty the block -- for writing */
142 void empty_block(DEV_BLOCK *block)
143 {
144    block->binbuf = WRITE_BLKHDR_LENGTH;
145    block->bufp = block->buf + block->binbuf;
146    block->read_len = 0;
147    block->write_failed = false;
148    block->block_read = false;
149    block->FirstIndex = block->LastIndex = 0;
150 }
151
152 /*
153  * Create block header just before write. The space
154  * in the buffer should have already been reserved by
155  * init_block.
156  */
157 static void ser_block_header(DEV_BLOCK *block)
158 {
159    ser_declare;
160    uint32_t CheckSum = 0;
161    uint32_t block_len = block->binbuf;
162    
163    Dmsg1(190, "ser_block_header: block_len=%d\n", block_len);
164    ser_begin(block->buf, BLKHDR2_LENGTH);
165    ser_uint32(CheckSum);
166    ser_uint32(block_len);
167    ser_uint32(block->BlockNumber);
168    ser_bytes(WRITE_BLKHDR_ID, BLKHDR_ID_LENGTH);
169    if (BLOCK_VER >= 2) {
170       ser_uint32(block->VolSessionId);
171       ser_uint32(block->VolSessionTime);
172    }
173
174    /* Checksum whole block except for the checksum */
175    CheckSum = bcrc32((uint8_t *)block->buf+BLKHDR_CS_LENGTH, 
176                  block_len-BLKHDR_CS_LENGTH);
177    Dmsg1(190, "ser_bloc_header: checksum=%x\n", CheckSum);
178    ser_begin(block->buf, BLKHDR2_LENGTH);
179    ser_uint32(CheckSum);              /* now add checksum to block header */
180 }
181
182 /*
183  * Unserialized the block header for reading block.
184  *  This includes setting all the buffer pointers correctly.
185  *
186  *  Returns: 0 on failure (not a block)
187  *           1 on success
188  */
189 static int unser_block_header(DEVICE *dev, DEV_BLOCK *block)
190 {
191    ser_declare;
192    char Id[BLKHDR_ID_LENGTH+1];
193    uint32_t CheckSum, BlockCheckSum;
194    uint32_t block_len;
195    uint32_t block_end;
196    uint32_t BlockNumber;
197    int bhl;
198
199    unser_begin(block->buf, BLKHDR_LENGTH);
200    unser_uint32(CheckSum);
201    unser_uint32(block_len);
202    unser_uint32(BlockNumber);
203    unser_bytes(Id, BLKHDR_ID_LENGTH);
204    ASSERT(unser_length(block->buf) == BLKHDR1_LENGTH);
205
206    Id[BLKHDR_ID_LENGTH] = 0;
207    if (Id[3] == '1') {
208       bhl = BLKHDR1_LENGTH;
209       block->BlockVer = 1;
210       block->bufp = block->buf + bhl;
211       if (strncmp(Id, BLKHDR1_ID, BLKHDR_ID_LENGTH) != 0) {
212          Mmsg2(&dev->errmsg, _("Buffer ID error. Wanted: %s, got %s. Buffer discarded.\n"),
213             BLKHDR1_ID, Id);
214          Emsg0(M_ERROR, 0, dev->errmsg);
215          return 0;
216       }
217    } else if (Id[3] == '2') {
218       unser_uint32(block->VolSessionId);
219       unser_uint32(block->VolSessionTime);
220       bhl = BLKHDR2_LENGTH;
221       block->BlockVer = 2;
222       block->bufp = block->buf + bhl;
223       if (strncmp(Id, BLKHDR2_ID, BLKHDR_ID_LENGTH) != 0) {
224          Mmsg2(&dev->errmsg, _("Buffer ID error. Wanted: %s, got %s. Buffer discarded.\n"),
225             BLKHDR2_ID, Id);
226          Emsg0(M_ERROR, 0, dev->errmsg);
227          return 0;
228       }
229    } else {
230       Mmsg1(&dev->errmsg, _("Expected block-id BB01 or BB02, got %s. Buffer discarded.\n"), Id);
231       Emsg0(M_ERROR, 0, dev->errmsg);
232       return 0;
233    }
234
235    /* Sanity check */
236    if (block_len > MAX_BLOCK_LENGTH) {
237       Mmsg1(&dev->errmsg,  _("Block length %u is insane (too large), probably due to a bad archive.\n"),
238          block_len);
239       Emsg0(M_ERROR, 0, dev->errmsg);
240       return 0;
241    }
242
243    Dmsg1(190, "unser_block_header block_len=%d\n", block_len);
244    /* Find end of block or end of buffer whichever is smaller */
245    if (block_len > block->read_len) {
246       block_end = block->read_len;
247    } else {
248       block_end = block_len;
249    }
250    block->binbuf = block_end - bhl;
251    block->block_len = block_len;
252    block->BlockNumber = BlockNumber;
253    Dmsg3(190, "Read binbuf = %d %d block_len=%d\n", block->binbuf,
254       bhl, block_len);
255    if (block_len <= block->read_len) {
256       BlockCheckSum = bcrc32((uint8_t *)block->buf+BLKHDR_CS_LENGTH,
257                          block_len-BLKHDR_CS_LENGTH);
258       if (BlockCheckSum != CheckSum) {
259          Dmsg2(00, "Block checksum mismatch: calc=%x blk=%x\n", BlockCheckSum,
260             CheckSum);
261          Mmsg3(&dev->errmsg, _("Block checksum mismatch in block %u: calc=%x blk=%x\n"), 
262             (unsigned)BlockNumber, BlockCheckSum, CheckSum);
263          return 0;
264       }
265    }
266    return 1;
267 }
268
269 /*  
270  * Write a block to the device, with locking and unlocking
271  *
272  * Returns: 1 on success
273  *        : 0 on failure
274  *
275  */
276 int write_block_to_device(JCR *jcr, DEVICE *dev, DEV_BLOCK *block)
277 {
278    int stat = 1;
279    lock_device(dev);
280
281    /*
282     * If a new volume has been mounted since our last write
283     *   Create a JobMedia record for the previous volume written,
284     *   and set new parameters to write this volume   
285     * The saem applies for if we are in a new file.
286     */
287    if (jcr->NewVol || jcr->NewFile) {
288       /* Create a jobmedia record for this job */
289       if (!dir_create_jobmedia_record(jcr)) {
290          Jmsg(jcr, M_ERROR, 0, _("Could not create JobMedia record for Volume=\"%s\" Job=%s\n"),
291             jcr->VolCatInfo.VolCatName, jcr->Job);
292          set_new_volume_parameters(jcr, dev);
293          unlock_device(dev);
294          return 0;
295       }
296       if (jcr->NewVol) {
297          /* Note, setting a new volume also handles any pending new file */
298          set_new_volume_parameters(jcr, dev);
299          jcr->NewFile = false;        /* this handled for new file too */
300       } else {
301          set_new_file_parameters(jcr, dev);
302       }
303    }
304
305    if (!write_block_to_dev(jcr, dev, block)) {
306        stat = fixup_device_block_write_error(jcr, dev, block);
307    }
308
309    unlock_device(dev);
310    return stat;
311 }
312
313 /*
314  * Write a block to the device 
315  *
316  *  Returns: 1 on success or EOT
317  *           0 on hard error
318  */
319 int write_block_to_dev(JCR *jcr, DEVICE *dev, DEV_BLOCK *block)
320 {
321    ssize_t stat = 0;
322    uint32_t wlen;                     /* length to write */
323    int hit_max1, hit_max2;
324    bool ok;
325
326 #ifdef NO_TAPE_WRITE_TEST
327    empty_block(block);
328    return 1;
329 #endif
330    ASSERT(block->binbuf == ((uint32_t) (block->bufp - block->buf)));
331
332    /* dump_block(block, "before write"); */
333    if (dev->state & ST_WEOT) {
334       Dmsg0(100, "return write_block_to_dev with ST_WEOT\n");
335       Jmsg(jcr, M_FATAL, 0,  _("Cannot write block. Device at EOM.\n"));
336       return 0;
337    }
338    wlen = block->binbuf;
339    if (wlen <= WRITE_BLKHDR_LENGTH) {  /* Does block have data in it? */
340       Dmsg0(100, "return write_block_to_dev no data to write\n");
341       return 1;
342    }
343    /* 
344     * Clear to the end of the buffer if it is not full,
345     *  and on tape devices, apply min and fixed blocking.
346     */
347    if (wlen != block->buf_len) {
348       uint32_t blen;                  /* current buffer length */
349
350       Dmsg2(200, "binbuf=%d buf_len=%d\n", block->binbuf, block->buf_len);
351       blen = wlen;
352
353       /* Adjust write size to min/max for tapes only */
354       if (dev->state & ST_TAPE) {
355          if (wlen < dev->min_block_size) {
356             wlen =  ((dev->min_block_size + TAPE_BSIZE - 1) / TAPE_BSIZE) * TAPE_BSIZE;
357          }
358          /* check for fixed block size */
359          if (dev->min_block_size == dev->max_block_size) {
360             wlen = block->buf_len;    /* fixed block size already rounded */
361          }
362       }
363       if (wlen-blen > 0) {
364          memset(block->bufp, 0, wlen-blen); /* clear garbage */
365       }
366    }  
367
368    ser_block_header(block);
369
370    /* Limit maximum Volume size to value specified by user */
371    hit_max1 = (dev->max_volume_size > 0) &&
372        ((dev->VolCatInfo.VolCatBytes + block->binbuf)) >= dev->max_volume_size;
373    hit_max2 = (dev->VolCatInfo.VolCatMaxBytes > 0) &&
374        ((dev->VolCatInfo.VolCatBytes + block->binbuf)) >= dev->VolCatInfo.VolCatMaxBytes;
375    if (hit_max1 || hit_max2) {   
376       char ed1[50];
377       uint64_t max_cap;
378       Dmsg0(10, "==== Output bytes Triggered medium max capacity.\n");
379       if (hit_max1) {
380          max_cap = dev->max_volume_size;
381       } else {
382          max_cap = dev->VolCatInfo.VolCatMaxBytes;
383       }
384       Jmsg(jcr, M_INFO, 0, _("User defined maximum volume capacity %s exceeded on device %s.\n"),
385             edit_uint64(max_cap, ed1),  dev->dev_name);
386       block->write_failed = true;
387       weof_dev(dev, 2);               /* end the tape */
388       dev->state |= (ST_EOF | ST_EOT | ST_WEOT);
389       return 0;   
390    }
391
392    /* Limit maximum File size on volume to user specified value */
393    if (dev->state & ST_TAPE) {
394       if ((dev->max_file_size > 0) && 
395           (dev->file_addr+block->binbuf) >= dev->max_file_size) {
396
397          /* Write EOF */
398          if (weof_dev(dev, 1) != 0) {            /* write eof */
399             Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
400             block->write_failed = true;
401             dev->state |= (ST_EOF | ST_EOT | ST_WEOT);
402             return 0;   
403          }
404
405          /* Do bookkeeping to handle EOF just written */
406          if (!dir_create_jobmedia_record(jcr)) {
407              Jmsg(jcr, M_ERROR, 0, _("Could not create JobMedia record for Volume=\"%s\" Job=%s\n"),
408                   jcr->VolCatInfo.VolCatName, jcr->Job);
409              return 0;
410          }
411          /* 
412           * Walk through all attached jcrs indicating the file has changed   
413           */
414          Dmsg1(100, "Walk attached jcrs. Volume=%s\n", dev->VolCatInfo.VolCatName);
415          for (JCR *mjcr=NULL; (mjcr=next_attached_jcr(dev, mjcr)); ) {
416             if (mjcr->JobId == 0) {
417                continue;                 /* ignore console */
418             }
419             mjcr->NewFile = true;
420          }
421          set_new_file_parameters(jcr, dev);
422       }
423    }
424
425    dev->VolCatInfo.VolCatWrites++;
426    Dmsg1(300, "Write block of %u bytes\n", wlen);      
427    stat = write(dev->fd, block->buf, (size_t)wlen);
428    if (stat != (ssize_t)wlen) {
429       /* We should check for errno == ENOSPC, BUT many 
430        * devices simply report EIO when the volume is full.
431        * With a little more thought we may be able to check
432        * capacity and distinguish real errors and EOT
433        * conditions.  In any case, we probably want to
434        * simulate an End of Medium.
435        */
436       if (stat == -1) {
437          /* I have added the ifdefing here because it appears on
438           * FreeBSD where MTIOCERRSTAT is defined, this not only
439           * clears the error but clears the residual unwritten
440           * buffers -> data loss. As a consequence, on those
441           * systems (FreeBSD like), do the clrerror() only after
442           * the weof_dev() call.
443           */
444          clrerror_dev(dev, -1);
445          if (dev->dev_errno == 0) {
446             dev->dev_errno = ENOSPC;        /* out of space */
447          }
448          Jmsg(jcr, M_ERROR, 0, _("Write error on device %s. ERR=%s.\n"), 
449             dev->dev_name, strerror(dev->dev_errno));
450       } else {
451         dev->dev_errno = ENOSPC;            /* out of space */
452          Jmsg3(jcr, M_INFO, 0, _("End of medium on device %s. Write of %u bytes got %d.\n"), 
453             dev->dev_name, wlen, stat);
454       }  
455
456       Dmsg6(100, "=== Write error. size=%u rtn=%d dev_blk=%d blk_blk=%d errno=%d: ERR=%s\n", 
457          wlen, stat, dev->block_num, block->BlockNumber, dev->dev_errno, strerror(dev->dev_errno));
458
459       block->write_failed = true;
460       if (weof_dev(dev, 2) != 0) {         /* end the tape */
461          Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
462       }
463       dev->state |= (ST_EOF | ST_EOT | ST_WEOT);
464         
465       ok = true;
466 #define CHECK_LAST_BLOCK
467 #ifdef  CHECK_LAST_BLOCK
468       /* 
469        * If the device is a tape and it supports backspace record,
470        *   we backspace over two eof marks and over the last record,
471        *   then re-read it and verify that the block number is
472        *   correct.
473        */
474       if (dev->state & ST_TAPE && dev_cap(dev, CAP_BSR)) {
475
476          /* Now back up over what we wrote and read the last block */
477          if (bsf_dev(dev, 1) != 0 || bsf_dev(dev, 1) != 0) {
478             ok = false;
479             Jmsg(jcr, M_ERROR, 0, _("Backspace file at EOT failed. ERR=%s\n"), strerror(dev->dev_errno));
480          }
481          /* Backspace over record */
482          if (ok && bsr_dev(dev, 1) != 0) {
483             ok = false;
484             Jmsg(jcr, M_ERROR, 0, _("Backspace record at EOT failed. ERR=%s\n"), strerror(dev->dev_errno));
485             /*
486              *  On FreeBSD systems, if the user got here, it is likely that his/her
487              *    tape drive is "frozen".  The correct thing to do is a 
488              *    rewind(), but if we do that, higher levels in cleaning up, will
489              *    most likely write the EOS record over the beginning of the
490              *    tape.  The rewind *is* done later in mount.c when another
491              *    tape is requested. Note, the clrerror_dev() call in bsr_dev()
492              *    calls ioctl(MTCERRSTAT), which *should* fix the problem.
493              */
494          }
495          if (ok) {
496             DEV_BLOCK *lblock = new_block(dev);
497             /* Note, this can destroy dev->errmsg */
498             if (!read_block_from_dev(jcr, dev, lblock, NO_BLOCK_NUMBER_CHECK)) {
499                Jmsg(jcr, M_ERROR, 0, _("Re-read last block at EOT failed. ERR=%s"), dev->errmsg);
500             } else {
501                if (lblock->BlockNumber+1 == block->BlockNumber) {
502                   Jmsg(jcr, M_INFO, 0, _("Re-read of last block succeeded.\n"));
503                } else {
504                   Jmsg(jcr, M_ERROR, 0, _(
505 "Re-read of last block failed. Last block=%u Current block=%u.\n"),
506                        lblock->BlockNumber, block->BlockNumber);
507                }
508             }
509             free_block(lblock);
510          }
511       }
512 #endif
513       return 0;
514    }
515
516    /* We successfully wrote the block, now do housekeeping */
517
518    dev->VolCatInfo.VolCatBytes += block->binbuf;
519    dev->VolCatInfo.VolCatBlocks++;   
520    dev->file_addr += wlen;
521    dev->EndBlock = dev->block_num;
522    dev->EndFile  = dev->file;
523    dev->block_num++;
524    block->BlockNumber++;
525
526    /* Update jcr values */
527    if (dev->state & ST_TAPE) {
528       jcr->EndBlock = dev->EndBlock;
529       jcr->EndFile  = dev->EndFile;
530    } else {
531       jcr->EndBlock = (uint32_t)dev->file_addr;
532       jcr->EndFile = (uint32_t)(dev->file_addr >> 32);
533    }
534    if (jcr->VolFirstIndex == 0 && block->FirstIndex > 0) {
535       jcr->VolFirstIndex = block->FirstIndex;
536    }
537    if (block->LastIndex > 0) {
538       jcr->VolLastIndex = block->LastIndex;
539    }
540    jcr->WroteVol = true;
541
542    Dmsg2(190, "write_block: wrote block %d bytes=%d\n", dev->block_num,
543       wlen);
544    empty_block(block);
545    return 1;
546 }
547
548 /*  
549  * Read block with locking
550  *
551  */
552 int read_block_from_device(JCR *jcr, DEVICE *dev, DEV_BLOCK *block, bool check_block_numbers)
553 {
554    int stat;
555    Dmsg0(90, "Enter read_block_from_device\n");
556    lock_device(dev);
557    stat = read_block_from_dev(jcr, dev, block, check_block_numbers);
558    unlock_device(dev);
559    Dmsg0(90, "Leave read_block_from_device\n");
560    return stat;
561 }
562
563 /*
564  * Read the next block into the block structure and unserialize
565  *  the block header.  For a file, the block may be partially
566  *  or completely in the current buffer.
567  */
568 int read_block_from_dev(JCR *jcr, DEVICE *dev, DEV_BLOCK *block, bool check_block_numbers)
569 {
570    ssize_t stat;
571    int looping;
572    uint32_t BlockNumber;
573    int retry = 0;
574
575    if (dev_state(dev, ST_EOT)) {
576       return 0;
577    }
578    looping = 0;
579    Dmsg1(100, "Full read() in read_block_from_device() len=%d\n",
580          block->buf_len);
581 reread:
582    if (looping > 1) {
583       Mmsg1(&dev->errmsg, _("Block buffer size looping problem on device %s\n"),
584          dev->dev_name);
585       Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
586       block->read_len = 0;
587       return 0;
588    }
589    do {
590       stat = read(dev->fd, block->buf, (size_t)block->buf_len);
591       if (retry == 1) {
592          dev->VolCatInfo.VolCatErrors++;   
593       }
594    } while (stat == -1 && (errno == EINTR || errno == EIO) && retry++ < 11);
595    if (stat < 0) {
596       Dmsg1(90, "Read device got: ERR=%s\n", strerror(errno));
597       clrerror_dev(dev, -1);
598       block->read_len = 0;
599       Mmsg2(&dev->errmsg, _("Read error on device %s. ERR=%s.\n"), 
600          dev->dev_name, strerror(dev->dev_errno));
601       Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
602       if (dev->state & ST_EOF) {  /* EOF just seen? */
603          dev->state |= ST_EOT;    /* yes, error => EOT */
604       }
605       return 0;
606    }
607    Dmsg1(90, "Read device got %d bytes\n", stat);
608    if (stat == 0) {             /* Got EOF ! */
609       dev->block_num = block->read_len = 0;
610       Mmsg1(&dev->errmsg, _("Read zero bytes on device %s.\n"), dev->dev_name);
611       if (dev->state & ST_EOF) { /* EOF already read? */
612          dev->state |= ST_EOT;  /* yes, 2 EOFs => EOT */
613          block->read_len = 0;
614          return 0;
615       }
616       dev->file++;              /* increment file */
617       dev->state |= ST_EOF;     /* set EOF read */
618       block->read_len = 0;
619       return 0;                 /* return eof */
620    }
621    /* Continue here for successful read */
622    block->read_len = stat;      /* save length read */
623    if (block->read_len < BLKHDR2_LENGTH) {
624       Mmsg2(&dev->errmsg, _("Very short block of %d bytes on device %s discarded.\n"), 
625          block->read_len, dev->dev_name);
626       Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
627       dev->state |= ST_SHORT;   /* set short block */
628       block->read_len = block->binbuf = 0;
629       return 0;                 /* return error */
630    }  
631
632    BlockNumber = block->BlockNumber + 1;
633    if (!unser_block_header(dev, block)) {
634       block->read_len = 0;
635       return 0;
636    }
637
638    /*
639     * If the block is bigger than the buffer, we reposition for
640     *  re-reading the block, allocate a buffer of the correct size,
641     *  and go re-read.
642     */
643    if (block->block_len > block->buf_len) {
644       Mmsg2(&dev->errmsg,  _("Block length %u is greater than buffer %u. Attempting recovery.\n"),
645          block->block_len, block->buf_len);
646       Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
647       Pmsg1(000, "%s", dev->errmsg);
648       /* Attempt to reposition to re-read the block */
649       if (dev->state & ST_TAPE) {
650          Dmsg0(100, "Backspace record for reread.\n");
651          if (bsr_dev(dev, 1) != 0) {
652             Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
653             block->read_len = 0;
654             return 0;
655          }
656       } else {
657          Dmsg0(100, "Seek to beginning of block for reread.\n");
658          off_t pos = lseek(dev->fd, (off_t)0, SEEK_CUR); /* get curr pos */
659          pos -= block->read_len;
660          lseek(dev->fd, pos, SEEK_SET);   
661       }
662       Mmsg1(&dev->errmsg, _("Setting block buffer size to %u bytes.\n"), block->block_len);
663       Jmsg(jcr, M_INFO, 0, "%s", dev->errmsg);
664       Pmsg1(000, "%s", dev->errmsg);
665       /* Set new block length */
666       dev->max_block_size = block->block_len;
667       block->buf_len = block->block_len;
668       free_memory(block->buf);
669       block->buf = get_memory(block->buf_len);
670       empty_block(block);
671       looping++;
672       goto reread;                    /* re-read block with correct block size */
673    }
674
675    if (block->block_len > block->read_len) {
676       Mmsg2(&dev->errmsg, _("Short block of %d bytes on device %s discarded.\n"), 
677          block->read_len, dev->dev_name);
678       Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
679       dev->state |= ST_SHORT;   /* set short block */
680       block->read_len = block->binbuf = 0;
681       return 0;                 /* return error */
682    }  
683
684    dev->state &= ~(ST_EOF|ST_SHORT); /* clear EOF and short block */
685    dev->VolCatInfo.VolCatReads++;   
686    dev->VolCatInfo.VolCatRBytes += block->read_len;
687
688    dev->VolCatInfo.VolCatBytes += block->block_len;
689    dev->VolCatInfo.VolCatBlocks++;   
690    dev->file_addr += block->block_len;
691    dev->EndBlock = dev->block_num;
692    dev->EndFile  = dev->file;
693    dev->block_num++;
694
695    /* Update jcr values */
696    if (dev->state & ST_TAPE) {
697       jcr->EndBlock = dev->EndBlock;
698       jcr->EndFile  = dev->EndFile;
699    } else {
700       jcr->EndBlock = (uint32_t)dev->file_addr;
701       jcr->EndFile = (uint32_t)(dev->file_addr >> 32);
702    }
703
704    /*
705     * If we read a short block on disk,
706     * seek to beginning of next block. This saves us
707     * from shuffling blocks around in the buffer. Take a
708     * look at this from an efficiency stand point later, but
709     * it should only happen once at the end of each job.
710     *
711     * I've been lseek()ing negative relative to SEEK_CUR for 30
712     *   years now. However, it seems that with the new off_t definition,
713     *   it is not possible to seek negative amounts, so we use two
714     *   lseek(). One to get the position, then the second to do an
715     *   absolute positioning -- so much for efficiency.  KES Sep 02.
716     */
717    Dmsg0(200, "At end of read block\n");
718    if (block->read_len > block->block_len && !(dev->state & ST_TAPE)) {
719       off_t pos = lseek(dev->fd, (off_t)0, SEEK_CUR); /* get curr pos */
720       pos -= (block->read_len - block->block_len);
721       lseek(dev->fd, pos, SEEK_SET);   
722       Dmsg2(100, "Did lseek blk_size=%d rdlen=%d\n", block->block_len,
723             block->read_len);
724    }
725    Dmsg2(200, "Exit read_block read_len=%d block_len=%d\n",
726       block->read_len, block->block_len);
727    block->block_read = true;
728    return 1;
729 }