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