22277abab07d9d4cb3f876b956acd3371ba2f4ce
[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 "lib/util/server_id.h"
25 #include "smbd/smbd.h"
26 #include "smbd/globals.h"
27 #include "messages.h"
28 #include "locking/leases_db.h"
29 #include "../librpc/gen_ndr/ndr_open_files.h"
30
31 /*
32  * helper function used by the kernel oplock backends to post the break message
33  */
34 void break_kernel_oplock(struct messaging_context *msg_ctx, files_struct *fsp)
35 {
36         uint8_t msg[MSG_SMB_KERNEL_BREAK_SIZE];
37
38         /* Put the kernel break info into the message. */
39         push_file_id_24((char *)msg, &fsp->file_id);
40         SIVAL(msg,24,fsp->fh->gen_id);
41
42         /* Don't need to be root here as we're only ever
43            sending to ourselves. */
44
45         messaging_send_buf(msg_ctx, messaging_server_id(msg_ctx),
46                            MSG_SMB_KERNEL_BREAK,
47                            msg, MSG_SMB_KERNEL_BREAK_SIZE);
48 }
49
50 /****************************************************************************
51  Attempt to set an oplock on a file. Succeeds if kernel oplocks are
52  disabled (just sets flags).
53 ****************************************************************************/
54
55 NTSTATUS set_file_oplock(files_struct *fsp)
56 {
57         struct smbd_server_connection *sconn = fsp->conn->sconn;
58         struct kernel_oplocks *koplocks = sconn->oplocks.kernel_ops;
59         bool use_kernel = lp_kernel_oplocks(SNUM(fsp->conn)) &&
60                         (koplocks != NULL);
61
62         if (fsp->oplock_type == LEVEL_II_OPLOCK && use_kernel) {
63                 DEBUG(10, ("Refusing level2 oplock, kernel oplocks "
64                            "don't support them\n"));
65                 return NT_STATUS_NOT_SUPPORTED;
66         }
67
68         if ((fsp->oplock_type != NO_OPLOCK) &&
69             use_kernel &&
70             !koplocks->ops->set_oplock(koplocks, fsp, fsp->oplock_type))
71         {
72                 return map_nt_error_from_unix(errno);
73         }
74
75         fsp->sent_oplock_break = NO_BREAK_SENT;
76         if (fsp->oplock_type == LEVEL_II_OPLOCK) {
77                 sconn->oplocks.level_II_open++;
78         } else if (EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type)) {
79                 sconn->oplocks.exclusive_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_str_dbg(fsp), 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 NT_STATUS_OK;
89 }
90
91 static void release_fsp_kernel_oplock(files_struct *fsp)
92 {
93         struct smbd_server_connection *sconn = fsp->conn->sconn;
94         struct kernel_oplocks *koplocks = sconn->oplocks.kernel_ops;
95         bool use_kernel;
96
97         if (koplocks == NULL) {
98                 return;
99         }
100         use_kernel = lp_kernel_oplocks(SNUM(fsp->conn));
101         if (!use_kernel) {
102                 return;
103         }
104         if (fsp->oplock_type == NO_OPLOCK) {
105                 return;
106         }
107         if (fsp->oplock_type == LEASE_OPLOCK) {
108                 /*
109                  * For leases we don't touch kernel oplocks at all
110                  */
111                 return;
112         }
113
114         koplocks->ops->release_oplock(koplocks, fsp, NO_OPLOCK);
115 }
116
117 /****************************************************************************
118  Attempt to release an oplock on a file. Decrements oplock count.
119 ****************************************************************************/
120
121 static void release_file_oplock(files_struct *fsp)
122 {
123         struct smbd_server_connection *sconn = fsp->conn->sconn;
124
125         release_fsp_kernel_oplock(fsp);
126
127         if (fsp->oplock_type == LEVEL_II_OPLOCK) {
128                 sconn->oplocks.level_II_open--;
129         } else if (EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type)) {
130                 sconn->oplocks.exclusive_open--;
131         }
132
133         SMB_ASSERT(sconn->oplocks.exclusive_open>=0);
134         SMB_ASSERT(sconn->oplocks.level_II_open>=0);
135
136         fsp->oplock_type = NO_OPLOCK;
137         fsp->sent_oplock_break = NO_BREAK_SENT;
138
139         flush_write_cache(fsp, SAMBA_OPLOCK_RELEASE_FLUSH);
140         delete_write_cache(fsp);
141
142         TALLOC_FREE(fsp->oplock_timeout);
143 }
144
145 /****************************************************************************
146  Attempt to downgrade an oplock on a file. Doesn't decrement oplock count.
147 ****************************************************************************/
148
149 static void downgrade_file_oplock(files_struct *fsp)
150 {
151         struct smbd_server_connection *sconn = fsp->conn->sconn;
152         struct kernel_oplocks *koplocks = sconn->oplocks.kernel_ops;
153         bool use_kernel = lp_kernel_oplocks(SNUM(fsp->conn)) &&
154                         (koplocks != NULL);
155
156         if (!EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type)) {
157                 DEBUG(0, ("trying to downgrade an already-downgraded oplock!\n"));
158                 return;
159         }
160
161         if (use_kernel) {
162                 koplocks->ops->release_oplock(koplocks, fsp, LEVEL_II_OPLOCK);
163         }
164         fsp->oplock_type = LEVEL_II_OPLOCK;
165         sconn->oplocks.exclusive_open--;
166         sconn->oplocks.level_II_open++;
167         fsp->sent_oplock_break = NO_BREAK_SENT;
168
169         flush_write_cache(fsp, SAMBA_OPLOCK_RELEASE_FLUSH);
170         delete_write_cache(fsp);
171
172         TALLOC_FREE(fsp->oplock_timeout);
173 }
174
175 uint32_t get_lease_type(const struct share_mode_data *d,
176                         const struct share_mode_entry *e)
177 {
178         if (e->op_type == LEASE_OPLOCK) {
179                 NTSTATUS status;
180                 uint32_t current_state;
181
182                 status = leases_db_get(
183                         &e->client_guid,
184                         &e->lease_key,
185                         &d->id,
186                         &current_state,
187                         NULL,   /* breaking */
188                         NULL,   /* breaking_to_requested */
189                         NULL,   /* breaking_to_required */
190                         NULL,   /* lease_version */
191                         NULL);  /* epoch */
192                 SMB_ASSERT(NT_STATUS_IS_OK(status));
193                 return current_state;
194         }
195         return map_oplock_to_lease_type(e->op_type);
196 }
197
198 bool update_num_read_oplocks(files_struct *fsp, struct share_mode_lock *lck)
199 {
200         struct share_mode_data *d = lck->data;
201         struct byte_range_lock *br_lck;
202         uint32_t num_read_oplocks = 0;
203         uint32_t i;
204
205         if (fsp_lease_type_is_exclusive(fsp)) {
206                 const struct share_mode_entry *e = NULL;
207                 uint32_t e_lease_type = 0;
208
209                 /*
210                  * If we're fully exclusive, we don't need a brlock entry
211                  */
212                 remove_stale_share_mode_entries(d);
213
214                 e = find_share_mode_entry(lck, fsp);
215                 if (e != NULL) {
216                         e_lease_type = get_lease_type(d, e);
217                 }
218
219                 if (!lease_type_is_exclusive(e_lease_type)) {
220                         char *timestr = NULL;
221
222                         timestr = timeval_string(talloc_tos(),
223                                                  &fsp->open_time,
224                                                  true);
225
226                         NDR_PRINT_DEBUG(share_mode_data, d);
227                         DBG_ERR("file [%s] file_id [%s] gen_id [%lu] "
228                                 "open_time[%s] lease_type [0x%x] "
229                                 "oplock_type [0x%x]\n",
230                                 fsp_str_dbg(fsp),
231                                 file_id_string_tos(&fsp->file_id),
232                                 fsp->fh->gen_id, timestr,
233                                 e_lease_type, fsp->oplock_type);
234
235                         smb_panic("Found non-exclusive lease");
236                 }
237
238                 return true;
239         }
240
241         for (i=0; i<d->num_share_modes; i++) {
242                 struct share_mode_entry *e = &d->share_modes[i];
243                 uint32_t e_lease_type = get_lease_type(d, e);
244
245                 if (e_lease_type & SMB2_LEASE_READ) {
246                         num_read_oplocks += 1;
247                 }
248         }
249
250         br_lck = brl_get_locks_readonly(fsp);
251         if (br_lck == NULL) {
252                 return false;
253         }
254         if (brl_num_read_oplocks(br_lck) == num_read_oplocks) {
255                 return true;
256         }
257
258         br_lck = brl_get_locks(talloc_tos(), fsp);
259         if (br_lck == NULL) {
260                 return false;
261         }
262         brl_set_num_read_oplocks(br_lck, num_read_oplocks);
263         TALLOC_FREE(br_lck);
264         return true;
265 }
266
267 /****************************************************************************
268  Remove a file oplock with lock already held. Copes with level II and exclusive.
269 ****************************************************************************/
270
271 bool remove_oplock_under_lock(files_struct *fsp, struct share_mode_lock *lck)
272 {
273         bool ret;
274
275         ret = remove_share_oplock(lck, fsp);
276         if (!ret) {
277                 DBG_ERR("failed to remove share oplock for "
278                         "file %s, %s, %s\n",
279                         fsp_str_dbg(fsp), fsp_fnum_dbg(fsp),
280                         file_id_string_tos(&fsp->file_id));
281         }
282         release_file_oplock(fsp);
283
284         ret = update_num_read_oplocks(fsp, lck);
285         if (!ret) {
286                 DBG_ERR("update_num_read_oplocks failed for "
287                         "file %s, %s, %s\n",
288                         fsp_str_dbg(fsp), fsp_fnum_dbg(fsp),
289                         file_id_string_tos(&fsp->file_id));
290         }
291
292         return ret;
293 }
294
295 /****************************************************************************
296  Remove a file oplock. Copes with level II and exclusive.
297  Locks then unlocks the share mode lock. Client can decide to go directly
298  to none even if a "break-to-level II" was sent.
299 ****************************************************************************/
300
301 bool remove_oplock(files_struct *fsp)
302 {
303         bool ret;
304         struct share_mode_lock *lck;
305
306         DBG_DEBUG("remove_oplock called for %s\n", fsp_str_dbg(fsp));
307
308         /* Remove the oplock flag from the sharemode. */
309         lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
310         if (lck == NULL) {
311                 DBG_ERR("failed to lock share entry for "
312                          "file %s\n", fsp_str_dbg(fsp));
313                 return false;
314         }
315
316         ret = remove_oplock_under_lock(fsp, lck);
317
318         TALLOC_FREE(lck);
319         return ret;
320 }
321
322 /*
323  * Deal with a reply when a break-to-level II was sent.
324  */
325 bool downgrade_oplock(files_struct *fsp)
326 {
327         bool ret;
328         struct share_mode_lock *lck;
329
330         DEBUG(10, ("downgrade_oplock called for %s\n",
331                    fsp_str_dbg(fsp)));
332
333         lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
334         if (lck == NULL) {
335                 DEBUG(0,("downgrade_oplock: failed to lock share entry for "
336                          "file %s\n", fsp_str_dbg(fsp)));
337                 return False;
338         }
339         ret = downgrade_share_oplock(lck, fsp);
340         if (!ret) {
341                 DEBUG(0,("downgrade_oplock: failed to downgrade share oplock "
342                          "for file %s, %s, file_id %s\n",
343                          fsp_str_dbg(fsp), fsp_fnum_dbg(fsp),
344                          file_id_string_tos(&fsp->file_id)));
345         }
346         downgrade_file_oplock(fsp);
347
348         ret = update_num_read_oplocks(fsp, lck);
349         if (!ret) {
350                 DEBUG(0, ("%s: update_num_read_oplocks failed for "
351                          "file %s, %s, %s\n",
352                           __func__, fsp_str_dbg(fsp), fsp_fnum_dbg(fsp),
353                          file_id_string_tos(&fsp->file_id)));
354         }
355
356         TALLOC_FREE(lck);
357         return ret;
358 }
359
360 static void lease_timeout_handler(struct tevent_context *ctx,
361                                   struct tevent_timer *te,
362                                   struct timeval now,
363                                   void *private_data)
364 {
365         struct fsp_lease *lease =
366                 talloc_get_type_abort(private_data,
367                 struct fsp_lease);
368         struct files_struct *fsp;
369         struct share_mode_lock *lck;
370         uint16_t old_epoch = lease->lease.lease_epoch;
371
372         fsp = file_find_one_fsp_from_lease_key(lease->sconn,
373                                                &lease->lease.lease_key);
374         if (fsp == NULL) {
375                 /* race? */
376                 TALLOC_FREE(lease->timeout);
377                 return;
378         }
379
380         /*
381          * Paranoia check: There can only be one fsp_lease per lease
382          * key
383          */
384         SMB_ASSERT(fsp->lease == lease);
385
386         lck = get_existing_share_mode_lock(
387                         talloc_tos(), fsp->file_id);
388         if (lck == NULL) {
389                 /* race? */
390                 TALLOC_FREE(lease->timeout);
391                 return;
392         }
393
394         fsp_lease_update(lck, fsp_client_guid(fsp), lease);
395
396         if (lease->lease.lease_epoch != old_epoch) {
397                 /*
398                  * If the epoch changed we need to wait for
399                  * the next timeout to happen.
400                  */
401                 DEBUG(10, ("lease break timeout race (epoch) for file %s - ignoring\n",
402                            fsp_str_dbg(fsp)));
403                 TALLOC_FREE(lck);
404                 return;
405         }
406
407         if (!(lease->lease.lease_flags & SMB2_LEASE_FLAG_BREAK_IN_PROGRESS)) {
408                 /*
409                  * If the epoch changed we need to wait for
410                  * the next timeout to happen.
411                  */
412                 DEBUG(10, ("lease break timeout race (flags) for file %s - ignoring\n",
413                            fsp_str_dbg(fsp)));
414                 TALLOC_FREE(lck);
415                 return;
416         }
417
418         DEBUG(1, ("lease break timed out for file %s -- replying anyway\n",
419                   fsp_str_dbg(fsp)));
420         (void)downgrade_lease(lease->sconn->client->connections,
421                         1,
422                         &fsp->file_id,
423                         &lease->lease.lease_key,
424                         SMB2_LEASE_NONE);
425
426         TALLOC_FREE(lck);
427 }
428
429 bool fsp_lease_update(struct share_mode_lock *lck,
430                       const struct GUID *client_guid,
431                       struct fsp_lease *lease)
432 {
433         uint32_t current_state;
434         bool breaking;
435         uint16_t lease_version, epoch;
436         NTSTATUS status;
437
438         status = leases_db_get(client_guid,
439                                &lease->lease.lease_key,
440                                &lck->data->id,
441                                &current_state,
442                                &breaking,
443                                NULL, /* breaking_to_requested */
444                                NULL, /* breaking_to_required */
445                                &lease_version,
446                                &epoch);
447         if (!NT_STATUS_IS_OK(status)) {
448                 DBG_WARNING("Could not find lease entry: %s\n",
449                             nt_errstr(status));
450                 TALLOC_FREE(lease->timeout);
451                 lease->lease.lease_state = SMB2_LEASE_NONE;
452                 lease->lease.lease_epoch += 1;
453                 lease->lease.lease_flags = 0;
454                 return false;
455         }
456
457         DEBUG(10,("%s: refresh lease state\n", __func__));
458
459         /* Ensure we're in sync with current lease state. */
460         if (lease->lease.lease_epoch != epoch) {
461                 DEBUG(10,("%s: cancel outdated timeout\n", __func__));
462                 TALLOC_FREE(lease->timeout);
463         }
464         lease->lease.lease_epoch = epoch;
465         lease->lease.lease_state = current_state;
466
467         if (breaking) {
468                 lease->lease.lease_flags |= SMB2_LEASE_FLAG_BREAK_IN_PROGRESS;
469
470                 if (lease->timeout == NULL) {
471                         struct timeval t = timeval_current_ofs(OPLOCK_BREAK_TIMEOUT, 0);
472
473                         DEBUG(10,("%s: setup timeout handler\n", __func__));
474
475                         lease->timeout = tevent_add_timer(lease->sconn->ev_ctx,
476                                                           lease, t,
477                                                           lease_timeout_handler,
478                                                           lease);
479                         if (lease->timeout == NULL) {
480                                 DEBUG(0, ("%s: Could not add lease timeout handler\n",
481                                           __func__));
482                         }
483                 }
484         } else {
485                 lease->lease.lease_flags &= ~SMB2_LEASE_FLAG_BREAK_IN_PROGRESS;
486                 TALLOC_FREE(lease->timeout);
487         }
488
489         return true;
490 }
491
492 struct downgrade_lease_additional_state {
493         struct tevent_immediate *im;
494         struct smbXsrv_connection *xconn;
495         uint32_t break_flags;
496         struct smb2_lease_key lease_key;
497         uint32_t break_from;
498         uint32_t break_to;
499         uint16_t new_epoch;
500 };
501
502 static void downgrade_lease_additional_trigger(struct tevent_context *ev,
503                                                struct tevent_immediate *im,
504                                                void *private_data)
505 {
506         struct downgrade_lease_additional_state *state =
507                 talloc_get_type_abort(private_data,
508                 struct downgrade_lease_additional_state);
509         struct smbXsrv_connection *xconn = state->xconn;
510         NTSTATUS status;
511
512         status = smbd_smb2_send_lease_break(xconn,
513                                             state->new_epoch,
514                                             state->break_flags,
515                                             &state->lease_key,
516                                             state->break_from,
517                                             state->break_to);
518         TALLOC_FREE(state);
519         if (!NT_STATUS_IS_OK(status)) {
520                 smbd_server_connection_terminate(xconn,
521                                                  nt_errstr(status));
522                 return;
523         }
524 }
525
526 struct downgrade_lease_fsps_state {
527         struct file_id id;
528         struct share_mode_lock *lck;
529         const struct smb2_lease_key *key;
530 };
531
532 static struct files_struct *downgrade_lease_fsps(struct files_struct *fsp,
533                                                  void *private_data)
534 {
535         struct downgrade_lease_fsps_state *state =
536                 (struct downgrade_lease_fsps_state *)private_data;
537
538         if (fsp->oplock_type != LEASE_OPLOCK) {
539                 return NULL;
540         }
541         if (!smb2_lease_key_equal(&fsp->lease->lease.lease_key, state->key)) {
542                 return NULL;
543         }
544         if (!file_id_equal(&fsp->file_id, &state->id)) {
545                 return NULL;
546         }
547
548         fsp_lease_update(state->lck, fsp_client_guid(fsp), fsp->lease);
549
550         return NULL;
551 }
552
553 NTSTATUS downgrade_lease(struct smbXsrv_connection *xconn,
554                          uint32_t num_file_ids,
555                          const struct file_id *ids,
556                          const struct smb2_lease_key *key,
557                          uint32_t lease_state)
558 {
559         struct smbd_server_connection *sconn = xconn->client->sconn;
560         const struct GUID *client_guid = NULL;
561         struct share_mode_lock *lck;
562         const struct file_id id = ids[0];
563         uint32_t current_state, breaking_to_requested, breaking_to_required;
564         bool breaking;
565         uint16_t lease_version, epoch;
566         NTSTATUS status;
567         uint32_t i;
568
569         DEBUG(10, ("%s: Downgrading %s to %x\n", __func__,
570                    file_id_string_tos(&id), (unsigned)lease_state));
571
572         lck = get_existing_share_mode_lock(talloc_tos(), id);
573         if (lck == NULL) {
574                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
575         }
576
577         client_guid = &sconn->client->connections->smb2.client.guid;
578
579         status = leases_db_get(client_guid,
580                                key,
581                                &id,
582                                &current_state,
583                                &breaking,
584                                &breaking_to_requested,
585                                &breaking_to_required,
586                                &lease_version,
587                                &epoch);
588         if (!NT_STATUS_IS_OK(status)) {
589                 DBG_WARNING("leases_db_get returned %s\n",
590                             nt_errstr(status));
591                 TALLOC_FREE(lck);
592                 return status;
593         }
594
595         if (!breaking) {
596                 DBG_WARNING("Attempt to break from %"PRIu32" to %"PRIu32" - "
597                             "but we're not in breaking state\n",
598                             current_state, lease_state);
599                 TALLOC_FREE(lck);
600                 return NT_STATUS_UNSUCCESSFUL;
601         }
602
603         /*
604          * Can't upgrade anything: breaking_to_requested (and current_state)
605          * must be a strict bitwise superset of new_lease_state
606          */
607         if ((lease_state & breaking_to_requested) != lease_state) {
608                 DBG_WARNING("Attempt to upgrade from %"PRIu32" to %"PRIu32" "
609                             "- expected %"PRIu32"\n",
610                             current_state, lease_state,
611                             breaking_to_requested);
612                 TALLOC_FREE(lck);
613                 return NT_STATUS_REQUEST_NOT_ACCEPTED;
614         }
615
616         if (current_state != lease_state) {
617                 current_state = lease_state;
618         }
619
620         status = NT_STATUS_OK;
621
622         if ((lease_state & ~breaking_to_required) != 0) {
623                 struct downgrade_lease_additional_state *state;
624
625                 DBG_INFO("lease state %"PRIu32" not fully broken from "
626                          "%"PRIu32" to %"PRIu32"\n",
627                          lease_state,
628                          current_state,
629                          breaking_to_required);
630
631                 breaking_to_requested = breaking_to_required;
632
633                 if (current_state & (SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE)) {
634                         /*
635                          * Here we break in steps, as windows does
636                          * see the breaking3 and v2_breaking3 tests.
637                          */
638                         breaking_to_requested |= SMB2_LEASE_READ;
639                 }
640
641                 state = talloc_zero(xconn,
642                                     struct downgrade_lease_additional_state);
643                 if (state == NULL) {
644                         TALLOC_FREE(lck);
645                         return NT_STATUS_NO_MEMORY;
646                 }
647
648                 state->im = tevent_create_immediate(state);
649                 if (state->im == NULL) {
650                         TALLOC_FREE(state);
651                         TALLOC_FREE(lck);
652                         return NT_STATUS_NO_MEMORY;
653                 }
654
655                 state->xconn = xconn;
656                 state->lease_key = *key;
657                 state->break_from = current_state;
658                 state->break_to = breaking_to_requested;
659                 if (lease_version > 1) {
660                         state->new_epoch = epoch;
661                 }
662
663                 if (current_state & (SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE)) {
664                         state->break_flags =
665                                 SMB2_NOTIFY_BREAK_LEASE_FLAG_ACK_REQUIRED;
666                 } else {
667                         /*
668                          * This is an async break without
669                          * SMB2_NOTIFY_BREAK_LEASE_FLAG_ACK_REQUIRED
670                          *
671                          * we need to store NONE state in the
672                          * database.
673                          */
674                         current_state = 0;
675                         breaking_to_requested = 0;
676                         breaking_to_required = 0;
677                         breaking = false;
678
679                         {
680                                 NTSTATUS set_status;
681
682                                 set_status = leases_db_set(
683                                         &sconn->client->connections->
684                                         smb2.client.guid,
685                                         key,
686                                         current_state,
687                                         breaking,
688                                         breaking_to_requested,
689                                         breaking_to_required,
690                                         lease_version,
691                                         epoch);
692
693                                 if (!NT_STATUS_IS_OK(set_status)) {
694                                         DBG_DEBUG("leases_db_set failed: %s\n",
695                                                   nt_errstr(set_status));
696                                         return set_status;
697                                 }
698                         }
699                 }
700
701                 tevent_schedule_immediate(state->im,
702                                           xconn->client->raw_ev_ctx,
703                                           downgrade_lease_additional_trigger,
704                                           state);
705
706                 status = NT_STATUS_OPLOCK_BREAK_IN_PROGRESS;
707         } else {
708                 DBG_DEBUG("breaking from %"PRIu32" to %"PRIu32" - "
709                           "expected %"PRIu32"\n",
710                           current_state,
711                           lease_state,
712                           breaking_to_requested);
713
714                 breaking_to_requested = 0;
715                 breaking_to_required = 0;
716                 breaking = false;
717         }
718
719         {
720                 NTSTATUS set_status;
721
722                 set_status = leases_db_set(
723                         client_guid,
724                         key,
725                         current_state,
726                         breaking,
727                         breaking_to_requested,
728                         breaking_to_required,
729                         lease_version,
730                         epoch);
731
732                 if (!NT_STATUS_IS_OK(set_status)) {
733                         DBG_DEBUG("leases_db_set failed: %s\n",
734                                   nt_errstr(set_status));
735                         TALLOC_FREE(lck);
736                         return set_status;
737                 }
738         }
739
740         DEBUG(10, ("%s: Downgrading %s to %x => %s\n", __func__,
741                    file_id_string_tos(&id), (unsigned)lease_state, nt_errstr(status)));
742
743         /*
744          * No, we did not modify the share mode array. We did modify
745          * the leases_db. But without this we don't notify a lease
746          * break waiter via dbwrap_watch_record. We need to make
747          * leases_db watched too.
748          */
749         lck->data->modified = true;
750
751         {
752                 struct downgrade_lease_fsps_state state = {
753                         .id = id, .lck = lck, .key = key,
754                 };
755
756                 files_forall(sconn, downgrade_lease_fsps, &state);
757         }
758
759         TALLOC_FREE(lck);
760         DEBUG(10, ("%s: Downgrading %s to %x => %s\n", __func__,
761                    file_id_string_tos(&id), (unsigned)lease_state, nt_errstr(status)));
762
763         /*
764          * Dynamic share case. Ensure other opens are copies.
765          * This will only be breaking to NONE.
766          */
767
768         for (i = 1; i < num_file_ids; i++) {
769                 lck = get_existing_share_mode_lock(talloc_tos(), ids[i]);
770                 if (lck == NULL) {
771                         return NT_STATUS_OBJECT_NAME_NOT_FOUND;
772                 }
773
774                 {
775                         struct downgrade_lease_fsps_state state = {
776                                 .id = ids[i], .lck = lck, .key = key,
777                         };
778
779                         files_forall(sconn, downgrade_lease_fsps, &state);
780                 }
781
782                 DEBUG(10, ("%s: Downgrading %s to %x => %s\n", __func__,
783                         file_id_string_tos(&ids[i]), (unsigned)lease_state, nt_errstr(status)));
784
785                 TALLOC_FREE(lck);
786         }
787
788         return status;
789 }
790
791 /****************************************************************************
792  Set up an oplock break message.
793 ****************************************************************************/
794
795 #define SMB1_BREAK_MESSAGE_LENGTH (smb_size + 8*2)
796
797 static void new_break_message_smb1(files_struct *fsp, int cmd,
798                                    char result[SMB1_BREAK_MESSAGE_LENGTH])
799 {
800         memset(result,'\0',smb_size);
801         srv_set_message(result,8,0,true);
802         SCVAL(result,smb_com,SMBlockingX);
803         SSVAL(result,smb_tid,fsp->conn->cnum);
804         SSVAL(result,smb_pid,0xFFFF);
805         SSVAL(result,smb_uid,0);
806         SSVAL(result,smb_mid,0xFFFF);
807         SCVAL(result,smb_vwv0,0xFF);
808         SSVAL(result,smb_vwv2,fsp->fnum);
809         SCVAL(result,smb_vwv3,LOCKING_ANDX_OPLOCK_RELEASE);
810         SCVAL(result,smb_vwv3+1,cmd);
811 }
812
813 /****************************************************************************
814  Function to do the waiting before sending a local break.
815 ****************************************************************************/
816
817 static void wait_before_sending_break(void)
818 {
819         long wait_time = (long)lp_oplock_break_wait_time();
820
821         if (wait_time) {
822                 smb_msleep(wait_time);
823         }
824 }
825
826 /****************************************************************************
827  Ensure that we have a valid oplock.
828 ****************************************************************************/
829
830 static files_struct *initial_break_processing(
831         struct smbd_server_connection *sconn, struct file_id id,
832         unsigned long file_id)
833 {
834         files_struct *fsp = NULL;
835
836         DEBUG(3, ("initial_break_processing: called for %s/%u\n"
837                   "Current oplocks_open (exclusive = %d, levelII = %d)\n",
838                   file_id_string_tos(&id), (int)file_id,
839                   sconn->oplocks.exclusive_open,
840                   sconn->oplocks.level_II_open));
841
842         /*
843          * We need to search the file open table for the
844          * entry containing this dev and inode, and ensure
845          * we have an oplock on it.
846          */
847
848         fsp = file_find_dif(sconn, id, file_id);
849
850         if(fsp == NULL) {
851                 /* The file could have been closed in the meantime - return success. */
852                 DEBUG(3, ("initial_break_processing: cannot find open file "
853                           "with file_id %s gen_id = %lu, allowing break to "
854                           "succeed.\n", file_id_string_tos(&id), file_id));
855                 return NULL;
856         }
857
858         /* Ensure we have an oplock on the file */
859
860         /*
861          * There is a potential race condition in that an oplock could
862          * have been broken due to another udp request, and yet there are
863          * still oplock break messages being sent in the udp message
864          * queue for this file. So return true if we don't have an oplock,
865          * as we may have just freed it.
866          */
867
868         if(fsp->oplock_type == NO_OPLOCK) {
869                 DEBUG(3, ("initial_break_processing: file %s (file_id = %s "
870                           "gen_id = %lu) has no oplock. Allowing break to "
871                           "succeed regardless.\n", fsp_str_dbg(fsp),
872                           file_id_string_tos(&id), fsp->fh->gen_id));
873                 return NULL;
874         }
875
876         return fsp;
877 }
878
879 static void oplock_timeout_handler(struct tevent_context *ctx,
880                                    struct tevent_timer *te,
881                                    struct timeval now,
882                                    void *private_data)
883 {
884         files_struct *fsp = (files_struct *)private_data;
885
886         SMB_ASSERT(fsp->sent_oplock_break != NO_BREAK_SENT);
887
888         /* Remove the timed event handler. */
889         TALLOC_FREE(fsp->oplock_timeout);
890         DEBUG(0, ("Oplock break failed for file %s -- replying anyway\n",
891                   fsp_str_dbg(fsp)));
892         remove_oplock(fsp);
893 }
894
895 /*******************************************************************
896  Add a timeout handler waiting for the client reply.
897 *******************************************************************/
898
899 static void add_oplock_timeout_handler(files_struct *fsp)
900 {
901         if (fsp->oplock_timeout != NULL) {
902                 DEBUG(0, ("Logic problem -- have an oplock event hanging "
903                           "around\n"));
904         }
905
906         fsp->oplock_timeout =
907                 tevent_add_timer(fsp->conn->sconn->ev_ctx, fsp,
908                                  timeval_current_ofs(OPLOCK_BREAK_TIMEOUT, 0),
909                                  oplock_timeout_handler, fsp);
910
911         if (fsp->oplock_timeout == NULL) {
912                 DEBUG(0, ("Could not add oplock timeout handler\n"));
913         }
914 }
915
916 static void send_break_message_smb1(files_struct *fsp, int level)
917 {
918         struct smbXsrv_connection *xconn = NULL;
919         char break_msg[SMB1_BREAK_MESSAGE_LENGTH];
920
921         /*
922          * For SMB1 we only have one connection
923          */
924         xconn = fsp->conn->sconn->client->connections;
925
926         new_break_message_smb1(fsp, level, break_msg);
927
928         show_msg(break_msg);
929         if (!srv_send_smb(xconn,
930                         break_msg, false, 0,
931                         IS_CONN_ENCRYPTED(fsp->conn),
932                         NULL)) {
933                 exit_server_cleanly("send_break_message_smb1: "
934                         "srv_send_smb failed.");
935         }
936 }
937
938 /*******************************************************************
939  This handles the generic oplock break message from another smbd.
940 *******************************************************************/
941
942 static void process_oplock_break_message(struct messaging_context *msg_ctx,
943                                          void *private_data,
944                                          uint32_t msg_type,
945                                          struct server_id src,
946                                          DATA_BLOB *data)
947 {
948         struct file_id id;
949         struct share_mode_entry msg;
950         files_struct *fsp;
951         bool use_kernel;
952         struct smbd_server_connection *sconn =
953                 talloc_get_type_abort(private_data,
954                 struct smbd_server_connection);
955         struct server_id self = messaging_server_id(sconn->msg_ctx);
956         struct kernel_oplocks *koplocks = sconn->oplocks.kernel_ops;
957         uint16_t break_from;
958         uint16_t break_to;
959         bool break_needed = true;
960         struct server_id_buf tmp;
961
962         if (data->data == NULL) {
963                 DEBUG(0, ("Got NULL buffer\n"));
964                 return;
965         }
966
967         if (data->length != MSG_SMB_SHARE_MODE_ENTRY_SIZE) {
968                 DEBUG(0, ("Got invalid msg len %d\n", (int)data->length));
969                 return;
970         }
971
972         /* De-linearize incoming message. */
973         message_to_share_mode_entry(&id, &msg, (char *)data->data);
974         break_to = msg.op_type;
975
976         DEBUG(10, ("Got oplock break to %u message from pid %s: %s/%llu\n",
977                    (unsigned)break_to, server_id_str_buf(src, &tmp),
978                    file_id_string_tos(&id),
979                    (unsigned long long)msg.share_file_id));
980
981         fsp = initial_break_processing(sconn, id, msg.share_file_id);
982
983         if (fsp == NULL) {
984                 /* We hit a race here. Break messages are sent, and before we
985                  * get to process this message, we have closed the file. */
986                 DEBUG(3, ("Did not find fsp\n"));
987                 return;
988         }
989
990         break_from = fsp_lease_type(fsp);
991
992         if (fsp->oplock_type != LEASE_OPLOCK) {
993                 if (fsp->sent_oplock_break != NO_BREAK_SENT) {
994                         /*
995                          * Nothing to do anymore
996                          */
997                         DEBUG(10, ("fsp->sent_oplock_break = %d\n",
998                                    fsp->sent_oplock_break));
999                         return;
1000                 }
1001         }
1002
1003         if (!(global_client_caps & CAP_LEVEL_II_OPLOCKS)) {
1004                 DEBUG(10, ("client_caps without level2 oplocks\n"));
1005                 break_to &= ~SMB2_LEASE_READ;
1006         }
1007
1008         use_kernel = lp_kernel_oplocks(SNUM(fsp->conn)) &&
1009                         (koplocks != NULL);
1010         if (use_kernel) {
1011                 DEBUG(10, ("Kernel oplocks don't allow level2\n"));
1012                 break_to &= ~SMB2_LEASE_READ;
1013         }
1014
1015         if (!lp_level2_oplocks(SNUM(fsp->conn))) {
1016                 DEBUG(10, ("no level2 oplocks by config\n"));
1017                 break_to &= ~SMB2_LEASE_READ;
1018         }
1019
1020         if (fsp->oplock_type == LEASE_OPLOCK) {
1021                 const struct GUID *client_guid = fsp_client_guid(fsp);
1022                 struct share_mode_lock *lck;
1023                 uint32_t current_state;
1024                 uint32_t breaking_to_requested, breaking_to_required;
1025                 bool breaking;
1026                 uint16_t lease_version, epoch;
1027                 NTSTATUS status;
1028
1029                 lck = get_existing_share_mode_lock(
1030                         talloc_tos(), fsp->file_id);
1031                 if (lck == NULL) {
1032                         /*
1033                          * We hit a race here. Break messages are sent, and
1034                          * before we get to process this message, we have closed
1035                          * the file.
1036                          */
1037                         DEBUG(3, ("Did not find share_mode\n"));
1038                         return;
1039                 }
1040
1041                 status = leases_db_get(client_guid,
1042                                        &fsp->lease->lease.lease_key,
1043                                        &id,
1044                                        &current_state,
1045                                        &breaking,
1046                                        &breaking_to_requested,
1047                                        &breaking_to_required,
1048                                        &lease_version,
1049                                        &epoch);
1050                 if (!NT_STATUS_IS_OK(status)) {
1051                         DBG_WARNING("leases_db_get returned %s\n",
1052                                     nt_errstr(status));
1053                         TALLOC_FREE(lck);
1054                         return;
1055                 }
1056
1057                 break_from = current_state;
1058                 break_to &= current_state;
1059
1060                 if (breaking) {
1061                         break_to &= breaking_to_required;
1062                         if (breaking_to_required != break_to) {
1063                                 /*
1064                                  * Note we don't increment the epoch
1065                                  * here, which might be a bug in
1066                                  * Windows too...
1067                                  */
1068                                 breaking_to_required = break_to;
1069                         }
1070                         break_needed = false;
1071                 } else if (current_state == break_to) {
1072                         break_needed = false;
1073                 } else if (current_state == SMB2_LEASE_READ) {
1074                         current_state = SMB2_LEASE_NONE;
1075                         /* Need to increment the epoch */
1076                         epoch += 1;
1077                 } else {
1078                         breaking = true;
1079                         breaking_to_required = break_to;
1080                         breaking_to_requested = break_to;
1081                         /* Need to increment the epoch */
1082                         epoch += 1;
1083                 }
1084
1085                 {
1086                         NTSTATUS set_status;
1087
1088                         set_status = leases_db_set(
1089                                 client_guid,
1090                                 &fsp->lease->lease.lease_key,
1091                                 current_state,
1092                                 breaking,
1093                                 breaking_to_requested,
1094                                 breaking_to_required,
1095                                 lease_version,
1096                                 epoch);
1097
1098                         if (!NT_STATUS_IS_OK(set_status)) {
1099                                 DBG_DEBUG("leases_db_set failed: %s\n",
1100                                           nt_errstr(set_status));
1101                                 return;
1102                         }
1103                 }
1104
1105                 /* Ensure we're in sync with current lease state. */
1106                 fsp_lease_update(lck, fsp_client_guid(fsp), fsp->lease);
1107
1108                 TALLOC_FREE(lck);
1109         }
1110
1111         if (!break_needed) {
1112                 DEBUG(10,("%s: skip break\n", __func__));
1113                 return;
1114         }
1115
1116         if ((break_from == SMB2_LEASE_NONE) && !break_needed) {
1117                 DEBUG(3, ("Already downgraded oplock to none on %s: %s\n",
1118                           file_id_string_tos(&fsp->file_id),
1119                           fsp_str_dbg(fsp)));
1120                 return;
1121         }
1122
1123         DEBUG(10, ("break_from=%u, break_to=%u\n",
1124                    (unsigned)break_from, (unsigned)break_to));
1125
1126         if ((break_from == break_to) && !break_needed) {
1127                 DEBUG(3, ("Already downgraded oplock to %u on %s: %s\n",
1128                           (unsigned)break_to,
1129                           file_id_string_tos(&fsp->file_id),
1130                           fsp_str_dbg(fsp)));
1131                 return;
1132         }
1133
1134         /* Need to wait before sending a break
1135            message if we sent ourselves this message. */
1136         if (serverid_equal(&self, &src)) {
1137                 wait_before_sending_break();
1138         }
1139
1140         if (sconn->using_smb2) {
1141                 send_break_message_smb2(fsp, break_from, break_to);
1142         } else {
1143                 send_break_message_smb1(fsp, (break_to & SMB2_LEASE_READ) ?
1144                                         OPLOCKLEVEL_II : OPLOCKLEVEL_NONE);
1145         }
1146
1147         if ((break_from == SMB2_LEASE_READ) &&
1148             (break_to == SMB2_LEASE_NONE)) {
1149                 /*
1150                  * This is an async break without a reply and thus no timeout
1151                  *
1152                  * leases are handled above.
1153                  */
1154                 if (fsp->oplock_type != LEASE_OPLOCK) {
1155                         remove_oplock(fsp);
1156                 }
1157                 return;
1158         }
1159         if (fsp->oplock_type == LEASE_OPLOCK) {
1160                 return;
1161         }
1162
1163         fsp->sent_oplock_break = (break_to & SMB2_LEASE_READ) ?
1164                 LEVEL_II_BREAK_SENT:BREAK_TO_NONE_SENT;
1165
1166         add_oplock_timeout_handler(fsp);
1167 }
1168
1169 /*******************************************************************
1170  This handles the kernel oplock break message.
1171 *******************************************************************/
1172
1173 static void process_kernel_oplock_break(struct messaging_context *msg_ctx,
1174                                         void *private_data,
1175                                         uint32_t msg_type,
1176                                         struct server_id src,
1177                                         DATA_BLOB *data)
1178 {
1179         struct file_id id;
1180         unsigned long file_id;
1181         files_struct *fsp;
1182         struct smbd_server_connection *sconn =
1183                 talloc_get_type_abort(private_data,
1184                 struct smbd_server_connection);
1185         struct server_id_buf tmp;
1186
1187         if (data->data == NULL) {
1188                 DEBUG(0, ("Got NULL buffer\n"));
1189                 return;
1190         }
1191
1192         if (data->length != MSG_SMB_KERNEL_BREAK_SIZE) {
1193                 DEBUG(0, ("Got invalid msg len %d\n", (int)data->length));
1194                 return;
1195         }
1196
1197         /* Pull the data from the message. */
1198         pull_file_id_24((char *)data->data, &id);
1199         file_id = (unsigned long)IVAL(data->data, 24);
1200
1201         DEBUG(10, ("Got kernel oplock break message from pid %s: %s/%u\n",
1202                    server_id_str_buf(src, &tmp), file_id_string_tos(&id),
1203                    (unsigned int)file_id));
1204
1205         fsp = initial_break_processing(sconn, id, file_id);
1206
1207         if (fsp == NULL) {
1208                 DEBUG(3, ("Got a kernel oplock break message for a file "
1209                           "I don't know about\n"));
1210                 return;
1211         }
1212
1213         if (fsp->sent_oplock_break != NO_BREAK_SENT) {
1214                 /* This is ok, kernel oplocks come in completely async */
1215                 DEBUG(3, ("Got a kernel oplock request while waiting for a "
1216                           "break reply\n"));
1217                 return;
1218         }
1219
1220         if (sconn->using_smb2) {
1221                 send_break_message_smb2(fsp, 0, OPLOCKLEVEL_NONE);
1222         } else {
1223                 send_break_message_smb1(fsp, OPLOCKLEVEL_NONE);
1224         }
1225
1226         fsp->sent_oplock_break = BREAK_TO_NONE_SENT;
1227
1228         add_oplock_timeout_handler(fsp);
1229 }
1230
1231 static bool file_has_read_oplocks(struct files_struct *fsp)
1232 {
1233         struct byte_range_lock *brl;
1234         uint32_t num_read_oplocks = 0;
1235
1236         brl = brl_get_locks_readonly(fsp);
1237         if (brl == NULL) {
1238                 return false;
1239         }
1240
1241         num_read_oplocks = brl_num_read_oplocks(brl);
1242
1243         DBG_DEBUG("num_read_oplocks = %"PRIu32"\n", num_read_oplocks);
1244
1245         return (num_read_oplocks != 0);
1246 }
1247
1248 struct break_to_none_state {
1249         struct smbd_server_connection *sconn;
1250         struct file_id id;
1251         struct smb2_lease_key lease_key;
1252         struct GUID client_guid;
1253 };
1254 static void do_break_to_none(struct tevent_context *ctx,
1255                              struct tevent_immediate *im,
1256                              void *private_data);
1257
1258 /****************************************************************************
1259  This function is called on any file modification or lock request. If a file
1260  is level 2 oplocked then it must tell all other level 2 holders to break to
1261  none.
1262 ****************************************************************************/
1263
1264 static void contend_level2_oplocks_begin_default(files_struct *fsp,
1265                                               enum level2_contention_type type)
1266 {
1267         struct smbd_server_connection *sconn = fsp->conn->sconn;
1268         struct tevent_immediate *im;
1269         struct break_to_none_state *state;
1270         bool has_read_oplocks;
1271
1272         /*
1273          * If this file is level II oplocked then we need
1274          * to grab the shared memory lock and inform all
1275          * other files with a level II lock that they need
1276          * to flush their read caches. We keep the lock over
1277          * the shared memory area whilst doing this.
1278          */
1279
1280         if (fsp_lease_type_is_exclusive(fsp)) {
1281                 /*
1282                  * There can't be any level2 oplocks, we're alone.
1283                  */
1284                 return;
1285         }
1286
1287         has_read_oplocks = file_has_read_oplocks(fsp);
1288         if (!has_read_oplocks) {
1289                 DEBUG(10, ("No read oplocks around\n"));
1290                 return;
1291         }
1292
1293         /*
1294          * When we get here we might have a brlock entry locked. Also
1295          * locking the share mode entry would violate the locking
1296          * order. Breaking level2 oplocks to none is asynchronous
1297          * anyway, so we postpone this into an immediate event.
1298          */
1299
1300         state = talloc(sconn, struct break_to_none_state);
1301         if (state == NULL) {
1302                 DEBUG(1, ("talloc failed\n"));
1303                 return;
1304         }
1305         *state = (struct break_to_none_state) {
1306                 .sconn = sconn, .id = fsp->file_id,
1307         };
1308
1309         if (fsp->oplock_type == LEASE_OPLOCK) {
1310                 state->client_guid = *fsp_client_guid(fsp);
1311                 state->lease_key = fsp->lease->lease.lease_key;
1312                 DEBUG(10, ("Breaking through lease key %"PRIu64"/%"PRIu64"\n",
1313                            state->lease_key.data[0],
1314                            state->lease_key.data[1]));
1315         }
1316
1317         im = tevent_create_immediate(state);
1318         if (im == NULL) {
1319                 DEBUG(1, ("tevent_create_immediate failed\n"));
1320                 TALLOC_FREE(state);
1321                 return;
1322         }
1323         tevent_schedule_immediate(im, sconn->ev_ctx, do_break_to_none, state);
1324 }
1325
1326 static void send_break_to_none(struct messaging_context *msg_ctx,
1327                                const struct file_id *id,
1328                                const struct share_mode_entry *e)
1329 {
1330         char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
1331
1332         share_mode_entry_to_message(msg, id, e);
1333         /* Overload entry->op_type */
1334         SSVAL(msg, OP_BREAK_MSG_OP_TYPE_OFFSET, NO_OPLOCK);
1335
1336         messaging_send_buf(msg_ctx, e->pid, MSG_SMB_BREAK_REQUEST,
1337                            (uint8_t *)msg, sizeof(msg));
1338 }
1339
1340 static bool do_break_lease_to_none(struct share_mode_lock *lck,
1341                                    struct share_mode_entry *e,
1342                                    void *private_data)
1343 {
1344         struct break_to_none_state *state = talloc_get_type_abort(
1345                 private_data, struct break_to_none_state);
1346         uint32_t current_state = 0;
1347         bool our_own;
1348         NTSTATUS status;
1349
1350         DBG_DEBUG("lease_key=%"PRIu64"/%"PRIu64"\n",
1351                   e->lease_key.data[0],
1352                   e->lease_key.data[1]);
1353
1354         status = leases_db_get(&e->client_guid,
1355                                &e->lease_key,
1356                                &state->id,
1357                                &current_state,
1358                                NULL, /* breaking */
1359                                NULL, /* breaking_to_requested */
1360                                NULL, /* breaking_to_required */
1361                                NULL, /* lease_version */
1362                                NULL); /* epoch */
1363         if (!NT_STATUS_IS_OK(status)) {
1364                 DBG_WARNING("leases_db_get failed: %s\n",
1365                             nt_errstr(status));
1366                 return false;
1367         }
1368
1369         if ((current_state & SMB2_LEASE_READ) == 0) {
1370                 return false;
1371         }
1372
1373         our_own = smb2_lease_equal(&state->client_guid,
1374                                    &state->lease_key,
1375                                    &e->client_guid,
1376                                    &e->lease_key);
1377         if (our_own) {
1378                 DEBUG(10, ("Don't break our own lease\n"));
1379                 return false;
1380         }
1381
1382         DBG_DEBUG("Breaking %"PRIu64"/%"PRIu64" to none\n",
1383                   e->lease_key.data[0],
1384                   e->lease_key.data[1]);
1385
1386         send_break_to_none(state->sconn->msg_ctx, &state->id, e);
1387
1388         return false;
1389 }
1390
1391 static void do_break_to_none(struct tevent_context *ctx,
1392                              struct tevent_immediate *im,
1393                              void *private_data)
1394 {
1395         struct break_to_none_state *state = talloc_get_type_abort(
1396                 private_data, struct break_to_none_state);
1397         uint32_t i;
1398         struct share_mode_lock *lck;
1399         struct share_mode_data *d;
1400         bool ok;
1401
1402         lck = get_existing_share_mode_lock(talloc_tos(), state->id);
1403         if (lck == NULL) {
1404                 DEBUG(1, ("%s: failed to lock share mode entry for file %s.\n",
1405                           __func__, file_id_string_tos(&state->id)));
1406                 goto done;
1407         }
1408         d = lck->data;
1409
1410         /*
1411          * Walk leases and oplocks separately: We have to send one break per
1412          * lease. If we have multiple share_mode_entry having a common lease,
1413          * we would break the lease twice if we don't walk the leases list
1414          * separately.
1415          */
1416
1417         ok = share_mode_forall_leases(lck, do_break_lease_to_none, state);
1418         if (!ok) {
1419                 DBG_WARNING("share_mode_forall_leases failed\n");
1420         }
1421
1422         for(i = 0; i < d->num_share_modes; i++) {
1423                 struct share_mode_entry *e = &d->share_modes[i];
1424
1425                 if (!is_valid_share_mode_entry(e)) {
1426                         continue;
1427                 }
1428                 if (e->op_type == LEASE_OPLOCK) {
1429                         /*
1430                          * Took care of those in the loop above
1431                          */
1432                         continue;
1433                 }
1434
1435                 /*
1436                  * As there could have been multiple writes waiting at the
1437                  * lock_share_entry gate we may not be the first to
1438                  * enter. Hence the state of the op_types in the share mode
1439                  * entries may be partly NO_OPLOCK and partly LEVEL_II
1440                  * oplock. It will do no harm to re-send break messages to
1441                  * those smbd's that are still waiting their turn to remove
1442                  * their LEVEL_II state, and also no harm to ignore existing
1443                  * NO_OPLOCK states. JRA.
1444                  */
1445
1446                 DEBUG(10, ("%s: share_entry[%i]->op_type == %d\n", __func__,
1447                            i, e->op_type ));
1448
1449                 if (e->op_type == NO_OPLOCK) {
1450                         continue;
1451                 }
1452
1453                 /* Paranoia .... */
1454                 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
1455                         DEBUG(0,("%s: PANIC. "
1456                                  "share mode entry %d is an exclusive "
1457                                  "oplock !\n", __func__, i ));
1458                         TALLOC_FREE(lck);
1459                         abort();
1460                 }
1461
1462                 send_break_to_none(state->sconn->msg_ctx, &state->id, e);
1463         }
1464
1465         /* We let the message receivers handle removing the oplock state
1466            in the share mode lock db. */
1467
1468         TALLOC_FREE(lck);
1469 done:
1470         TALLOC_FREE(state);
1471         return;
1472 }
1473
1474 void smbd_contend_level2_oplocks_begin(files_struct *fsp,
1475                                   enum level2_contention_type type)
1476 {
1477         contend_level2_oplocks_begin_default(fsp, type);
1478 }
1479
1480 void smbd_contend_level2_oplocks_end(files_struct *fsp,
1481                                 enum level2_contention_type type)
1482 {
1483         return;
1484 }
1485
1486 /****************************************************************************
1487  Linearize a share mode entry struct to an internal oplock break message.
1488 ****************************************************************************/
1489
1490 void share_mode_entry_to_message(char *msg, const struct file_id *id,
1491                                  const struct share_mode_entry *e)
1492 {
1493         SIVAL(msg,OP_BREAK_MSG_PID_OFFSET,(uint32_t)e->pid.pid);
1494         SBVAL(msg,OP_BREAK_MSG_MID_OFFSET,e->op_mid);
1495         SSVAL(msg,OP_BREAK_MSG_OP_TYPE_OFFSET,e->op_type);
1496         SIVAL(msg,OP_BREAK_MSG_ACCESS_MASK_OFFSET,e->access_mask);
1497         SIVAL(msg,OP_BREAK_MSG_SHARE_ACCESS_OFFSET,e->share_access);
1498         SIVAL(msg,OP_BREAK_MSG_PRIV_OFFSET,e->private_options);
1499         SIVAL(msg,OP_BREAK_MSG_TIME_SEC_OFFSET,(uint32_t)e->time.tv_sec);
1500         SIVAL(msg,OP_BREAK_MSG_TIME_USEC_OFFSET,(uint32_t)e->time.tv_usec);
1501         /*
1502          * "id" used to be part of share_mode_entry, thus the strange
1503          * place to put this. Feel free to move somewhere else :-)
1504          */
1505         push_file_id_24(msg+OP_BREAK_MSG_DEV_OFFSET, id);
1506         SIVAL(msg,OP_BREAK_MSG_FILE_ID_OFFSET,e->share_file_id);
1507         SIVAL(msg,OP_BREAK_MSG_UID_OFFSET,e->uid);
1508         SSVAL(msg,OP_BREAK_MSG_FLAGS_OFFSET,e->flags);
1509         SIVAL(msg,OP_BREAK_MSG_NAME_HASH_OFFSET,e->name_hash);
1510         SIVAL(msg,OP_BREAK_MSG_VNN_OFFSET,e->pid.vnn);
1511 }
1512
1513 /****************************************************************************
1514  De-linearize an internal oplock break message to a share mode entry struct.
1515 ****************************************************************************/
1516
1517 void message_to_share_mode_entry(struct file_id *id,
1518                                  struct share_mode_entry *e,
1519                                  const char *msg)
1520 {
1521         e->pid.pid = (pid_t)IVAL(msg,OP_BREAK_MSG_PID_OFFSET);
1522         e->op_mid = BVAL(msg,OP_BREAK_MSG_MID_OFFSET);
1523         e->op_type = SVAL(msg,OP_BREAK_MSG_OP_TYPE_OFFSET);
1524         e->access_mask = IVAL(msg,OP_BREAK_MSG_ACCESS_MASK_OFFSET);
1525         e->share_access = IVAL(msg,OP_BREAK_MSG_SHARE_ACCESS_OFFSET);
1526         e->private_options = IVAL(msg,OP_BREAK_MSG_PRIV_OFFSET);
1527         e->time.tv_sec = (time_t)IVAL(msg,OP_BREAK_MSG_TIME_SEC_OFFSET);
1528         e->time.tv_usec = (int)IVAL(msg,OP_BREAK_MSG_TIME_USEC_OFFSET);
1529         /*
1530          * "id" used to be part of share_mode_entry, thus the strange
1531          * place to put this. Feel free to move somewhere else :-)
1532          */
1533         pull_file_id_24(msg+OP_BREAK_MSG_DEV_OFFSET, id);
1534         e->share_file_id = (unsigned long)IVAL(msg,OP_BREAK_MSG_FILE_ID_OFFSET);
1535         e->uid = (uint32_t)IVAL(msg,OP_BREAK_MSG_UID_OFFSET);
1536         e->flags = (uint16_t)SVAL(msg,OP_BREAK_MSG_FLAGS_OFFSET);
1537         e->name_hash = IVAL(msg,OP_BREAK_MSG_NAME_HASH_OFFSET);
1538         e->pid.vnn = IVAL(msg,OP_BREAK_MSG_VNN_OFFSET);
1539 }
1540
1541 /****************************************************************************
1542  Setup oplocks for this process.
1543 ****************************************************************************/
1544
1545 bool init_oplocks(struct smbd_server_connection *sconn)
1546 {
1547         DEBUG(3,("init_oplocks: initializing messages.\n"));
1548
1549         messaging_register(sconn->msg_ctx, sconn, MSG_SMB_BREAK_REQUEST,
1550                            process_oplock_break_message);
1551         messaging_register(sconn->msg_ctx, sconn, MSG_SMB_KERNEL_BREAK,
1552                            process_kernel_oplock_break);
1553         return true;
1554 }
1555
1556 void init_kernel_oplocks(struct smbd_server_connection *sconn)
1557 {
1558         struct kernel_oplocks *koplocks = sconn->oplocks.kernel_ops;
1559
1560         /* only initialize once */
1561         if (koplocks == NULL) {
1562 #ifdef HAVE_KERNEL_OPLOCKS_LINUX
1563                 koplocks = linux_init_kernel_oplocks(sconn);
1564 #endif
1565                 sconn->oplocks.kernel_ops = koplocks;
1566         }
1567 }