Remove reply_unixerror() - no longer needed. Should make Metze's refactoring a lot...
[samba.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    Copyright (C) Jeremy Allison 2000-2002. - write cache.
7    
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12    
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17    
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include "includes.h"
23 #include "smbd/globals.h"
24
25 static bool setup_write_cache(files_struct *, SMB_OFF_T);
26
27 /****************************************************************************
28  Read from write cache if we can.
29 ****************************************************************************/
30
31 static bool read_from_write_cache(files_struct *fsp,char *data,SMB_OFF_T pos,size_t n)
32 {
33         write_cache *wcp = fsp->wcp;
34
35         if(!wcp) {
36                 return False;
37         }
38
39         if( n > wcp->data_size || pos < wcp->offset || pos + n > wcp->offset + wcp->data_size) {
40                 return False;
41         }
42
43         memcpy(data, wcp->data + (pos - wcp->offset), n);
44
45         DO_PROFILE_INC(writecache_read_hits);
46
47         return True;
48 }
49
50 /****************************************************************************
51  Read from a file.
52 ****************************************************************************/
53
54 ssize_t read_file(files_struct *fsp,char *data,SMB_OFF_T pos,size_t n)
55 {
56         ssize_t ret=0,readret;
57
58         /* you can't read from print files */
59         if (fsp->print_file) {
60                 errno = EBADF;
61                 return -1;
62         }
63
64         /*
65          * Serve from write cache if we can.
66          */
67
68         if(read_from_write_cache(fsp, data, pos, n)) {
69                 fsp->fh->pos = pos + n;
70                 fsp->fh->position_information = fsp->fh->pos;
71                 return n;
72         }
73
74         flush_write_cache(fsp, READ_FLUSH);
75
76         fsp->fh->pos = pos;
77
78         if (n > 0) {
79 #ifdef DMF_FIX
80                 int numretries = 3;
81 tryagain:
82                 readret = SMB_VFS_PREAD(fsp,data,n,pos);
83
84                 if (readret == -1) {
85                         if ((errno == EAGAIN) && numretries) {
86                                 DEBUG(3,("read_file EAGAIN retry in 10 seconds\n"));
87                                 (void)sleep(10);
88                                 --numretries;
89                                 goto tryagain;
90                         }
91                         return -1;
92                 }
93 #else /* NO DMF fix. */
94                 readret = SMB_VFS_PREAD(fsp,data,n,pos);
95
96                 if (readret == -1) {
97                         return -1;
98                 }
99 #endif
100                 if (readret > 0) {
101                         ret += readret;
102                 }
103         }
104
105         DEBUG(10,("read_file (%s): pos = %.0f, size = %lu, returned %lu\n",
106                 fsp->fsp_name, (double)pos, (unsigned long)n, (long)ret ));
107
108         fsp->fh->pos += ret;
109         fsp->fh->position_information = fsp->fh->pos;
110
111         return(ret);
112 }
113
114 /****************************************************************************
115  *Really* write to a file.
116 ****************************************************************************/
117
118 static ssize_t real_write_file(struct smb_request *req,
119                                 files_struct *fsp,
120                                 const char *data,
121                                 SMB_OFF_T pos,
122                                 size_t n)
123 {
124         ssize_t ret;
125
126         if (pos == -1) {
127                 ret = vfs_write_data(req, fsp, data, n);
128         } else {
129                 fsp->fh->pos = pos;
130                 if (pos && lp_strict_allocate(SNUM(fsp->conn))) {
131                         if (vfs_fill_sparse(fsp, pos) == -1) {
132                                 return -1;
133                         }
134                 }
135                 ret = vfs_pwrite_data(req, fsp, data, n, pos);
136         }
137
138         DEBUG(10,("real_write_file (%s): pos = %.0f, size = %lu, returned %ld\n",
139                 fsp->fsp_name, (double)pos, (unsigned long)n, (long)ret ));
140
141         if (ret != -1) {
142                 fsp->fh->pos += ret;
143
144 /* Yes - this is correct - writes don't update this. JRA. */
145 /* Found by Samba4 tests. */
146 #if 0
147                 fsp->position_information = fsp->pos;
148 #endif
149         }
150
151         return ret;
152 }
153
154 /****************************************************************************
155  File size cache change.
156  Updates size on disk but doesn't flush the cache.
157 ****************************************************************************/
158
159 static int wcp_file_size_change(files_struct *fsp)
160 {
161         int ret;
162         write_cache *wcp = fsp->wcp;
163
164         wcp->file_size = wcp->offset + wcp->data_size;
165         ret = SMB_VFS_FTRUNCATE(fsp, wcp->file_size);
166         if (ret == -1) {
167                 DEBUG(0,("wcp_file_size_change (%s): ftruncate of size %.0f error %s\n",
168                         fsp->fsp_name, (double)wcp->file_size, strerror(errno) ));
169         }
170         return ret;
171 }
172
173 static void update_write_time_handler(struct event_context *ctx,
174                                       struct timed_event *te,
175                                       struct timeval now,
176                                       void *private_data)
177 {
178         files_struct *fsp = (files_struct *)private_data;
179
180         /* Remove the timed event handler. */
181         TALLOC_FREE(fsp->update_write_time_event);
182         DEBUG(5, ("Update write time on %s\n", fsp->fsp_name));
183
184         /* change the write time if not already changed by someone else */
185         update_write_time(fsp);
186 }
187
188 /*********************************************************
189  Schedule a write time update for WRITE_TIME_UPDATE_USEC_DELAY
190  in the future.
191 *********************************************************/
192
193 void trigger_write_time_update(struct files_struct *fsp)
194 {
195         int delay;
196
197         if (fsp->posix_open) {
198                 /* Don't use delayed writes on POSIX files. */
199                 return;
200         }
201
202         if (fsp->write_time_forced) {
203                 /* No point - "sticky" write times
204                  * in effect.
205                  */
206                 return;
207         }
208
209         if (fsp->update_write_time_triggered) {
210                 /*
211                  * We only update the write time
212                  * on the first write. After that
213                  * no other writes affect this.
214                  */
215                 return;
216         }
217         fsp->update_write_time_triggered = true;
218
219         delay = lp_parm_int(SNUM(fsp->conn),
220                             "smbd", "writetimeupdatedelay",
221                             WRITE_TIME_UPDATE_USEC_DELAY);
222
223         /* trigger the update 2 seconds later */
224         fsp->update_write_time_on_close = true;
225         fsp->update_write_time_event =
226                 event_add_timed(smbd_event_context(), NULL,
227                                 timeval_current_ofs(0, delay),
228                                 update_write_time_handler, fsp);
229 }
230
231 void trigger_write_time_update_immediate(struct files_struct *fsp)
232 {
233         if (fsp->posix_open) {
234                 /* Don't use delayed writes on POSIX files. */
235                 return;
236         }
237
238         if (fsp->write_time_forced) {
239                 /*
240                  * No point - "sticky" write times
241                  * in effect.
242                  */
243                 return;
244         }
245
246         TALLOC_FREE(fsp->update_write_time_event);
247         DEBUG(5, ("Update write time immediate on %s\n", fsp->fsp_name));
248
249         fsp->update_write_time_triggered = true;
250
251         fsp->update_write_time_on_close = false;
252         update_write_time(fsp);
253 }
254
255 /****************************************************************************
256  Write to a file.
257 ****************************************************************************/
258
259 ssize_t write_file(struct smb_request *req,
260                         files_struct *fsp,
261                         const char *data,
262                         SMB_OFF_T pos,
263                         size_t n)
264 {
265         write_cache *wcp = fsp->wcp;
266         ssize_t total_written = 0;
267         int write_path = -1;
268
269         if (fsp->print_file) {
270                 uint32 jobid;
271
272                 if (!rap_to_pjobid(fsp->rap_print_jobid, NULL, &jobid)) {
273                         DEBUG(3,("write_file: Unable to map RAP jobid %u to jobid.\n",
274                                                 (unsigned int)fsp->rap_print_jobid ));
275                         errno = EBADF;
276                         return -1;
277                 }
278
279                 return print_job_write(SNUM(fsp->conn), jobid, data, pos, n);
280         }
281
282         if (!fsp->can_write) {
283                 errno = EPERM;
284                 return -1;
285         }
286
287         if (!fsp->modified) {
288                 struct smb_filename *smb_fname = NULL;
289                 NTSTATUS status;
290
291                 fsp->modified = True;
292
293                 status = create_synthetic_smb_fname_split(talloc_tos(),
294                                                           fsp->fsp_name, NULL,
295                                                           &smb_fname);
296                 if (!NT_STATUS_IS_OK(status)) {
297                         errno = map_errno_from_nt_status(status);
298                         return -1;
299                 }
300
301                 if (SMB_VFS_FSTAT(fsp, &smb_fname->st) == 0) {
302                         int dosmode;
303                         trigger_write_time_update(fsp);
304                         dosmode = dos_mode(fsp->conn, smb_fname);
305                         if ((lp_store_dos_attributes(SNUM(fsp->conn)) ||
306                                         MAP_ARCHIVE(fsp->conn)) &&
307                                         !IS_DOS_ARCHIVE(dosmode)) {
308                                 file_set_dosmode(fsp->conn, smb_fname,
309                                                 dosmode | aARCH, NULL, false);
310                         }
311
312                         /*
313                          * If this is the first write and we have an exclusive oplock then setup
314                          * the write cache.
315                          */
316
317                         if (EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type) && !wcp) {
318                                 setup_write_cache(fsp,
319                                                   smb_fname->st.st_ex_size);
320                                 wcp = fsp->wcp;
321                         }
322                 }
323                 TALLOC_FREE(smb_fname);
324         }
325
326 #ifdef WITH_PROFILE
327         DO_PROFILE_INC(writecache_total_writes);
328         if (!fsp->oplock_type) {
329                 DO_PROFILE_INC(writecache_non_oplock_writes);
330         }
331 #endif
332
333         /*
334          * If this file is level II oplocked then we need
335          * to grab the shared memory lock and inform all
336          * other files with a level II lock that they need
337          * to flush their read caches. We keep the lock over
338          * the shared memory area whilst doing this.
339          */
340
341         /* This should actually be improved to span the write. */
342         contend_level2_oplocks_begin(fsp, LEVEL2_CONTEND_WRITE);
343         contend_level2_oplocks_end(fsp, LEVEL2_CONTEND_WRITE);
344
345 #ifdef WITH_PROFILE
346         if (profile_p && profile_p->writecache_total_writes % 500 == 0) {
347                 DEBUG(3,("WRITECACHE: initwrites=%u abutted=%u total=%u \
348 nonop=%u allocated=%u active=%u direct=%u perfect=%u readhits=%u\n",
349                         profile_p->writecache_init_writes,
350                         profile_p->writecache_abutted_writes,
351                         profile_p->writecache_total_writes,
352                         profile_p->writecache_non_oplock_writes,
353                         profile_p->writecache_allocated_write_caches,
354                         profile_p->writecache_num_write_caches,
355                         profile_p->writecache_direct_writes,
356                         profile_p->writecache_num_perfect_writes,
357                         profile_p->writecache_read_hits ));
358
359                 DEBUG(3,("WRITECACHE: Flushes SEEK=%d, READ=%d, WRITE=%d, READRAW=%d, OPLOCK=%d, CLOSE=%d, SYNC=%d\n",
360                         profile_p->writecache_flushed_writes[SEEK_FLUSH],
361                         profile_p->writecache_flushed_writes[READ_FLUSH],
362                         profile_p->writecache_flushed_writes[WRITE_FLUSH],
363                         profile_p->writecache_flushed_writes[READRAW_FLUSH],
364                         profile_p->writecache_flushed_writes[OPLOCK_RELEASE_FLUSH],
365                         profile_p->writecache_flushed_writes[CLOSE_FLUSH],
366                         profile_p->writecache_flushed_writes[SYNC_FLUSH] ));
367         }
368 #endif
369
370         if (wcp && req->unread_bytes) {
371                 /* If we're using receivefile don't
372                  * deal with a write cache.
373                  */
374                 flush_write_cache(fsp, WRITE_FLUSH);
375                 delete_write_cache(fsp);
376                 wcp = NULL;
377         }
378
379         if(!wcp) {
380                 DO_PROFILE_INC(writecache_direct_writes);
381                 total_written = real_write_file(req, fsp, data, pos, n);
382                 return total_written;
383         }
384
385         DEBUG(9,("write_file (%s)(fd=%d pos=%.0f size=%u) wcp->offset=%.0f wcp->data_size=%u\n",
386                 fsp->fsp_name, fsp->fh->fd, (double)pos, (unsigned int)n, (double)wcp->offset, (unsigned int)wcp->data_size));
387
388         fsp->fh->pos = pos + n;
389
390         /*
391          * If we have active cache and it isn't contiguous then we flush.
392          * NOTE: There is a small problem with running out of disk ....
393          */
394
395         if (wcp->data_size) {
396                 bool cache_flush_needed = False;
397
398                 if ((pos >= wcp->offset) && (pos <= wcp->offset + wcp->data_size)) {
399       
400                         /* ASCII art.... JRA.
401
402       +--------------+-----
403       | Cached data  | Rest of allocated cache buffer....
404       +--------------+-----
405
406             +-------------------+
407             | Data to write     |
408             +-------------------+
409
410                         */
411
412                         /*
413                          * Start of write overlaps or abutts the existing data.
414                          */
415
416                         size_t data_used = MIN((wcp->alloc_size - (pos - wcp->offset)), n);
417
418                         memcpy(wcp->data + (pos - wcp->offset), data, data_used);
419
420                         /*
421                          * Update the current buffer size with the new data.
422                          */
423
424                         if(pos + data_used > wcp->offset + wcp->data_size) {
425                                 wcp->data_size = pos + data_used - wcp->offset;
426                         }
427
428                         /*
429                          * Update the file size if changed.
430                          */
431
432                         if (wcp->offset + wcp->data_size > wcp->file_size) {
433                                 if (wcp_file_size_change(fsp) == -1) {
434                                         return -1;
435                                 }
436                         }
437
438                         /*
439                          * If we used all the data then
440                          * return here.
441                          */
442
443                         if(n == data_used) {
444                                 return n;
445                         } else {
446                                 cache_flush_needed = True;
447                         }
448                         /*
449                          * Move the start of data forward by the amount used,
450                          * cut down the amount left by the same amount.
451                          */
452
453                         data += data_used;
454                         pos += data_used;
455                         n -= data_used;
456
457                         DO_PROFILE_INC(writecache_abutted_writes);
458                         total_written = data_used;
459
460                         write_path = 1;
461
462                 } else if ((pos < wcp->offset) && (pos + n > wcp->offset) && 
463                                         (pos + n <= wcp->offset + wcp->alloc_size)) {
464
465                         /* ASCII art.... JRA.
466
467                         +---------------+
468                         | Cache buffer  |
469                         +---------------+
470
471             +-------------------+
472             | Data to write     |
473             +-------------------+
474
475                         */
476
477                         /*
478                          * End of write overlaps the existing data.
479                          */
480
481                         size_t data_used = pos + n - wcp->offset;
482
483                         memcpy(wcp->data, data + n - data_used, data_used);
484
485                         /*
486                          * Update the current buffer size with the new data.
487                          */
488
489                         if(pos + n > wcp->offset + wcp->data_size) {
490                                 wcp->data_size = pos + n - wcp->offset;
491                         }
492
493                         /*
494                          * Update the file size if changed.
495                          */
496
497                         if (wcp->offset + wcp->data_size > wcp->file_size) {
498                                 if (wcp_file_size_change(fsp) == -1) {
499                                         return -1;
500                                 }
501                         }
502
503                         /*
504                          * We don't need to move the start of data, but we
505                          * cut down the amount left by the amount used.
506                          */
507
508                         n -= data_used;
509
510                         /*
511                          * We cannot have used all the data here.
512                          */
513
514                         cache_flush_needed = True;
515
516                         DO_PROFILE_INC(writecache_abutted_writes);
517                         total_written = data_used;
518
519                         write_path = 2;
520
521                 } else if ( (pos >= wcp->file_size) && 
522                                         (wcp->offset + wcp->data_size == wcp->file_size) &&
523                                         (pos > wcp->offset + wcp->data_size) && 
524                                         (pos < wcp->offset + wcp->alloc_size) ) {
525
526                         /* ASCII art.... JRA.
527
528                        End of file ---->|
529
530                         +---------------+---------------+
531                         | Cached data   | Cache buffer  |
532                         +---------------+---------------+
533
534                                               +-------------------+
535                                               | Data to write     |
536                                               +-------------------+
537
538                         */
539
540                         /*
541                          * Non-contiguous write part of which fits within
542                          * the cache buffer and is extending the file
543                          * and the cache contents reflect the current
544                          * data up to the current end of the file.
545                          */
546
547                         size_t data_used;
548
549                         if(pos + n <= wcp->offset + wcp->alloc_size) {
550                                 data_used = n;
551                         } else {
552                                 data_used = wcp->offset + wcp->alloc_size - pos;
553                         }
554
555                         /*
556                          * Fill in the non-continuous area with zeros.
557                          */
558
559                         memset(wcp->data + wcp->data_size, '\0',
560                                 pos - (wcp->offset + wcp->data_size) );
561
562                         memcpy(wcp->data + (pos - wcp->offset), data, data_used);
563
564                         /*
565                          * Update the current buffer size with the new data.
566                          */
567
568                         if(pos + data_used > wcp->offset + wcp->data_size) {
569                                 wcp->data_size = pos + data_used - wcp->offset;
570                         }
571
572                         /*
573                          * Update the file size if changed.
574                          */
575
576                         if (wcp->offset + wcp->data_size > wcp->file_size) {
577                                 if (wcp_file_size_change(fsp) == -1) {
578                                         return -1;
579                                 }
580                         }
581
582                         /*
583                          * If we used all the data then
584                          * return here.
585                          */
586
587                         if(n == data_used) {
588                                 return n;
589                         } else {
590                                 cache_flush_needed = True;
591                         }
592
593                         /*
594                          * Move the start of data forward by the amount used,
595                          * cut down the amount left by the same amount.
596                          */
597
598                         data += data_used;
599                         pos += data_used;
600                         n -= data_used;
601
602                         DO_PROFILE_INC(writecache_abutted_writes);
603                         total_written = data_used;
604
605                         write_path = 3;
606
607                 } else if ( (pos >= wcp->file_size) &&
608                             (n == 1) &&
609                             (wcp->file_size == wcp->offset + wcp->data_size) &&
610                             (pos < wcp->file_size + wcp->alloc_size)) {
611
612                         /*
613
614                 End of file ---->|
615
616                  +---------------+---------------+
617                  | Cached data   | Cache buffer  |
618                  +---------------+---------------+
619
620                                  |<------- allocated size ---------------->|
621
622                                                          +--------+
623                                                          | 1 Byte |
624                                                          +--------+
625
626                         MS-Office seems to do this a lot to determine if there's enough
627                         space on the filesystem to write a new file.
628
629                         Change to :
630
631                 End of file ---->|
632                                  +-----------------------+--------+
633                                  | Zeroed Cached data    | 1 Byte |
634                                  +-----------------------+--------+
635                         */
636
637                         flush_write_cache(fsp, WRITE_FLUSH);
638                         wcp->offset = wcp->file_size;
639                         wcp->data_size = pos - wcp->file_size + 1;
640                         memset(wcp->data, '\0', wcp->data_size);
641                         memcpy(wcp->data + wcp->data_size-1, data, 1);
642
643                         /*
644                          * Update the file size if changed.
645                          */
646
647                         if (wcp->offset + wcp->data_size > wcp->file_size) {
648                                 if (wcp_file_size_change(fsp) == -1) {
649                                         return -1;
650                                 }
651                         }
652
653                         return n;
654
655                 } else {
656
657                         /* ASCII art..... JRA.
658
659    Case 1).
660
661                         +---------------+---------------+
662                         | Cached data   | Cache buffer  |
663                         +---------------+---------------+
664
665                                                               +-------------------+
666                                                               | Data to write     |
667                                                               +-------------------+
668
669    Case 2).
670
671                            +---------------+---------------+
672                            | Cached data   | Cache buffer  |
673                            +---------------+---------------+
674
675    +-------------------+
676    | Data to write     |
677    +-------------------+
678
679     Case 3).
680
681                            +---------------+---------------+
682                            | Cached data   | Cache buffer  |
683                            +---------------+---------------+
684
685                   +-----------------------------------------------------+
686                   | Data to write                                       |
687                   +-----------------------------------------------------+
688
689                   */
690
691                         /*
692                          * Write is bigger than buffer, or there is no overlap on the
693                          * low or high ends.
694                          */
695
696                         DEBUG(9,("write_file: non cacheable write : fd = %d, pos = %.0f, len = %u, current cache pos = %.0f \
697 len = %u\n",fsp->fh->fd, (double)pos, (unsigned int)n, (double)wcp->offset, (unsigned int)wcp->data_size ));
698
699                         /*
700                          * If write would fit in the cache, and is larger than
701                          * the data already in the cache, flush the cache and
702                          * preferentially copy the data new data into it. Otherwise
703                          * just write the data directly.
704                          */
705
706                         if ( n <= wcp->alloc_size && n > wcp->data_size) {
707                                 cache_flush_needed = True;
708                         } else {
709                                 ssize_t ret = real_write_file(NULL,fsp, data, pos, n);
710
711                                 /*
712                                  * If the write overlaps the entire cache, then
713                                  * discard the current contents of the cache.
714                                  * Fix from Rasmus Borup Hansen rbh@math.ku.dk.
715                                  */
716
717                                 if ((pos <= wcp->offset) &&
718                                                 (pos + n >= wcp->offset + wcp->data_size) ) {
719                                         DEBUG(9,("write_file: discarding overwritten write \
720 cache: fd = %d, off=%.0f, size=%u\n", fsp->fh->fd, (double)wcp->offset, (unsigned int)wcp->data_size ));
721                                         wcp->data_size = 0;
722                                 }
723
724                                 DO_PROFILE_INC(writecache_direct_writes);
725                                 if (ret == -1) {
726                                         return ret;
727                                 }
728
729                                 if (pos + ret > wcp->file_size) {
730                                         wcp->file_size = pos + ret;
731                                 }
732
733                                 return ret;
734                         }
735
736                         write_path = 4;
737
738                 }
739
740                 if (cache_flush_needed) {
741                         DEBUG(3,("WRITE_FLUSH:%d: due to noncontinuous write: fd = %d, size = %.0f, pos = %.0f, \
742 n = %u, wcp->offset=%.0f, wcp->data_size=%u\n",
743                                 write_path, fsp->fh->fd, (double)wcp->file_size, (double)pos, (unsigned int)n,
744                                 (double)wcp->offset, (unsigned int)wcp->data_size ));
745
746                         flush_write_cache(fsp, WRITE_FLUSH);
747                 }
748         }
749
750         /*
751          * If the write request is bigger than the cache
752          * size, write it all out.
753          */
754
755         if (n > wcp->alloc_size ) {
756                 ssize_t ret = real_write_file(NULL,fsp, data, pos, n);
757                 if (ret == -1) {
758                         return -1;
759                 }
760
761                 if (pos + ret > wcp->file_size) {
762                         wcp->file_size = pos + n;
763                 }
764
765                 DO_PROFILE_INC(writecache_direct_writes);
766                 return total_written + n;
767         }
768
769         /*
770          * If there's any data left, cache it.
771          */
772
773         if (n) {
774 #ifdef WITH_PROFILE
775                 if (wcp->data_size) {
776                         DO_PROFILE_INC(writecache_abutted_writes);
777                 } else {
778                         DO_PROFILE_INC(writecache_init_writes);
779                 }
780 #endif
781                 memcpy(wcp->data+wcp->data_size, data, n);
782                 if (wcp->data_size == 0) {
783                         wcp->offset = pos;
784                         DO_PROFILE_INC(writecache_num_write_caches);
785                 }
786                 wcp->data_size += n;
787
788                 /*
789                  * Update the file size if changed.
790                  */
791
792                 if (wcp->offset + wcp->data_size > wcp->file_size) {
793                         if (wcp_file_size_change(fsp) == -1) {
794                                 return -1;
795                         }
796                 }
797                 DEBUG(9,("wcp->offset = %.0f wcp->data_size = %u cache return %u\n",
798                         (double)wcp->offset, (unsigned int)wcp->data_size, (unsigned int)n));
799
800                 total_written += n;
801                 return total_written; /* .... that's a write :) */
802         }
803   
804         return total_written;
805 }
806
807 /****************************************************************************
808  Delete the write cache structure.
809 ****************************************************************************/
810
811 void delete_write_cache(files_struct *fsp)
812 {
813         write_cache *wcp;
814
815         if(!fsp) {
816                 return;
817         }
818
819         if(!(wcp = fsp->wcp)) {
820                 return;
821         }
822
823         DO_PROFILE_DEC(writecache_allocated_write_caches);
824         allocated_write_caches--;
825
826         SMB_ASSERT(wcp->data_size == 0);
827
828         SAFE_FREE(wcp->data);
829         SAFE_FREE(fsp->wcp);
830
831         DEBUG(10,("delete_write_cache: File %s deleted write cache\n", fsp->fsp_name ));
832 }
833
834 /****************************************************************************
835  Setup the write cache structure.
836 ****************************************************************************/
837
838 static bool setup_write_cache(files_struct *fsp, SMB_OFF_T file_size)
839 {
840         ssize_t alloc_size = lp_write_cache_size(SNUM(fsp->conn));
841         write_cache *wcp;
842
843         if (allocated_write_caches >= MAX_WRITE_CACHES) {
844                 return False;
845         }
846
847         if(alloc_size == 0 || fsp->wcp) {
848                 return False;
849         }
850
851         if((wcp = SMB_MALLOC_P(write_cache)) == NULL) {
852                 DEBUG(0,("setup_write_cache: malloc fail.\n"));
853                 return False;
854         }
855
856         wcp->file_size = file_size;
857         wcp->offset = 0;
858         wcp->alloc_size = alloc_size;
859         wcp->data_size = 0;
860         if((wcp->data = (char *)SMB_MALLOC(wcp->alloc_size)) == NULL) {
861                 DEBUG(0,("setup_write_cache: malloc fail for buffer size %u.\n",
862                         (unsigned int)wcp->alloc_size ));
863                 SAFE_FREE(wcp);
864                 return False;
865         }
866
867         memset(wcp->data, '\0', wcp->alloc_size );
868
869         fsp->wcp = wcp;
870         DO_PROFILE_INC(writecache_allocated_write_caches);
871         allocated_write_caches++;
872
873         DEBUG(10,("setup_write_cache: File %s allocated write cache size %lu\n",
874                 fsp->fsp_name, (unsigned long)wcp->alloc_size ));
875
876         return True;
877 }
878
879 /****************************************************************************
880  Cope with a size change.
881 ****************************************************************************/
882
883 void set_filelen_write_cache(files_struct *fsp, SMB_OFF_T file_size)
884 {
885         if(fsp->wcp) {
886                 /* The cache *must* have been flushed before we do this. */
887                 if (fsp->wcp->data_size != 0) {
888                         char *msg;
889                         if (asprintf(&msg, "set_filelen_write_cache: size change "
890                                  "on file %s with write cache size = %lu\n",
891                                  fsp->fsp_name,
892                                  (unsigned long)fsp->wcp->data_size) != -1) {
893                                 smb_panic(msg);
894                         } else {
895                                 smb_panic("set_filelen_write_cache");
896                         }
897                 }
898                 fsp->wcp->file_size = file_size;
899         }
900 }
901
902 /*******************************************************************
903  Flush a write cache struct to disk.
904 ********************************************************************/
905
906 ssize_t flush_write_cache(files_struct *fsp, enum flush_reason_enum reason)
907 {
908         write_cache *wcp = fsp->wcp;
909         size_t data_size;
910         ssize_t ret;
911
912         if(!wcp || !wcp->data_size) {
913                 return 0;
914         }
915
916         data_size = wcp->data_size;
917         wcp->data_size = 0;
918
919         DO_PROFILE_DEC_INC(writecache_num_write_caches,writecache_flushed_writes[reason]);
920
921         DEBUG(9,("flushing write cache: fd = %d, off=%.0f, size=%u\n",
922                 fsp->fh->fd, (double)wcp->offset, (unsigned int)data_size));
923
924 #ifdef WITH_PROFILE
925         if(data_size == wcp->alloc_size) {
926                 DO_PROFILE_INC(writecache_num_perfect_writes);
927         }
928 #endif
929
930         ret = real_write_file(NULL, fsp, wcp->data, wcp->offset, data_size);
931
932         /*
933          * Ensure file size if kept up to date if write extends file.
934          */
935
936         if ((ret != -1) && (wcp->offset + ret > wcp->file_size)) {
937                 wcp->file_size = wcp->offset + ret;
938         }
939
940         return ret;
941 }
942
943 /*******************************************************************
944 sync a file
945 ********************************************************************/
946
947 NTSTATUS sync_file(connection_struct *conn, files_struct *fsp, bool write_through)
948 {
949         if (fsp->fh->fd == -1)
950                 return NT_STATUS_INVALID_HANDLE;
951
952         if (lp_strict_sync(SNUM(conn)) &&
953             (lp_syncalways(SNUM(conn)) || write_through)) {
954                 int ret = flush_write_cache(fsp, SYNC_FLUSH);
955                 if (ret == -1) {
956                         return map_nt_error_from_unix(errno);
957                 }
958                 ret = SMB_VFS_FSYNC(fsp);
959                 if (ret == -1) {
960                         return map_nt_error_from_unix(errno);
961                 }
962         }
963         return NT_STATUS_OK;
964 }
965
966 /************************************************************
967  Perform a stat whether a valid fd or not.
968 ************************************************************/
969
970 int fsp_stat(files_struct *fsp, SMB_STRUCT_STAT *pst)
971 {
972         if (fsp->fh->fd == -1) {
973                 return vfs_stat_smb_fname(fsp->conn, fsp->fsp_name, pst);
974         } else {
975                 return SMB_VFS_FSTAT(fsp, pst);
976         }
977 }