summaryrefslogtreecommitdiff
path: root/source3/smbd/fileio.c
blob: a00b368f92bc7d0f31299968c7cebfd6f4f12264 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
/*
   Unix SMB/Netbios implementation.
   Version 1.9.
   read/write to a files_struct
   Copyright (C) Andrew Tridgell 1992-1998
   Copyright (C) Jeremy Allison 2000-2002. - write cache.

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "includes.h"
#include "printing.h"
#include "smbd/smbd.h"
#include "smbd/globals.h"
#include "smbprofile.h"

struct write_cache {
	off_t file_size;
	off_t offset;
	size_t alloc_size;
	size_t data_size;
	char *data;
};

static bool setup_write_cache(files_struct *, off_t);

/****************************************************************************
 Read from write cache if we can.
****************************************************************************/

static bool read_from_write_cache(files_struct *fsp,char *data,off_t pos,size_t n)
{
	struct write_cache *wcp = fsp->wcp;

	if(!wcp) {
		return False;
	}

	if( n > wcp->data_size || pos < wcp->offset || pos + n > wcp->offset + wcp->data_size) {
		return False;
	}

	memcpy(data, wcp->data + (pos - wcp->offset), n);

	DO_PROFILE_INC(writecache_cached_reads);

	return True;
}

/****************************************************************************
 Read from a file.
****************************************************************************/

ssize_t read_file(files_struct *fsp,char *data,off_t pos,size_t n)
{
	ssize_t ret = 0;

	/* you can't read from print files */
	if (fsp->print_file) {
		errno = EBADF;
		return -1;
	}

	/*
	 * Serve from write cache if we can.
	 */

	if(read_from_write_cache(fsp, data, pos, n)) {
		fsp->fh->pos = pos + n;
		fsp->fh->position_information = fsp->fh->pos;
		return n;
	}

	flush_write_cache(fsp, SAMBA_READ_FLUSH);

	fsp->fh->pos = pos;

	if (n > 0) {
		ret = SMB_VFS_PREAD(fsp,data,n,pos);

		if (ret == -1) {
			return -1;
		}
	}

	DEBUG(10,("read_file (%s): pos = %.0f, size = %lu, returned %lu\n",
		  fsp_str_dbg(fsp), (double)pos, (unsigned long)n, (long)ret));

	fsp->fh->pos += ret;
	fsp->fh->position_information = fsp->fh->pos;

	return(ret);
}

/****************************************************************************
 *Really* write to a file.
****************************************************************************/

static ssize_t real_write_file(struct smb_request *req,
				files_struct *fsp,
				const char *data,
				off_t pos,
				size_t n)
{
	ssize_t ret;

	fsp->fh->pos = pos;
	if (pos && lp_strict_allocate(SNUM(fsp->conn) &&
			!fsp->is_sparse)) {
		if (vfs_fill_sparse(fsp, pos) == -1) {
			return -1;
		}
	}
	ret = vfs_pwrite_data(req, fsp, data, n, pos);

	DEBUG(10,("real_write_file (%s): pos = %.0f, size = %lu, returned %ld\n",
		  fsp_str_dbg(fsp), (double)pos, (unsigned long)n, (long)ret));

	if (ret != -1) {
		fsp->fh->pos += ret;

/* Yes - this is correct - writes don't update this. JRA. */
/* Found by Samba4 tests. */
#if 0
		fsp->position_information = fsp->pos;
#endif
	}

	return ret;
}

/****************************************************************************
 File size cache change.
 Updates size on disk but doesn't flush the cache.
****************************************************************************/

static int wcp_file_size_change(files_struct *fsp)
{
	int ret;
	struct write_cache *wcp = fsp->wcp;

	wcp->file_size = wcp->offset + wcp->data_size;
	ret = SMB_VFS_FTRUNCATE(fsp, wcp->file_size);
	if (ret == -1) {
		DEBUG(0,("wcp_file_size_change (%s): ftruncate of size %.0f "
			 "error %s\n", fsp_str_dbg(fsp),
			 (double)wcp->file_size, strerror(errno)));
	}
	return ret;
}

