2 * Copyright (c) 2004-2008 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
29 #include <sys/param.h>
30 #include <sys/systm.h>
31 #include <sys/event.h> // for kqueue related stuff
32 #include <sys/fsevents.h>
35 #include <sys/namei.h>
36 #include <sys/filedesc.h>
37 #include <sys/kernel.h>
38 #include <sys/file_internal.h>
40 #include <sys/vnode_internal.h>
41 #include <sys/mount_internal.h>
42 #include <sys/proc_internal.h>
43 #include <sys/kauth.h>
45 #include <sys/malloc.h>
46 #include <sys/dirent.h>
48 #include <sys/sysctl.h>
50 #include <machine/cons.h>
51 #include <miscfs/specfs/specdev.h>
52 #include <miscfs/devfs/devfs.h>
53 #include <sys/filio.h>
54 #include <kern/locks.h>
55 #include <libkern/OSAtomic.h>
56 #include <kern/zalloc.h>
57 #include <mach/mach_time.h>
58 #include <kern/thread_call.h>
59 #include <kern/clock.h>
61 #include <security/audit/audit.h>
62 #include <bsm/audit_kevents.h>
64 #include <pexpert/pexpert.h>
66 typedef struct kfs_event
{
67 LIST_ENTRY(kfs_event
) kevent_list
;
68 int16_t type
; // type code of this event
69 u_int16_t flags
, // per-event flags
70 len
; // the length of the path in "str"
71 int32_t refcount
; // number of clients referencing this
72 pid_t pid
; // pid of the process that did the op
74 uint64_t abstime
; // when this event happened (mach_absolute_time())
83 struct kfs_event
*dest
; // if this is a two-file op
86 // flags for the flags field
87 #define KFSE_COMBINED_EVENTS 0x0001
88 #define KFSE_CONTAINS_DROPPED_EVENTS 0x0002
89 #define KFSE_RECYCLED_EVENT 0x0004
90 #define KFSE_BEING_CREATED 0x0008
92 LIST_HEAD(kfse_list
, kfs_event
) kfse_list_head
= LIST_HEAD_INITIALIZER(x
);
93 int num_events_outstanding
= 0;
94 int num_pending_rename
= 0;
97 struct fsevent_handle
;
99 typedef struct fs_event_watcher
{
100 int8_t *event_list
; // the events we're interested in
102 dev_t
*devices_not_to_watch
; // report events from devices not in this list
103 uint32_t num_devices
;
105 kfs_event
**event_queue
;
106 int32_t eventq_size
; // number of event pointers in queue
108 int32_t rd
; // read index into the event_queue
109 int32_t wr
; // write index into the event_queue
112 uint32_t num_dropped
;
113 uint64_t max_event_id
;
114 struct fsevent_handle
*fseh
;
116 char proc_name
[(2 * MAXCOMLEN
) + 1];
119 // fs_event_watcher flags
120 #define WATCHER_DROPPED_EVENTS 0x0001
121 #define WATCHER_CLOSING 0x0002
122 #define WATCHER_WANTS_COMPACT_EVENTS 0x0004
123 #define WATCHER_WANTS_EXTENDED_INFO 0x0008
124 #define WATCHER_APPLE_SYSTEM_SERVICE 0x0010 // fseventsd, coreservicesd, mds
126 #define MAX_WATCHERS 8
127 static fs_event_watcher
*watcher_table
[MAX_WATCHERS
];
129 #define DEFAULT_MAX_KFS_EVENTS 4096
130 static int max_kfs_events
= DEFAULT_MAX_KFS_EVENTS
;
132 // we allocate kfs_event structures out of this zone
133 static zone_t event_zone
;
134 static int fs_event_init
= 0;
137 // this array records whether anyone is interested in a
138 // particular type of event. if no one is, we bail out
139 // early from the event delivery
141 static int16_t fs_event_type_watchers
[FSE_MAX_EVENTS
];
143 static int watcher_add_event(fs_event_watcher
*watcher
, kfs_event
*kfse
);
144 static void fsevents_wakeup(fs_event_watcher
*watcher
);
149 static lck_grp_attr_t
* fsevent_group_attr
;
150 static lck_attr_t
* fsevent_lock_attr
;
151 static lck_grp_t
* fsevent_mutex_group
;
153 static lck_grp_t
* fsevent_rw_group
;
155 static lck_rw_t event_handling_lock
; // handles locking for event manipulation and recycling
156 static lck_mtx_t watch_table_lock
;
157 static lck_mtx_t event_buf_lock
;
158 static lck_mtx_t event_writer_lock
;
161 /* Explicitly declare qsort so compiler doesn't complain */
162 __private_extern__
void qsort(
166 int (*)(const void *, const void *));
170 /* From kdp_udp.c + user mode Libc - this ought to be in a library */
172 strnstr(char *s
, const char *find
, size_t slen
)
177 if ((c
= *find
++) != '\0') {
181 if ((sc
= *s
++) == '\0' || slen
-- < 1)
186 } while (strncmp(s
, find
, len
) != 0);
193 is_ignored_directory(const char *path
) {
199 #define IS_TLD(x) strnstr((char *) path, x, MAXPATHLEN)
200 if (IS_TLD("/.Spotlight-V100/") ||
201 IS_TLD("/.MobileBackups/") ||
202 IS_TLD("/Backups.backupdb/")) {
211 fsevents_internal_init(void)
215 if (fs_event_init
++ != 0) {
219 for(i
=0; i
< FSE_MAX_EVENTS
; i
++) {
220 fs_event_type_watchers
[i
] = 0;
223 memset(watcher_table
, 0, sizeof(watcher_table
));
225 fsevent_lock_attr
= lck_attr_alloc_init();
226 fsevent_group_attr
= lck_grp_attr_alloc_init();
227 fsevent_mutex_group
= lck_grp_alloc_init("fsevent-mutex", fsevent_group_attr
);
228 fsevent_rw_group
= lck_grp_alloc_init("fsevent-rw", fsevent_group_attr
);
230 lck_mtx_init(&watch_table_lock
, fsevent_mutex_group
, fsevent_lock_attr
);
231 lck_mtx_init(&event_buf_lock
, fsevent_mutex_group
, fsevent_lock_attr
);
232 lck_mtx_init(&event_writer_lock
, fsevent_mutex_group
, fsevent_lock_attr
);
234 lck_rw_init(&event_handling_lock
, fsevent_rw_group
, fsevent_lock_attr
);
236 PE_get_default("kern.maxkfsevents", &max_kfs_events
, sizeof(max_kfs_events
));
238 event_zone
= zinit(sizeof(kfs_event
),
239 max_kfs_events
* sizeof(kfs_event
),
240 max_kfs_events
* sizeof(kfs_event
),
242 if (event_zone
== NULL
) {
243 printf("fsevents: failed to initialize the event zone.\n");
246 // mark the zone as exhaustible so that it will not
247 // ever grow beyond what we initially filled it with
248 zone_change(event_zone
, Z_EXHAUST
, TRUE
);
249 zone_change(event_zone
, Z_COLLECT
, FALSE
);
250 zone_change(event_zone
, Z_CALLERACCT
, FALSE
);
252 if (zfill(event_zone
, max_kfs_events
) < max_kfs_events
) {
253 printf("fsevents: failed to pre-fill the event zone.\n");
259 lock_watch_table(void)
261 lck_mtx_lock(&watch_table_lock
);
265 unlock_watch_table(void)
267 lck_mtx_unlock(&watch_table_lock
);
271 lock_fs_event_list(void)
273 lck_mtx_lock(&event_buf_lock
);
277 unlock_fs_event_list(void)
279 lck_mtx_unlock(&event_buf_lock
);
283 static void release_event_ref(kfs_event
*kfse
);
286 watcher_cares_about_dev(fs_event_watcher
*watcher
, dev_t dev
)
290 // if devices_not_to_watch is NULL then we care about all
291 // events from all devices
292 if (watcher
->devices_not_to_watch
== NULL
) {
296 for(i
=0; i
< watcher
->num_devices
; i
++) {
297 if (dev
== watcher
->devices_not_to_watch
[i
]) {
298 // found a match! that means we do not
299 // want events from this device.
304 // if we're here it's not in the devices_not_to_watch[]
305 // list so that means we do care about it
311 need_fsevent(int type
, vnode_t vp
)
313 if (type
>= 0 && type
< FSE_MAX_EVENTS
&& fs_event_type_watchers
[type
] == 0)
316 // events in /dev aren't really interesting...
317 if (vp
->v_tag
== VT_DEVFS
) {
325 #define is_throw_away(x) ((x) == FSE_STAT_CHANGED || (x) == FSE_CONTENT_MODIFIED)
328 // Ways that an event can be reused:
330 // "combined" events mean that there were two events for
331 // the same vnode or path and we're combining both events
332 // into a single event. The primary event gets a bit that
333 // marks it as having been combined. The secondary event
334 // is essentially dropped and the kfse structure reused.
336 // "collapsed" means that multiple events below a given
337 // directory are collapsed into a single event. in this
338 // case, the directory that we collapse into and all of
339 // its children must be re-scanned.
341 // "recycled" means that we're completely blowing away
342 // the event since there are other events that have info
343 // about the same vnode or path (and one of those other
344 // events will be marked as combined or collapsed as
347 #define KFSE_COMBINED 0x0001
348 #define KFSE_COLLAPSED 0x0002
349 #define KFSE_RECYCLED 0x0004
352 int num_parent_switch
= 0;
353 int num_recycled_rename
= 0;
355 static struct timeval last_print
;
358 // These variables are used to track coalescing multiple identical
359 // events for the same vnode/pathname. If we get the same event
360 // type and same vnode/pathname as the previous event, we just drop
361 // the event since it's superfluous. This improves some micro-
362 // benchmarks considerably and actually has a real-world impact on
363 // tests like a Finder copy where multiple stat-changed events can
366 static int last_event_type
=-1;
367 static void *last_ptr
=NULL
;
368 static char last_str
[MAXPATHLEN
];
369 static int last_nlen
=0;
370 static int last_vid
=-1;
371 static uint64_t last_coalesced_time
=0;
372 static void *last_event_ptr
=NULL
;
373 int last_coalesced
= 0;
374 static mach_timebase_info_data_t sTimebaseInfo
= { 0, 0 };
378 add_fsevent(int type
, vfs_context_t ctx
, ...)
380 struct proc
*p
= vfs_context_proc(ctx
);
381 int i
, arg_type
, ret
;
382 kfs_event
*kfse
, *kfse_dest
=NULL
, *cur
;
383 fs_event_watcher
*watcher
;
385 int error
= 0, did_alloc
=0;
387 uint64_t now
, elapsed
;
395 // ignore bogus event types..
396 if (type
< 0 || type
>= FSE_MAX_EVENTS
) {
400 // if no one cares about this type of event, bail out
401 if (fs_event_type_watchers
[type
] == 0) {
407 now
= mach_absolute_time();
409 // find a free event and snag it for our use
410 // NOTE: do not do anything that would block until
411 // the lock is dropped.
412 lock_fs_event_list();
415 // check if this event is identical to the previous one...
416 // (as long as it's not an event type that can never be the
417 // same as a previous event)
419 if (type
!= FSE_CREATE_FILE
&& type
!= FSE_DELETE
&& type
!= FSE_RENAME
&& type
!= FSE_EXCHANGE
&& type
!= FSE_CHOWN
) {
421 int vid
=0, was_str
=0, nlen
=0;
423 for(arg_type
=va_arg(ap
, int32_t); arg_type
!= FSE_ARG_DONE
; arg_type
=va_arg(ap
, int32_t)) {
425 case FSE_ARG_VNODE
: {
426 ptr
= va_arg(ap
, void *);
427 vid
= vnode_vid((struct vnode
*)ptr
);
431 case FSE_ARG_STRING
: {
432 nlen
= va_arg(ap
, int32_t);
433 ptr
= va_arg(ap
, void *);
443 if ( sTimebaseInfo
.denom
== 0 ) {
444 (void) clock_timebase_info(&sTimebaseInfo
);
447 elapsed
= (now
- last_coalesced_time
);
448 if (sTimebaseInfo
.denom
!= sTimebaseInfo
.numer
) {
449 if (sTimebaseInfo
.denom
== 1) {
450 elapsed
*= sTimebaseInfo
.numer
;
452 // this could overflow... the worst that will happen is that we'll
453 // send (or not send) an extra event so I'm not going to worry about
454 // doing the math right like dtrace_abs_to_nano() does.
455 elapsed
= (elapsed
* sTimebaseInfo
.numer
) / (uint64_t)sTimebaseInfo
.denom
;
459 if (type
== last_event_type
460 && (elapsed
< 1000000000)
462 ((vid
&& vid
== last_vid
&& last_ptr
== ptr
)
464 (last_str
[0] && last_nlen
== nlen
&& ptr
&& strcmp(last_str
, ptr
) == 0))
468 unlock_fs_event_list();
475 strlcpy(last_str
, ptr
, sizeof(last_str
));
479 last_event_type
= type
;
480 last_coalesced_time
= now
;
486 kfse
= zalloc_noblock(event_zone
);
487 if (kfse
&& (type
== FSE_RENAME
|| type
== FSE_EXCHANGE
)) {
488 kfse_dest
= zalloc_noblock(event_zone
);
489 if (kfse_dest
== NULL
) {
491 zfree(event_zone
, kfse
);
497 if (kfse
== NULL
) { // yikes! no free events
498 unlock_fs_event_list();
501 for(i
=0; i
< MAX_WATCHERS
; i
++) {
502 watcher
= watcher_table
[i
];
503 if (watcher
== NULL
) {
507 watcher
->flags
|= WATCHER_DROPPED_EVENTS
;
508 fsevents_wakeup(watcher
);
510 unlock_watch_table();
513 struct timeval current_tv
;
517 // only print a message at most once every 5 seconds
518 microuptime(¤t_tv
);
519 if ((current_tv
.tv_sec
- last_print
.tv_sec
) > 10) {
521 void *junkptr
=zalloc_noblock(event_zone
), *listhead
=kfse_list_head
.lh_first
;
523 printf("add_fsevent: event queue is full! dropping events (num dropped events: %d; num events outstanding: %d).\n", num_dropped
, num_events_outstanding
);
524 printf("add_fsevent: kfse_list head %p ; num_pending_rename %d\n", listhead
, num_pending_rename
);
525 printf("add_fsevent: zalloc sez: %p\n", junkptr
);
526 printf("add_fsevent: event_zone info: %d 0x%x\n", ((int *)event_zone
)[0], ((int *)event_zone
)[1]);
527 for(ii
=0; ii
< MAX_WATCHERS
; ii
++) {
528 if (watcher_table
[ii
] == NULL
) {
532 printf("add_fsevent: watcher %s %p: rd %4d wr %4d q_size %4d flags 0x%x\n",
533 watcher_table
[ii
]->proc_name
,
535 watcher_table
[ii
]->rd
, watcher_table
[ii
]->wr
,
536 watcher_table
[ii
]->eventq_size
, watcher_table
[ii
]->flags
);
539 last_print
= current_tv
;
541 zfree(event_zone
, junkptr
);
547 release_pathbuff(pathbuff
);
553 memset(kfse
, 0, sizeof(kfs_event
));
555 OSBitOrAtomic16(KFSE_BEING_CREATED
, &kfse
->flags
);
557 last_event_ptr
= kfse
;
560 kfse
->pid
= p
->p_pid
;
561 if (type
== FSE_RENAME
|| type
== FSE_EXCHANGE
) {
562 memset(kfse_dest
, 0, sizeof(kfs_event
));
563 kfse_dest
->refcount
= 1;
564 OSBitOrAtomic16(KFSE_BEING_CREATED
, &kfse_dest
->flags
);
565 kfse_dest
->type
= type
;
566 kfse_dest
->pid
= p
->p_pid
;
567 kfse_dest
->abstime
= now
;
569 kfse
->dest
= kfse_dest
;
572 num_events_outstanding
++;
573 if (kfse
->type
== FSE_RENAME
) {
574 num_pending_rename
++;
576 LIST_INSERT_HEAD(&kfse_list_head
, kfse
, kevent_list
);
578 if (kfse
->refcount
< 1) {
579 panic("add_fsevent: line %d: kfse recount %d but should be at least 1\n", __LINE__
, kfse
->refcount
);
582 unlock_fs_event_list(); // at this point it's safe to unlock
585 // now process the arguments passed in and copy them into
590 for(arg_type
=va_arg(ap
, int32_t); arg_type
!= FSE_ARG_DONE
; arg_type
=va_arg(ap
, int32_t))
593 case FSE_ARG_VNODE
: {
594 // this expands out into multiple arguments to the client
596 struct vnode_attr va
;
598 if (kfse
->str
!= NULL
) {
602 vp
= va_arg(ap
, struct vnode
*);
604 panic("add_fsevent: you can't pass me a NULL vnode ptr (type %d)!\n",
609 VATTR_WANTED(&va
, va_fsid
);
610 VATTR_WANTED(&va
, va_fileid
);
611 VATTR_WANTED(&va
, va_mode
);
612 VATTR_WANTED(&va
, va_uid
);
613 VATTR_WANTED(&va
, va_gid
);
614 if ((ret
= vnode_getattr(vp
, &va
, vfs_context_kernel())) != 0) {
615 // printf("add_fsevent: failed to getattr on vp %p (%d)\n", cur->fref.vp, ret);
621 cur
->dev
= dev
= (dev_t
)va
.va_fsid
;
622 cur
->ino
= (ino64_t
)va
.va_fileid
;
623 cur
->mode
= (int32_t)vnode_vttoif(vnode_vtype(vp
)) | va
.va_mode
;
624 cur
->uid
= va
.va_uid
;
625 cur
->gid
= va
.va_gid
;
627 // if we haven't gotten the path yet, get it.
628 if (pathbuff
== NULL
) {
629 pathbuff
= get_pathbuff();
630 pathbuff_len
= MAXPATHLEN
;
633 if ((ret
= vn_getpath(vp
, pathbuff
, &pathbuff_len
)) != 0 || pathbuff
[0] == '\0') {
635 cur
->flags
|= KFSE_CONTAINS_DROPPED_EVENTS
;
638 if (vp
->v_parent
!= NULL
) {
640 } else if (vp
->v_mount
) {
641 strlcpy(pathbuff
, vp
->v_mount
->mnt_vfsstat
.f_mntonname
, MAXPATHLEN
);
651 pathbuff_len
= MAXPATHLEN
;
652 ret
= vn_getpath(vp
, pathbuff
, &pathbuff_len
);
653 } while (ret
== ENOSPC
);
655 if (ret
!= 0 || vp
== NULL
) {
662 // store the path by adding it to the global string table
663 cur
->len
= pathbuff_len
;
664 cur
->str
= vfs_addname(pathbuff
, pathbuff_len
, 0, 0);
665 if (cur
->str
== NULL
|| cur
->str
[0] == '\0') {
666 panic("add_fsevent: was not able to add path %s to event %p.\n", pathbuff
, cur
);
669 release_pathbuff(pathbuff
);
675 case FSE_ARG_FINFO
: {
678 fse
= va_arg(ap
, fse_info
*);
680 cur
->dev
= dev
= (dev_t
)fse
->dev
;
681 cur
->ino
= (ino64_t
)fse
->ino
;
682 cur
->mode
= (int32_t)fse
->mode
;
683 cur
->uid
= (uid_t
)fse
->uid
;
684 cur
->gid
= (uid_t
)fse
->gid
;
685 // if it's a hard-link and this is the last link, flag it
686 if ((fse
->mode
& FSE_MODE_HLINK
) && fse
->nlink
== 0) {
687 cur
->mode
|= FSE_MODE_LAST_HLINK
;
689 if (cur
->mode
& FSE_TRUNCATED_PATH
) {
690 cur
->flags
|= KFSE_CONTAINS_DROPPED_EVENTS
;
691 cur
->mode
&= ~FSE_TRUNCATED_PATH
;
697 if (kfse
->str
!= NULL
) {
701 cur
->len
= (int16_t)(va_arg(ap
, int32_t) & 0x7fff);
703 cur
->str
= vfs_addname(va_arg(ap
, char *), cur
->len
, 0, 0);
705 printf("add_fsevent: funny looking string length: %d\n", (int)cur
->len
);
707 cur
->str
= vfs_addname("/", cur
->len
, 0, 0);
709 if (cur
->str
[0] == 0) {
710 printf("add_fsevent: bogus looking string (len %d)\n", cur
->len
);
715 printf("add_fsevent: unknown type %d\n", arg_type
);
716 // just skip one 32-bit word and hope we sync up...
717 (void)va_arg(ap
, int32_t);
722 OSBitAndAtomic16(~KFSE_BEING_CREATED
, &kfse
->flags
);
724 OSBitAndAtomic16(~KFSE_BEING_CREATED
, &kfse_dest
->flags
);
728 // now we have to go and let everyone know that
729 // is interested in this type of event
733 for(i
=0; i
< MAX_WATCHERS
; i
++) {
734 watcher
= watcher_table
[i
];
735 if (watcher
== NULL
) {
739 if ( watcher
->event_list
[type
] == FSE_REPORT
740 && watcher_cares_about_dev(watcher
, dev
)) {
742 if (watcher_add_event(watcher
, kfse
) != 0) {
743 watcher
->num_dropped
++;
748 // if (kfse->refcount < 1) {
749 // panic("add_fsevent: line %d: kfse recount %d but should be at least 1\n", __LINE__, kfse->refcount);
753 unlock_watch_table();
758 release_pathbuff(pathbuff
);
762 release_event_ref(kfse
);
769 release_event_ref(kfs_event
*kfse
)
772 kfs_event copy
, dest_copy
;
775 old_refcount
= OSAddAtomic(-1, &kfse
->refcount
);
776 if (old_refcount
> 1) {
780 lock_fs_event_list();
781 if (last_event_ptr
== kfse
) {
782 last_event_ptr
= NULL
;
783 last_event_type
= -1;
784 last_coalesced_time
= 0;
787 if (kfse
->refcount
< 0) {
788 panic("release_event_ref: bogus kfse refcount %d\n", kfse
->refcount
);
791 if (kfse
->refcount
> 0 || kfse
->type
== FSE_INVALID
) {
792 // This is very subtle. Either of these conditions can
793 // be true if an event got recycled while we were waiting
794 // on the fs_event_list lock or the event got recycled,
795 // delivered, _and_ free'd by someone else while we were
796 // waiting on the fs event list lock. In either case
797 // we need to just unlock the list and return without
798 // doing anything because if the refcount is > 0 then
799 // someone else will take care of free'ing it and when
800 // the kfse->type is invalid then someone else already
801 // has handled free'ing the event (while we were blocked
802 // on the event list lock).
804 unlock_fs_event_list();
809 // make a copy of this so we can free things without
810 // holding the fs_event_buf lock
813 if (kfse
->dest
&& OSAddAtomic(-1, &kfse
->dest
->refcount
) == 1) {
814 dest_copy
= *kfse
->dest
;
816 dest_copy
.str
= NULL
;
818 dest_copy
.type
= FSE_INVALID
;
821 kfse
->pid
= kfse
->type
; // save this off for debugging...
822 kfse
->uid
= (uid_t
)(long)kfse
->str
; // save this off for debugging...
823 kfse
->gid
= (gid_t
)(long)current_thread();
825 kfse
->str
= (char *)0xdeadbeef; // XXXdbg - catch any cheaters...
827 if (dest_copy
.type
!= FSE_INVALID
) {
828 kfse
->dest
->str
= (char *)0xbadc0de; // XXXdbg - catch any cheaters...
829 kfse
->dest
->type
= FSE_INVALID
;
831 if (kfse
->dest
->kevent_list
.le_prev
!= NULL
) {
832 num_events_outstanding
--;
833 LIST_REMOVE(kfse
->dest
, kevent_list
);
834 memset(&kfse
->dest
->kevent_list
, 0xa5, sizeof(kfse
->dest
->kevent_list
));
837 zfree(event_zone
, kfse
->dest
);
840 // mark this fsevent as invalid
845 kfse
->type
= FSE_INVALID
;
847 if (kfse
->kevent_list
.le_prev
!= NULL
) {
848 num_events_outstanding
--;
849 if (otype
== FSE_RENAME
) {
850 num_pending_rename
--;
852 LIST_REMOVE(kfse
, kevent_list
);
853 memset(&kfse
->kevent_list
, 0, sizeof(kfse
->kevent_list
));
857 zfree(event_zone
, kfse
);
859 unlock_fs_event_list();
861 // if we have a pointer in the union
863 if (copy
.len
== 0) { // and it's not a string
864 panic("%s:%d: no more fref.vp!\n", __FILE__
, __LINE__
);
865 // vnode_rele_ext(copy.fref.vp, O_EVTONLY, 0);
866 } else { // else it's a string
867 vfs_removename(copy
.str
);
871 if (dest_copy
.type
!= FSE_INVALID
&& dest_copy
.str
) {
872 if (dest_copy
.len
== 0) {
873 panic("%s:%d: no more fref.vp!\n", __FILE__
, __LINE__
);
874 // vnode_rele_ext(dest_copy.fref.vp, O_EVTONLY, 0);
876 vfs_removename(dest_copy
.str
);
882 add_watcher(int8_t *event_list
, int32_t num_events
, int32_t eventq_size
, fs_event_watcher
**watcher_out
, void *fseh
)
885 fs_event_watcher
*watcher
;
887 if (eventq_size
<= 0 || eventq_size
> 100*max_kfs_events
) {
888 eventq_size
= max_kfs_events
;
891 // Note: the event_queue follows the fs_event_watcher struct
892 // in memory so we only have to do one allocation
895 sizeof(fs_event_watcher
) + eventq_size
* sizeof(kfs_event
*),
897 if (watcher
== NULL
) {
901 watcher
->event_list
= event_list
;
902 watcher
->num_events
= num_events
;
903 watcher
->devices_not_to_watch
= NULL
;
904 watcher
->num_devices
= 0;
906 watcher
->event_queue
= (kfs_event
**)&watcher
[1];
907 watcher
->eventq_size
= eventq_size
;
910 watcher
->blockers
= 0;
911 watcher
->num_readers
= 0;
912 watcher
->max_event_id
= 0;
913 watcher
->fseh
= fseh
;
914 watcher
->pid
= proc_selfpid();
915 proc_selfname(watcher
->proc_name
, sizeof(watcher
->proc_name
));
917 watcher
->num_dropped
= 0; // XXXdbg - debugging
919 if (!strncmp(watcher
->proc_name
, "fseventsd", sizeof(watcher
->proc_name
)) ||
920 !strncmp(watcher
->proc_name
, "coreservicesd", sizeof(watcher
->proc_name
)) ||
921 !strncmp(watcher
->proc_name
, "mds", sizeof(watcher
->proc_name
))) {
922 watcher
->flags
|= WATCHER_APPLE_SYSTEM_SERVICE
;
924 printf("fsevents: watcher %s (pid: %d) - Using /dev/fsevents directly is unsupported. Migrate to FSEventsFramework\n",
925 watcher
->proc_name
, watcher
->pid
);
930 // now update the global list of who's interested in
931 // events of a particular type...
932 for(i
=0; i
< num_events
; i
++) {
933 if (event_list
[i
] != FSE_IGNORE
&& i
< FSE_MAX_EVENTS
) {
934 fs_event_type_watchers
[i
]++;
938 for(i
=0; i
< MAX_WATCHERS
; i
++) {
939 if (watcher_table
[i
] == NULL
) {
941 watcher_table
[i
] = watcher
;
946 if (i
> MAX_WATCHERS
) {
947 printf("fsevents: too many watchers!\n");
948 unlock_watch_table();
952 unlock_watch_table();
954 *watcher_out
= watcher
;
962 remove_watcher(fs_event_watcher
*target
)
965 fs_event_watcher
*watcher
;
970 for(j
=0; j
< MAX_WATCHERS
; j
++) {
971 watcher
= watcher_table
[j
];
972 if (watcher
!= target
) {
976 watcher_table
[j
] = NULL
;
978 for(i
=0; i
< watcher
->num_events
; i
++) {
979 if (watcher
->event_list
[i
] != FSE_IGNORE
&& i
< FSE_MAX_EVENTS
) {
980 fs_event_type_watchers
[i
]--;
984 if (watcher
->flags
& WATCHER_CLOSING
) {
985 unlock_watch_table();
989 // printf("fsevents: removing watcher %p (rd %d wr %d num_readers %d flags 0x%x)\n", watcher, watcher->rd, watcher->wr, watcher->num_readers, watcher->flags);
990 watcher
->flags
|= WATCHER_CLOSING
;
991 OSAddAtomic(1, &watcher
->num_readers
);
993 unlock_watch_table();
995 while (watcher
->num_readers
> 1 && counter
++ < 5000) {
997 fsevents_wakeup(watcher
); // in case they're asleep
998 unlock_watch_table();
1000 tsleep(watcher
, PRIBIO
, "fsevents-close", 1);
1002 if (counter
++ >= 5000) {
1003 // printf("fsevents: close: still have readers! (%d)\n", watcher->num_readers);
1004 panic("fsevents: close: still have readers! (%d)\n", watcher
->num_readers
);
1007 // drain the event_queue
1009 lck_rw_lock_exclusive(&event_handling_lock
);
1010 while(watcher
->rd
!= watcher
->wr
) {
1011 kfse
= watcher
->event_queue
[watcher
->rd
];
1012 watcher
->event_queue
[watcher
->rd
] = NULL
;
1013 watcher
->rd
= (watcher
->rd
+1) % watcher
->eventq_size
;
1015 if (kfse
!= NULL
&& kfse
->type
!= FSE_INVALID
&& kfse
->refcount
>= 1) {
1016 release_event_ref(kfse
);
1019 lck_rw_unlock_exclusive(&event_handling_lock
);
1021 if (watcher
->event_list
) {
1022 FREE(watcher
->event_list
, M_TEMP
);
1023 watcher
->event_list
= NULL
;
1025 if (watcher
->devices_not_to_watch
) {
1026 FREE(watcher
->devices_not_to_watch
, M_TEMP
);
1027 watcher
->devices_not_to_watch
= NULL
;
1029 FREE(watcher
, M_TEMP
);
1034 unlock_watch_table();
1038 #define EVENT_DELAY_IN_MS 10
1039 static thread_call_t event_delivery_timer
= NULL
;
1040 static int timer_set
= 0;
1044 delayed_event_delivery(__unused
void *param0
, __unused
void *param1
)
1050 for(i
=0; i
< MAX_WATCHERS
; i
++) {
1051 if (watcher_table
[i
] != NULL
&& watcher_table
[i
]->rd
!= watcher_table
[i
]->wr
) {
1052 fsevents_wakeup(watcher_table
[i
]);
1058 unlock_watch_table();
1063 // The watch table must be locked before calling this function.
1066 schedule_event_wakeup(void)
1070 if (event_delivery_timer
== NULL
) {
1071 event_delivery_timer
= thread_call_allocate((thread_call_func_t
)delayed_event_delivery
, NULL
);
1074 clock_interval_to_deadline(EVENT_DELAY_IN_MS
, 1000 * 1000, &deadline
);
1076 thread_call_enter_delayed(event_delivery_timer
, deadline
);
1082 #define MAX_NUM_PENDING 16
1085 // NOTE: the watch table must be locked before calling
1089 watcher_add_event(fs_event_watcher
*watcher
, kfs_event
*kfse
)
1091 if (kfse
->abstime
> watcher
->max_event_id
) {
1092 watcher
->max_event_id
= kfse
->abstime
;
1095 if (((watcher
->wr
+ 1) % watcher
->eventq_size
) == watcher
->rd
) {
1096 watcher
->flags
|= WATCHER_DROPPED_EVENTS
;
1097 fsevents_wakeup(watcher
);
1101 OSAddAtomic(1, &kfse
->refcount
);
1102 watcher
->event_queue
[watcher
->wr
] = kfse
;
1104 watcher
->wr
= (watcher
->wr
+ 1) % watcher
->eventq_size
;
1107 // wake up the watcher if there are more than MAX_NUM_PENDING events.
1108 // otherwise schedule a timer (if one isn't already set) which will
1109 // send any pending events if no more are received in the next
1110 // EVENT_DELAY_IN_MS milli-seconds.
1112 int32_t num_pending
= 0;
1113 if (watcher
->rd
< watcher
->wr
) {
1114 num_pending
= watcher
->wr
- watcher
->rd
;
1117 if (watcher
->rd
> watcher
->wr
) {
1118 num_pending
= watcher
->wr
+ watcher
->eventq_size
- watcher
->rd
;
1121 if (num_pending
> (watcher
->eventq_size
*3/4) && !(watcher
->flags
& WATCHER_APPLE_SYSTEM_SERVICE
)) {
1122 /* Non-Apple Service is falling behind, start dropping events for this process */
1123 lck_rw_lock_exclusive(&event_handling_lock
);
1124 while (watcher
->rd
!= watcher
->wr
) {
1125 kfse
= watcher
->event_queue
[watcher
->rd
];
1126 watcher
->event_queue
[watcher
->rd
] = NULL
;
1127 watcher
->rd
= (watcher
->rd
+1) % watcher
->eventq_size
;
1129 if (kfse
!= NULL
&& kfse
->type
!= FSE_INVALID
&& kfse
->refcount
>= 1) {
1130 release_event_ref(kfse
);
1133 watcher
->flags
|= WATCHER_DROPPED_EVENTS
;
1134 lck_rw_unlock_exclusive(&event_handling_lock
);
1136 printf("fsevents: watcher falling behind: %s (pid: %d) rd: %4d wr: %4d q_size: %4d flags: 0x%x\n",
1137 watcher
->proc_name
, watcher
->pid
, watcher
->rd
, watcher
->wr
,
1138 watcher
->eventq_size
, watcher
->flags
);
1140 fsevents_wakeup(watcher
);
1141 } else if (num_pending
> MAX_NUM_PENDING
) {
1142 fsevents_wakeup(watcher
);
1143 } else if (timer_set
== 0) {
1144 schedule_event_wakeup();
1151 fill_buff(uint16_t type
, int32_t size
, const void *data
,
1152 char *buff
, int32_t *_buff_idx
, int32_t buff_sz
,
1155 int32_t amt
, error
= 0, buff_idx
= *_buff_idx
;
1159 // the +1 on the size is to guarantee that the main data
1160 // copy loop will always copy at least 1 byte
1162 if ((buff_sz
- buff_idx
) <= (int)(2*sizeof(uint16_t) + 1)) {
1163 if (buff_idx
> uio_resid(uio
)) {
1168 error
= uiomove(buff
, buff_idx
, uio
);
1175 // copy out the header (type & size)
1176 memcpy(&buff
[buff_idx
], &type
, sizeof(uint16_t));
1177 buff_idx
+= sizeof(uint16_t);
1179 tmp
= size
& 0xffff;
1180 memcpy(&buff
[buff_idx
], &tmp
, sizeof(uint16_t));
1181 buff_idx
+= sizeof(uint16_t);
1183 // now copy the body of the data, flushing along the way
1184 // if the buffer fills up.
1187 amt
= (size
< (buff_sz
- buff_idx
)) ? size
: (buff_sz
- buff_idx
);
1188 memcpy(&buff
[buff_idx
], data
, amt
);
1192 data
= (const char *)data
+ amt
;
1193 if (size
> (buff_sz
- buff_idx
)) {
1194 if (buff_idx
> uio_resid(uio
)) {
1198 error
= uiomove(buff
, buff_idx
, uio
);
1205 if (amt
== 0) { // just in case...
1211 *_buff_idx
= buff_idx
;
1217 static int copy_out_kfse(fs_event_watcher
*watcher
, kfs_event
*kfse
, struct uio
*uio
) __attribute__((noinline
));
1220 copy_out_kfse(fs_event_watcher
*watcher
, kfs_event
*kfse
, struct uio
*uio
)
1229 if (kfse
->type
== FSE_INVALID
) {
1230 panic("fsevents: copy_out_kfse: asked to copy out an invalid event (kfse %p, refcount %d fref ptr %p)\n", kfse
, kfse
->refcount
, kfse
->str
);
1233 if (kfse
->flags
& KFSE_BEING_CREATED
) {
1237 if (kfse
->type
== FSE_RENAME
&& kfse
->dest
== NULL
) {
1239 // This can happen if an event gets recycled but we had a
1240 // pointer to it in our event queue. The event is the
1241 // destination of a rename which we'll process separately
1242 // (that is, another kfse points to this one so it's ok
1243 // to skip this guy because we'll process it when we process
1249 if (watcher
->flags
& WATCHER_WANTS_EXTENDED_INFO
) {
1251 type
= (kfse
->type
& 0xfff);
1253 if (kfse
->flags
& KFSE_CONTAINS_DROPPED_EVENTS
) {
1254 type
|= (FSE_CONTAINS_DROPPED_EVENTS
<< FSE_FLAG_SHIFT
);
1255 } else if (kfse
->flags
& KFSE_COMBINED_EVENTS
) {
1256 type
|= (FSE_COMBINED_EVENTS
<< FSE_FLAG_SHIFT
);
1260 type
= (int32_t)kfse
->type
;
1263 // copy out the type of the event
1264 memcpy(evbuff
, &type
, sizeof(int32_t));
1265 evbuff_idx
+= sizeof(int32_t);
1267 // copy out the pid of the person that generated the event
1268 memcpy(&evbuff
[evbuff_idx
], &kfse
->pid
, sizeof(pid_t
));
1269 evbuff_idx
+= sizeof(pid_t
);
1275 if (cur
->str
== NULL
|| cur
->str
[0] == '\0') {
1276 printf("copy_out_kfse:2: empty/short path (%s)\n", cur
->str
);
1277 error
= fill_buff(FSE_ARG_STRING
, 2, "/", evbuff
, &evbuff_idx
, sizeof(evbuff
), uio
);
1279 error
= fill_buff(FSE_ARG_STRING
, cur
->len
, cur
->str
, evbuff
, &evbuff_idx
, sizeof(evbuff
), uio
);
1285 if (cur
->dev
== 0 && cur
->ino
== 0) {
1286 // this happens when a rename event happens and the
1287 // destination of the rename did not previously exist.
1288 // it thus has no other file info so skip copying out
1289 // the stuff below since it isn't initialized
1294 if (watcher
->flags
& WATCHER_WANTS_COMPACT_EVENTS
) {
1297 finfo_size
= sizeof(dev_t
) + sizeof(ino64_t
) + sizeof(int32_t) + sizeof(uid_t
) + sizeof(gid_t
);
1298 error
= fill_buff(FSE_ARG_FINFO
, finfo_size
, &cur
->ino
, evbuff
, &evbuff_idx
, sizeof(evbuff
), uio
);
1305 error
= fill_buff(FSE_ARG_DEV
, sizeof(dev_t
), &cur
->dev
, evbuff
, &evbuff_idx
, sizeof(evbuff
), uio
);
1310 ino
= (ino_t
)cur
->ino
;
1311 error
= fill_buff(FSE_ARG_INO
, sizeof(ino_t
), &ino
, evbuff
, &evbuff_idx
, sizeof(evbuff
), uio
);
1316 error
= fill_buff(FSE_ARG_MODE
, sizeof(int32_t), &cur
->mode
, evbuff
, &evbuff_idx
, sizeof(evbuff
), uio
);
1321 error
= fill_buff(FSE_ARG_UID
, sizeof(uid_t
), &cur
->uid
, evbuff
, &evbuff_idx
, sizeof(evbuff
), uio
);
1326 error
= fill_buff(FSE_ARG_GID
, sizeof(gid_t
), &cur
->gid
, evbuff
, &evbuff_idx
, sizeof(evbuff
), uio
);
1339 // very last thing: the time stamp
1340 error
= fill_buff(FSE_ARG_INT64
, sizeof(uint64_t), &cur
->abstime
, evbuff
, &evbuff_idx
, sizeof(evbuff
), uio
);
1345 // check if the FSE_ARG_DONE will fit
1346 if (sizeof(uint16_t) > sizeof(evbuff
) - evbuff_idx
) {
1347 if (evbuff_idx
> uio_resid(uio
)) {
1351 error
= uiomove(evbuff
, evbuff_idx
, uio
);
1358 tmp16
= FSE_ARG_DONE
;
1359 memcpy(&evbuff
[evbuff_idx
], &tmp16
, sizeof(uint16_t));
1360 evbuff_idx
+= sizeof(uint16_t);
1362 // flush any remaining data in the buffer (and hopefully
1363 // in most cases this is the only uiomove we'll do)
1364 if (evbuff_idx
> uio_resid(uio
)) {
1367 error
= uiomove(evbuff
, evbuff_idx
, uio
);
1378 fmod_watch(fs_event_watcher
*watcher
, struct uio
*uio
)
1381 user_ssize_t last_full_event_resid
;
1386 last_full_event_resid
= uio_resid(uio
);
1388 // need at least 2048 bytes of space (maxpathlen + 1 event buf)
1389 if (uio_resid(uio
) < 2048 || watcher
== NULL
) {
1393 if (watcher
->flags
& WATCHER_CLOSING
) {
1397 if (OSAddAtomic(1, &watcher
->num_readers
) != 0) {
1398 // don't allow multiple threads to read from the fd at the same time
1399 OSAddAtomic(-1, &watcher
->num_readers
);
1404 if (watcher
->rd
== watcher
->wr
) {
1405 if (watcher
->flags
& WATCHER_CLOSING
) {
1406 OSAddAtomic(-1, &watcher
->num_readers
);
1409 OSAddAtomic(1, &watcher
->blockers
);
1411 // there's nothing to do, go to sleep
1412 error
= tsleep((caddr_t
)watcher
, PUSER
|PCATCH
, "fsevents_empty", 0);
1414 OSAddAtomic(-1, &watcher
->blockers
);
1416 if (error
!= 0 || (watcher
->flags
& WATCHER_CLOSING
)) {
1417 OSAddAtomic(-1, &watcher
->num_readers
);
1422 // if we dropped events, return that as an event first
1423 if (watcher
->flags
& WATCHER_DROPPED_EVENTS
) {
1424 int32_t val
= FSE_EVENTS_DROPPED
;
1426 error
= uiomove((caddr_t
)&val
, sizeof(int32_t), uio
);
1428 val
= 0; // a fake pid
1429 error
= uiomove((caddr_t
)&val
, sizeof(int32_t), uio
);
1431 tmp16
= FSE_ARG_DONE
; // makes it a consistent msg
1432 error
= uiomove((caddr_t
)&tmp16
, sizeof(int16_t), uio
);
1434 last_full_event_resid
= uio_resid(uio
);
1438 OSAddAtomic(-1, &watcher
->num_readers
);
1442 watcher
->flags
&= ~WATCHER_DROPPED_EVENTS
;
1447 lck_rw_lock_shared(&event_handling_lock
);
1448 while (uio_resid(uio
) > 0 && watcher
->rd
!= watcher
->wr
) {
1449 if (watcher
->flags
& WATCHER_CLOSING
) {
1454 // check if the event is something of interest to us
1455 // (since it may have been recycled/reused and changed
1456 // its type or which device it is for)
1458 kfse
= watcher
->event_queue
[watcher
->rd
];
1459 if (!kfse
|| kfse
->type
== FSE_INVALID
|| kfse
->refcount
< 1) {
1463 if (watcher
->event_list
[kfse
->type
] == FSE_REPORT
&& watcher_cares_about_dev(watcher
, kfse
->dev
)) {
1465 if (!(watcher
->flags
& WATCHER_APPLE_SYSTEM_SERVICE
) & is_ignored_directory(kfse
->str
)) {
1466 // If this is not an Apple System Service, skip specified directories
1473 if (last_event_ptr
== kfse
) {
1474 last_event_ptr
= NULL
;
1475 last_event_type
= -1;
1476 last_coalesced_time
= 0;
1478 error
= copy_out_kfse(watcher
, kfse
, uio
);
1480 // if an event won't fit or encountered an error while
1481 // we were copying it out, then backup to the last full
1482 // event and just bail out. if the error was ENOENT
1483 // then we can continue regular processing, otherwise
1484 // we should unlock things and return.
1485 uio_setresid(uio
, last_full_event_resid
);
1486 if (error
!= ENOENT
) {
1487 lck_rw_unlock_shared(&event_handling_lock
);
1493 last_full_event_resid
= uio_resid(uio
);
1497 watcher
->event_queue
[watcher
->rd
] = NULL
;
1498 watcher
->rd
= (watcher
->rd
+ 1) % watcher
->eventq_size
;
1500 release_event_ref(kfse
);
1502 lck_rw_unlock_shared(&event_handling_lock
);
1504 if (skipped
&& error
== 0) {
1509 OSAddAtomic(-1, &watcher
->num_readers
);
1515 // release any references we might have on vnodes which are
1516 // the mount point passed to us (so that it can be cleanly
1519 // since we don't want to lose the events we'll convert the
1520 // vnode refs to full paths.
1523 fsevent_unmount(__unused
struct mount
*mp
)
1525 // we no longer maintain pointers to vnodes so
1526 // there is nothing to do...
1531 // /dev/fsevents device code
1533 static int fsevents_installed
= 0;
1535 typedef struct fsevent_handle
{
1538 fs_event_watcher
*watcher
;
1539 struct klist knotes
;
1543 #define FSEH_CLOSING 0x0001
1546 fseventsf_read(struct fileproc
*fp
, struct uio
*uio
,
1547 __unused
int flags
, __unused vfs_context_t ctx
)
1549 fsevent_handle
*fseh
= (struct fsevent_handle
*)fp
->f_fglob
->fg_data
;
1552 error
= fmod_watch(fseh
->watcher
, uio
);
1559 fseventsf_write(__unused
struct fileproc
*fp
, __unused
struct uio
*uio
,
1560 __unused
int flags
, __unused vfs_context_t ctx
)
1565 #pragma pack(push, 4)
1566 typedef struct ext_fsevent_dev_filter_args
{
1567 uint32_t num_devices
;
1568 user_addr_t devices
;
1569 } ext_fsevent_dev_filter_args
;
1572 #define NEW_FSEVENTS_DEVICE_FILTER _IOW('s', 100, ext_fsevent_dev_filter_args)
1574 typedef struct old_fsevent_dev_filter_args
{
1575 uint32_t num_devices
;
1577 } old_fsevent_dev_filter_args
;
1579 #define OLD_FSEVENTS_DEVICE_FILTER _IOW('s', 100, old_fsevent_dev_filter_args)
1582 /* need this in spite of the padding due to alignment of devices */
1583 typedef struct fsevent_dev_filter_args32
{
1584 uint32_t num_devices
;
1587 } fsevent_dev_filter_args32
;
1591 fseventsf_ioctl(struct fileproc
*fp
, u_long cmd
, caddr_t data
, vfs_context_t ctx
)
1593 fsevent_handle
*fseh
= (struct fsevent_handle
*)fp
->f_fglob
->fg_data
;
1595 ext_fsevent_dev_filter_args
*devfilt_args
, _devfilt_args
;
1597 if (proc_is64bit(vfs_context_proc(ctx
))) {
1598 devfilt_args
= (ext_fsevent_dev_filter_args
*)data
;
1600 else if (cmd
== OLD_FSEVENTS_DEVICE_FILTER
) {
1601 old_fsevent_dev_filter_args
*udev_filt_args
= (old_fsevent_dev_filter_args
*)data
;
1603 devfilt_args
= &_devfilt_args
;
1604 memset(devfilt_args
, 0, sizeof(ext_fsevent_dev_filter_args
));
1606 devfilt_args
->num_devices
= udev_filt_args
->num_devices
;
1607 devfilt_args
->devices
= CAST_USER_ADDR_T(udev_filt_args
->devices
);
1611 fsevent_dev_filter_args32
*udev_filt_args
= (fsevent_dev_filter_args32
*)data
;
1613 fsevent_dev_filter_args
*udev_filt_args
= (fsevent_dev_filter_args
*)data
;
1616 devfilt_args
= &_devfilt_args
;
1617 memset(devfilt_args
, 0, sizeof(ext_fsevent_dev_filter_args
));
1619 devfilt_args
->num_devices
= udev_filt_args
->num_devices
;
1620 devfilt_args
->devices
= CAST_USER_ADDR_T(udev_filt_args
->devices
);
1623 OSAddAtomic(1, &fseh
->active
);
1624 if (fseh
->flags
& FSEH_CLOSING
) {
1625 OSAddAtomic(-1, &fseh
->active
);
1634 case FSEVENTS_WANT_COMPACT_EVENTS
: {
1635 fseh
->watcher
->flags
|= WATCHER_WANTS_COMPACT_EVENTS
;
1639 case FSEVENTS_WANT_EXTENDED_INFO
: {
1640 fseh
->watcher
->flags
|= WATCHER_WANTS_EXTENDED_INFO
;
1644 case FSEVENTS_GET_CURRENT_ID
: {
1645 *(uint64_t *)data
= fseh
->watcher
->max_event_id
;
1650 case OLD_FSEVENTS_DEVICE_FILTER
:
1651 case NEW_FSEVENTS_DEVICE_FILTER
: {
1652 int new_num_devices
;
1653 dev_t
*devices_not_to_watch
, *tmp
=NULL
;
1655 if (devfilt_args
->num_devices
> 256) {
1660 new_num_devices
= devfilt_args
->num_devices
;
1661 if (new_num_devices
== 0) {
1662 tmp
= fseh
->watcher
->devices_not_to_watch
;
1665 fseh
->watcher
->devices_not_to_watch
= NULL
;
1666 fseh
->watcher
->num_devices
= new_num_devices
;
1667 unlock_watch_table();
1675 MALLOC(devices_not_to_watch
, dev_t
*,
1676 new_num_devices
* sizeof(dev_t
),
1678 if (devices_not_to_watch
== NULL
) {
1683 ret
= copyin(devfilt_args
->devices
,
1684 (void *)devices_not_to_watch
,
1685 new_num_devices
* sizeof(dev_t
));
1687 FREE(devices_not_to_watch
, M_TEMP
);
1692 fseh
->watcher
->num_devices
= new_num_devices
;
1693 tmp
= fseh
->watcher
->devices_not_to_watch
;
1694 fseh
->watcher
->devices_not_to_watch
= devices_not_to_watch
;
1695 unlock_watch_table();
1709 OSAddAtomic(-1, &fseh
->active
);
1715 fseventsf_select(struct fileproc
*fp
, int which
, __unused
void *wql
, vfs_context_t ctx
)
1717 fsevent_handle
*fseh
= (struct fsevent_handle
*)fp
->f_fglob
->fg_data
;
1720 if ((which
!= FREAD
) || (fseh
->watcher
->flags
& WATCHER_CLOSING
)) {
1725 // if there's nothing in the queue, we're not ready
1726 if (fseh
->watcher
->rd
!= fseh
->watcher
->wr
) {
1731 selrecord(vfs_context_proc(ctx
), &fseh
->si
, wql
);
1740 fseventsf_stat(__unused
struct fileproc
*fp
, __unused
struct stat
*sb
, __unused vfs_context_t ctx
)
1747 fseventsf_close(struct fileglob
*fg
, __unused vfs_context_t ctx
)
1749 fsevent_handle
*fseh
= (struct fsevent_handle
*)fg
->fg_data
;
1750 fs_event_watcher
*watcher
;
1752 OSBitOrAtomic(FSEH_CLOSING
, &fseh
->flags
);
1753 while (OSAddAtomic(0, &fseh
->active
) > 0) {
1754 tsleep((caddr_t
)fseh
->watcher
, PRIBIO
, "fsevents-close", 1);
1757 watcher
= fseh
->watcher
;
1759 fseh
->watcher
= NULL
;
1761 remove_watcher(watcher
);
1768 filt_fsevent_detach(struct knote
*kn
)
1770 fsevent_handle
*fseh
= (struct fsevent_handle
*)kn
->kn_hook
;
1774 KNOTE_DETACH(&fseh
->knotes
, kn
);
1776 unlock_watch_table();
1780 * Determine whether this knote should be active
1782 * This is kind of subtle.
1783 * --First, notice if the vnode has been revoked: in so, override hint
1784 * --EVFILT_READ knotes are checked no matter what the hint is
1785 * --Other knotes activate based on hint.
1786 * --If hint is revoke, set special flags and activate
1789 filt_fsevent(struct knote
*kn
, long hint
)
1791 fsevent_handle
*fseh
= (struct fsevent_handle
*)kn
->kn_hook
;
1793 int32_t rd
, wr
, amt
;
1795 if (NOTE_REVOKE
== hint
) {
1796 kn
->kn_flags
|= (EV_EOF
| EV_ONESHOT
);
1800 rd
= fseh
->watcher
->rd
;
1801 wr
= fseh
->watcher
->wr
;
1805 amt
= fseh
->watcher
->eventq_size
- (rd
- wr
);
1808 switch(kn
->kn_filter
) {
1812 if (kn
->kn_data
!= 0) {
1817 /* Check events this note matches against the hint */
1818 if (kn
->kn_sfflags
& hint
) {
1819 kn
->kn_fflags
|= hint
; /* Set which event occurred */
1821 if (kn
->kn_fflags
!= 0) {
1835 struct filterops fsevent_filtops
= {
1838 .f_detach
= filt_fsevent_detach
,
1839 .f_event
= filt_fsevent
1843 fseventsf_kqfilter(__unused
struct fileproc
*fp
, __unused
struct knote
*kn
, __unused vfs_context_t ctx
)
1845 fsevent_handle
*fseh
= (struct fsevent_handle
*)fp
->f_fglob
->fg_data
;
1847 kn
->kn_hook
= (void*)fseh
;
1849 kn
->kn_fop
= &fsevent_filtops
;
1853 KNOTE_ATTACH(&fseh
->knotes
, kn
);
1855 unlock_watch_table();
1861 fseventsf_drain(struct fileproc
*fp
, __unused vfs_context_t ctx
)
1864 fsevent_handle
*fseh
= (struct fsevent_handle
*)fp
->f_fglob
->fg_data
;
1866 fseh
->watcher
->flags
|= WATCHER_CLOSING
;
1868 // if there are people still waiting, sleep for 10ms to
1869 // let them clean up and get out of there. however we
1870 // also don't want to get stuck forever so if they don't
1871 // exit after 5 seconds we're tearing things down anyway.
1872 while(fseh
->watcher
->blockers
&& counter
++ < 500) {
1873 // issue wakeup in case anyone is blocked waiting for an event
1874 // do this each time we wakeup in case the blocker missed
1875 // the wakeup due to the unprotected test of WATCHER_CLOSING
1876 // and decision to tsleep in fmod_watch... this bit of
1877 // latency is a decent tradeoff against not having to
1878 // take and drop a lock in fmod_watch
1880 fsevents_wakeup(fseh
->watcher
);
1881 unlock_watch_table();
1883 tsleep((caddr_t
)fseh
->watcher
, PRIBIO
, "watcher-close", 1);
1891 fseventsopen(__unused dev_t dev
, __unused
int flag
, __unused
int mode
, __unused
struct proc
*p
)
1901 fseventsclose(__unused dev_t dev
, __unused
int flag
, __unused
int mode
, __unused
struct proc
*p
)
1907 fseventsread(__unused dev_t dev
, __unused
struct uio
*uio
, __unused
int ioflag
)
1914 parse_buffer_and_add_events(const char *buffer
, int bufsize
, vfs_context_t ctx
, long *remainder
)
1916 const fse_info
*finfo
, *dest_finfo
;
1917 const char *path
, *ptr
, *dest_path
, *event_start
=buffer
;
1918 int path_len
, type
, dest_path_len
, err
= 0;
1922 while ((ptr
+sizeof(int)+sizeof(fse_info
)+1) < buffer
+bufsize
) {
1923 type
= *(const int *)ptr
;
1924 if (type
< 0 || type
>= FSE_MAX_EVENTS
) {
1931 finfo
= (const fse_info
*)ptr
;
1932 ptr
+= sizeof(fse_info
);
1935 while(ptr
< buffer
+bufsize
&& *ptr
!= '\0') {
1939 if (ptr
>= buffer
+bufsize
) {
1943 ptr
++; // advance over the trailing '\0'
1945 path_len
= ptr
- path
;
1947 if (type
!= FSE_RENAME
&& type
!= FSE_EXCHANGE
) {
1948 event_start
= ptr
; // record where the next event starts
1950 err
= add_fsevent(type
, ctx
, FSE_ARG_STRING
, path_len
, path
, FSE_ARG_FINFO
, finfo
, FSE_ARG_DONE
);
1958 // if we're here we have to slurp up the destination finfo
1959 // and path so that we can pass them to the add_fsevent()
1960 // call. basically it's a copy of the above code.
1962 dest_finfo
= (const fse_info
*)ptr
;
1963 ptr
+= sizeof(fse_info
);
1966 while(ptr
< buffer
+bufsize
&& *ptr
!= '\0') {
1970 if (ptr
>= buffer
+bufsize
) {
1974 ptr
++; // advance over the trailing '\0'
1975 event_start
= ptr
; // record where the next event starts
1977 dest_path_len
= ptr
- dest_path
;
1979 // If the destination inode number is non-zero, generate a rename
1980 // with both source and destination FSE_ARG_FINFO. Otherwise generate
1981 // a rename with only one FSE_ARG_FINFO. If you need to inject an
1982 // exchange with an inode of zero, just make that inode (and its path)
1983 // come in as the first one, not the second.
1985 if (dest_finfo
->ino
) {
1986 err
= add_fsevent(type
, ctx
,
1987 FSE_ARG_STRING
, path_len
, path
, FSE_ARG_FINFO
, finfo
,
1988 FSE_ARG_STRING
, dest_path_len
, dest_path
, FSE_ARG_FINFO
, dest_finfo
,
1991 err
= add_fsevent(type
, ctx
,
1992 FSE_ARG_STRING
, path_len
, path
, FSE_ARG_FINFO
, finfo
,
1993 FSE_ARG_STRING
, dest_path_len
, dest_path
,
2003 // if the last event wasn't complete, set the remainder
2004 // to be the last event start boundary.
2006 *remainder
= (long)((buffer
+bufsize
) - event_start
);
2013 // Note: this buffer size can not ever be less than
2014 // 2*MAXPATHLEN + 2*sizeof(fse_info) + sizeof(int)
2015 // because that is the max size for a single event.
2016 // I made it 4k to be a "nice" size. making it
2017 // smaller is not a good idea.
2019 #define WRITE_BUFFER_SIZE 4096
2020 char *write_buffer
=NULL
;
2023 fseventswrite(__unused dev_t dev
, struct uio
*uio
, __unused
int ioflag
)
2026 vfs_context_t ctx
= vfs_context_current();
2027 long offset
=0, remainder
;
2029 lck_mtx_lock(&event_writer_lock
);
2031 if (write_buffer
== NULL
) {
2032 if (kmem_alloc(kernel_map
, (vm_offset_t
*)&write_buffer
, WRITE_BUFFER_SIZE
)) {
2033 lck_mtx_unlock(&event_writer_lock
);
2039 // this loop copies in and processes the events written.
2040 // it takes care to copy in reasonable size chunks and
2041 // process them. if there is an event that spans a chunk
2042 // boundary we're careful to copy those bytes down to the
2043 // beginning of the buffer and read the next chunk in just
2046 while(uio_resid(uio
)) {
2047 if (uio_resid(uio
) > (WRITE_BUFFER_SIZE
-offset
)) {
2048 count
= WRITE_BUFFER_SIZE
- offset
;
2050 count
= uio_resid(uio
);
2053 error
= uiomove(write_buffer
+offset
, count
, uio
);
2058 // printf("fsevents: write: copied in %d bytes (offset: %ld)\n", count, offset);
2059 error
= parse_buffer_and_add_events(write_buffer
, offset
+count
, ctx
, &remainder
);
2065 // if there's any remainder, copy it down to the beginning
2066 // of the buffer so that it will get processed the next time
2067 // through the loop. note that the remainder always starts
2068 // at an event boundary.
2070 if (remainder
!= 0) {
2071 // printf("fsevents: write: an event spanned a %d byte boundary. remainder: %ld\n",
2072 // WRITE_BUFFER_SIZE, remainder);
2073 memmove(write_buffer
, (write_buffer
+count
+offset
) - remainder
, remainder
);
2080 lck_mtx_unlock(&event_writer_lock
);
2086 static struct fileops fsevents_fops
= {
2096 typedef struct ext_fsevent_clone_args
{
2097 user_addr_t event_list
;
2099 int32_t event_queue_depth
;
2101 } ext_fsevent_clone_args
;
2103 typedef struct old_fsevent_clone_args
{
2104 uint32_t event_list
;
2106 int32_t event_queue_depth
;
2108 } old_fsevent_clone_args
;
2110 #define OLD_FSEVENTS_CLONE _IOW('s', 1, old_fsevent_clone_args)
2113 fseventsioctl(__unused dev_t dev
, u_long cmd
, caddr_t data
, __unused
int flag
, struct proc
*p
)
2117 fsevent_handle
*fseh
= NULL
;
2118 ext_fsevent_clone_args
*fse_clone_args
, _fse_clone
;
2120 int is64bit
= proc_is64bit(p
);
2123 case OLD_FSEVENTS_CLONE
: {
2124 old_fsevent_clone_args
*old_args
= (old_fsevent_clone_args
*)data
;
2126 fse_clone_args
= &_fse_clone
;
2127 memset(fse_clone_args
, 0, sizeof(ext_fsevent_clone_args
));
2129 fse_clone_args
->event_list
= CAST_USER_ADDR_T(old_args
->event_list
);
2130 fse_clone_args
->num_events
= old_args
->num_events
;
2131 fse_clone_args
->event_queue_depth
= old_args
->event_queue_depth
;
2132 fse_clone_args
->fd
= CAST_USER_ADDR_T(old_args
->fd
);
2136 case FSEVENTS_CLONE
:
2138 fse_clone_args
= (ext_fsevent_clone_args
*)data
;
2140 fsevent_clone_args
*ufse_clone
= (fsevent_clone_args
*)data
;
2142 fse_clone_args
= &_fse_clone
;
2143 memset(fse_clone_args
, 0, sizeof(ext_fsevent_clone_args
));
2145 fse_clone_args
->event_list
= CAST_USER_ADDR_T(ufse_clone
->event_list
);
2146 fse_clone_args
->num_events
= ufse_clone
->num_events
;
2147 fse_clone_args
->event_queue_depth
= ufse_clone
->event_queue_depth
;
2148 fse_clone_args
->fd
= CAST_USER_ADDR_T(ufse_clone
->fd
);
2152 if (fse_clone_args
->num_events
< 0 || fse_clone_args
->num_events
> 4096) {
2156 MALLOC(fseh
, fsevent_handle
*, sizeof(fsevent_handle
),
2161 memset(fseh
, 0, sizeof(fsevent_handle
));
2163 klist_init(&fseh
->knotes
);
2165 MALLOC(event_list
, int8_t *,
2166 fse_clone_args
->num_events
* sizeof(int8_t),
2168 if (event_list
== NULL
) {
2173 error
= copyin(fse_clone_args
->event_list
,
2175 fse_clone_args
->num_events
* sizeof(int8_t));
2177 FREE(event_list
, M_TEMP
);
2182 error
= add_watcher(event_list
,
2183 fse_clone_args
->num_events
,
2184 fse_clone_args
->event_queue_depth
,
2188 FREE(event_list
, M_TEMP
);
2193 fseh
->watcher
->fseh
= fseh
;
2195 error
= falloc(p
, &f
, &fd
, vfs_context_current());
2197 FREE(event_list
, M_TEMP
);
2202 f
->f_fglob
->fg_flag
= FREAD
| FWRITE
;
2203 f
->f_fglob
->fg_type
= DTYPE_FSEVENTS
;
2204 f
->f_fglob
->fg_ops
= &fsevents_fops
;
2205 f
->f_fglob
->fg_data
= (caddr_t
) fseh
;
2207 error
= copyout((void *)&fd
, fse_clone_args
->fd
, sizeof(int32_t));
2212 procfdtbl_releasefd(p
, fd
, NULL
);
2213 fp_drop(p
, fd
, f
, 1);
2227 fsevents_wakeup(fs_event_watcher
*watcher
)
2229 selwakeup(&watcher
->fseh
->si
);
2230 KNOTE(&watcher
->fseh
->knotes
, NOTE_WRITE
|NOTE_NONE
);
2231 wakeup((caddr_t
)watcher
);
2236 * A struct describing which functions will get invoked for certain
2239 static struct cdevsw fsevents_cdevsw
=
2241 fseventsopen
, /* open */
2242 fseventsclose
, /* close */
2243 fseventsread
, /* read */
2244 fseventswrite
, /* write */
2245 fseventsioctl
, /* ioctl */
2246 (stop_fcn_t
*)&nulldev
, /* stop */
2247 (reset_fcn_t
*)&nulldev
, /* reset */
2249 eno_select
, /* select */
2250 eno_mmap
, /* mmap */
2251 eno_strat
, /* strategy */
2252 eno_getc
, /* getc */
2253 eno_putc
, /* putc */
2259 * Called to initialize our device,
2260 * and to register ourselves with devfs
2268 if (fsevents_installed
) {
2272 fsevents_installed
= 1;
2274 ret
= cdevsw_add(-1, &fsevents_cdevsw
);
2276 fsevents_installed
= 0;
2280 devfs_make_node(makedev (ret
, 0), DEVFS_CHAR
,
2281 UID_ROOT
, GID_WHEEL
, 0644, "fsevents", 0);
2283 fsevents_internal_init();
2292 MALLOC_ZONE(path
, char *, MAXPATHLEN
, M_NAMEI
, M_WAITOK
);
2297 release_pathbuff(char *path
)
2303 FREE_ZONE(path
, MAXPATHLEN
, M_NAMEI
);
2307 get_fse_info(struct vnode
*vp
, fse_info
*fse
, __unused vfs_context_t ctx
)
2309 struct vnode_attr va
;
2312 VATTR_WANTED(&va
, va_fsid
);
2313 VATTR_WANTED(&va
, va_fileid
);
2314 VATTR_WANTED(&va
, va_mode
);
2315 VATTR_WANTED(&va
, va_uid
);
2316 VATTR_WANTED(&va
, va_gid
);
2317 if (vp
->v_flag
& VISHARDLINK
) {
2318 if (vp
->v_type
== VDIR
) {
2319 VATTR_WANTED(&va
, va_dirlinkcount
);
2321 VATTR_WANTED(&va
, va_nlink
);
2325 if (vnode_getattr(vp
, &va
, vfs_context_kernel()) != 0) {
2326 memset(fse
, 0, sizeof(fse_info
));
2330 return vnode_get_fse_info_from_vap(vp
, fse
, &va
);
2334 vnode_get_fse_info_from_vap(vnode_t vp
, fse_info
*fse
, struct vnode_attr
*vap
)
2336 fse
->ino
= (ino64_t
)vap
->va_fileid
;
2337 fse
->dev
= (dev_t
)vap
->va_fsid
;
2338 fse
->mode
= (int32_t)vnode_vttoif(vnode_vtype(vp
)) | vap
->va_mode
;
2339 fse
->uid
= (uid_t
)vap
->va_uid
;
2340 fse
->gid
= (gid_t
)vap
->va_gid
;
2341 if (vp
->v_flag
& VISHARDLINK
) {
2342 fse
->mode
|= FSE_MODE_HLINK
;
2343 if (vp
->v_type
== VDIR
) {
2344 fse
->nlink
= (uint64_t)vap
->va_dirlinkcount
;
2346 fse
->nlink
= (uint64_t)vap
->va_nlink
;
2354 create_fsevent_from_kevent(vnode_t vp
, uint32_t kevents
, struct vnode_attr
*vap
)
2356 int fsevent_type
=FSE_CONTENT_MODIFIED
, len
; // the default is the most pessimistic
2357 char pathbuf
[MAXPATHLEN
];
2361 if (kevents
& VNODE_EVENT_DELETE
) {
2362 fsevent_type
= FSE_DELETE
;
2363 } else if (kevents
& (VNODE_EVENT_EXTEND
|VNODE_EVENT_WRITE
)) {
2364 fsevent_type
= FSE_CONTENT_MODIFIED
;
2365 } else if (kevents
& VNODE_EVENT_LINK
) {
2366 fsevent_type
= FSE_CREATE_FILE
;
2367 } else if (kevents
& VNODE_EVENT_RENAME
) {
2368 fsevent_type
= FSE_CREATE_FILE
; // XXXdbg - should use FSE_RENAME but we don't have the destination info;
2369 } else if (kevents
& (VNODE_EVENT_FILE_CREATED
|VNODE_EVENT_FILE_REMOVED
|VNODE_EVENT_DIR_CREATED
|VNODE_EVENT_DIR_REMOVED
)) {
2370 fsevent_type
= FSE_STAT_CHANGED
; // XXXdbg - because vp is a dir and the thing created/removed lived inside it
2371 } else { // a catch all for VNODE_EVENT_PERMS, VNODE_EVENT_ATTRIB and anything else
2372 fsevent_type
= FSE_STAT_CHANGED
;
2375 // printf("convert_kevent: kevents 0x%x fsevent type 0x%x (for %s)\n", kevents, fsevent_type, vp->v_name ? vp->v_name : "(no-name)");
2377 fse
.dev
= vap
->va_fsid
;
2378 fse
.ino
= vap
->va_fileid
;
2379 fse
.mode
= vnode_vttoif(vnode_vtype(vp
)) | (uint32_t)vap
->va_mode
;
2380 if (vp
->v_flag
& VISHARDLINK
) {
2381 fse
.mode
|= FSE_MODE_HLINK
;
2382 if (vp
->v_type
== VDIR
) {
2383 fse
.nlink
= vap
->va_dirlinkcount
;
2385 fse
.nlink
= vap
->va_nlink
;
2389 if (vp
->v_type
== VDIR
) {
2390 fse
.mode
|= FSE_REMOTE_DIR_EVENT
;
2394 fse
.uid
= vap
->va_uid
;
2395 fse
.gid
= vap
->va_gid
;
2397 len
= sizeof(pathbuf
);
2398 if (vn_getpath(vp
, pathbuf
, &len
) == 0) {
2399 add_fsevent(fsevent_type
, vfs_context_current(), FSE_ARG_STRING
, len
, pathbuf
, FSE_ARG_FINFO
, &fse
, FSE_ARG_DONE
);
2404 #else /* CONFIG_FSE */
2406 * The get_pathbuff and release_pathbuff routines are used in places not
2407 * related to fsevents, and it's a handy abstraction, so define trivial
2408 * versions that don't cache a pool of buffers. This way, we don't have
2409 * to conditionalize the callers, and they still get the advantage of the
2410 * pool of buffers if CONFIG_FSE is turned on.
2416 MALLOC_ZONE(path
, char *, MAXPATHLEN
, M_NAMEI
, M_WAITOK
);
2421 release_pathbuff(char *path
)
2423 FREE_ZONE(path
, MAXPATHLEN
, M_NAMEI
);
2425 #endif /* CONFIG_FSE */