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