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