void fsp_flush_write_time_update(struct files_struct *fsp)
{
	/*
	 * Note this won't expect any impersonation!
	 * So don't call any SMB_VFS operations here!
	 */

	DEBUG(5, ("Update write time on %s\n", fsp_str_dbg(fsp)));

	/* change the write time in the open file db. */
	(void)set_write_time(fsp->file_id, timespec_current());

	/* And notify. */
        notify_fname(fsp->conn, NOTIFY_ACTION_MODIFIED,
                     FILE_NOTIFY_CHANGE_LAST_WRITE, fsp->fsp_name->base_name);

	/* Remove the timed event handler. */
	TALLOC_FREE(fsp->update_write_time_event);
}

static void update_write_time_handler(struct tevent_context *ctx,
				      struct tevent_timer *te,
				      struct timeval now,
				      void *private_data)
{
	files_struct *fsp = (files_struct *)private_data;
	fsp_flush_write_time_update(fsp);
}

/*********************************************************
 Schedule a write time update for WRITE_TIME_UPDATE_USEC_DELAY
 in the future.
*********************************************************/

void trigger_write_time_update(struct files_struct *fsp)
{
	int delay;

	if (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) {
		/* Don't use delayed writes on POSIX files. */
		return;
	}

	if (fsp->write_time_forced) {
		/* No point - "sticky" write times
		 * in effect.
		 */
		return;
	}

	/* We need to remember someone did a write
	 * and update to current time on close. */

	fsp->update_write_time_on_close = true;

	if (fsp->update_write_time_triggered) {
		/*
		 * We only update the write time after 2 seconds
		 * on the first normal write. After that
		 * no other writes affect this until close.
		 */
		return;
	}
	fsp->update_write_time_triggered = true;

	delay = lp_parm_int(SNUM(fsp->conn),
			    "smbd", "writetimeupdatedelay",
			    WRITE_TIME_UPDATE_USEC_DELAY);

	DEBUG(5, ("Update write time %d usec later on %s\n",
		  delay, fsp_str_dbg(fsp)));

	/* trigger the update 2 seconds later */
	fsp->update_write_time_event =
		tevent_add_timer(fsp->conn->sconn->ev_ctx, NULL,
				 timeval_current_ofs_usec(delay),
				 update_write_time_handler, fsp);
}

void trigger_write_time_update_immediate(struct files_struct *fsp)
{
	struct smb_file_time ft;

	if (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) {
		/* Don't use delayed writes on POSIX files. */
		return;
	}

        if (fsp->write_time_forced) {
		/*
		 * No point - "sticky" write times
		 * in effect.
		 */
                return;
        }

	TALLOC_FREE(fsp->update_write_time_event);
	DEBUG(5, ("Update write time immediate on %s\n",
		  fsp_str_dbg(fsp)));

	/* After an immediate update, reset the trigger. */
	fsp->update_write_time_triggered = true;
        fsp->update_write_time_on_close = false;

	ft = (struct smb_file_time) { .mtime = timespec_current() };

	/* Update the time in the open file db. */
	(void)set_write_time(fsp->file_id, ft.mtime);

	/* Now set on disk - takes care of notify. */
	(void)smb_set_file_time(fsp->conn, fsp, fsp->fsp_name, &ft, false);
}

void mark_file_modified(files_struct *fsp)
{
	int dosmode;

	if (fsp->modified) {
		return;
	}

	fsp->modified = true;

	if (SMB_VFS_FSTAT(fsp, &fsp->fsp_name->st) != 0) {
		return;
	}
	trigger_write_time_update(fsp);

	if (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) {
		return;
	}
	if (!(lp_store_dos_attributes(SNUM(fsp->conn)) ||
	      MAP_ARCHIVE(fsp->conn))) {
		return;
	}

	dosmode = dos_mode(fsp->conn, fsp->fsp_name);
	if (IS_DOS_ARCHIVE(dosmode)) {
		return;
	}
	file_set_dosmode(fsp->conn, fsp->fsp_name,
			 dosmode | FILE_ATTRIBUTE_ARCHIVE, NULL, false);
}

/****************************************************************************
 Write to a file.
****************************************************************************/

