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