]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/block.c
Add TwoEOF directive + enhance fill command
[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  * Only the first block checksum error was reported.
132  *   If there are more, report it now.
133  */
134 void print_block_read_errors(JCR *jcr, DEV_BLOCK *block)
135 {
136    if (block->read_errors > 1) {
137       Jmsg(jcr, M_ERROR, 0, _("%d block read errors ignored.\n"),
138          block->read_errors);
139    }
140 }
141
142 /*
143  * Free block 
144  */
145 void free_block(DEV_BLOCK *block)
146 {
147    Dmsg1(199, "free_block buffer %x\n", block->buf);
148    free_memory(block->buf);
149    Dmsg1(199, "free_block block %x\n", block);
150    free_memory((POOLMEM *)block);
151 }
152
153 /* Empty the block -- for writing */
154 void empty_block(DEV_BLOCK *block)
155 {
156    block->binbuf = WRITE_BLKHDR_LENGTH;
157    block->bufp = block->buf + block->binbuf;
158    block->read_len = 0;
159    block->write_failed = false;
160    block->block_read = false;
161    block->FirstIndex = block->LastIndex = 0;
162 }
163
164 /*
165  * Create block header just before write. The space
166  * in the buffer should have already been reserved by
167  * init_block.
168  */
169 static void ser_block_header(DEV_BLOCK *block)
170 {
171    ser_declare;
172    uint32_t CheckSum = 0;
173    uint32_t block_len = block->binbuf;
174    
175    Dmsg1(190, "ser_block_header: block_len=%d\n", block_len);
176    ser_begin(block->buf, BLKHDR2_LENGTH);
177    ser_uint32(CheckSum);
178    ser_uint32(block_len);
179    ser_uint32(block->BlockNumber);
180    ser_bytes(WRITE_BLKHDR_ID, BLKHDR_ID_LENGTH);
181    if (BLOCK_VER >= 2) {
182       ser_uint32(block->VolSessionId);
183       ser_uint32(block->VolSessionTime);
184    }
185
186    /* Checksum whole block except for the checksum */
187    CheckSum = bcrc32((uint8_t *)block->buf+BLKHDR_CS_LENGTH, 
188                  block_len-BLKHDR_CS_LENGTH);
189    Dmsg1(190, "ser_bloc_header: checksum=%x\n", CheckSum);
190    ser_begin(block->buf, BLKHDR2_LENGTH);
191    ser_uint32(CheckSum);              /* now add checksum to block header */
192 }
193
194 /*
195  * Unserialize the block header for reading block.
196  *  This includes setting all the buffer pointers correctly.
197  *
198  *  Returns: 0 on failure (not a block)
199  *           1 on success
200  */
201 static int unser_block_header(JCR *jcr, DEVICE *dev, DEV_BLOCK *block)
202 {
203    ser_declare;
204    char Id[BLKHDR_ID_LENGTH+1];
205    uint32_t CheckSum, BlockCheckSum;
206    uint32_t block_len;
207    uint32_t block_end;
208    uint32_t BlockNumber;
209    int bhl;
210
211    unser_begin(block->buf, BLKHDR_LENGTH);
212    unser_uint32(CheckSum);
213    unser_uint32(block_len);
214    unser_uint32(BlockNumber);
215    unser_bytes(Id, BLKHDR_ID_LENGTH);
216    ASSERT(unser_length(block->buf) == BLKHDR1_LENGTH);
217
218    Id[BLKHDR_ID_LENGTH] = 0;
219    if (Id[3] == '1') {
220       bhl = BLKHDR1_LENGTH;
221       block->BlockVer = 1;
222       block->bufp = block->buf + bhl;
223       if (strncmp(Id, BLKHDR1_ID, BLKHDR_ID_LENGTH) != 0) {
224          Mmsg2(&dev->errmsg, _("Buffer ID error. Wanted: %s, got %s. Buffer discarded.\n"),
225             BLKHDR1_ID, Id);
226          if (block->read_errors == 0 || verbose >= 2) {
227             Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
228          }
229          block->read_errors++;
230          return 0;
231       }
232    } else if (Id[3] == '2') {
233       unser_uint32(block->VolSessionId);
234       unser_uint32(block->VolSessionTime);
235       bhl = BLKHDR2_LENGTH;
236       block->BlockVer = 2;
237       block->bufp = block->buf + bhl;
238       if (strncmp(Id, BLKHDR2_ID, BLKHDR_ID_LENGTH) != 0) {
239          Mmsg2(&dev->errmsg, _("Buffer ID error. Wanted: %s, got %s. Buffer discarded.\n"),
240             BLKHDR2_ID, Id);
241          if (block->read_errors == 0 || verbose >= 2) {
242             Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
243          }
244          block->read_errors++;
245          return 0;
246       }
247    } else {
248       Mmsg1(&dev->errmsg, _("Expected block-id BB01 or BB02, got %s. Buffer discarded.\n"), Id);
249       if (block->read_errors == 0 || verbose >= 2) {
250          Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
251       }
252       block->read_errors++;
253       return 0;
254    }
255
256    /* Sanity check */
257    if (block_len > MAX_BLOCK_LENGTH) {
258       Mmsg1(&dev->errmsg,  _("Block length %u is insane (too large), probably due to a bad archive.\n"),
259          block_len);
260       if (block->read_errors == 0 || verbose >= 2) {
261          Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
262       }
263       block->read_errors++;
264       return 0;
265    }
266
267    Dmsg1(190, "unser_block_header block_len=%d\n", block_len);
268    /* Find end of block or end of buffer whichever is smaller */
269    if (block_len > block->read_len) {
270       block_end = block->read_len;
271    } else {
272       block_end = block_len;
273    }
274    block->binbuf = block_end - bhl;
275    block->block_len = block_len;
276    block->BlockNumber = BlockNumber;
277    Dmsg3(190, "Read binbuf = %d %d block_len=%d\n", block->binbuf,
278       bhl, block_len);
279    if (block_len <= block->read_len) {
280       BlockCheckSum = bcrc32((uint8_t *)block->buf+BLKHDR_CS_LENGTH,
281                          block_len-BLKHDR_CS_LENGTH);
282       if (BlockCheckSum != CheckSum) {
283          Mmsg3(&dev->errmsg, _("Block checksum mismatch in block %u: calc=%x blk=%x\n"), 
284             (unsigned)BlockNumber, BlockCheckSum, CheckSum);
285          if (block->read_errors == 0 || verbose >= 2) {
286             Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
287          }
288          block->read_errors++;
289          return 0;
290       }
291    }
292    return 1;
293 }
294
295 /*  
296  * Write a block to the device, with locking and unlocking
297  *
298  * Returns: 1 on success
299  *        : 0 on failure
300  *
301  */
302 int write_block_to_device(JCR *jcr, DEVICE *dev, DEV_BLOCK *block)
303 {
304    int stat = 1;
305    lock_device(dev);
306
307    /*
308     * If a new volume has been mounted since our last write
309     *   Create a JobMedia record for the previous volume written,
310     *   and set new parameters to write this volume   
311     * The saem applies for if we are in a new file.
312     */
313    if (jcr->NewVol || jcr->NewFile) {
314       /* Create a jobmedia record for this job */
315       if (!dir_create_jobmedia_record(jcr)) {
316          Jmsg(jcr, M_ERROR, 0, _("Could not create JobMedia record for Volume=\"%s\" Job=%s\n"),
317             jcr->VolCatInfo.VolCatName, jcr->Job);
318          set_new_volume_parameters(jcr, dev);
319          unlock_device(dev);
320          return 0;
321       }
322       if (jcr->NewVol) {
323          /* Note, setting a new volume also handles any pending new file */
324          set_new_volume_parameters(jcr, dev);
325          jcr->NewFile = false;        /* this handled for new file too */
326       } else {
327          set_new_file_parameters(jcr, dev);
328       }
329    }
330
331    if (!write_block_to_dev(jcr, dev, block)) {
332        stat = fixup_device_block_write_error(jcr, dev, block);
333    }
334
335    unlock_device(dev);
336    return stat;
337 }
338
339 /*
340  * Write a block to the device 
341  *
342  *  Returns: 1 on success or EOT
343  *           0 on hard error
344  */
345 int write_block_to_dev(JCR *jcr, DEVICE *dev, DEV_BLOCK *block)
346 {
347    ssize_t stat = 0;
348    uint32_t wlen;                     /* length to write */
349    int hit_max1, hit_max2;
350    bool ok;
351
352 #ifdef NO_TAPE_WRITE_TEST
353    empty_block(block);
354    return 1;
355 #endif
356    ASSERT(block->binbuf == ((uint32_t) (block->bufp - block->buf)));
357
358    /* dump_block(block, "before write"); */
359    if (dev->state & ST_WEOT) {
360       Dmsg0(100, "return write_block_to_dev with ST_WEOT\n");
361       Jmsg(jcr, M_FATAL, 0,  _("Cannot write block. Device at EOM.\n"));
362       return 0;
363    }
364    wlen = block->binbuf;
365    if (wlen <= WRITE_BLKHDR_LENGTH) {  /* Does block have data in it? */
366       Dmsg0(100, "return write_block_to_dev no data to write\n");
367       return 1;
368    }
369    /* 
370     * Clear to the end of the buffer if it is not full,
371     *  and on tape devices, apply min and fixed blocking.
372     */
373    if (wlen != block->buf_len) {
374       uint32_t blen;                  /* current buffer length */
375
376       Dmsg2(200, "binbuf=%d buf_len=%d\n", block->binbuf, block->buf_len);
377       blen = wlen;
378
379       /* Adjust write size to min/max for tapes only */
380       if (dev->state & ST_TAPE) {
381          if (wlen < dev->min_block_size) {
382             wlen =  ((dev->min_block_size + TAPE_BSIZE - 1) / TAPE_BSIZE) * TAPE_BSIZE;
383          }
384          /* check for fixed block size */
385          if (dev->min_block_size == dev->max_block_size) {
386             wlen = block->buf_len;    /* fixed block size already rounded */
387          }
388       }
389       if (wlen-blen > 0) {
390          memset(block->bufp, 0, wlen-blen); /* clear garbage */
391       }
392    }  
393
394    ser_block_header(block);
395
396    /* Limit maximum Volume size to value specified by user */
397    hit_max1 = (dev->max_volume_size > 0) &&
398        ((dev->VolCatInfo.VolCatBytes + block->binbuf)) >= dev->max_volume_size;
399    hit_max2 = (dev->VolCatInfo.VolCatMaxBytes > 0) &&
400        ((dev->VolCatInfo.VolCatBytes + block->binbuf)) >= dev->VolCatInfo.VolCatMaxBytes;
401    if (hit_max1 || hit_max2) {   
402       char ed1[50];
403       uint64_t max_cap;
404       Dmsg0(10, "==== Output bytes Triggered medium max capacity.\n");
405       if (hit_max1) {
406          max_cap = dev->max_volume_size;
407       } else {
408          max_cap = dev->VolCatInfo.VolCatMaxBytes;
409       }
410       Jmsg(jcr, M_INFO, 0, _("User defined maximum volume capacity %s exceeded on device %s.\n"),
411             edit_uint64(max_cap, ed1),  dev->dev_name);
412       block->write_failed = true;
413       if (weof_dev(dev, 1) != 0) {            /* end tape */
414          Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
415       }
416       /* Don't do update after second EOF or file count will be wrong */
417       Dmsg0(100, "dir_update_volume_info\n");
418       dir_update_volume_info(jcr, dev, 0);
419       if (dev_cap(dev, CAP_TWOEOF) && weof_dev(dev, 1) != 0) {  /* write eof */
420          Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
421       }
422       dev->state |= (ST_EOF | ST_EOT | ST_WEOT);
423       return 0;   
424    }
425
426    /* Limit maximum File size on volume to user specified value */
427    if (dev_state(dev, ST_TAPE)) {
428       if ((dev->max_file_size > 0) && 
429           (dev->file_addr+block->binbuf) >= dev->max_file_size) {
430
431          /* Write EOF */
432          if (weof_dev(dev, 1) != 0) {            /* write eof */
433             Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
434             block->write_failed = true;
435             dev->state |= (ST_EOF | ST_EOT | ST_WEOT);
436             Dmsg0(100, "dir_update_volume_info\n");
437             dir_update_volume_info(jcr, dev, 0);
438             return 0;   
439          }
440
441          /* Do bookkeeping to handle EOF just written */
442          Dmsg0(100, "dir_update_volume_info\n");
443          dir_update_volume_info(jcr, dev, 0);
444          if (!dir_create_jobmedia_record(jcr)) {
445              Jmsg(jcr, M_ERROR, 0, _("Could not create JobMedia record for Volume=\"%s\" Job=%s\n"),
446                   jcr->VolCatInfo.VolCatName, jcr->Job);
447              return 0;
448          }
449          /* 
450           * Walk through all attached jcrs indicating the file has changed   
451           */
452          Dmsg1(100, "Walk attached jcrs. Volume=%s\n", dev->VolCatInfo.VolCatName);
453          for (JCR *mjcr=NULL; (mjcr=next_attached_jcr(dev, mjcr)); ) {
454             if (mjcr->JobId == 0) {
455                continue;                 /* ignore console */
456             }
457             mjcr->NewFile = true;     /* set reminder to do set_new_file_params */
458          }
459          set_new_file_parameters(jcr, dev);
460       }
461    }
462
463    dev->VolCatInfo.VolCatWrites++;
464    Dmsg1(300, "Write block of %u bytes\n", wlen);      
465    stat = write(dev->fd, block->buf, (size_t)wlen);
466    if (stat != (ssize_t)wlen) {
467       /* We should check for errno == ENOSPC, BUT many 
468        * devices simply report EIO when the volume is full.
469        * With a little more thought we may be able to check
470        * capacity and distinguish real errors and EOT
471        * conditions.  In any case, we probably want to
472        * simulate an End of Medium.
473        */
474       if (stat == -1) {
475          /* I have added the ifdefing here because it appears on
476           * FreeBSD where MTIOCERRSTAT is defined, this not only
477           * clears the error but clears the residual unwritten
478           * buffers -> data loss. As a consequence, on those
479           * systems (FreeBSD like), do the clrerror() only after
480           * the weof_dev() call.
481           */
482          clrerror_dev(dev, -1);
483          if (dev->dev_errno == 0) {
484             dev->dev_errno = ENOSPC;        /* out of space */
485          }
486          Jmsg(jcr, M_ERROR, 0, _("Write error on device %s. ERR=%s.\n"), 
487             dev->dev_name, strerror(dev->dev_errno));
488       } else {
489         dev->dev_errno = ENOSPC;            /* out of space */
490          Jmsg3(jcr, M_INFO, 0, _("End of medium on device %s. Write of %u bytes got %d.\n"), 
491             dev->dev_name, wlen, stat);
492       }  
493
494       Dmsg6(100, "=== Write error. size=%u rtn=%d dev_blk=%d blk_blk=%d errno=%d: ERR=%s\n", 
495          wlen, stat, dev->block_num, block->BlockNumber, dev->dev_errno, strerror(dev->dev_errno));
496
497       block->write_failed = true;
498       if (weof_dev(dev, 1) != 0) {         /* end the tape */
499          Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
500       }
501       Dmsg0(100, "dir_update_volume_info\n");
502       dir_update_volume_info(jcr, dev, 0);
503       if (dev_cap(dev, CAP_TWOEOF) && weof_dev(dev, 1) != 0) {  /* end the tape */
504          Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
505       }
506       dev->state |= (ST_EOF | ST_EOT | ST_WEOT);
507         
508       ok = true;
509 #define CHECK_LAST_BLOCK
510 #ifdef  CHECK_LAST_BLOCK
511       /* 
512        * If the device is a tape and it supports backspace record,
513        *   we backspace over one or two eof marks depending on 
514        *   how many we just wrote, then over the last record,
515        *   then re-read it and verify that the block number is
516        *   correct.
517        */
518       if (dev->state & ST_TAPE && dev_cap(dev, CAP_BSR)) {
519
520          /* Now back up over what we wrote and read the last block */
521          if (!bsf_dev(dev, 1)) {
522             ok = false;
523             Jmsg(jcr, M_ERROR, 0, _("Backspace file at EOT failed. ERR=%s\n"), strerror(dev->dev_errno));
524          }
525          if (ok && dev_cap(dev, CAP_TWOEOF) && !bsf_dev(dev, 1)) {
526             ok = false;
527             Jmsg(jcr, M_ERROR, 0, _("Backspace file at EOT failed. ERR=%s\n"), strerror(dev->dev_errno));
528          }
529          /* Backspace over record */
530          if (ok && !bsr_dev(dev, 1)) {
531             ok = false;
532             Jmsg(jcr, M_ERROR, 0, _("Backspace record at EOT failed. ERR=%s\n"), strerror(dev->dev_errno));
533             /*
534              *  On FreeBSD systems, if the user got here, it is likely that his/her
535              *    tape drive is "frozen".  The correct thing to do is a 
536              *    rewind(), but if we do that, higher levels in cleaning up, will
537              *    most likely write the EOS record over the beginning of the
538              *    tape.  The rewind *is* done later in mount.c when another
539              *    tape is requested. Note, the clrerror_dev() call in bsr_dev()
540              *    calls ioctl(MTCERRSTAT), which *should* fix the problem.
541              */
542          }
543          if (ok) {
544             DEV_BLOCK *lblock = new_block(dev);
545             /* Note, this can destroy dev->errmsg */
546             if (!read_block_from_dev(jcr, dev, lblock, NO_BLOCK_NUMBER_CHECK)) {
547                Jmsg(jcr, M_ERROR, 0, _("Re-read last block at EOT failed. ERR=%s"), dev->errmsg);
548             } else {
549                if (lblock->BlockNumber+1 == block->BlockNumber) {
550                   Jmsg(jcr, M_INFO, 0, _("Re-read of last block succeeded.\n"));
551                } else {
552                   Jmsg(jcr, M_ERROR, 0, _(
553 "Re-read of last block failed. Last block=%u Current block=%u.\n"),
554                        lblock->BlockNumber, block->BlockNumber);
555                }
556             }
557             free_block(lblock);
558          }
559       }
560 #endif
561       return 0;
562    }
563
564    /* We successfully wrote the block, now do housekeeping */
565
566    dev->VolCatInfo.VolCatBytes += block->binbuf;
567    dev->VolCatInfo.VolCatBlocks++;   
568    dev->file_addr += wlen;
569    dev->EndBlock = dev->block_num;
570    dev->EndFile  = dev->file;
571    dev->block_num++;
572    block->BlockNumber++;
573
574    /* Update jcr values */
575    if (dev_state(dev, ST_TAPE)) {
576       jcr->EndBlock = dev->EndBlock;
577       jcr->EndFile  = dev->EndFile;
578    } else {
579       jcr->EndBlock = (uint32_t)dev->file_addr;
580       jcr->EndFile = (uint32_t)(dev->file_addr >> 32);
581    }
582    if (jcr->VolFirstIndex == 0 && block->FirstIndex > 0) {
583       jcr->VolFirstIndex = block->FirstIndex;
584    }
585    if (block->LastIndex > 0) {
586       jcr->VolLastIndex = block->LastIndex;
587    }
588    jcr->WroteVol = true;
589
590    Dmsg2(190, "write_block: wrote block %d bytes=%d\n", dev->block_num,
591       wlen);
592    empty_block(block);
593    return 1;
594 }
595
596 /*  
597  * Read block with locking
598  *
599  */
600 int read_block_from_device(JCR *jcr, DEVICE *dev, DEV_BLOCK *block, bool check_block_numbers)
601 {
602    int stat;
603    Dmsg0(90, "Enter read_block_from_device\n");
604    lock_device(dev);
605    stat = read_block_from_dev(jcr, dev, block, check_block_numbers);
606    unlock_device(dev);
607    Dmsg0(90, "Leave read_block_from_device\n");
608    return stat;
609 }
610
611 /*
612  * Read the next block into the block structure and unserialize
613  *  the block header.  For a file, the block may be partially
614  *  or completely in the current buffer.
615  */
616 int read_block_from_dev(JCR *jcr, DEVICE *dev, DEV_BLOCK *block, bool check_block_numbers)
617 {
618    ssize_t stat;
619    int looping;
620    uint32_t BlockNumber;
621    int retry;
622
623    if (dev_state(dev, ST_EOT)) {
624       return 0;
625    }
626    looping = 0;
627    Dmsg1(100, "Full read() in read_block_from_device() len=%d\n",
628          block->buf_len);
629 reread:
630    if (looping > 1) {
631       Mmsg1(&dev->errmsg, _("Block buffer size looping problem on device %s\n"),
632          dev->dev_name);
633       Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
634       block->read_len = 0;
635       return 0;
636    }
637    retry = 0;
638    do {
639       stat = read(dev->fd, block->buf, (size_t)block->buf_len);
640       if (retry == 1) {
641          dev->VolCatInfo.VolCatErrors++;   
642       }
643    } while (stat == -1 && (errno == EINTR || errno == EIO) && retry++ < 11);
644 // Dmsg1(100, "read stat = %d\n", stat);
645    if (stat < 0) {
646       Dmsg1(90, "Read device got: ERR=%s\n", strerror(errno));
647       clrerror_dev(dev, -1);
648       block->read_len = 0;
649       Mmsg2(&dev->errmsg, _("Read error on device %s. ERR=%s.\n"), 
650          dev->dev_name, strerror(dev->dev_errno));
651       Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
652       if (dev->state & ST_EOF) {  /* EOF just seen? */
653          dev->state |= ST_EOT;    /* yes, error => EOT */
654       }
655       return 0;
656    }
657    Dmsg1(90, "Read device got %d bytes\n", stat);
658    if (stat == 0) {             /* Got EOF ! */
659       dev->block_num = block->read_len = 0;
660       Mmsg1(&dev->errmsg, _("Read zero bytes on device %s.\n"), dev->dev_name);
661       if (dev->state & ST_EOF) { /* EOF already read? */
662          dev->state |= ST_EOT;  /* yes, 2 EOFs => EOT */
663          block->read_len = 0;
664          return 0;
665       }
666       dev->file++;              /* increment file */
667       dev->state |= ST_EOF;     /* set EOF read */
668       block->read_len = 0;
669       return 0;                 /* return eof */
670    }
671    /* Continue here for successful read */
672    block->read_len = stat;      /* save length read */
673    if (block->read_len < BLKHDR2_LENGTH) {
674       Mmsg2(&dev->errmsg, _("Very short block of %d bytes on device %s discarded.\n"), 
675          block->read_len, dev->dev_name);
676       Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
677       dev->state |= ST_SHORT;   /* set short block */
678       block->read_len = block->binbuf = 0;
679       return 0;                 /* return error */
680    }  
681
682    BlockNumber = block->BlockNumber + 1;
683    if (!unser_block_header(jcr, dev, block)) {
684       block->read_len = 0;
685       return 0;
686    }
687
688    /*
689     * If the block is bigger than the buffer, we reposition for
690     *  re-reading the block, allocate a buffer of the correct size,
691     *  and go re-read.
692     */
693    if (block->block_len > block->buf_len) {
694       Mmsg2(&dev->errmsg,  _("Block length %u is greater than buffer %u. Attempting recovery.\n"),
695          block->block_len, block->buf_len);
696       Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
697       Pmsg1(000, "%s", dev->errmsg);
698       /* Attempt to reposition to re-read the block */
699       if (dev->state & ST_TAPE) {
700          Dmsg0(100, "Backspace record for reread.\n");
701          if (!bsr_dev(dev, 1)) {
702             Jmsg(jcr, M_ERROR, 0, "%s", strerror_dev(dev));
703             block->read_len = 0;
704             return 0;
705          }
706       } else {
707          Dmsg0(100, "Seek to beginning of block for reread.\n");
708          off_t pos = lseek(dev->fd, (off_t)0, SEEK_CUR); /* get curr pos */
709          pos -= block->read_len;
710          lseek(dev->fd, pos, SEEK_SET);   
711       }
712       Mmsg1(&dev->errmsg, _("Setting block buffer size to %u bytes.\n"), block->block_len);
713       Jmsg(jcr, M_INFO, 0, "%s", dev->errmsg);
714       Pmsg1(000, "%s", dev->errmsg);
715       /* Set new block length */
716       dev->max_block_size = block->block_len;
717       block->buf_len = block->block_len;
718       free_memory(block->buf);
719       block->buf = get_memory(block->buf_len);
720       empty_block(block);
721       looping++;
722       goto reread;                    /* re-read block with correct block size */
723    }
724
725    if (block->block_len > block->read_len) {
726       Mmsg3(&dev->errmsg, _("Short block at %u of %d bytes on device %s discarded.\n"), 
727          dev->block_num, block->read_len, dev->dev_name);
728       Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
729       dev->state |= ST_SHORT;   /* set short block */
730       block->read_len = block->binbuf = 0;
731       return 0;                 /* return error */
732    }  
733
734    dev->state &= ~(ST_EOF|ST_SHORT); /* clear EOF and short block */
735    dev->VolCatInfo.VolCatReads++;   
736    dev->VolCatInfo.VolCatRBytes += block->read_len;
737
738    dev->VolCatInfo.VolCatBytes += block->block_len;
739    dev->VolCatInfo.VolCatBlocks++;   
740    dev->file_addr += block->block_len;
741    dev->EndBlock = dev->block_num;
742    dev->EndFile  = dev->file;
743    dev->block_num++;
744
745    /* Update jcr values */
746    if (dev->state & ST_TAPE) {
747       jcr->EndBlock = dev->EndBlock;
748       jcr->EndFile  = dev->EndFile;
749    } else {
750       jcr->EndBlock = (uint32_t)dev->file_addr;
751       jcr->EndFile = (uint32_t)(dev->file_addr >> 32);
752    }
753
754    /*
755     * If we read a short block on disk,
756     * seek to beginning of next block. This saves us
757     * from shuffling blocks around in the buffer. Take a
758     * look at this from an efficiency stand point later, but
759     * it should only happen once at the end of each job.
760     *
761     * I've been lseek()ing negative relative to SEEK_CUR for 30
762     *   years now. However, it seems that with the new off_t definition,
763     *   it is not possible to seek negative amounts, so we use two
764     *   lseek(). One to get the position, then the second to do an
765     *   absolute positioning -- so much for efficiency.  KES Sep 02.
766     */
767    Dmsg0(200, "At end of read block\n");
768    if (block->read_len > block->block_len && !(dev->state & ST_TAPE)) {
769       off_t pos = lseek(dev->fd, (off_t)0, SEEK_CUR); /* get curr pos */
770       pos -= (block->read_len - block->block_len);
771       lseek(dev->fd, pos, SEEK_SET);   
772       Dmsg2(100, "Did lseek blk_size=%d rdlen=%d\n", block->block_len,
773             block->read_len);
774    }
775    Dmsg2(200, "Exit read_block read_len=%d block_len=%d\n",
776       block->read_len, block->block_len);
777    block->block_read = true;
778    return 1;
779 }