ssize_t write_file(struct smb_request *req,
			files_struct *fsp,
			const char *data,
			off_t pos,
			size_t n)
{
	struct write_cache *wcp = fsp->wcp;
	ssize_t total_written = 0;
	int write_path = -1;

	if (fsp->print_file) {
		uint32_t t;
		int ret;

		ret = print_spool_write(fsp, data, n, pos, &t);
		if (ret) {
			errno = ret;
			return -1;
		}
		return t;
	}

	if (!fsp->can_write) {
		errno = EPERM;
		return -1;
	}

	/*
	 * If this is the first write and we have an exclusive oplock
	 * then setup the write cache.
	 */

	if (!fsp->modified &&
	    EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type) &&
	    (wcp == NULL)) {
		/*
		 * Note: no write cache with leases!
		 * as the handles would have to share the write cache
		 * that's possible but an improvement for another day...
		 */
		setup_write_cache(fsp, fsp->fsp_name->st.st_ex_size);
		wcp = fsp->wcp;
	}

	mark_file_modified(fsp);

	DO_PROFILE_INC(writecache_total_writes);
	if (!fsp->oplock_type) {
		DO_PROFILE_INC(writecache_non_oplock_writes);
	}

	/*
	 * If this file is level II oplocked then we need
	 * to grab the shared memory lock and inform all
	 * other files with a level II lock that they need
	 * to flush their read caches. We keep the lock over
	 * the shared memory area whilst doing this.
	 */

	/* This should actually be improved to span the write. */
	contend_level2_oplocks_begin(fsp, LEVEL2_CONTEND_WRITE);
	contend_level2_oplocks_end(fsp, LEVEL2_CONTEND_WRITE);

	if (wcp && req->unread_bytes) {
		/* If we're using receivefile don't
		 * deal with a write cache.
		 */
		flush_write_cache(fsp, SAMBA_WRITE_FLUSH);
		delete_write_cache(fsp);
		wcp = NULL;
	}

	if(!wcp) {
		DO_PROFILE_INC(writecache_direct_writes);
		total_written = real_write_file(req, fsp, data, pos, n);
		return total_written;
	}

	DEBUG(9,("write_file (%s)(fd=%d pos=%.0f size=%u) wcp->offset=%.0f "
		 "wcp->data_size=%u\n", fsp_str_dbg(fsp), fsp->fh->fd,
		 (double)pos, (unsigned int)n, (double)wcp->offset,
		 (unsigned int)wcp->data_size));

	fsp->fh->pos = pos + n;

	if ((n == 1) && (data[0] == '\0') && (pos > wcp->file_size)) {
		int ret;

		/*
		 * This is a 1-byte write of a 0 beyond the EOF and
		 * thus implicitly also beyond the current active
		 * write cache, the typical file-extending (and
		 * allocating, but we're using the write cache here)
		 * write done by Windows. We just have to ftruncate
		 * the file and rely on posix semantics to return
		 * zeros for non-written file data that is within the
		 * file length.
		 *
		 * We can not use wcp_file_size_change here because we
		 * might have an existing write cache, and
		 * wcp_file_size_change assumes a change to just the
		 * end of the current write cache.
		 */

		wcp->file_size = pos + 1;
		ret = SMB_VFS_FTRUNCATE(fsp, wcp->file_size);
		if (ret == -1) {
			DEBUG(0, ("wcp_file_size_change (%s): ftruncate of "
				  "size %.0f error %s\n", fsp_str_dbg(fsp),
				  (double)wcp->file_size, strerror(errno)));
			return -1;
		}
		return 1;
	}


	/*
	 * If we have active cache and it isn't contiguous then we flush.
	 * NOTE: There is a small problem with running out of disk ....
	 */

	if (wcp->data_size) {
		bool cache_flush_needed = False;

		if ((pos >= wcp->offset) &&
		    (pos <= wcp->offset + wcp->data_size)) {

			/* ASCII art.... JRA.

      +--------------+-----
      | Cached data  | Rest of allocated cache buffer....
      +--------------+-----

            +-------------------+
            | Data to write     |
            +-------------------+

	    		*/

			/*
			 * Start of write overlaps or abutts the existing data.
			 */

			size_t data_used;

			data_used = MIN((wcp->alloc_size - (pos - wcp->offset)),
					n);

			memcpy(wcp->data + (pos - wcp->offset), data,
			       data_used);

			/*
			 * Update the current buffer size with the new data.
			 */

			if(pos + data_used > wcp->offset + wcp->data_size) {
				wcp->data_size = pos + data_used - wcp->offset;
			}

			/*
			 * Update the file size if changed.
			 */

			if (wcp->offset + wcp->data_size > wcp->file_size) {
				if (wcp_file_size_change(fsp) == -1) {
					return -1;
				}
			}

			/*
			 * If we used all the data then
			 * return here.
			 */

			if(n == data_used) {
				return n;
			} else {
				cache_flush_needed = True;
			}
			/*
			 * Move the start of data forward by the amount used,
			 * cut down the amount left by the same amount.
			 */

			data += data_used;
			pos += data_used;
			n -= data_used;

			DO_PROFILE_INC(writecache_abutted_writes);
			total_written = data_used;

			write_path = 1;

		} else if ((pos < wcp->offset) &&
			   (pos + n > wcp->offset) &&
			   (pos + n <= wcp->offset + wcp->alloc_size)) {

			/* ASCII art.... JRA.

                        +---------------+
                        | Cache buffer  |
                        +---------------+

            +-------------------+
            | Data to write     |
            +-------------------+

	    		*/

			/*
			 * End of write overlaps the existing data.
			 */

			size_t data_used = pos + n - wcp->offset;

			memcpy(wcp->data, data + n - data_used, data_used);

			/*
			 * Update the current buffer size with the new data.
			 */

			if(pos + n > wcp->offset + wcp->data_size) {
				wcp->data_size = pos + n - wcp->offset;
			}

			/*
			 * Update the file size if changed.
			 */

			if (wcp->offset + wcp->data_size > wcp->file_size) {
				if (wcp_file_size_change(fsp) == -1) {
					return -1;
				}
			}

			/*
			 * We don't need to move the start of data, but we
			 * cut down the amount left by the amount used.
			 */

			n -= data_used;

			/*
			 * We cannot have used all the data here.
			 */

			cache_flush_needed = True;

			DO_PROFILE_INC(writecache_abutted_writes);
			total_written = data_used;

			write_path = 2;

		} else if ((pos >= wcp->file_size) &&
			   (wcp->offset + wcp->data_size == wcp->file_size) &&
			   (pos > wcp->offset + wcp->data_size) &&
			   (pos < wcp->offset + wcp->alloc_size) ) {

			/* ASCII art.... JRA.

                       End of file ---->|

                        +---------------+---------------+
                        | Cached data   | Cache buffer  |
                        +---------------+---------------+

                                              +-------------------+
                                              | Data to write     |
                                              +-------------------+

	    		*/

			/*
			 * Non-contiguous write part of which fits within
			 * the cache buffer and is extending the file
			 * and the cache contents reflect the current
			 * data up to the current end of the file.
			 */

			size_t data_used;

			if(pos + n <= wcp->offset + wcp->alloc_size) {
				data_used = n;
			} else {
				data_used = wcp->offset+wcp->alloc_size-pos;
			}

			/*
			 * Fill in the non-continuous area with zeros.
			 */

			memset(wcp->data + wcp->data_size, '\0',
				pos - (wcp->offset + wcp->data_size) );

			memcpy(wcp->data + (pos - wcp->offset), data,
			       data_used);

			/*
			 * Update the current buffer size with the new data.
			 */

			if(pos + data_used > wcp->offset + wcp->data_size) {
				wcp->data_size = pos + data_used - wcp->offset;
			}

			/*
			 * Update the file size if changed.
			 */

			if (wcp->offset + wcp->data_size > wcp->file_size) {
				if (wcp_file_size_change(fsp) == -1) {
					return -1;
				}
			}

			/*
			 * If we used all the data then
			 * return here.
			 */

			if(n == data_used) {
				return n;
			} else {
				cache_flush_needed = True;
			}

			/*
			 * Move the start of data forward by the amount used,
			 * cut down the amount left by the same amount.
			 */

			data += data_used;
			pos += data_used;
			n -= data_used;

			DO_PROFILE_INC(writecache_abutted_writes);
			total_written = data_used;

			write_path = 3;

                } else if ( (pos >= wcp->file_size) &&
			    (n == 1) &&
			    (wcp->file_size == wcp->offset + wcp->data_size) &&
			    (pos < wcp->file_size + wcp->alloc_size)) {

                        /*

                End of file ---->|

                 +---------------+---------------+
                 | Cached data   | Cache buffer  |
                 +---------------+---------------+

                                 |<------- allocated size ---------------->|

                                                         +--------+
                                                         | 1 Byte |
                                                         +--------+

			MS-Office seems to do this a lot to determine if
			there's enough space on the filesystem to write a new
			file.

			Change to :

                End of file ---->|
                                 +-----------------------+--------+
                                 | Zeroed Cached data    | 1 Byte |
                                 +-----------------------+--------+
                        */

			flush_write_cache(fsp, SAMBA_WRITE_FLUSH);
			wcp->offset = wcp->file_size;
			wcp->data_size = pos - wcp->file_size + 1;
			memset(wcp->data, '\0', wcp->data_size);
			memcpy(wcp->data + wcp->data_size-1, data, 1);

			/*
			 * Update the file size if changed.
			 */

			if (wcp->offset + wcp->data_size > wcp->file_size) {
				if (wcp_file_size_change(fsp) == -1) {
					return -1;
				}
			}

			return n;

		} else {

			/* ASCII art..... JRA.

   Case 1).

                        +---------------+---------------+
                        | Cached data   | Cache buffer  |
                        +---------------+---------------+

                                                              +---------------+
                                                              | Data to write |
                                                              +---------------+

   Case 2).

                           +---------------+---------------+
                           | Cached data   | Cache buffer  |
                           +---------------+---------------+

   +-------------------+
   | Data to write     |
   +-------------------+

    Case 3).

                           +---------------+---------------+
                           | Cached data   | Cache buffer  |
                           +---------------+---------------+

                  +-----------------------------------------------------+
                  | Data to write                                       |
                  +-----------------------------------------------------+

		  */

 			/*
			 * Write is bigger than buffer, or there is no
			 * overlap on the low or high ends.
			 */

			DEBUG(9,("write_file: non cacheable write : fd = %d, "
				 "pos = %.0f, len = %u, "
				 "current cache pos = %.0f len = %u\n",
				 fsp->fh->fd, (double)pos, (unsigned int)n,
				 (double)wcp->offset,
				 (unsigned int)wcp->data_size ));

			/*
			 * If write would fit in the cache, and is
			 * larger than the data already in the cache,
			 * flush the cache and preferentially copy the
			 * data new data into it. Otherwise just write
			 * the data directly.
			 */

			if ( n <= wcp->alloc_size && n > wcp->data_size) {
				cache_flush_needed = True;
			} else {
				ssize_t ret = real_write_file(NULL, fsp, data,
							      pos, n);

				/*
				 * If the write overlaps the entire
				 * cache, then discard the current
				 * contents of the cache.  Fix from
				 * Rasmus Borup Hansen rbh@math.ku.dk.
				 */

				if ((pos <= wcp->offset) &&
				    (pos + n >= wcp->offset+wcp->data_size)) {
					DEBUG(9,("write_file: discarding "
						 "overwritten write cache: "
						 "fd = %d, off=%.0f, "
						 "size=%u\n", fsp->fh->fd,
						 (double)wcp->offset,
						 (unsigned)wcp->data_size));
					wcp->data_size = 0;
				}

				DO_PROFILE_INC(writecache_direct_writes);
				if (ret == -1) {
					return ret;
				}

				if (pos + ret > wcp->file_size) {
					wcp->file_size = pos + ret;
				}

				return ret;
			}

			write_path = 4;

		}

		if (cache_flush_needed) {
			DEBUG(3, ("SAMBA_WRITE_FLUSH:%d: due to noncontinuous "
				  "write: fd = %d, size = %.0f, pos = %.0f, "
				  "n = %u, wcp->offset=%.0f, "
				  "wcp->data_size=%u\n",
				  write_path, fsp->fh->fd,
				  (double)wcp->file_size, (double)pos,
				  (unsigned int)n, (double)wcp->offset,
				  (unsigned int)wcp->data_size ));

			flush_write_cache(fsp, SAMBA_WRITE_FLUSH);
		}
	}

	/*
	 * If the write request is bigger than the cache
	 * size, write it all out.
	 */

	if (n > wcp->alloc_size ) {
		ssize_t ret = real_write_file(NULL,fsp, data, pos, n);
		if (ret == -1) {
			return -1;
		}

		if (pos + ret > wcp->file_size) {
			wcp->file_size = pos + n;
		}

		DO_PROFILE_INC(writecache_direct_writes);
		return total_written + n;
	}

	/*
	 * If there's any data left, cache it.
	 */

	if (n) {
		DO_PROFILE_INC(writecache_cached_writes);
		if (wcp->data_size) {
			DO_PROFILE_INC(writecache_abutted_writes);
		} else {
			DO_PROFILE_INC(writecache_init_writes);
		}

		if ((wcp->data_size == 0)
		    && (pos > wcp->file_size)
		    && (pos + n <= wcp->file_size + wcp->alloc_size)) {
			/*
			 * This is a write completely beyond the
			 * current EOF, but within reach of the write
			 * cache. We expect fill-up writes pretty
			 * soon, so it does not make sense to start
			 * the write cache at the current
			 * offset. These fill-up writes would trigger
			 * separate pwrites or even unnecessary cache
			 * flushes because they overlap if this is a
			 * one-byte allocating write.
			 */
			wcp->offset = wcp->file_size;
			wcp->data_size = pos - wcp->file_size;
			memset(wcp->data, 0, wcp->data_size);
		}

		memcpy(wcp->data+wcp->data_size, data, n);
		if (wcp->data_size == 0) {
			wcp->offset = pos;
		}
		wcp->data_size += n;

		/*
		 * Update the file size if changed.
		 */

		if (wcp->offset + wcp->data_size > wcp->file_size) {
			if (wcp_file_size_change(fsp) == -1) {
				return -1;
			}
		}
		DEBUG(9, ("wcp->offset = %.0f wcp->data_size = %u cache "
			  "return %u\n",
			  (double)wcp->offset, (unsigned int)wcp->data_size,
			  (unsigned int)n));

		total_written += n;
		return total_written; /* .... that's a write :) */
	}

	return total_written;
}

