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