Move the "oplock file with byte range locks" check to the correct place, where we...
[samba.git] / source3 / smbd / oplock.c
1 /* 
2    Unix SMB/CIFS implementation.
3    oplock processing
4    Copyright (C) Andrew Tridgell 1992-1998
5    Copyright (C) Jeremy Allison 1998 - 2001
6    Copyright (C) Volker Lendecke 2005
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 #define DBGC_CLASS DBGC_LOCKING
23 #include "includes.h"
24 #include "smbd/globals.h"
25 #include "librpc/gen_ndr/messaging.h"
26
27 /****************************************************************************
28  Get the number of current exclusive oplocks.
29 ****************************************************************************/
30
31 int32 get_number_of_exclusive_open_oplocks(void)
32 {
33   return exclusive_oplocks_open;
34 }
35
36 /*
37  * helper function used by the kernel oplock backends to post the break message
38  */
39 void break_kernel_oplock(struct messaging_context *msg_ctx, files_struct *fsp)
40 {
41         uint8_t msg[MSG_SMB_KERNEL_BREAK_SIZE];
42
43         /* Put the kernel break info into the message. */
44         push_file_id_24((char *)msg, &fsp->file_id);
45         SIVAL(msg,24,fsp->fh->gen_id);
46
47         /* Don't need to be root here as we're only ever
48            sending to ourselves. */
49
50         messaging_send_buf(msg_ctx, messaging_server_id(msg_ctx),
51                            MSG_SMB_KERNEL_BREAK,
52                            msg, MSG_SMB_KERNEL_BREAK_SIZE);
53 }
54
55 /****************************************************************************
56  Attempt to set an oplock on a file. Succeeds if kernel oplocks are
57  disabled (just sets flags) and no byte-range locks in the file. Returns True
58  if oplock set.
59 ****************************************************************************/
60
61 bool set_file_oplock(files_struct *fsp, int oplock_type)
62 {
63         if (fsp->oplock_type == LEVEL_II_OPLOCK) {
64                 if (koplocks &&
65                     !(koplocks->flags & KOPLOCKS_LEVEL2_SUPPORTED)) {
66                         DEBUG(10, ("Refusing level2 oplock, kernel oplocks "
67                                    "don't support them\n"));
68                         return false;
69                 }
70         }
71
72         if ((fsp->oplock_type != NO_OPLOCK) &&
73             (fsp->oplock_type != FAKE_LEVEL_II_OPLOCK) &&
74             koplocks &&
75             !koplocks->ops->set_oplock(koplocks, fsp, oplock_type)) {
76                 return False;
77         }
78
79         fsp->oplock_type = oplock_type;
80         fsp->sent_oplock_break = NO_BREAK_SENT;
81         if (oplock_type == LEVEL_II_OPLOCK) {
82                 level_II_oplocks_open++;
83         } else if (EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type)) {
84                 exclusive_oplocks_open++;
85         }
86
87         DEBUG(5,("set_file_oplock: granted oplock on file %s, %s/%lu, "
88                     "tv_sec = %x, tv_usec = %x\n",
89                  fsp_str_dbg(fsp), file_id_string_tos(&fsp->file_id),
90                  fsp->fh->gen_id, (int)fsp->open_time.tv_sec,
91                  (int)fsp->open_time.tv_usec ));
92
93         return True;
94 }
95
96 /****************************************************************************
97  Attempt to release an oplock on a file. Decrements oplock count.
98 ****************************************************************************/
99
100 void release_file_oplock(files_struct *fsp)
101 {
102         if ((fsp->oplock_type != NO_OPLOCK) &&
103             (fsp->oplock_type != FAKE_LEVEL_II_OPLOCK) &&
104             koplocks) {
105                 koplocks->ops->release_oplock(koplocks, fsp, NO_OPLOCK);
106         }
107
108         if (fsp->oplock_type == LEVEL_II_OPLOCK) {
109                 level_II_oplocks_open--;
110         } else if (EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type)) {
111                 exclusive_oplocks_open--;
112         }
113
114         SMB_ASSERT(exclusive_oplocks_open>=0);
115         SMB_ASSERT(level_II_oplocks_open>=0);
116
117         if (EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type)) {
118                 /* This doesn't matter for close. */
119                 fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
120         } else {
121                 fsp->oplock_type = NO_OPLOCK;
122         }
123         fsp->sent_oplock_break = NO_BREAK_SENT;
124
125         flush_write_cache(fsp, OPLOCK_RELEASE_FLUSH);
126         delete_write_cache(fsp);
127
128         TALLOC_FREE(fsp->oplock_timeout);
129 }
130
131 /****************************************************************************
132  Attempt to downgrade an oplock on a file. Doesn't decrement oplock count.
133 ****************************************************************************/
134
135 static void downgrade_file_oplock(files_struct *fsp)
136 {
137         if (!EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type)) {
138                 DEBUG(0, ("trying to downgrade an already-downgraded oplock!\n"));
139                 return;
140         }
141
142         if (koplocks) {
143                 koplocks->ops->release_oplock(koplocks, fsp, LEVEL_II_OPLOCK);
144         }
145         fsp->oplock_type = LEVEL_II_OPLOCK;
146         exclusive_oplocks_open--;
147         level_II_oplocks_open++;
148         fsp->sent_oplock_break = NO_BREAK_SENT;
149 }
150
151 /****************************************************************************
152  Remove a file oplock. Copes with level II and exclusive.
153  Locks then unlocks the share mode lock. Client can decide to go directly
154  to none even if a "break-to-level II" was sent.
155 ****************************************************************************/
156
157 bool remove_oplock(files_struct *fsp)
158 {
159         bool ret;
160         struct share_mode_lock *lck;
161
162         /* Remove the oplock flag from the sharemode. */
163         lck = get_share_mode_lock(talloc_tos(), fsp->file_id, NULL, NULL,
164                                   NULL);
165         if (lck == NULL) {
166                 DEBUG(0,("remove_oplock: failed to lock share entry for "
167                          "file %s\n", fsp_str_dbg(fsp)));
168                 return False;
169         }
170         ret = remove_share_oplock(lck, fsp);
171         if (!ret) {
172                 DEBUG(0,("remove_oplock: failed to remove share oplock for "
173                          "file %s fnum %d, %s\n",
174                          fsp_str_dbg(fsp), fsp->fnum,
175                          file_id_string_tos(&fsp->file_id)));
176         }
177         release_file_oplock(fsp);
178         TALLOC_FREE(lck);
179         return ret;
180 }
181
182 /*
183  * Deal with a reply when a break-to-level II was sent.
184  */
185 bool downgrade_oplock(files_struct *fsp)
186 {
187         bool ret;
188         struct share_mode_lock *lck;
189
190         lck = get_share_mode_lock(talloc_tos(), fsp->file_id, NULL, NULL,
191                                   NULL);
192         if (lck == NULL) {
193                 DEBUG(0,("downgrade_oplock: failed to lock share entry for "
194                          "file %s\n", fsp_str_dbg(fsp)));
195                 return False;
196         }
197         ret = downgrade_share_oplock(lck, fsp);
198         if (!ret) {
199                 DEBUG(0,("downgrade_oplock: failed to downgrade share oplock "
200                          "for file %s fnum %d, file_id %s\n",
201                          fsp_str_dbg(fsp), fsp->fnum,
202                          file_id_string_tos(&fsp->file_id)));
203         }
204
205         downgrade_file_oplock(fsp);
206         TALLOC_FREE(lck);
207         return ret;
208 }
209
210 /*
211  * Some kernel oplock implementations handle the notification themselves.
212  */
213 bool should_notify_deferred_opens()
214 {
215         return !(koplocks &&
216                 (koplocks->flags & KOPLOCKS_DEFERRED_OPEN_NOTIFICATION));
217 }
218
219 /****************************************************************************
220  Set up an oplock break message.
221 ****************************************************************************/
222
223 static char *new_break_message_smb1(TALLOC_CTX *mem_ctx,
224                                    files_struct *fsp, int cmd)
225 {
226         char *result = TALLOC_ARRAY(mem_ctx, char, smb_size + 8*2 + 0);
227
228         if (result == NULL) {
229                 DEBUG(0, ("talloc failed\n"));
230                 return NULL;
231         }
232
233         memset(result,'\0',smb_size);
234         srv_set_message(result,8,0,true);
235         SCVAL(result,smb_com,SMBlockingX);
236         SSVAL(result,smb_tid,fsp->conn->cnum);
237         SSVAL(result,smb_pid,0xFFFF);
238         SSVAL(result,smb_uid,0);
239         SSVAL(result,smb_mid,0xFFFF);
240         SCVAL(result,smb_vwv0,0xFF);
241         SSVAL(result,smb_vwv2,fsp->fnum);
242         SCVAL(result,smb_vwv3,LOCKING_ANDX_OPLOCK_RELEASE);
243         SCVAL(result,smb_vwv3+1,cmd);
244         return result;
245 }
246
247 /****************************************************************************
248  Function to do the waiting before sending a local break.
249 ****************************************************************************/
250
251 static void wait_before_sending_break(void)
252 {
253         long wait_time = (long)lp_oplock_break_wait_time();
254
255         if (wait_time) {
256                 smb_msleep(wait_time);
257         }
258 }
259
260 /****************************************************************************
261  Ensure that we have a valid oplock.
262 ****************************************************************************/
263
264 static files_struct *initial_break_processing(
265         struct smbd_server_connection *sconn, struct file_id id,
266         unsigned long file_id)
267 {
268         files_struct *fsp = NULL;
269
270         if( DEBUGLVL( 3 ) ) {
271                 dbgtext( "initial_break_processing: called for %s/%u\n",
272                          file_id_string_tos(&id), (int)file_id);
273                 dbgtext( "Current oplocks_open (exclusive = %d, levelII = %d)\n",
274                         exclusive_oplocks_open, level_II_oplocks_open );
275         }
276
277         /*
278          * We need to search the file open table for the
279          * entry containing this dev and inode, and ensure
280          * we have an oplock on it.
281          */
282
283         fsp = file_find_dif(sconn, id, file_id);
284
285         if(fsp == NULL) {
286                 /* The file could have been closed in the meantime - return success. */
287                 if( DEBUGLVL( 3 ) ) {
288                         dbgtext( "initial_break_processing: cannot find open file with " );
289                         dbgtext( "file_id %s gen_id = %lu", file_id_string_tos(&id), file_id);
290                         dbgtext( "allowing break to succeed.\n" );
291                 }
292                 return NULL;
293         }
294
295         /* Ensure we have an oplock on the file */
296
297         /*
298          * There is a potential race condition in that an oplock could
299          * have been broken due to another udp request, and yet there are
300          * still oplock break messages being sent in the udp message
301          * queue for this file. So return true if we don't have an oplock,
302          * as we may have just freed it.
303          */
304
305         if(fsp->oplock_type == NO_OPLOCK) {
306                 if( DEBUGLVL( 3 ) ) {
307                         dbgtext( "initial_break_processing: file %s ",
308                                  fsp_str_dbg(fsp));
309                         dbgtext( "(file_id = %s gen_id = %lu) has no oplock.\n",
310                                  file_id_string_tos(&id), fsp->fh->gen_id );
311                         dbgtext( "Allowing break to succeed regardless.\n" );
312                 }
313                 return NULL;
314         }
315
316         return fsp;
317 }
318
319 static void oplock_timeout_handler(struct event_context *ctx,
320                                    struct timed_event *te,
321                                    struct timeval now,
322                                    void *private_data)
323 {
324         files_struct *fsp = (files_struct *)private_data;
325
326         /* Remove the timed event handler. */
327         TALLOC_FREE(fsp->oplock_timeout);
328         DEBUG(0, ("Oplock break failed for file %s -- replying anyway\n",
329                   fsp_str_dbg(fsp)));
330         remove_oplock(fsp);
331         reply_to_oplock_break_requests(fsp);
332 }
333
334 /*******************************************************************
335  Add a timeout handler waiting for the client reply.
336 *******************************************************************/
337
338 static void add_oplock_timeout_handler(files_struct *fsp)
339 {
340         /*
341          * If kernel oplocks already notifies smbds when an oplock break times
342          * out, just return.
343          */
344         if (koplocks &&
345             (koplocks->flags & KOPLOCKS_TIMEOUT_NOTIFICATION)) {
346                 return;
347         }
348
349         if (fsp->oplock_timeout != NULL) {
350                 DEBUG(0, ("Logic problem -- have an oplock event hanging "
351                           "around\n"));
352         }
353
354         fsp->oplock_timeout =
355                 event_add_timed(smbd_event_context(), fsp,
356                                 timeval_current_ofs(OPLOCK_BREAK_TIMEOUT, 0),
357                                 oplock_timeout_handler, fsp);
358
359         if (fsp->oplock_timeout == NULL) {
360                 DEBUG(0, ("Could not add oplock timeout handler\n"));
361         }
362 }
363
364 static void send_break_message_smb1(files_struct *fsp, int level)
365 {
366         char *break_msg = new_break_message_smb1(talloc_tos(),
367                                         fsp,
368                                         level);
369         if (break_msg == NULL) {
370                 exit_server("Could not talloc break_msg\n");
371         }
372
373         show_msg(break_msg);
374         if (!srv_send_smb(fsp->conn->sconn,
375                         break_msg, false, 0,
376                         IS_CONN_ENCRYPTED(fsp->conn),
377                         NULL)) {
378                 exit_server_cleanly("send_break_message_smb1: "
379                         "srv_send_smb failed.");
380         }
381
382         TALLOC_FREE(break_msg);
383 }
384
385 void break_level2_to_none_async(files_struct *fsp)
386 {
387         struct smbd_server_connection *sconn = fsp->conn->sconn;
388
389         if (fsp->oplock_type == NO_OPLOCK) {
390                 /* We already got a "break to none" message and we've handled
391                  * it.  just ignore. */
392                 DEBUG(3, ("process_oplock_async_level2_break_message: already "
393                           "broken to none, ignoring.\n"));
394                 return;
395         }
396
397         if (fsp->oplock_type == FAKE_LEVEL_II_OPLOCK) {
398                 /* Don't tell the client, just downgrade. */
399                 DEBUG(3, ("process_oplock_async_level2_break_message: "
400                           "downgrading fake level 2 oplock.\n"));
401                 remove_oplock(fsp);
402                 return;
403         }
404
405         /* Ensure we're really at level2 state. */
406         SMB_ASSERT(fsp->oplock_type == LEVEL_II_OPLOCK);
407
408         DEBUG(10,("process_oplock_async_level2_break_message: sending break "
409                   "to none message for fid %d, file %s\n", fsp->fnum,
410                   fsp_str_dbg(fsp)));
411
412         /* Now send a break to none message to our client. */
413         if (sconn->using_smb2) {
414                 send_break_message_smb2(fsp, OPLOCKLEVEL_NONE);
415         } else {
416                 send_break_message_smb1(fsp, OPLOCKLEVEL_NONE);
417         }
418
419         /* Async level2 request, don't send a reply, just remove the oplock. */
420         remove_oplock(fsp);
421 }
422
423 /*******************************************************************
424  This handles the case of a write triggering a break to none
425  message on a level2 oplock.
426  When we get this message we may be in any of three states :
427  NO_OPLOCK, LEVEL_II, FAKE_LEVEL2. We only send a message to
428  the client for LEVEL2.
429 *******************************************************************/
430
431 void process_oplock_async_level2_break_message(struct messaging_context *msg_ctx,
432                                                       void *private_data,
433                                                       uint32_t msg_type,
434                                                       struct server_id src,
435                                                       DATA_BLOB *data)
436 {
437         struct smbd_server_connection *sconn;
438         struct share_mode_entry msg;
439         files_struct *fsp;
440
441         if (data->data == NULL) {
442                 DEBUG(0, ("Got NULL buffer\n"));
443                 return;
444         }
445
446         sconn = msg_ctx_to_sconn(msg_ctx);
447         if (sconn == NULL) {
448                 DEBUG(1, ("could not find sconn\n"));
449                 return;
450         }
451
452         if (data->length != MSG_SMB_SHARE_MODE_ENTRY_SIZE) {
453                 DEBUG(0, ("Got invalid msg len %d\n", (int)data->length));
454                 return;
455         }
456
457         /* De-linearize incoming message. */
458         message_to_share_mode_entry(&msg, (char *)data->data);
459
460         DEBUG(10, ("Got oplock async level 2 break message from pid %s: "
461                    "%s/%lu\n", procid_str(talloc_tos(), &src),
462                    file_id_string_tos(&msg.id), msg.share_file_id));
463
464         fsp = initial_break_processing(sconn, msg.id, msg.share_file_id);
465
466         if (fsp == NULL) {
467                 /* We hit a race here. Break messages are sent, and before we
468                  * get to process this message, we have closed the file. 
469                  * No need to reply as this is an async message. */
470                 DEBUG(3, ("process_oplock_async_level2_break_message: Did not find fsp, ignoring\n"));
471                 return;
472         }
473
474         break_level2_to_none_async(fsp);
475 }
476
477 /*******************************************************************
478  This handles the generic oplock break message from another smbd.
479 *******************************************************************/
480
481 static void process_oplock_break_message(struct messaging_context *msg_ctx,
482                                          void *private_data,
483                                          uint32_t msg_type,
484                                          struct server_id src,
485                                          DATA_BLOB *data)
486 {
487         struct smbd_server_connection *sconn;
488         struct share_mode_entry msg;
489         files_struct *fsp;
490         bool break_to_level2 = False;
491
492         if (data->data == NULL) {
493                 DEBUG(0, ("Got NULL buffer\n"));
494                 return;
495         }
496
497         sconn = msg_ctx_to_sconn(msg_ctx);
498         if (sconn == NULL) {
499                 DEBUG(1, ("could not find sconn\n"));
500                 return;
501         }
502
503         if (data->length != MSG_SMB_SHARE_MODE_ENTRY_SIZE) {
504                 DEBUG(0, ("Got invalid msg len %d\n", (int)data->length));
505                 return;
506         }
507
508         /* De-linearize incoming message. */
509         message_to_share_mode_entry(&msg, (char *)data->data);
510
511         DEBUG(10, ("Got oplock break message from pid %s: %s/%lu\n",
512                    procid_str(talloc_tos(), &src), file_id_string_tos(&msg.id),
513                    msg.share_file_id));
514
515         fsp = initial_break_processing(sconn, msg.id, msg.share_file_id);
516
517         if (fsp == NULL) {
518                 /* We hit a race here. Break messages are sent, and before we
519                  * get to process this message, we have closed the file. Reply
520                  * with 'ok, oplock broken' */
521                 DEBUG(3, ("Did not find fsp\n"));
522
523                 /* We just send the same message back. */
524                 messaging_send_buf(msg_ctx, src, MSG_SMB_BREAK_RESPONSE,
525                                    (uint8 *)data->data,
526                                    MSG_SMB_SHARE_MODE_ENTRY_SIZE);
527                 return;
528         }
529
530         if (fsp->sent_oplock_break != NO_BREAK_SENT) {
531                 /* Remember we have to inform the requesting PID when the
532                  * client replies */
533                 msg.pid = src;
534                 ADD_TO_ARRAY(NULL, struct share_mode_entry, msg,
535                              &fsp->pending_break_messages,
536                              &fsp->num_pending_break_messages);
537                 return;
538         }
539
540         if (EXCLUSIVE_OPLOCK_TYPE(msg.op_type) &&
541             !EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type)) {
542                 DEBUG(3, ("Already downgraded oplock on %s: %s\n",
543                           file_id_string_tos(&fsp->file_id),
544                           fsp_str_dbg(fsp)));
545                 /* We just send the same message back. */
546                 messaging_send_buf(msg_ctx, src, MSG_SMB_BREAK_RESPONSE,
547                                    (uint8 *)data->data,
548                                    MSG_SMB_SHARE_MODE_ENTRY_SIZE);
549                 return;
550         }
551
552         if ((global_client_caps & CAP_LEVEL_II_OPLOCKS) && 
553             !(msg.op_type & FORCE_OPLOCK_BREAK_TO_NONE) &&
554             !(koplocks && !(koplocks->flags & KOPLOCKS_LEVEL2_SUPPORTED)) &&
555             lp_level2_oplocks(SNUM(fsp->conn))) {
556                 break_to_level2 = True;
557         }
558
559         /* Need to wait before sending a break
560            message if we sent ourselves this message. */
561         if (procid_is_me(&src)) {
562                 wait_before_sending_break();
563         }
564
565         if (sconn->using_smb2) {
566                 send_break_message_smb2(fsp, break_to_level2 ?
567                         OPLOCKLEVEL_II : OPLOCKLEVEL_NONE);
568         } else {
569                 send_break_message_smb1(fsp, break_to_level2 ?
570                         OPLOCKLEVEL_II : OPLOCKLEVEL_NONE);
571         }
572
573         fsp->sent_oplock_break = break_to_level2 ? LEVEL_II_BREAK_SENT:BREAK_TO_NONE_SENT;
574
575         msg.pid = src;
576         ADD_TO_ARRAY(NULL, struct share_mode_entry, msg,
577                      &fsp->pending_break_messages,
578                      &fsp->num_pending_break_messages);
579
580         add_oplock_timeout_handler(fsp);
581 }
582
583 /*******************************************************************
584  This handles the kernel oplock break message.
585 *******************************************************************/
586
587 static void process_kernel_oplock_break(struct messaging_context *msg_ctx,
588                                         void *private_data,
589                                         uint32_t msg_type,
590                                         struct server_id src,
591                                         DATA_BLOB *data)
592 {
593         struct smbd_server_connection *sconn;
594         struct file_id id;
595         unsigned long file_id;
596         files_struct *fsp;
597
598         if (data->data == NULL) {
599                 DEBUG(0, ("Got NULL buffer\n"));
600                 return;
601         }
602
603         if (data->length != MSG_SMB_KERNEL_BREAK_SIZE) {
604                 DEBUG(0, ("Got invalid msg len %d\n", (int)data->length));
605                 return;
606         }
607
608         sconn = msg_ctx_to_sconn(msg_ctx);
609         if (sconn == NULL) {
610                 DEBUG(1, ("could not find sconn\n"));
611                 return;
612         }
613
614         /* Pull the data from the message. */
615         pull_file_id_24((char *)data->data, &id);
616         file_id = (unsigned long)IVAL(data->data, 24);
617
618         DEBUG(10, ("Got kernel oplock break message from pid %s: %s/%u\n",
619                    procid_str(talloc_tos(), &src), file_id_string_tos(&id),
620                    (unsigned int)file_id));
621
622         fsp = initial_break_processing(sconn, id, file_id);
623
624         if (fsp == NULL) {
625                 DEBUG(3, ("Got a kernel oplock break message for a file "
626                           "I don't know about\n"));
627                 return;
628         }
629
630         if (fsp->sent_oplock_break != NO_BREAK_SENT) {
631                 /* This is ok, kernel oplocks come in completely async */
632                 DEBUG(3, ("Got a kernel oplock request while waiting for a "
633                           "break reply\n"));
634                 return;
635         }
636
637         if (sconn->using_smb2) {
638                 send_break_message_smb2(fsp, OPLOCKLEVEL_NONE);
639         } else {
640                 send_break_message_smb1(fsp, OPLOCKLEVEL_NONE);
641         }
642
643         fsp->sent_oplock_break = BREAK_TO_NONE_SENT;
644
645         add_oplock_timeout_handler(fsp);
646 }
647
648 void reply_to_oplock_break_requests(files_struct *fsp)
649 {
650         int i;
651
652         /*
653          * If kernel oplocks already notifies smbds when oplocks are
654          * broken/removed, just return.
655          */
656         if (koplocks &&
657             (koplocks->flags & KOPLOCKS_OPLOCK_BROKEN_NOTIFICATION)) {
658                 return;
659         }
660
661         for (i=0; i<fsp->num_pending_break_messages; i++) {
662                 struct share_mode_entry *e = &fsp->pending_break_messages[i];
663                 char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
664
665                 share_mode_entry_to_message(msg, e);
666
667                 messaging_send_buf(fsp->conn->sconn->msg_ctx, e->pid,
668                                    MSG_SMB_BREAK_RESPONSE,
669                                    (uint8 *)msg,
670                                    MSG_SMB_SHARE_MODE_ENTRY_SIZE);
671         }
672
673         SAFE_FREE(fsp->pending_break_messages);
674         fsp->num_pending_break_messages = 0;
675         if (fsp->oplock_timeout != NULL) {
676                 /* Remove the timed event handler. */
677                 TALLOC_FREE(fsp->oplock_timeout);
678                 fsp->oplock_timeout = NULL;
679         }
680         return;
681 }
682
683 static void process_oplock_break_response(struct messaging_context *msg_ctx,
684                                           void *private_data,
685                                           uint32_t msg_type,
686                                           struct server_id src,
687                                           DATA_BLOB *data)
688 {
689         struct share_mode_entry msg;
690
691         if (data->data == NULL) {
692                 DEBUG(0, ("Got NULL buffer\n"));
693                 return;
694         }
695
696         if (data->length != MSG_SMB_SHARE_MODE_ENTRY_SIZE) {
697                 DEBUG(0, ("Got invalid msg len %u\n",
698                           (unsigned int)data->length));
699                 return;
700         }
701
702         /* De-linearize incoming message. */
703         message_to_share_mode_entry(&msg, (char *)data->data);
704
705         DEBUG(10, ("Got oplock break response from pid %s: %s/%lu mid %llu\n",
706                    procid_str(talloc_tos(), &src), file_id_string_tos(&msg.id),
707                    msg.share_file_id, (unsigned long long)msg.op_mid));
708
709         schedule_deferred_open_message_smb(msg.op_mid);
710 }
711
712 static void process_open_retry_message(struct messaging_context *msg_ctx,
713                                        void *private_data,
714                                        uint32_t msg_type,
715                                        struct server_id src,
716                                        DATA_BLOB *data)
717 {
718         struct share_mode_entry msg;
719         
720         if (data->data == NULL) {
721                 DEBUG(0, ("Got NULL buffer\n"));
722                 return;
723         }
724
725         if (data->length != MSG_SMB_SHARE_MODE_ENTRY_SIZE) {
726                 DEBUG(0, ("Got invalid msg len %d\n", (int)data->length));
727                 return;
728         }
729
730         /* De-linearize incoming message. */
731         message_to_share_mode_entry(&msg, (char *)data->data);
732
733         DEBUG(10, ("Got open retry msg from pid %s: %s mid %llu\n",
734                    procid_str(talloc_tos(), &src), file_id_string_tos(&msg.id),
735                    (unsigned long long)msg.op_mid));
736
737         schedule_deferred_open_message_smb(msg.op_mid);
738 }
739
740 /****************************************************************************
741  This function is called on any file modification or lock request. If a file
742  is level 2 oplocked then it must tell all other level 2 holders to break to
743  none.
744 ****************************************************************************/
745
746 static void contend_level2_oplocks_begin_default(files_struct *fsp,
747                                               enum level2_contention_type type)
748 {
749         int i;
750         struct share_mode_lock *lck;
751
752         /*
753          * If this file is level II oplocked then we need
754          * to grab the shared memory lock and inform all
755          * other files with a level II lock that they need
756          * to flush their read caches. We keep the lock over
757          * the shared memory area whilst doing this.
758          */
759
760         if (!LEVEL_II_OPLOCK_TYPE(fsp->oplock_type))
761                 return;
762
763         lck = get_share_mode_lock(talloc_tos(), fsp->file_id, NULL, NULL,
764                                   NULL);
765         if (lck == NULL) {
766                 DEBUG(0,("release_level_2_oplocks_on_change: failed to lock "
767                          "share mode entry for file %s.\n", fsp_str_dbg(fsp)));
768                 return;
769         }
770
771         DEBUG(10,("release_level_2_oplocks_on_change: num_share_modes = %d\n", 
772                   lck->num_share_modes ));
773
774         for(i = 0; i < lck->num_share_modes; i++) {
775                 struct share_mode_entry *share_entry = &lck->share_modes[i];
776                 char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
777
778                 if (!is_valid_share_mode_entry(share_entry)) {
779                         continue;
780                 }
781
782                 /*
783                  * As there could have been multiple writes waiting at the
784                  * lock_share_entry gate we may not be the first to
785                  * enter. Hence the state of the op_types in the share mode
786                  * entries may be partly NO_OPLOCK and partly LEVEL_II or FAKE_LEVEL_II
787                  * oplock. It will do no harm to re-send break messages to
788                  * those smbd's that are still waiting their turn to remove
789                  * their LEVEL_II state, and also no harm to ignore existing
790                  * NO_OPLOCK states. JRA.
791                  */
792
793                 DEBUG(10,("release_level_2_oplocks_on_change: "
794                           "share_entry[%i]->op_type == %d\n",
795                           i, share_entry->op_type ));
796
797                 if (share_entry->op_type == NO_OPLOCK) {
798                         continue;
799                 }
800
801                 /* Paranoia .... */
802                 if (EXCLUSIVE_OPLOCK_TYPE(share_entry->op_type)) {
803                         DEBUG(0,("release_level_2_oplocks_on_change: PANIC. "
804                                  "share mode entry %d is an exlusive "
805                                  "oplock !\n", i ));
806                         TALLOC_FREE(lck);
807                         abort();
808                 }
809
810                 share_mode_entry_to_message(msg, share_entry);
811
812                 /*
813                  * Deal with a race condition when breaking level2
814                  * oplocks. Don't send all the messages and release
815                  * the lock, this allows someone else to come in and
816                  * get a level2 lock before any of the messages are
817                  * processed, and thus miss getting a break message.
818                  * Ensure at least one entry (the one we're breaking)
819                  * is processed immediately under the lock and becomes
820                  * set as NO_OPLOCK to stop any waiter getting a level2.
821                  * Bugid #5980.
822                  */
823
824                 if (procid_is_me(&share_entry->pid)) {
825                         struct files_struct *cur_fsp =
826                                 initial_break_processing(fsp->conn->sconn,
827                                         share_entry->id,
828                                         share_entry->share_file_id);
829                         wait_before_sending_break();
830                         if (cur_fsp != NULL) {
831                                 break_level2_to_none_async(cur_fsp);
832                         } else {
833                                 DEBUG(3, ("release_level_2_oplocks_on_change: "
834                                 "Did not find fsp, ignoring\n"));
835                         }
836                 } else {
837                         messaging_send_buf(fsp->conn->sconn->msg_ctx,
838                                         share_entry->pid,
839                                         MSG_SMB_ASYNC_LEVEL2_BREAK,
840                                         (uint8 *)msg,
841                                         MSG_SMB_SHARE_MODE_ENTRY_SIZE);
842                 }
843         }
844
845         /* We let the message receivers handle removing the oplock state
846            in the share mode lock db. */
847
848         TALLOC_FREE(lck);
849 }
850
851 void contend_level2_oplocks_begin(files_struct *fsp,
852                                   enum level2_contention_type type)
853 {
854         if (koplocks && koplocks->ops->contend_level2_oplocks_begin) {
855                 koplocks->ops->contend_level2_oplocks_begin(fsp, type);
856                 return;
857         }
858
859         contend_level2_oplocks_begin_default(fsp, type);
860 }
861
862 void contend_level2_oplocks_end(files_struct *fsp,
863                                 enum level2_contention_type type)
864 {
865         /* Only kernel oplocks implement this so far */
866         if (koplocks && koplocks->ops->contend_level2_oplocks_end) {
867                 koplocks->ops->contend_level2_oplocks_end(fsp, type);
868         }
869 }
870
871 /****************************************************************************
872  Linearize a share mode entry struct to an internal oplock break message.
873 ****************************************************************************/
874
875 void share_mode_entry_to_message(char *msg, const struct share_mode_entry *e)
876 {
877         SIVAL(msg,OP_BREAK_MSG_PID_OFFSET,(uint32)e->pid.pid);
878         SBVAL(msg,OP_BREAK_MSG_MID_OFFSET,e->op_mid);
879         SSVAL(msg,OP_BREAK_MSG_OP_TYPE_OFFSET,e->op_type);
880         SIVAL(msg,OP_BREAK_MSG_ACCESS_MASK_OFFSET,e->access_mask);
881         SIVAL(msg,OP_BREAK_MSG_SHARE_ACCESS_OFFSET,e->share_access);
882         SIVAL(msg,OP_BREAK_MSG_PRIV_OFFSET,e->private_options);
883         SIVAL(msg,OP_BREAK_MSG_TIME_SEC_OFFSET,(uint32_t)e->time.tv_sec);
884         SIVAL(msg,OP_BREAK_MSG_TIME_USEC_OFFSET,(uint32_t)e->time.tv_usec);
885         push_file_id_24(msg+OP_BREAK_MSG_DEV_OFFSET, &e->id);
886         SIVAL(msg,OP_BREAK_MSG_FILE_ID_OFFSET,e->share_file_id);
887         SIVAL(msg,OP_BREAK_MSG_UID_OFFSET,e->uid);
888         SSVAL(msg,OP_BREAK_MSG_FLAGS_OFFSET,e->flags);
889         SIVAL(msg,OP_BREAK_MSG_NAME_HASH_OFFSET,e->name_hash);
890 #ifdef CLUSTER_SUPPORT
891         SIVAL(msg,OP_BREAK_MSG_VNN_OFFSET,e->pid.vnn);
892 #endif
893 }
894
895 /****************************************************************************
896  De-linearize an internal oplock break message to a share mode entry struct.
897 ****************************************************************************/
898
899 void message_to_share_mode_entry(struct share_mode_entry *e, char *msg)
900 {
901         e->pid.pid = (pid_t)IVAL(msg,OP_BREAK_MSG_PID_OFFSET);
902         e->op_mid = BVAL(msg,OP_BREAK_MSG_MID_OFFSET);
903         e->op_type = SVAL(msg,OP_BREAK_MSG_OP_TYPE_OFFSET);
904         e->access_mask = IVAL(msg,OP_BREAK_MSG_ACCESS_MASK_OFFSET);
905         e->share_access = IVAL(msg,OP_BREAK_MSG_SHARE_ACCESS_OFFSET);
906         e->private_options = IVAL(msg,OP_BREAK_MSG_PRIV_OFFSET);
907         e->time.tv_sec = (time_t)IVAL(msg,OP_BREAK_MSG_TIME_SEC_OFFSET);
908         e->time.tv_usec = (int)IVAL(msg,OP_BREAK_MSG_TIME_USEC_OFFSET);
909         pull_file_id_24(msg+OP_BREAK_MSG_DEV_OFFSET, &e->id);
910         e->share_file_id = (unsigned long)IVAL(msg,OP_BREAK_MSG_FILE_ID_OFFSET);
911         e->uid = (uint32)IVAL(msg,OP_BREAK_MSG_UID_OFFSET);
912         e->flags = (uint16)SVAL(msg,OP_BREAK_MSG_FLAGS_OFFSET);
913         e->name_hash = IVAL(msg,OP_BREAK_MSG_NAME_HASH_OFFSET);
914 #ifdef CLUSTER_SUPPORT
915         e->pid.vnn = IVAL(msg,OP_BREAK_MSG_VNN_OFFSET);
916 #endif
917 }
918
919 /****************************************************************************
920  Setup oplocks for this process.
921 ****************************************************************************/
922
923 bool init_oplocks(struct messaging_context *msg_ctx)
924 {
925         DEBUG(3,("init_oplocks: initializing messages.\n"));
926
927         messaging_register(msg_ctx, NULL, MSG_SMB_BREAK_REQUEST,
928                            process_oplock_break_message);
929         messaging_register(msg_ctx, NULL, MSG_SMB_ASYNC_LEVEL2_BREAK,
930                            process_oplock_async_level2_break_message);
931         messaging_register(msg_ctx, NULL, MSG_SMB_BREAK_RESPONSE,
932                            process_oplock_break_response);
933         messaging_register(msg_ctx, NULL, MSG_SMB_KERNEL_BREAK,
934                            process_kernel_oplock_break);
935         messaging_register(msg_ctx, NULL, MSG_SMB_OPEN_RETRY,
936                            process_open_retry_message);
937
938         if (lp_kernel_oplocks()) {
939 #if HAVE_KERNEL_OPLOCKS_IRIX
940                 koplocks = irix_init_kernel_oplocks(NULL);
941 #elif HAVE_KERNEL_OPLOCKS_LINUX
942                 koplocks = linux_init_kernel_oplocks(NULL);
943 #elif HAVE_ONEFS
944 #error Isilon, please check if the NULL context is okay here. Thanks!
945                 koplocks = onefs_init_kernel_oplocks(NULL);
946 #endif
947         }
948
949         return True;
950 }