/****************************************************************************
 Delete the write cache structure.
****************************************************************************/

void delete_write_cache(files_struct *fsp)
{
	struct write_cache *wcp;

	if(!fsp) {
		return;
	}

	if(!(wcp = fsp->wcp)) {
		return;
	}

	DO_PROFILE_INC(writecache_deallocations);
	allocated_write_caches--;

	SMB_ASSERT(wcp->data_size == 0);

	SAFE_FREE(wcp->data);
	SAFE_FREE(fsp->wcp);

	DEBUG(10,("delete_write_cache: File %s deleted write cache\n",
		  fsp_str_dbg(fsp)));
}

/****************************************************************************
 Setup the write cache structure.
****************************************************************************/

static bool setup_write_cache(files_struct *fsp, off_t file_size)
{
	ssize_t alloc_size = lp_write_cache_size(SNUM(fsp->conn));
	struct write_cache *wcp;

	if (allocated_write_caches >= MAX_WRITE_CACHES) {
		return False;
	}

	if(alloc_size == 0 || fsp->wcp) {
		return False;
	}

	if((wcp = SMB_MALLOC_P(struct write_cache)) == NULL) {
		DEBUG(0,("setup_write_cache: malloc fail.\n"));
		return False;
	}

	wcp->file_size = file_size;
	wcp->offset = 0;
	wcp->alloc_size = alloc_size;
	wcp->data_size = 0;
	if((wcp->data = (char *)SMB_MALLOC(wcp->alloc_size)) == NULL) {
		DEBUG(0,("setup_write_cache: malloc fail for buffer size %u.\n",
			(unsigned int)wcp->alloc_size ));
		SAFE_FREE(wcp);
		return False;
	}

	memset(wcp->data, '\0', wcp->alloc_size );

	fsp->wcp = wcp;
	DO_PROFILE_INC(writecache_allocations);
	allocated_write_caches++;

	DEBUG(10,("setup_write_cache: File %s allocated write cache size %lu\n",
		  fsp_str_dbg(fsp), (unsigned long)wcp->alloc_size));

	return True;
}

