]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/block.c
1c73dc47d536724f641ba879dde59cff436b7dfd
[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-2004 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 static bool terminate_writing_volume(DCR *dcr);
37
38 /*
39  * Dump the block header, then walk through
40  * the block printing out the record headers.
41  */
42 void dump_block(DEV_BLOCK *b, const char *msg)
43 {
44    ser_declare;
45    char *p;
46    char Id[BLKHDR_ID_LENGTH+1];
47    uint32_t CheckSum, BlockCheckSum;
48    uint32_t block_len;
49    uint32_t BlockNumber;
50    uint32_t VolSessionId, VolSessionTime, data_len;
51    int32_t  FileIndex;
52    int32_t  Stream;
53    int bhl, rhl;
54
55    unser_begin(b->buf, BLKHDR1_LENGTH);
56    unser_uint32(CheckSum);
57    unser_uint32(block_len);
58    unser_uint32(BlockNumber);
59    unser_bytes(Id, BLKHDR_ID_LENGTH);
60    ASSERT(unser_length(b->buf) == BLKHDR1_LENGTH);
61    Id[BLKHDR_ID_LENGTH] = 0;
62    if (Id[3] == '2') {
63       unser_uint32(VolSessionId);
64       unser_uint32(VolSessionTime);
65       bhl = BLKHDR2_LENGTH;
66       rhl = RECHDR2_LENGTH;
67    } else {
68       VolSessionId = VolSessionTime = 0;
69       bhl = BLKHDR1_LENGTH;
70       rhl = RECHDR1_LENGTH;
71    }
72
73    if (block_len > 100000) {
74       Dmsg3(20, "Dump block %s 0x%x blocksize too big %u\n", msg, b, block_len);
75       return;
76    }
77
78    BlockCheckSum = bcrc32((uint8_t *)b->buf+BLKHDR_CS_LENGTH,
79                          block_len-BLKHDR_CS_LENGTH);
80    Pmsg6(000, "Dump block %s %x: size=%d BlkNum=%d\n\
81                Hdrcksum=%x cksum=%x\n",
82       msg, b, block_len, BlockNumber, CheckSum, BlockCheckSum);
83    p = b->buf + bhl;
84    while (p < (b->buf + block_len+WRITE_RECHDR_LENGTH)) { 
85       unser_begin(p, WRITE_RECHDR_LENGTH);
86       if (rhl == RECHDR1_LENGTH) {
87          unser_uint32(VolSessionId);
88          unser_uint32(VolSessionTime);
89       }
90       unser_int32(FileIndex);
91       unser_int32(Stream);
92       unser_uint32(data_len);
93       Pmsg6(000, "   Rec: VId=%u VT=%u FI=%s Strm=%s len=%d p=%x\n",
94            VolSessionId, VolSessionTime, FI_to_ascii(FileIndex), 
95            stream_to_ascii(Stream, FileIndex), data_len, p);
96       p += data_len + rhl;
97   }
98 }
99     
100 /*
101  * Create a new block structure.                           
102  * We pass device so that the block can inherit the
103  * min and max block sizes.
104  */
105 DEV_BLOCK *new_block(DEVICE *dev)
106 {
107    DEV_BLOCK *block = (DEV_BLOCK *)get_memory(sizeof(DEV_BLOCK));
108
109    memset(block, 0, sizeof(DEV_BLOCK));
110
111    /* If the user has specified a max_block_size, use it as the default */
112    if (dev->max_block_size == 0) {
113       block->buf_len = DEFAULT_BLOCK_SIZE;
114    } else {
115       block->buf_len = dev->max_block_size;
116    }
117    block->dev = dev;
118    block->block_len = block->buf_len;  /* default block size */
119    block->buf = get_memory(block->buf_len); 
120    empty_block(block);
121    block->BlockVer = BLOCK_VER;       /* default write version */
122    Dmsg1(350, "Returning new block=%x\n", block);
123    return block;
124 }
125
126
127 /*
128  * Duplicate an existing block (eblock)
129  */
130 DEV_BLOCK *dup_block(DEV_BLOCK *eblock)
131 {
132    DEV_BLOCK *block = (DEV_BLOCK *)get_memory(sizeof(DEV_BLOCK));
133    int buf_len = sizeof_pool_memory(eblock->buf);
134
135    memcpy(block, eblock, sizeof(DEV_BLOCK));
136    block->buf = get_memory(buf_len);
137    memcpy(block->buf, eblock->buf, buf_len);
138    return block;
139 }
140
141
142 /* 
143  * Only the first block checksum error was reported.
144  *   If there are more, report it now.
145  */
146 void print_block_read_errors(JCR *jcr, DEV_BLOCK *block)
147 {
148    if (block->read_errors > 1) {
149       Jmsg(jcr, M_ERROR, 0, _("%d block read errors not printed.\n"),
150          block->read_errors);
151    }
152 }
153
154 /*
155  * Free block 
156  */
157 void free_block(DEV_BLOCK *block)
158 {
159    Dmsg1(199, "free_block buffer %x\n", block->buf);
160    free_memory(block->buf);
161    Dmsg1(199, "free_block block %x\n", block);
162    free_memory((POOLMEM *)block);
163 }
164
165 /* Empty the block -- for writing */
166 void empty_block(DEV_BLOCK *block)
167 {
168    block->binbuf = WRITE_BLKHDR_LENGTH;
169    block->bufp = block->buf + block->binbuf;
170    block->read_len = 0;
171    block->write_failed = false;
172    block->block_read = false;
173    block->FirstIndex = block->LastIndex = 0;
174 }
175
176 /*
177  * Create block header just before write. The space
178  * in the buffer should have already been reserved by
179  * init_block.
180  */
181 void ser_block_header(DEV_BLOCK *block)
182 {
183    ser_declare;
184    uint32_t CheckSum = 0;
185    uint32_t block_len = block->binbuf;
186    
187    Dmsg1(390, "ser_block_header: block_len=%d\n", block_len);
188    ser_begin(block->buf, BLKHDR2_LENGTH);
189    ser_uint32(CheckSum);
190    ser_uint32(block_len);
191    ser_uint32(block->BlockNumber);
192    ser_bytes(WRITE_BLKHDR_ID, BLKHDR_ID_LENGTH);
193    if (BLOCK_VER >= 2) {
194       ser_uint32(block->VolSessionId);
195       ser_uint32(block->VolSessionTime);
196    }
197
198    /* Checksum whole block except for the checksum */
199    CheckSum = bcrc32((uint8_t *)block->buf+BLKHDR_CS_LENGTH, 
200                  block_len-BLKHDR_CS_LENGTH);
201    Dmsg1(390, "ser_bloc_header: checksum=%x\n", CheckSum);
202    ser_begin(block->buf, BLKHDR2_LENGTH);
203    ser_uint32(CheckSum);              /* now add checksum to block header */
204 }
205
206 /*
207  * Unserialize the block header for reading block.
208  *  This includes setting all the buffer pointers correctly.
209  *
210  *  Returns: false on failure (not a block)
211  *           true  on success
212  */
213 static bool unser_block_header(JCR *jcr, DEVICE *dev, DEV_BLOCK *block)
214 {
215    ser_declare;
216    char Id[BLKHDR_ID_LENGTH+1];
217    uint32_t CheckSum, BlockCheckSum;
218    uint32_t block_len;
219    uint32_t block_end;
220    uint32_t BlockNumber;
221    int bhl;
222
223    unser_begin(block->buf, BLKHDR_LENGTH);
224    unser_uint32(CheckSum);
225    unser_uint32(block_len);
226    unser_uint32(BlockNumber);
227    unser_bytes(Id, BLKHDR_ID_LENGTH);
228    ASSERT(unser_length(block->buf) == BLKHDR1_LENGTH);
229
230    Id[BLKHDR_ID_LENGTH] = 0;
231    if (Id[3] == '1') {
232       bhl = BLKHDR1_LENGTH;
233       block->BlockVer = 1;
234       block->bufp = block->buf + bhl;
235       if (strncmp(Id, BLKHDR1_ID, BLKHDR_ID_LENGTH) != 0) {
236          dev->dev_errno = EIO;
237          Mmsg4(dev->errmsg, _("Volume data error at %u:%u! Wanted ID: \"%s\", got \"%s\". Buffer discarded.\n"),
238             dev->file, dev->block_num, BLKHDR1_ID, Id);
239          if (block->read_errors == 0 || verbose >= 2) {
240             Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
241          }
242          block->read_errors++;
243          return false;
244       }
245    } else if (Id[3] == '2') {
246       unser_uint32(block->VolSessionId);
247       unser_uint32(block->VolSessionTime);
248       bhl = BLKHDR2_LENGTH;
249       block->BlockVer = 2;
250       block->bufp = block->buf + bhl;
251       if (strncmp(Id, BLKHDR2_ID, BLKHDR_ID_LENGTH) != 0) {
252          dev->dev_errno = EIO;
253          Mmsg4(dev->errmsg, _("Volume data error at %u:%u! Wanted ID: \"%s\", got \"%s\". Buffer discarded.\n"),
254             dev->file, dev->block_num, BLKHDR2_ID, Id);
255          if (block->read_errors == 0 || verbose >= 2) {
256             Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
257          }
258          block->read_errors++;
259          return false;
260       }
261    } else {
262       dev->dev_errno = EIO;
263       Mmsg4(dev->errmsg, _("Volume data error at %u:%u! Wanted ID: \"%s\", got \"%s\". Buffer discarded.\n"),
264           dev->file, dev->block_num, BLKHDR2_ID, Id);
265       if (block->read_errors == 0 || verbose >= 2) {
266          Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
267       }
268       block->read_errors++;
269       unser_uint32(block->VolSessionId);
270       unser_uint32(block->VolSessionTime);
271       return false;
272    }
273
274    /* Sanity check */
275    if (block_len > MAX_BLOCK_LENGTH) {
276       dev->dev_errno = EIO;
277       Mmsg3(dev->errmsg,  _("Volume data error at %u:%u! Block length %u is insane (too large), probably due to a bad archive.\n"),
278          dev->file, dev->block_num, block_len);
279       if (block->read_errors == 0 || verbose >= 2) {
280          Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
281       }
282       block->read_errors++;
283       return false;
284    }
285
286    Dmsg1(390, "unser_block_header block_len=%d\n", block_len);
287    /* Find end of block or end of buffer whichever is smaller */
288    if (block_len > block->read_len) {
289       block_end = block->read_len;
290    } else {
291       block_end = block_len;
292    }
293    block->binbuf = block_end - bhl;
294    block->block_len = block_len;
295    block->BlockNumber = BlockNumber;
296    Dmsg3(390, "Read binbuf = %d %d block_len=%d\n", block->binbuf,
297       bhl, block_len);
298    if (block_len <= block->read_len) {
299       BlockCheckSum = bcrc32((uint8_t *)block->buf+BLKHDR_CS_LENGTH,
300                          block_len-BLKHDR_CS_LENGTH);
301       if (BlockCheckSum != CheckSum) {
302          dev->dev_errno = EIO;
303          Mmsg5(dev->errmsg, _("Volume data error at %u:%u! Block checksum mismatch in block %u: calc=%x blk=%x\n"), 
304             dev->file, dev->block_num, (unsigned)BlockNumber, BlockCheckSum, CheckSum);
305          if (block->read_errors == 0 || verbose >= 2) {
306             Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
307          }
308          block->read_errors++;
309          if (!forge_on) {
310             return false;
311          }
312       }
313    }
314    return true;
315 }
316
317 /*  
318  * Write a block to the device, with locking and unlocking
319  *
320  * Returns: true  on success
321  *        : false on failure
322  *
323  */
324 bool write_block_to_device(DCR *dcr)
325 {
326    bool stat = true;
327    DEVICE *dev = dcr->dev;
328    JCR *jcr = dcr->jcr;
329
330    if (dcr->spooling) {
331       stat = write_block_to_spool_file(dcr);
332       return stat;
333    }
334
335    if (!dcr->dev_locked) {
336       lock_device(dev);
337    }
338
339    /*
340     * If a new volume has been mounted since our last write
341     *   Create a JobMedia record for the previous volume written,
342     *   and set new parameters to write this volume   
343     * The same applies for if we are in a new file.
344     */
345    if (dcr->NewVol || dcr->NewFile) {
346       if (job_canceled(jcr)) {
347          stat = false;
348          goto bail_out;
349       }
350       /* Create a jobmedia record for this job */
351       if (!dir_create_jobmedia_record(dcr)) {
352          dev->dev_errno = EIO;
353          Jmsg(jcr, M_FATAL, 0, _("Could not create JobMedia record for Volume=\"%s\" Job=%s\n"),
354             dcr->VolCatInfo.VolCatName, jcr->Job);
355          set_new_volume_parameters(dcr);
356          stat = false;
357          goto bail_out;
358       }
359       if (dcr->NewVol) {
360          /* Note, setting a new volume also handles any pending new file */
361          set_new_volume_parameters(dcr);
362          dcr->NewFile = false;        /* this handled for new file too */
363       } else {
364          set_new_file_parameters(dcr);
365       }
366    }
367
368    if (!write_block_to_dev(dcr)) {
369        if (job_canceled(jcr)) {
370           stat = false;
371        } else {
372           stat = fixup_device_block_write_error(dcr);
373        }
374    }
375
376 bail_out:
377    if (!dcr->dev_locked) {
378       unlock_device(dev);
379    }
380    return stat;
381 }
382
383 /*
384  * Write a block to the device 
385  *
386  *  Returns: true  on success or EOT
387  *           false on hard error
388  */
389 bool write_block_to_dev(DCR *dcr)
390 {
391    ssize_t stat = 0;
392    uint32_t wlen;                     /* length to write */
393    int hit_max1, hit_max2;
394    bool ok = true;
395    DEVICE *dev = dcr->dev;
396    JCR *jcr = dcr->jcr;
397    DEV_BLOCK *block = dcr->block;
398
399 #ifdef NO_TAPE_WRITE_TEST
400    empty_block(block);
401    return true;
402 #endif
403    ASSERT(block->binbuf == ((uint32_t) (block->bufp - block->buf)));
404
405    /* dump_block(block, "before write"); */
406    if (dev->state & ST_WEOT) {
407       Dmsg0(100, "return write_block_to_dev with ST_WEOT\n");
408       dev->dev_errno = ENOSPC;
409       Jmsg(jcr, M_FATAL, 0,  _("Cannot write block. Device at EOM.\n"));
410       return false;
411    }
412    if (!(dev->state & ST_APPEND)) {
413       dev->dev_errno = EIO;
414       Jmsg(jcr, M_FATAL, 0, _("Attempt to write on read-only Volume.\n"));
415       return false;
416    }
417    wlen = block->binbuf;
418    if (wlen <= WRITE_BLKHDR_LENGTH) {  /* Does block have data in it? */
419       Dmsg0(100, "return write_block_to_dev no data to write\n");
420       return true;
421    }
422    /* 
423     * Clear to the end of the buffer if it is not full,
424     *  and on tape devices, apply min and fixed blocking.
425     */
426    if (wlen != block->buf_len) {
427       uint32_t blen;                  /* current buffer length */
428
429       Dmsg2(200, "binbuf=%d buf_len=%d\n", block->binbuf, block->buf_len);
430       blen = wlen;
431
432       /* Adjust write size to min/max for tapes only */
433       if (dev->state & ST_TAPE) {
434          /* check for fixed block size */
435          if (dev->min_block_size == dev->max_block_size) {
436             wlen = block->buf_len;    /* fixed block size already rounded */
437          /* Check for min block size */
438          } else if (wlen < dev->min_block_size) {
439             wlen =  ((dev->min_block_size + TAPE_BSIZE - 1) / TAPE_BSIZE) * TAPE_BSIZE;
440          /* Ensure size is rounded */
441          } else {
442             wlen = ((wlen + TAPE_BSIZE - 1) / TAPE_BSIZE) * TAPE_BSIZE;
443          }
444       }
445       if (wlen-blen > 0) {
446          memset(block->bufp, 0, wlen-blen); /* clear garbage */
447       }
448    }  
449
450    ser_block_header(block);
451
452    /* Limit maximum Volume size to value specified by user */
453    hit_max1 = (dev->max_volume_size > 0) &&
454        ((dev->VolCatInfo.VolCatBytes + block->binbuf)) >= dev->max_volume_size;
455    hit_max2 = (dev->VolCatInfo.VolCatMaxBytes > 0) &&
456        ((dev->VolCatInfo.VolCatBytes + block->binbuf)) >= dev->VolCatInfo.VolCatMaxBytes;
457    if (hit_max1 || hit_max2) {   
458       char ed1[50];
459       uint64_t max_cap;
460       Dmsg0(10, "==== Output bytes Triggered medium max capacity.\n");
461       if (hit_max1) {
462          max_cap = dev->max_volume_size;
463       } else {
464          max_cap = dev->VolCatInfo.VolCatMaxBytes;
465       }
466       Jmsg(jcr, M_INFO, 0, _("User defined maximum volume capacity %s exceeded on device %s.\n"),
467             edit_uint64_with_commas(max_cap, ed1),  dev->dev_name);
468       terminate_writing_volume(dcr);
469       dev->dev_errno = ENOSPC;
470       return false;
471    }
472
473    /* Limit maximum File size on volume to user specified value */
474    if ((dev->max_file_size > 0) && 
475        (dev->file_size+block->binbuf) >= dev->max_file_size) {
476       dev->file_size = 0;             /* reset file size */
477
478       if (dev_state(dev, ST_TAPE) && weof_dev(dev, 1) != 0) {            /* write eof */
479          Dmsg0(190, "WEOF error in max file size.\n");
480          terminate_writing_volume(dcr);
481          dev->dev_errno = ENOSPC;
482          return false;
483       }
484
485       /* Create a JobMedia record so restore can seek */
486       if (!dir_create_jobmedia_record(dcr)) {
487          Dmsg0(190, "Error from create_job_media.\n");
488          dev->dev_errno = EIO;
489           Jmsg(jcr, M_FATAL, 0, _("Could not create JobMedia record for Volume=\"%s\" Job=%s\n"),
490                dcr->VolCatInfo.VolCatName, jcr->Job);
491           terminate_writing_volume(dcr);
492           dev->dev_errno = EIO;
493           return false;
494       }
495       dev->VolCatInfo.VolCatFiles = dev->file;
496       if (!dir_update_volume_info(dcr, false)) {
497          Dmsg0(190, "Error from update_vol_info.\n");
498          terminate_writing_volume(dcr);
499          dev->dev_errno = EIO;
500          return false;
501       }
502       Dmsg0(100, "dir_update_volume_info max file size -- OK\n");
503
504
505       /*
506        * Walk through all attached dcrs setting flag to call
507        * set_new_file_parameters() when that dcr is next used.
508        */
509       DCR *mdcr;
510       foreach_dlist(mdcr, dev->attached_dcrs) {
511          if (mdcr->jcr->JobId == 0) {
512             continue;
513          }
514          mdcr->NewFile = true;        /* set reminder to do set_new_file_params */
515       }
516       /* Set new file/block parameters for current dcr */
517       set_new_file_parameters(dcr);
518    }
519
520    dev->VolCatInfo.VolCatWrites++;
521    Dmsg1(300, "Write block of %u bytes\n", wlen);      
522 #ifdef DEBUG_BLOCK_ZEROING
523    uint32_t *bp = (uint32_t *)block->buf;
524    if (bp[0] == 0 && bp[1] == 0 && bp[2] == 0 && block->buf[12] == 0) {
525       Jmsg0(jcr, M_ABORT, 0, "Write block header zeroed.\n");
526    }
527 #endif
528
529    stat = write(dev->fd, block->buf, (size_t)wlen);
530
531 #ifdef DEBUG_BLOCK_ZEROING
532    if (bp[0] == 0 && bp[1] == 0 && bp[2] == 0 && block->buf[12] == 0) {
533       Jmsg0(jcr, M_ABORT, 0, "Write block header zeroed.\n");
534    }
535 #endif
536
537    if (stat != (ssize_t)wlen) {
538       /* Some devices simply report EIO when the volume is full.
539        * With a little more thought we may be able to check
540        * capacity and distinguish real errors and EOT
541        * conditions.  In any case, we probably want to
542        * simulate an End of Medium.
543        */
544       if (stat == -1) {
545          berrno be;
546          clrerror_dev(dev, -1);
547          if (dev->dev_errno == 0) {
548             dev->dev_errno = ENOSPC;        /* out of space */
549          }
550          if (dev->dev_errno != ENOSPC) {
551             Jmsg4(jcr, M_ERROR, 0, _("Write error at %u:%u on device %s. ERR=%s.\n"), 
552                dev->file, dev->block_num, dev->dev_name, be.strerror());
553          }
554       } else {
555         dev->dev_errno = ENOSPC;            /* out of space */
556       }  
557       if (dev->dev_errno == ENOSPC) {
558          Jmsg(jcr, M_INFO, 0, _("End of Volume \"%s\" at %u:%u on device %s. Write of %u bytes got %d.\n"), 
559             dev->VolCatInfo.VolCatName,
560             dev->file, dev->block_num, dev->dev_name, wlen, stat);
561       }
562       Dmsg6(100, "=== Write error. size=%u rtn=%d dev_blk=%d blk_blk=%d errno=%d: ERR=%s\n", 
563          wlen, stat, dev->block_num, block->BlockNumber, dev->dev_errno, strerror(dev->dev_errno));
564
565       ok = terminate_writing_volume(dcr);
566       if (!ok && !forge_on) {
567          return false;
568       }
569
570 #define CHECK_LAST_BLOCK
571 #ifdef  CHECK_LAST_BLOCK
572       /* 
573        * If the device is a tape and it supports backspace record,
574        *   we backspace over one or two eof marks depending on 
575        *   how many we just wrote, then over the last record,
576        *   then re-read it and verify that the block number is
577        *   correct.
578        */
579       if (ok && (dev->state & ST_TAPE) && dev_cap(dev, CAP_BSR)) {
580          /* Now back up over what we wrote and read the last block */
581          if (!bsf_dev(dev, 1)) {
582             ok = false;
583             Jmsg(jcr, M_ERROR, 0, _("Backspace file at EOT failed. ERR=%s\n"), strerror(dev->dev_errno));
584          }
585          if (ok && dev_cap(dev, CAP_TWOEOF) && !bsf_dev(dev, 1)) {
586             ok = false;
587             Jmsg(jcr, M_ERROR, 0, _("Backspace file at EOT failed. ERR=%s\n"), strerror(dev->dev_errno));
588          }
589          /* Backspace over record */
590          if (ok && !bsr_dev(dev, 1)) {
591             ok = false;
592             Jmsg(jcr, M_ERROR, 0, _("Backspace record at EOT failed. ERR=%s\n"), strerror(dev->dev_errno));
593             /*
594              *  On FreeBSD systems, if the user got here, it is likely that his/her
595              *    tape drive is "frozen".  The correct thing to do is a 
596              *    rewind(), but if we do that, higher levels in cleaning up, will
597              *    most likely write the EOS record over the beginning of the
598              *    tape.  The rewind *is* done later in mount.c when another
599              *    tape is requested. Note, the clrerror_dev() call in bsr_dev()
600              *    calls ioctl(MTCERRSTAT), which *should* fix the problem.
601              */
602          }
603          if (ok) {
604             DEV_BLOCK *lblock = new_block(dev);
605             /* Note, this can destroy dev->errmsg */
606             dcr->block = lblock;
607             if (!read_block_from_dev(dcr, NO_BLOCK_NUMBER_CHECK)) {
608                Jmsg(jcr, M_ERROR, 0, _("Re-read last block at EOT failed. ERR=%s"), dev->errmsg);
609             } else {
610                if (lblock->BlockNumber+1 == block->BlockNumber) {
611                   Jmsg(jcr, M_INFO, 0, _("Re-read of last block succeeded.\n"));
612                } else {
613                   Jmsg(jcr, M_ERROR, 0, _(
614 "Re-read of last block failed. Last block=%u Current block=%u.\n"),
615                        lblock->BlockNumber, block->BlockNumber);
616                }
617             }
618             free_block(lblock);
619             dcr->block = block;
620          }
621       }
622 #endif
623       return false;
624    }
625
626    /* We successfully wrote the block, now do housekeeping */
627
628    dev->VolCatInfo.VolCatBytes += block->binbuf;
629    dev->VolCatInfo.VolCatBlocks++;   
630    dev->EndBlock = dev->block_num;
631    dev->EndFile  = dev->file;
632    dev->block_num++;
633    block->BlockNumber++;
634
635    /* Update dcr values */
636    if (dev_state(dev, ST_TAPE)) {
637       dcr->EndBlock = dev->EndBlock;
638       dcr->EndFile  = dev->EndFile;
639    } else {
640       /* Save address of start of block just written */
641       dcr->EndBlock = (uint32_t)dev->file_addr;
642       dcr->EndFile = (uint32_t)(dev->file_addr >> 32);
643    }
644    if (dcr->VolFirstIndex == 0 && block->FirstIndex > 0) {
645       dcr->VolFirstIndex = block->FirstIndex;
646    }
647    if (block->LastIndex > 0) {
648       dcr->VolLastIndex = block->LastIndex;
649    }
650    dcr->WroteVol = true;
651    dev->file_addr += wlen;            /* update file address */
652    dev->file_size += wlen;
653
654    Dmsg2(300, "write_block: wrote block %d bytes=%d\n", dev->block_num, wlen);
655    empty_block(block);
656    return true;
657 }
658
659 static bool terminate_writing_volume(DCR *dcr)
660 {
661    DEVICE *dev = dcr->dev;
662    bool ok = true;
663
664    /* Create a JobMedia record to indicated end of tape */
665    dev->VolCatInfo.VolCatFiles = dev->file;
666    if (!dir_create_jobmedia_record(dcr)) {
667       Dmsg0(190, "Error from create JobMedia\n");
668       dev->dev_errno = EIO;
669        Jmsg(dcr->jcr, M_FATAL, 0, _("Could not create JobMedia record for Volume=\"%s\" Job=%s\n"),
670             dcr->VolCatInfo.VolCatName, dcr->jcr->Job);
671        ok = false;
672        goto bail_out;
673    }
674    dcr->block->write_failed = true;
675    if (weof_dev(dev, 1) != 0) {         /* end the tape */
676       dev->VolCatInfo.VolCatErrors++;
677       Jmsg(dcr->jcr, M_ERROR, 0, "Error writing final EOF to tape. This tape may not be readable.\n"
678            "%s", dev->errmsg);
679       ok = false;
680       Dmsg0(100, "WEOF error.\n");
681    }
682    dev->VolCatInfo.VolCatFiles = dev->file;
683    if (!dir_update_volume_info(dcr, false)) {
684       ok = false;
685    }
686    Dmsg1(100, "dir_update_volume_info terminate writing -- %s\n", ok?"OK":"ERROR");
687
688
689    /*
690     * Walk through all attached dcrs setting flag to call
691     * set_new_file_parameters() when that dcr is next used.
692     */
693    DCR *mdcr;
694    foreach_dlist(mdcr, dev->attached_dcrs) {
695       if (mdcr->jcr->JobId == 0) {
696          continue;
697       }
698       mdcr->NewFile = true;        /* set reminder to do set_new_file_params */
699    }
700    /* Set new file/block parameters for current dcr */
701    set_new_file_parameters(dcr);
702
703    if (ok && dev_cap(dev, CAP_TWOEOF) && weof_dev(dev, 1) != 0) {  /* end the tape */
704       dev->VolCatInfo.VolCatErrors++;
705       /* This may not be fatal since we already wrote an EOF */
706       Jmsg(dcr->jcr, M_ERROR, 0, "%s", dev->errmsg);
707    }
708 bail_out:
709    dev->state |= (ST_EOF|ST_EOT|ST_WEOT);
710    dev->state &= ~ST_APPEND;          /* make tape read-only */
711    Dmsg1(100, "Leave terminate_writing_volume -- %s\n", ok?"OK":"ERROR");
712    return ok;
713 }
714
715
716 /*  
717  * Read block with locking
718  *
719  */
720 bool read_block_from_device(DCR *dcr, bool check_block_numbers)
721 {
722    bool stat;
723    DEVICE *dev = dcr->dev;
724    Dmsg0(200, "Enter read_block_from_device\n");
725    lock_device(dev);
726    stat = read_block_from_dev(dcr, check_block_numbers);
727    unlock_device(dev);
728    Dmsg0(200, "Leave read_block_from_device\n");
729    return stat;
730 }
731
732 /*
733  * Read the next block into the block structure and unserialize
734  *  the block header.  For a file, the block may be partially
735  *  or completely in the current buffer.
736  */
737 bool read_block_from_dev(DCR *dcr, bool check_block_numbers)
738 {
739    ssize_t stat;
740    int looping;
741    uint32_t BlockNumber;
742    int retry;
743    JCR *jcr = dcr->jcr;
744    DEVICE *dev = dcr->dev;
745    DEV_BLOCK *block = dcr->block;
746
747    if (dev_state(dev, ST_EOT)) {
748       return false;
749    }
750    looping = 0;
751    Dmsg1(200, "Full read() in read_block_from_device() len=%d\n",
752          block->buf_len);
753 reread:
754    if (looping > 1) {
755       dev->dev_errno = EIO;
756       Mmsg1(dev->errmsg, _("Block buffer size looping problem on device %s\n"),
757          dev->dev_name);
758       Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
759       block->read_len = 0;
760       return false;
761    }
762    retry = 0;
763    do {
764 //    uint32_t *bp = (uint32_t *)block->buf;
765 //    Dmsg3(000, "Read %p %u at %llu\n", block->buf, block->buf_len, lseek(dev->fd, 0, SEEK_CUR));
766
767       stat = read(dev->fd, block->buf, (size_t)block->buf_len);
768
769 //    Dmsg8(000, "stat=%d Csum=%u blen=%u bnum=%u %c%c%c%c\n",stat, bp[0],bp[1],bp[2],
770 //      block->buf[12],block->buf[13],block->buf[14],block->buf[15]);
771
772       if (retry == 1) {
773          dev->VolCatInfo.VolCatErrors++;   
774       }
775    } while (stat == -1 && (errno == EINTR || errno == EIO) && retry++ < 11);
776    if (stat < 0) {
777       berrno be;
778       clrerror_dev(dev, -1);
779       Dmsg1(200, "Read device got: ERR=%s\n", be.strerror());
780       block->read_len = 0;
781       Mmsg4(dev->errmsg, _("Read error at file:blk %u:%u on device %s. ERR=%s.\n"), 
782          dev->file, dev->block_num, dev->dev_name, be.strerror());
783       Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
784       if (dev->state & ST_EOF) {  /* EOF just seen? */
785          dev->state |= ST_EOT;    /* yes, error => EOT */
786       }
787       return false;
788    }
789    Dmsg1(200, "Read device got %d bytes\n", stat);
790    if (stat == 0) {             /* Got EOF ! */
791       dev->block_num = block->read_len = 0;
792       Mmsg3(dev->errmsg, _("Read zero bytes at %u:%u on device %s.\n"), 
793          dev->file, dev->block_num, dev->dev_name);
794       if (dev->state & ST_EOF) { /* EOF already read? */
795          dev->state |= ST_EOT;  /* yes, 2 EOFs => EOT */
796          block->read_len = 0;
797          return 0;
798       }
799       dev->file++;              /* increment file */
800       dev->state |= ST_EOF;     /* set EOF read */
801       block->read_len = 0;
802       return false;             /* return eof */
803    }
804    /* Continue here for successful read */
805    block->read_len = stat;      /* save length read */
806    if (block->read_len < BLKHDR2_LENGTH) {
807       dev->dev_errno = EIO;
808       Mmsg4(dev->errmsg, _("Volume data error at %u:%u! Very short block of %d bytes on device %s discarded.\n"), 
809          dev->file, dev->block_num, block->read_len, dev->dev_name);
810       Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
811       dev->state |= ST_SHORT;   /* set short block */
812       block->read_len = block->binbuf = 0;
813       return false;             /* return error */
814    }  
815
816    BlockNumber = block->BlockNumber + 1;
817    if (!unser_block_header(jcr, dev, block)) {
818       if (forge_on) {
819          dev->file_addr += block->read_len;
820          dev->file_size += block->read_len;
821          goto reread;
822       }
823       return false;
824    }
825
826    /*
827     * If the block is bigger than the buffer, we reposition for
828     *  re-reading the block, allocate a buffer of the correct size,
829     *  and go re-read.
830     */
831    if (block->block_len > block->buf_len) {
832       dev->dev_errno = EIO;
833       Mmsg2(dev->errmsg,  _("Block length %u is greater than buffer %u. Attempting recovery.\n"),
834          block->block_len, block->buf_len);
835       Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
836       Pmsg1(000, "%s", dev->errmsg);
837       /* Attempt to reposition to re-read the block */
838       if (dev->state & ST_TAPE) {
839          Dmsg0(200, "BSR for reread; block too big for buffer.\n");
840          if (!bsr_dev(dev, 1)) {
841             Jmsg(jcr, M_ERROR, 0, "%s", strerror_dev(dev));
842             block->read_len = 0;
843             return false;
844          }
845       } else {
846          Dmsg0(200, "Seek to beginning of block for reread.\n");
847          off_t pos = lseek(dev->fd, (off_t)0, SEEK_CUR); /* get curr pos */
848          pos -= block->read_len;
849          lseek(dev->fd, pos, SEEK_SET);   
850          dev->file_addr = pos;
851       }
852       Mmsg1(dev->errmsg, _("Setting block buffer size to %u bytes.\n"), block->block_len);
853       Jmsg(jcr, M_INFO, 0, "%s", dev->errmsg);
854       Pmsg1(000, "%s", dev->errmsg);
855       /* Set new block length */
856       dev->max_block_size = block->block_len;
857       block->buf_len = block->block_len;
858       free_memory(block->buf);
859       block->buf = get_memory(block->buf_len);
860       empty_block(block);
861       looping++;
862       goto reread;                    /* re-read block with correct block size */
863    }
864
865    if (block->block_len > block->read_len) {
866       dev->dev_errno = EIO;
867       Mmsg4(dev->errmsg, _("Volume data error at %u:%u! Short block of %d bytes on device %s discarded.\n"), 
868          dev->file, dev->block_num, block->read_len, dev->dev_name);
869       Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
870       dev->state |= ST_SHORT;   /* set short block */
871       block->read_len = block->binbuf = 0;
872       return false;             /* return error */
873    }  
874
875    dev->state &= ~(ST_EOF|ST_SHORT); /* clear EOF and short block */
876    dev->VolCatInfo.VolCatReads++;   
877    dev->VolCatInfo.VolCatRBytes += block->read_len;
878
879    dev->VolCatInfo.VolCatBytes += block->block_len;
880    dev->VolCatInfo.VolCatBlocks++;   
881    dev->EndBlock = dev->block_num;
882    dev->EndFile  = dev->file;
883    dev->block_num++;
884
885    /* Update dcr values */
886    if (dev->state & ST_TAPE) {
887       dcr->EndBlock = dev->EndBlock;
888       dcr->EndFile  = dev->EndFile;
889    } else {
890       dcr->EndBlock = (uint32_t)dev->file_addr;
891       dcr->EndFile = (uint32_t)(dev->file_addr >> 32);
892       dev->block_num = dcr->EndBlock;
893       dev->file = dcr->EndFile;
894    }
895    dev->file_addr += block->block_len;
896    dev->file_size += block->block_len;
897
898    /*
899     * If we read a short block on disk,
900     * seek to beginning of next block. This saves us
901     * from shuffling blocks around in the buffer. Take a
902     * look at this from an efficiency stand point later, but
903     * it should only happen once at the end of each job.
904     *
905     * I've been lseek()ing negative relative to SEEK_CUR for 30
906     *   years now. However, it seems that with the new off_t definition,
907     *   it is not possible to seek negative amounts, so we use two
908     *   lseek(). One to get the position, then the second to do an
909     *   absolute positioning -- so much for efficiency.  KES Sep 02.
910     */
911    Dmsg0(200, "At end of read block\n");
912    if (block->read_len > block->block_len && !(dev->state & ST_TAPE)) {
913       off_t pos = lseek(dev->fd, (off_t)0, SEEK_CUR); /* get curr pos */
914       pos -= (block->read_len - block->block_len);
915       lseek(dev->fd, pos, SEEK_SET);   
916       Dmsg2(200, "Did lseek blk_size=%d rdlen=%d\n", block->block_len,
917             block->read_len);
918       dev->file_addr = pos;
919       dev->file_size = pos;
920    }
921    Dmsg2(200, "Exit read_block read_len=%d block_len=%d\n",
922       block->read_len, block->block_len);
923    block->block_read = true;
924    return true;
925 }