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