/****************************************************************************
 Cope with a size change.
****************************************************************************/

void set_filelen_write_cache(files_struct *fsp, off_t file_size)
{
	if(fsp->wcp) {
		/* The cache *must* have been flushed before we do this. */
		if (fsp->wcp->data_size != 0) {
			char *msg;
			if (asprintf(&msg, "set_filelen_write_cache: size change "
				 "on file %s with write cache size = %lu\n",
				 fsp->fsp_name->base_name,
				 (unsigned long)fsp->wcp->data_size) != -1) {
				smb_panic(msg);
			} else {
				smb_panic("set_filelen_write_cache");
			}
		}
		fsp->wcp->file_size = file_size;
	}
}

/*******************************************************************
 Flush a write cache struct to disk.
********************************************************************/

ssize_t flush_write_cache(files_struct *fsp, enum flush_reason_enum reason)
{
	struct write_cache *wcp = fsp->wcp;
	size_t data_size;
	ssize_t ret;

	if(!wcp || !wcp->data_size) {
		return 0;
	}

	data_size = wcp->data_size;
	wcp->data_size = 0;

	switch (reason) {
	case SAMBA_SEEK_FLUSH:
		DO_PROFILE_INC(writecache_flush_reason_seek);
		break;
	case SAMBA_READ_FLUSH:
		DO_PROFILE_INC(writecache_flush_reason_read);
		break;
	case SAMBA_WRITE_FLUSH:
		DO_PROFILE_INC(writecache_flush_reason_write);;
		break;
	case SAMBA_READRAW_FLUSH:
		DO_PROFILE_INC(writecache_flush_reason_readraw);
		break;
	case SAMBA_OPLOCK_RELEASE_FLUSH:
		DO_PROFILE_INC(writecache_flush_reason_oplock);
		break;
	case SAMBA_CLOSE_FLUSH:
		DO_PROFILE_INC(writecache_flush_reason_close);
		break;
	case SAMBA_SYNC_FLUSH:
		DO_PROFILE_INC(writecache_flush_reason_sync);
		break;
	case SAMBA_SIZECHANGE_FLUSH:
		DO_PROFILE_INC(writecache_flush_reason_sizechange);
		break;
	default:
		break;
	}

	DEBUG(9,("flushing write cache: fd = %d, off=%.0f, size=%u\n",
		fsp->fh->fd, (double)wcp->offset, (unsigned int)data_size));

	if(data_size == wcp->alloc_size) {
		DO_PROFILE_INC(writecache_perfect_writes);
	}

	ret = real_write_file(NULL, fsp, wcp->data, wcp->offset, data_size);

	/*
	 * Ensure file size if kept up to date if write extends file.
	 */

	if ((ret != -1) && (wcp->offset + ret > wcp->file_size)) {
		wcp->file_size = wcp->offset + ret;
	}

	return ret;
}

/*******************************************************************
sync a file
********************************************************************/

NTSTATUS sync_file(connection_struct *conn, files_struct *fsp, bool write_through)
{
       	if (fsp->fh->fd == -1)
		return NT_STATUS_INVALID_HANDLE;

	if (lp_strict_sync(SNUM(conn)) &&
	    (lp_sync_always(SNUM(conn)) || write_through)) {
		int ret = flush_write_cache(fsp, SAMBA_SYNC_FLUSH);
		if (ret == -1) {
			return map_nt_error_from_unix(errno);
		}
		ret = smb_vfs_fsync_sync(fsp);
		if (ret == -1) {
			return map_nt_error_from_unix(errno);
		}
	}
	return NT_STATUS_OK;
}

/************************************************************
 Perform a stat whether a valid fd or not.
************************************************************/

int fsp_stat(files_struct *fsp)
{
	if (fsp->fh->fd == -1) {
		if (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) {
			return SMB_VFS_LSTAT(fsp->conn, fsp->fsp_name);
		} else {
			return SMB_VFS_STAT(fsp->conn, fsp->fsp_name);
		}
	} else {
		return SMB_VFS_FSTAT(fsp, &fsp->fsp_name->st);
	}
}