Ensure fsp->size is correct so readraw's return correct data.
[nivanova/samba-autobuild/.git] / source3 / smbd / fileio.c
1 /* 
2    Unix SMB/Netbios implementation.
3    Version 1.9.
4    read/write to a files_struct
5    Copyright (C) Andrew Tridgell 1992-1998
6    
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 */
21
22 #include "includes.h"
23
24 static BOOL setup_write_cache(files_struct *, SMB_OFF_T);
25
26 /****************************************************************************
27 seek a file. Try to avoid the seek if possible
28 ****************************************************************************/
29
30 SMB_OFF_T seek_file(files_struct *fsp,SMB_OFF_T pos)
31 {
32   SMB_OFF_T offset = 0;
33   SMB_OFF_T seek_ret;
34
35   if (fsp->print_file && lp_postscript(fsp->conn->service))
36     offset = 3;
37
38   seek_ret = fsp->conn->vfs_ops.lseek(fsp,fsp->fd,pos+offset,SEEK_SET);
39
40   /*
41    * We want to maintain the fiction that we can seek
42    * on a fifo for file system purposes. This allows 
43    * people to set up UNIX fifo's that feed data to Windows
44    * applications. JRA.
45    */
46
47   if((seek_ret == -1) && (errno == ESPIPE)) {
48     seek_ret = pos+offset;
49     errno = 0;
50   }
51
52   if((seek_ret == -1) || (seek_ret != pos+offset)) {
53     DEBUG(0,("seek_file: sys_lseek failed. Error was %s\n", strerror(errno) ));
54     fsp->pos = -1;
55     return -1;
56   }
57
58   fsp->pos = seek_ret - offset;
59
60   DEBUG(10,("seek_file: requested pos = %.0f, new pos = %.0f\n",
61         (double)(pos+offset), (double)fsp->pos ));
62
63   return(fsp->pos);
64 }
65
66 /****************************************************************************
67  Read from write cache if we can.
68 ****************************************************************************/
69
70
71 BOOL read_from_write_cache(files_struct *fsp,char *data,SMB_OFF_T pos,size_t n)
72 {
73   write_cache *wcp = fsp->wcp;
74
75   if(!wcp)
76     return False;
77
78   if(n > wcp->data_size || pos < wcp->offset || pos + n > wcp->offset + wcp->data_size)
79     return False;
80
81   memcpy(data, wcp->data + (pos - wcp->offset), n);
82
83   DO_PROFILE_INC(writecache_read_hits);
84
85   return True;
86 }
87
88 /****************************************************************************
89 read from a file
90 ****************************************************************************/
91
92 ssize_t read_file(files_struct *fsp,char *data,SMB_OFF_T pos,size_t n)
93 {
94         ssize_t ret=0,readret;
95
96         /* you can't read from print files */
97         if (fsp->print_file)
98                 return -1;
99
100         /*
101          * Serve from write cache if we can.
102          */
103
104         if(read_from_write_cache(fsp, data, pos, n))
105                 return n;
106
107         flush_write_cache(fsp, READ_FLUSH);
108
109         if (seek_file(fsp,pos) == -1) {
110                 DEBUG(3,("read_file: Failed to seek to %.0f\n",(double)pos));
111                 return(ret);
112         }
113   
114         if (n > 0) {
115 #ifdef DMF_FIX
116                 int numretries = 3;
117 tryagain:
118                 readret = fsp->conn->vfs_ops.read(fsp,fsp->fd,data,n);
119                 if (readret == -1) {
120                         if ((errno == EAGAIN) && numretries) {
121                                 DEBUG(3,("read_file EAGAIN retry in 10 seconds\n"));
122                                 (void)sleep(10);
123                                 --numretries;
124                                 goto tryagain;
125                         }
126                         return -1;
127                 }
128 #else /* NO DMF fix. */
129                 readret = fsp->conn->vfs_ops.read(fsp,fsp->fd,data,n);
130                 if (readret == -1)
131                         return -1;
132 #endif
133                 if (readret > 0)
134                         ret += readret;
135         }
136
137         return(ret);
138 }
139
140 /* how many write cache buffers have been allocated */
141 static unsigned int allocated_write_caches;
142
143 /****************************************************************************
144  *Really* write to a file.
145 ****************************************************************************/
146
147 static ssize_t real_write_file(files_struct *fsp,char *data,SMB_OFF_T pos, size_t n)
148 {
149   if ((pos != -1) && (seek_file(fsp,pos) == -1))
150     return -1;
151
152   return vfs_write_data(fsp,data,n);
153 }
154
155 /****************************************************************************
156 write to a file
157 ****************************************************************************/
158
159 ssize_t write_file(files_struct *fsp, char *data, SMB_OFF_T pos, size_t n)
160 {
161   write_cache *wcp = fsp->wcp;
162   ssize_t total_written = 0;
163   int write_path = -1; 
164
165   if (fsp->print_file) {
166           return print_job_write(fsp->print_jobid, data, n);
167   }
168
169   if (!fsp->can_write) {
170     errno = EPERM;
171     return(0);
172   }
173
174   if (!fsp->modified) {
175     SMB_STRUCT_STAT st;
176     fsp->modified = True;
177
178     if (fsp->conn->vfs_ops.fstat(fsp,fsp->fd,&st) == 0) {
179       int dosmode = dos_mode(fsp->conn,fsp->fsp_name,&st);
180       fsp->size = st.st_size;
181       if (MAP_ARCHIVE(fsp->conn) && !IS_DOS_ARCHIVE(dosmode)) { 
182         file_chmod(fsp->conn,fsp->fsp_name,dosmode | aARCH,&st);
183       }
184
185       /*
186        * If this is the first write and we have an exclusive oplock then setup
187        * the write cache.
188        */
189
190       if (EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type) && !wcp) {
191         setup_write_cache(fsp, st.st_size);
192         wcp = fsp->wcp;
193       } 
194     }  
195   }
196
197 #ifdef WITH_PROFILE
198   DO_PROFILE_INC(writecache_total_writes);
199   if (!fsp->oplock_type) {
200     DO_PROFILE_INC(writecache_non_oplock_writes);
201   }
202 #endif
203
204   /*
205    * If this file is level II oplocked then we need
206    * to grab the shared memory lock and inform all
207    * other files with a level II lock that they need
208    * to flush their read caches. We keep the lock over
209    * the shared memory area whilst doing this.
210    */
211
212   release_level_2_oplocks_on_change(fsp);
213
214 #ifdef WITH_PROFILE
215   if (profile_p && profile_p->writecache_total_writes % 500 == 0) {
216     DEBUG(3,("WRITECACHE: initwrites=%u abutted=%u total=%u \
217 nonop=%u allocated=%u active=%u direct=%u perfect=%u readhits=%u\n",
218         profile_p->writecache_init_writes,
219         profile_p->writecache_abutted_writes,
220         profile_p->writecache_total_writes,
221         profile_p->writecache_non_oplock_writes,
222         profile_p->writecache_allocated_write_caches,
223         profile_p->writecache_num_write_caches,
224         profile_p->writecache_direct_writes,
225         profile_p->writecache_num_perfect_writes,
226         profile_p->writecache_read_hits ));
227
228     DEBUG(3,("WRITECACHE: Flushes SEEK=%d, READ=%d, WRITE=%d, READRAW=%d, OPLOCK=%d, CLOSE=%d, SYNC=%d\n",
229         profile_p->writecache_flushed_writes[SEEK_FLUSH],
230         profile_p->writecache_flushed_writes[READ_FLUSH],
231         profile_p->writecache_flushed_writes[WRITE_FLUSH],
232         profile_p->writecache_flushed_writes[READRAW_FLUSH],
233         profile_p->writecache_flushed_writes[OPLOCK_RELEASE_FLUSH],
234         profile_p->writecache_flushed_writes[CLOSE_FLUSH],
235         profile_p->writecache_flushed_writes[SYNC_FLUSH] ));
236   }
237 #endif
238
239   if(!wcp) {
240     DO_PROFILE_INC(writecache_direct_writes);
241     total_written = real_write_file(fsp, data, pos, n);
242     if ((total_written != -1) && (pos + total_written > fsp->size))
243       fsp->size = pos + total_written;
244     return total_written;
245   }
246
247   DEBUG(9,("write_file(fd=%d pos=%.0f size=%u) wcp->offset=%.0f wcp->data_size=%u\n",
248            fsp->fd, (double)pos, (unsigned int)n, (double)wcp->offset, (unsigned int)wcp->data_size));
249
250   /* 
251    * If we have active cache and it isn't contiguous then we flush.
252    * NOTE: There is a small problem with running out of disk ....
253    */
254
255   if (wcp->data_size) {
256
257     BOOL cache_flush_needed = False;
258
259     if ((pos >= wcp->offset) && (pos <= wcp->offset + wcp->data_size)) {
260       
261       /*
262        * Start of write overlaps or abutts the existing data.
263        */
264
265       size_t data_used = MIN((wcp->alloc_size - (pos - wcp->offset)), n);
266
267       memcpy(wcp->data + (pos - wcp->offset), data, data_used);
268
269       /*
270        * Update the current buffer size with the new data.
271        */
272
273       if(pos + data_used > wcp->offset + wcp->data_size)
274         wcp->data_size = pos + data_used - wcp->offset;
275
276       /*
277        * Update the file size if changed.
278        */
279
280       if (wcp->offset + wcp->data_size > wcp->file_size)
281         fsp->size = wcp->file_size = wcp->offset + wcp->data_size;
282
283       /*
284        * If we used all the data then
285        * return here.
286        */
287
288       if(n == data_used)
289         return n;
290       else
291         cache_flush_needed = True;
292
293       /*
294        * Move the start of data forward by the amount used,
295        * cut down the amount left by the same amount.
296        */
297
298       data += data_used;
299       pos += data_used;
300       n -= data_used;
301
302       DO_PROFILE_INC(writecache_abutted_writes);
303       total_written = data_used;
304
305       write_path = 1;
306
307     } else if ((pos < wcp->offset) && (pos + n > wcp->offset) && 
308                (pos + n <= wcp->offset + wcp->alloc_size)) {
309
310       /*
311        * End of write overlaps the existing data.
312        */
313
314       size_t data_used = pos + n - wcp->offset;
315
316       memcpy(wcp->data, data + n - data_used, data_used);
317
318       /*
319        * Update the current buffer size with the new data.
320        */
321
322       if(pos + n > wcp->offset + wcp->data_size)
323         wcp->data_size = pos + n - wcp->offset;
324
325       /*
326        * Update the file size if changed.
327        */
328
329       if (wcp->offset + wcp->data_size > wcp->file_size)
330         fsp->size = wcp->file_size = wcp->offset + wcp->data_size;
331
332       /*
333        * We don't need to move the start of data, but we
334        * cut down the amount left by the amount used.
335        */
336
337       n -= data_used;
338
339       /*
340        * We cannot have used all the data here.
341        */
342
343       cache_flush_needed = True;
344
345       DO_PROFILE_INC(writecache_abutted_writes);
346       total_written = data_used;
347
348       write_path = 2;
349
350     } else if ( (pos >= wcp->file_size) && 
351                 (wcp->offset + wcp->data_size == wcp->file_size) &&
352                 (pos > wcp->offset + wcp->data_size) && 
353                 (pos < wcp->offset + wcp->alloc_size) ) {
354
355       /*
356        * Non-contiguous write part of which fits within
357        * the cache buffer and is extending the file
358        * and the cache contents reflect the current
359        * data up to the current end of the file.
360        */
361
362       size_t data_used;
363
364       if(pos + n <= wcp->offset + wcp->alloc_size)
365         data_used = n;
366       else
367         data_used = wcp->offset + wcp->alloc_size - pos;
368
369       /*
370        * Fill in the non-continuous area with zeros.
371        */
372
373       memset(wcp->data + wcp->data_size, '\0',
374              pos - (wcp->offset + wcp->data_size) );
375
376       memcpy(wcp->data + (pos - wcp->offset), data, data_used);
377
378       /*
379        * Update the current buffer size with the new data.
380        */
381
382       if(pos + data_used > wcp->offset + wcp->data_size)
383         wcp->data_size = pos + data_used - wcp->offset;
384
385       /*
386        * Update the file size if changed.
387        */
388
389       if (wcp->offset + wcp->data_size > wcp->file_size)
390         fsp->size = wcp->file_size = wcp->offset + wcp->data_size;
391
392       /*
393        * If we used all the data then
394        * return here.
395        */
396
397       if(n == data_used)
398         return n;
399       else
400         cache_flush_needed = True;
401
402       /*
403        * Move the start of data forward by the amount used,
404        * cut down the amount left by the same amount.
405        */
406
407       data += data_used;
408       pos += data_used;
409       n -= data_used;
410
411       DO_PROFILE_INC(writecache_abutted_writes);
412       total_written = data_used;
413
414       write_path = 3;
415
416     } else {
417
418       /*
419        * Write is bigger than buffer, or there is no overlap on the
420        * low or high ends.
421        */
422
423       DEBUG(9,("write_file: non cacheable write : fd = %d, pos = %.0f, len = %u, current cache pos = %.0f \
424 len = %u\n",fsp->fd, (double)pos, (unsigned int)n, (double)wcp->offset, (unsigned int)wcp->data_size ));
425
426       /*
427        * Update the file size if needed.
428        */
429
430       if(pos + n > wcp->file_size)
431         fsp->size = wcp->file_size = pos + n;
432
433       /*
434        * If write would fit in the cache, and is larger than
435        * the data already in the cache, flush the cache and
436        * preferentially copy the data new data into it. Otherwise
437        * just write the data directly.
438        */
439
440       if ( n <= wcp->alloc_size && n > wcp->data_size) {
441         cache_flush_needed = True;
442       } else {
443         ssize_t ret = real_write_file(fsp, data, pos, n);
444
445         DO_PROFILE_INC(writecache_direct_writes);
446         if (ret == -1)
447           return ret;
448
449         if (pos + ret > wcp->file_size)
450           fsp->size = wcp->file_size = pos + ret;
451
452         return ret;
453       }
454
455       write_path = 4;
456
457     }
458
459     if(wcp->data_size > wcp->file_size)
460       fsp->size = wcp->file_size = wcp->data_size;
461
462     if (cache_flush_needed) {
463       DEBUG(3,("WRITE_FLUSH:%d: due to noncontinuous write: fd = %d, size = %.0f, pos = %.0f, \
464 n = %u, wcp->offset=%.0f, wcp->data_size=%u\n",
465              write_path, fsp->fd, (double)wcp->file_size, (double)pos, (unsigned int)n,
466              (double)wcp->offset, (unsigned int)wcp->data_size ));
467
468       flush_write_cache(fsp, WRITE_FLUSH);
469     }
470   }
471
472   /*
473    * If the write request is bigger than the cache
474    * size, write it all out.
475    */
476
477   if (n > wcp->alloc_size ) {
478     ssize_t ret = real_write_file(fsp, data, pos, n);
479     if (ret == -1)
480       return -1;
481
482     if (pos + ret > wcp->file_size)
483       fsp->size = wcp->file_size = pos + n;
484
485     DO_PROFILE_INC(writecache_direct_writes);
486     return total_written + n;
487   }
488
489   /*
490    * If there's any data left, cache it.
491    */
492
493   if (n) {
494 #ifdef WITH_PROFILE
495     if (wcp->data_size) {
496       DO_PROFILE_INC(writecache_abutted_writes);
497     } else {
498       DO_PROFILE_INC(writecache_init_writes);
499     }
500 #endif
501     memcpy(wcp->data+wcp->data_size, data, n);
502     if (wcp->data_size == 0) {
503       wcp->offset = pos;
504       DO_PROFILE_INC(writecache_num_write_caches);
505     }
506     wcp->data_size += n;
507
508     /*
509      * Update the file size if changed.
510      */
511
512     if (wcp->offset + wcp->data_size > wcp->file_size)
513       fsp->size = wcp->file_size = wcp->offset + wcp->data_size;
514     DEBUG(9,("wcp->offset = %.0f wcp->data_size = %u cache return %u\n",
515                 (double)wcp->offset, (unsigned int)wcp->data_size, (unsigned int)n));
516
517     total_written += n;
518     return total_written; /* .... that's a write :) */
519   }
520   
521   return total_written;
522 }
523
524 /****************************************************************************
525  Delete the write cache structure.
526 ****************************************************************************/
527
528 void delete_write_cache(files_struct *fsp)
529 {
530   write_cache *wcp;
531
532   if(!fsp)
533     return;
534
535   if(!(wcp = fsp->wcp))
536     return;
537
538   DO_PROFILE_DEC(writecache_allocated_write_caches);
539   allocated_write_caches--;
540
541   SMB_ASSERT(wcp->data_size == 0);
542
543   SAFE_FREE(wcp->data);
544   SAFE_FREE(fsp->wcp);
545
546   DEBUG(10,("delete_write_cache: File %s deleted write cache\n", fsp->fsp_name ));
547
548 }
549
550 /****************************************************************************
551  Setup the write cache structure.
552 ****************************************************************************/
553
554 static BOOL setup_write_cache(files_struct *fsp, SMB_OFF_T file_size)
555 {
556   ssize_t alloc_size = lp_write_cache_size(SNUM(fsp->conn));
557   write_cache *wcp;
558
559   if (allocated_write_caches >= MAX_WRITE_CACHES) 
560         return False;
561
562   if(alloc_size == 0 || fsp->wcp)
563     return False;
564
565   if((wcp = (write_cache *)malloc(sizeof(write_cache))) == NULL) {
566     DEBUG(0,("setup_write_cache: malloc fail.\n"));
567     return False;
568   }
569
570   wcp->file_size = file_size;
571   wcp->offset = 0;
572   wcp->alloc_size = alloc_size;
573   wcp->data_size = 0;
574   if((wcp->data = malloc(wcp->alloc_size)) == NULL) {
575     DEBUG(0,("setup_write_cache: malloc fail for buffer size %u.\n",
576           (unsigned int)wcp->alloc_size ));
577     SAFE_FREE(wcp);
578     return False;
579   }
580
581   memset(wcp->data, '\0', wcp->alloc_size );
582
583   fsp->wcp = wcp;
584   DO_PROFILE_INC(writecache_allocated_write_caches);
585   allocated_write_caches++;
586
587   DEBUG(10,("setup_write_cache: File %s allocated write cache size %u\n",
588                 fsp->fsp_name, wcp->alloc_size ));
589
590   return True;
591 }
592
593 /****************************************************************************
594  Cope with a size change.
595 ****************************************************************************/
596
597 void set_filelen_write_cache(files_struct *fsp, SMB_OFF_T file_size)
598 {
599   fsp->size = file_size;
600   if(fsp->wcp) {
601     /* The cache *must* have been flushed before we do this. */
602     if (fsp->wcp->data_size != 0) {
603       pstring msg;
604       slprintf(msg, sizeof(msg)-1, "set_filelen_write_cache: size change \
605 on file %s with write cache size = %u\n", fsp->fsp_name, fsp->wcp->data_size );
606       smb_panic(msg);
607     }
608     fsp->wcp->file_size = file_size;
609   }
610 }
611
612 /*******************************************************************
613  Flush a write cache struct to disk.
614 ********************************************************************/
615
616 ssize_t flush_write_cache(files_struct *fsp, enum flush_reason_enum reason)
617 {
618   write_cache *wcp = fsp->wcp;
619   size_t data_size;
620   ssize_t ret;
621
622   if(!wcp || !wcp->data_size)
623     return 0;
624
625   data_size = wcp->data_size;
626   wcp->data_size = 0;
627
628   DO_PROFILE_DEC_INC(writecache_num_write_caches,writecache_flushed_writes[reason]);
629
630   DEBUG(9,("flushing write cache: fd = %d, off=%.0f, size=%u\n",
631            fsp->fd, (double)wcp->offset, (unsigned int)data_size));
632
633 #ifdef WITH_PROFILE
634   if(data_size == wcp->alloc_size)
635     DO_PROFILE_INC(writecache_num_perfect_writes);
636 #endif
637
638   ret = real_write_file(fsp, wcp->data, wcp->offset, data_size);
639
640   /*
641    * Ensure file size if kept up to date if write extends file.
642    */
643
644   if ((ret != -1) && (wcp->offset + ret > wcp->file_size))
645     wcp->file_size = wcp->offset + ret;
646
647   return ret;
648 }
649
650 /*******************************************************************
651 sync a file
652 ********************************************************************/
653
654 void sync_file(connection_struct *conn, files_struct *fsp)
655 {
656     if(lp_strict_sync(SNUM(conn)) && fsp->fd != -1) {
657       flush_write_cache(fsp, SYNC_FLUSH);
658       conn->vfs_ops.fsync(fsp,fsp->fd);
659     }
660 }