smbd: Simplify fsp_lease_update()
[metze/samba/wip.git] / source3 / smbd / oplock.c
1 /* 
2    Unix SMB/CIFS implementation.
3    oplock processing
4    Copyright (C) Andrew Tridgell 1992-1998
5    Copyright (C) Jeremy Allison 1998 - 2001
6    Copyright (C) Volker Lendecke 2005
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #define DBGC_CLASS DBGC_LOCKING
23 #include "includes.h"
24 #include "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(fsp);
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 files_struct *fsp)
430 {
431         const struct GUID *client_guid = fsp_client_guid(fsp);
432         struct fsp_lease *lease = fsp->lease;
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                                &fsp->lease->lease.lease_key,
440                                &fsp->file_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(fsp);
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 oplock_break_message *msg = NULL;
949         enum ndr_err_code ndr_err;
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
961         msg = talloc(talloc_tos(), struct oplock_break_message);
962         if (msg == NULL) {
963                 DBG_WARNING("talloc failed\n");
964                 return;
965         }
966
967         ndr_err = ndr_pull_struct_blob_all(
968                 data,
969                 msg,
970                 msg,
971                 (ndr_pull_flags_fn_t)ndr_pull_oplock_break_message);
972         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
973                 DBG_DEBUG("ndr_pull_oplock_break_message failed: %s\n",
974                           ndr_errstr(ndr_err));
975                 TALLOC_FREE(msg);
976                 return;
977         }
978         if (DEBUGLEVEL >= 10) {
979                 struct server_id_buf buf;
980                 DBG_DEBUG("Got break message from %s\n",
981                           server_id_str_buf(src, &buf));
982                 NDR_PRINT_DEBUG(oplock_break_message, msg);
983         }
984
985         break_to = msg->break_to;
986         fsp = initial_break_processing(sconn, msg->id, msg->share_file_id);
987
988         TALLOC_FREE(msg);
989
990         if (fsp == NULL) {
991                 /* We hit a race here. Break messages are sent, and before we
992                  * get to process this message, we have closed the file. */
993                 DEBUG(3, ("Did not find fsp\n"));
994                 return;
995         }
996
997         break_from = fsp_lease_type(fsp);
998
999         if (fsp->oplock_type != LEASE_OPLOCK) {
1000                 if (fsp->sent_oplock_break != NO_BREAK_SENT) {
1001                         /*
1002                          * Nothing to do anymore
1003                          */
1004                         DEBUG(10, ("fsp->sent_oplock_break = %d\n",
1005                                    fsp->sent_oplock_break));
1006                         return;
1007                 }
1008         }
1009
1010         if (!(global_client_caps & CAP_LEVEL_II_OPLOCKS)) {
1011                 DEBUG(10, ("client_caps without level2 oplocks\n"));
1012                 break_to &= ~SMB2_LEASE_READ;
1013         }
1014
1015         use_kernel = lp_kernel_oplocks(SNUM(fsp->conn)) &&
1016                         (koplocks != NULL);
1017         if (use_kernel) {
1018                 DEBUG(10, ("Kernel oplocks don't allow level2\n"));
1019                 break_to &= ~SMB2_LEASE_READ;
1020         }
1021
1022         if (!lp_level2_oplocks(SNUM(fsp->conn))) {
1023                 DEBUG(10, ("no level2 oplocks by config\n"));
1024                 break_to &= ~SMB2_LEASE_READ;
1025         }
1026
1027         if (fsp->oplock_type == LEASE_OPLOCK) {
1028                 const struct GUID *client_guid = fsp_client_guid(fsp);
1029                 struct share_mode_lock *lck;
1030                 uint32_t current_state;
1031                 uint32_t breaking_to_requested, breaking_to_required;
1032                 bool breaking;
1033                 uint16_t lease_version, epoch;
1034                 NTSTATUS status;
1035
1036                 lck = get_existing_share_mode_lock(
1037                         talloc_tos(), fsp->file_id);
1038                 if (lck == NULL) {
1039                         /*
1040                          * We hit a race here. Break messages are sent, and
1041                          * before we get to process this message, we have closed
1042                          * the file.
1043                          */
1044                         DEBUG(3, ("Did not find share_mode\n"));
1045                         return;
1046                 }
1047
1048                 status = leases_db_get(client_guid,
1049                                        &fsp->lease->lease.lease_key,
1050                                        &fsp->file_id,
1051                                        &current_state,
1052                                        &breaking,
1053                                        &breaking_to_requested,
1054                                        &breaking_to_required,
1055                                        &lease_version,
1056                                        &epoch);
1057                 if (!NT_STATUS_IS_OK(status)) {
1058                         DBG_WARNING("leases_db_get returned %s\n",
1059                                     nt_errstr(status));
1060                         TALLOC_FREE(lck);
1061                         return;
1062                 }
1063
1064                 break_from = current_state;
1065                 break_to &= current_state;
1066
1067                 if (breaking) {
1068                         break_to &= breaking_to_required;
1069                         if (breaking_to_required != break_to) {
1070                                 /*
1071                                  * Note we don't increment the epoch
1072                                  * here, which might be a bug in
1073                                  * Windows too...
1074                                  */
1075                                 breaking_to_required = break_to;
1076                         }
1077                         break_needed = false;
1078                 } else if (current_state == break_to) {
1079                         break_needed = false;
1080                 } else if (current_state == SMB2_LEASE_READ) {
1081                         current_state = SMB2_LEASE_NONE;
1082                         /* Need to increment the epoch */
1083                         epoch += 1;
1084                 } else {
1085                         breaking = true;
1086                         breaking_to_required = break_to;
1087                         breaking_to_requested = break_to;
1088                         /* Need to increment the epoch */
1089                         epoch += 1;
1090                 }
1091
1092                 {
1093                         NTSTATUS set_status;
1094
1095                         set_status = leases_db_set(
1096                                 client_guid,
1097                                 &fsp->lease->lease.lease_key,
1098                                 current_state,
1099                                 breaking,
1100                                 breaking_to_requested,
1101                                 breaking_to_required,
1102                                 lease_version,
1103                                 epoch);
1104
1105                         if (!NT_STATUS_IS_OK(set_status)) {
1106                                 DBG_DEBUG("leases_db_set failed: %s\n",
1107                                           nt_errstr(set_status));
1108                                 return;
1109                         }
1110                 }
1111
1112                 /* Ensure we're in sync with current lease state. */
1113                 fsp_lease_update(fsp);
1114
1115                 TALLOC_FREE(lck);
1116         }
1117
1118         if (!break_needed) {
1119                 DEBUG(10,("%s: skip break\n", __func__));
1120                 return;
1121         }
1122
1123         if ((break_from == SMB2_LEASE_NONE) && !break_needed) {
1124                 DEBUG(3, ("Already downgraded oplock to none on %s: %s\n",
1125                           file_id_string_tos(&fsp->file_id),
1126                           fsp_str_dbg(fsp)));
1127                 return;
1128         }
1129
1130         DEBUG(10, ("break_from=%u, break_to=%u\n",
1131                    (unsigned)break_from, (unsigned)break_to));
1132
1133         if ((break_from == break_to) && !break_needed) {
1134                 DEBUG(3, ("Already downgraded oplock to %u on %s: %s\n",
1135                           (unsigned)break_to,
1136                           file_id_string_tos(&fsp->file_id),
1137                           fsp_str_dbg(fsp)));
1138                 return;
1139         }
1140
1141         /* Need to wait before sending a break
1142            message if we sent ourselves this message. */
1143         if (serverid_equal(&self, &src)) {
1144                 wait_before_sending_break();
1145         }
1146
1147         if (sconn->using_smb2) {
1148                 send_break_message_smb2(fsp, break_from, break_to);
1149         } else {
1150                 send_break_message_smb1(fsp, (break_to & SMB2_LEASE_READ) ?
1151                                         OPLOCKLEVEL_II : OPLOCKLEVEL_NONE);
1152         }
1153
1154         if ((break_from == SMB2_LEASE_READ) &&
1155             (break_to == SMB2_LEASE_NONE)) {
1156                 /*
1157                  * This is an async break without a reply and thus no timeout
1158                  *
1159                  * leases are handled above.
1160                  */
1161                 if (fsp->oplock_type != LEASE_OPLOCK) {
1162                         remove_oplock(fsp);
1163                 }
1164                 return;
1165         }
1166         if (fsp->oplock_type == LEASE_OPLOCK) {
1167                 return;
1168         }
1169
1170         fsp->sent_oplock_break = (break_to & SMB2_LEASE_READ) ?
1171                 LEVEL_II_BREAK_SENT:BREAK_TO_NONE_SENT;
1172
1173         add_oplock_timeout_handler(fsp);
1174 }
1175
1176 /*******************************************************************
1177  This handles the kernel oplock break message.
1178 *******************************************************************/
1179
1180 static void process_kernel_oplock_break(struct messaging_context *msg_ctx,
1181                                         void *private_data,
1182                                         uint32_t msg_type,
1183                                         struct server_id src,
1184                                         DATA_BLOB *data)
1185 {
1186         struct file_id id;
1187         unsigned long file_id;
1188         files_struct *fsp;
1189         struct smbd_server_connection *sconn =
1190                 talloc_get_type_abort(private_data,
1191                 struct smbd_server_connection);
1192         struct server_id_buf tmp;
1193
1194         if (data->data == NULL) {
1195                 DEBUG(0, ("Got NULL buffer\n"));
1196                 return;
1197         }
1198
1199         if (data->length != MSG_SMB_KERNEL_BREAK_SIZE) {
1200                 DEBUG(0, ("Got invalid msg len %d\n", (int)data->length));
1201                 return;
1202         }
1203
1204         /* Pull the data from the message. */
1205         pull_file_id_24((char *)data->data, &id);
1206         file_id = (unsigned long)IVAL(data->data, 24);
1207
1208         DEBUG(10, ("Got kernel oplock break message from pid %s: %s/%u\n",
1209                    server_id_str_buf(src, &tmp), file_id_string_tos(&id),
1210                    (unsigned int)file_id));
1211
1212         fsp = initial_break_processing(sconn, id, file_id);
1213
1214         if (fsp == NULL) {
1215                 DEBUG(3, ("Got a kernel oplock break message for a file "
1216                           "I don't know about\n"));
1217                 return;
1218         }
1219
1220         if (fsp->sent_oplock_break != NO_BREAK_SENT) {
1221                 /* This is ok, kernel oplocks come in completely async */
1222                 DEBUG(3, ("Got a kernel oplock request while waiting for a "
1223                           "break reply\n"));
1224                 return;
1225         }
1226
1227         if (sconn->using_smb2) {
1228                 send_break_message_smb2(fsp, 0, OPLOCKLEVEL_NONE);
1229         } else {
1230                 send_break_message_smb1(fsp, OPLOCKLEVEL_NONE);
1231         }
1232
1233         fsp->sent_oplock_break = BREAK_TO_NONE_SENT;
1234
1235         add_oplock_timeout_handler(fsp);
1236 }
1237
1238 static bool file_has_read_oplocks(struct files_struct *fsp)
1239 {
1240         struct byte_range_lock *brl;
1241         uint32_t num_read_oplocks = 0;
1242
1243         brl = brl_get_locks_readonly(fsp);
1244         if (brl == NULL) {
1245                 return false;
1246         }
1247
1248         num_read_oplocks = brl_num_read_oplocks(brl);
1249
1250         DBG_DEBUG("num_read_oplocks = %"PRIu32"\n", num_read_oplocks);
1251
1252         return (num_read_oplocks != 0);
1253 }
1254
1255 struct break_to_none_state {
1256         struct smbd_server_connection *sconn;
1257         struct file_id id;
1258         struct smb2_lease_key lease_key;
1259         struct GUID client_guid;
1260 };
1261 static void do_break_to_none(struct tevent_context *ctx,
1262                              struct tevent_immediate *im,
1263                              void *private_data);
1264
1265 /****************************************************************************
1266  This function is called on any file modification or lock request. If a file
1267  is level 2 oplocked then it must tell all other level 2 holders to break to
1268  none.
1269 ****************************************************************************/
1270
1271 static void contend_level2_oplocks_begin_default(files_struct *fsp,
1272                                               enum level2_contention_type type)
1273 {
1274         struct smbd_server_connection *sconn = fsp->conn->sconn;
1275         struct tevent_immediate *im;
1276         struct break_to_none_state *state;
1277         bool has_read_oplocks;
1278
1279         /*
1280          * If this file is level II oplocked then we need
1281          * to grab the shared memory lock and inform all
1282          * other files with a level II lock that they need
1283          * to flush their read caches. We keep the lock over
1284          * the shared memory area whilst doing this.
1285          */
1286
1287         if (fsp_lease_type_is_exclusive(fsp)) {
1288                 /*
1289                  * There can't be any level2 oplocks, we're alone.
1290                  */
1291                 return;
1292         }
1293
1294         has_read_oplocks = file_has_read_oplocks(fsp);
1295         if (!has_read_oplocks) {
1296                 DEBUG(10, ("No read oplocks around\n"));
1297                 return;
1298         }
1299
1300         /*
1301          * When we get here we might have a brlock entry locked. Also
1302          * locking the share mode entry would violate the locking
1303          * order. Breaking level2 oplocks to none is asynchronous
1304          * anyway, so we postpone this into an immediate event.
1305          */
1306
1307         state = talloc(sconn, struct break_to_none_state);
1308         if (state == NULL) {
1309                 DEBUG(1, ("talloc failed\n"));
1310                 return;
1311         }
1312         *state = (struct break_to_none_state) {
1313                 .sconn = sconn, .id = fsp->file_id,
1314         };
1315
1316         if (fsp->oplock_type == LEASE_OPLOCK) {
1317                 state->client_guid = *fsp_client_guid(fsp);
1318                 state->lease_key = fsp->lease->lease.lease_key;
1319                 DEBUG(10, ("Breaking through lease key %"PRIu64"/%"PRIu64"\n",
1320                            state->lease_key.data[0],
1321                            state->lease_key.data[1]));
1322         }
1323
1324         im = tevent_create_immediate(state);
1325         if (im == NULL) {
1326                 DEBUG(1, ("tevent_create_immediate failed\n"));
1327                 TALLOC_FREE(state);
1328                 return;
1329         }
1330         tevent_schedule_immediate(im, sconn->ev_ctx, do_break_to_none, state);
1331 }
1332
1333 static void send_break_to_none(struct messaging_context *msg_ctx,
1334                                const struct file_id *id,
1335                                const struct share_mode_entry *e)
1336 {
1337         NTSTATUS status;
1338         status = send_break_message(msg_ctx, id, e, OPLOCK_NONE);
1339         if (!NT_STATUS_IS_OK(status)) {
1340                 DBG_DEBUG("send_break_message failed: %s\n",
1341                           nt_errstr(status));
1342         }
1343 }
1344
1345 static bool do_break_lease_to_none(struct share_mode_lock *lck,
1346                                    struct share_mode_entry *e,
1347                                    void *private_data)
1348 {
1349         struct break_to_none_state *state = talloc_get_type_abort(
1350                 private_data, struct break_to_none_state);
1351         uint32_t current_state = 0;
1352         bool our_own;
1353         NTSTATUS status;
1354
1355         DBG_DEBUG("lease_key=%"PRIu64"/%"PRIu64"\n",
1356                   e->lease_key.data[0],
1357                   e->lease_key.data[1]);
1358
1359         status = leases_db_get(&e->client_guid,
1360                                &e->lease_key,
1361                                &state->id,
1362                                &current_state,
1363                                NULL, /* breaking */
1364                                NULL, /* breaking_to_requested */
1365                                NULL, /* breaking_to_required */
1366                                NULL, /* lease_version */
1367                                NULL); /* epoch */
1368         if (!NT_STATUS_IS_OK(status)) {
1369                 DBG_WARNING("leases_db_get failed: %s\n",
1370                             nt_errstr(status));
1371                 return false;
1372         }
1373
1374         if ((current_state & SMB2_LEASE_READ) == 0) {
1375                 return false;
1376         }
1377
1378         our_own = smb2_lease_equal(&state->client_guid,
1379                                    &state->lease_key,
1380                                    &e->client_guid,
1381                                    &e->lease_key);
1382         if (our_own) {
1383                 DEBUG(10, ("Don't break our own lease\n"));
1384                 return false;
1385         }
1386
1387         DBG_DEBUG("Breaking %"PRIu64"/%"PRIu64" to none\n",
1388                   e->lease_key.data[0],
1389                   e->lease_key.data[1]);
1390
1391         send_break_to_none(state->sconn->msg_ctx, &state->id, e);
1392
1393         return false;
1394 }
1395
1396 static void do_break_to_none(struct tevent_context *ctx,
1397                              struct tevent_immediate *im,
1398                              void *private_data)
1399 {
1400         struct break_to_none_state *state = talloc_get_type_abort(
1401                 private_data, struct break_to_none_state);
1402         uint32_t i;
1403         struct share_mode_lock *lck;
1404         struct share_mode_data *d;
1405         bool ok;
1406
1407         lck = get_existing_share_mode_lock(talloc_tos(), state->id);
1408         if (lck == NULL) {
1409                 DEBUG(1, ("%s: failed to lock share mode entry for file %s.\n",
1410                           __func__, file_id_string_tos(&state->id)));
1411                 goto done;
1412         }
1413         d = lck->data;
1414
1415         /*
1416          * Walk leases and oplocks separately: We have to send one break per
1417          * lease. If we have multiple share_mode_entry having a common lease,
1418          * we would break the lease twice if we don't walk the leases list
1419          * separately.
1420          */
1421
1422         ok = share_mode_forall_leases(lck, do_break_lease_to_none, state);
1423         if (!ok) {
1424                 DBG_WARNING("share_mode_forall_leases failed\n");
1425         }
1426
1427         for(i = 0; i < d->num_share_modes; i++) {
1428                 struct share_mode_entry *e = &d->share_modes[i];
1429
1430                 if (!is_valid_share_mode_entry(e)) {
1431                         continue;
1432                 }
1433                 if (e->op_type == LEASE_OPLOCK) {
1434                         /*
1435                          * Took care of those in the loop above
1436                          */
1437                         continue;
1438                 }
1439
1440                 /*
1441                  * As there could have been multiple writes waiting at the
1442                  * lock_share_entry gate we may not be the first to
1443                  * enter. Hence the state of the op_types in the share mode
1444                  * entries may be partly NO_OPLOCK and partly LEVEL_II
1445                  * oplock. It will do no harm to re-send break messages to
1446                  * those smbd's that are still waiting their turn to remove
1447                  * their LEVEL_II state, and also no harm to ignore existing
1448                  * NO_OPLOCK states. JRA.
1449                  */
1450
1451                 DEBUG(10, ("%s: share_entry[%i]->op_type == %d\n", __func__,
1452                            i, e->op_type ));
1453
1454                 if (e->op_type == NO_OPLOCK) {
1455                         continue;
1456                 }
1457
1458                 /* Paranoia .... */
1459                 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
1460                         DEBUG(0,("%s: PANIC. "
1461                                  "share mode entry %d is an exclusive "
1462                                  "oplock !\n", __func__, i ));
1463                         TALLOC_FREE(lck);
1464                         abort();
1465                 }
1466
1467                 send_break_to_none(state->sconn->msg_ctx, &state->id, e);
1468         }
1469
1470         /* We let the message receivers handle removing the oplock state
1471            in the share mode lock db. */
1472
1473         TALLOC_FREE(lck);
1474 done:
1475         TALLOC_FREE(state);
1476         return;
1477 }
1478
1479 void smbd_contend_level2_oplocks_begin(files_struct *fsp,
1480                                   enum level2_contention_type type)
1481 {
1482         contend_level2_oplocks_begin_default(fsp, type);
1483 }
1484
1485 void smbd_contend_level2_oplocks_end(files_struct *fsp,
1486                                 enum level2_contention_type type)
1487 {
1488         return;
1489 }
1490
1491 /****************************************************************************
1492  Linearize a share mode entry struct to an internal oplock break message.
1493 ****************************************************************************/
1494
1495 void share_mode_entry_to_message(char *msg, const struct file_id *id,
1496                                  const struct share_mode_entry *e)
1497 {
1498         SIVAL(msg,OP_BREAK_MSG_PID_OFFSET,(uint32_t)e->pid.pid);
1499         SBVAL(msg,OP_BREAK_MSG_MID_OFFSET,e->op_mid);
1500         SSVAL(msg,OP_BREAK_MSG_OP_TYPE_OFFSET,e->op_type);
1501         SIVAL(msg,OP_BREAK_MSG_ACCESS_MASK_OFFSET,e->access_mask);
1502         SIVAL(msg,OP_BREAK_MSG_SHARE_ACCESS_OFFSET,e->share_access);
1503         SIVAL(msg,OP_BREAK_MSG_PRIV_OFFSET,e->private_options);
1504         SIVAL(msg,OP_BREAK_MSG_TIME_SEC_OFFSET,(uint32_t)e->time.tv_sec);
1505         SIVAL(msg,OP_BREAK_MSG_TIME_USEC_OFFSET,(uint32_t)e->time.tv_usec);
1506         /*
1507          * "id" used to be part of share_mode_entry, thus the strange
1508          * place to put this. Feel free to move somewhere else :-)
1509          */
1510         push_file_id_24(msg+OP_BREAK_MSG_DEV_OFFSET, id);
1511         SIVAL(msg,OP_BREAK_MSG_FILE_ID_OFFSET,e->share_file_id);
1512         SIVAL(msg,OP_BREAK_MSG_UID_OFFSET,e->uid);
1513         SSVAL(msg,OP_BREAK_MSG_FLAGS_OFFSET,e->flags);
1514         SIVAL(msg,OP_BREAK_MSG_NAME_HASH_OFFSET,e->name_hash);
1515         SIVAL(msg,OP_BREAK_MSG_VNN_OFFSET,e->pid.vnn);
1516 }
1517
1518 /****************************************************************************
1519  De-linearize an internal oplock break message to a share mode entry struct.
1520 ****************************************************************************/
1521
1522 void message_to_share_mode_entry(struct file_id *id,
1523                                  struct share_mode_entry *e,
1524                                  const char *msg)
1525 {
1526         e->pid.pid = (pid_t)IVAL(msg,OP_BREAK_MSG_PID_OFFSET);
1527         e->op_mid = BVAL(msg,OP_BREAK_MSG_MID_OFFSET);
1528         e->op_type = SVAL(msg,OP_BREAK_MSG_OP_TYPE_OFFSET);
1529         e->access_mask = IVAL(msg,OP_BREAK_MSG_ACCESS_MASK_OFFSET);
1530         e->share_access = IVAL(msg,OP_BREAK_MSG_SHARE_ACCESS_OFFSET);
1531         e->private_options = IVAL(msg,OP_BREAK_MSG_PRIV_OFFSET);
1532         e->time.tv_sec = (time_t)IVAL(msg,OP_BREAK_MSG_TIME_SEC_OFFSET);
1533         e->time.tv_usec = (int)IVAL(msg,OP_BREAK_MSG_TIME_USEC_OFFSET);
1534         /*
1535          * "id" used to be part of share_mode_entry, thus the strange
1536          * place to put this. Feel free to move somewhere else :-)
1537          */
1538         pull_file_id_24(msg+OP_BREAK_MSG_DEV_OFFSET, id);
1539         e->share_file_id = (unsigned long)IVAL(msg,OP_BREAK_MSG_FILE_ID_OFFSET);
1540         e->uid = (uint32_t)IVAL(msg,OP_BREAK_MSG_UID_OFFSET);
1541         e->flags = (uint16_t)SVAL(msg,OP_BREAK_MSG_FLAGS_OFFSET);
1542         e->name_hash = IVAL(msg,OP_BREAK_MSG_NAME_HASH_OFFSET);
1543         e->pid.vnn = IVAL(msg,OP_BREAK_MSG_VNN_OFFSET);
1544 }
1545
1546 /****************************************************************************
1547  Setup oplocks for this process.
1548 ****************************************************************************/
1549
1550 bool init_oplocks(struct smbd_server_connection *sconn)
1551 {
1552         DEBUG(3,("init_oplocks: initializing messages.\n"));
1553
1554         messaging_register(sconn->msg_ctx, sconn, MSG_SMB_BREAK_REQUEST,
1555                            process_oplock_break_message);
1556         messaging_register(sconn->msg_ctx, sconn, MSG_SMB_KERNEL_BREAK,
1557                            process_kernel_oplock_break);
1558         return true;
1559 }
1560
1561 void init_kernel_oplocks(struct smbd_server_connection *sconn)
1562 {
1563         struct kernel_oplocks *koplocks = sconn->oplocks.kernel_ops;
1564
1565         /* only initialize once */
1566         if (koplocks == NULL) {
1567 #ifdef HAVE_KERNEL_OPLOCKS_LINUX
1568                 koplocks = linux_init_kernel_oplocks(sconn);
1569 #endif
1570                 sconn->oplocks.kernel_ops = koplocks;
1571         }
1572 }