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