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