]> git.saurik.com Git - apple/xnu.git/blob - bsd/vfs/vfs_fsevents.c
887ee2888c5668a41fd5f55ecb4dc62dc22031f9
[apple/xnu.git] / bsd / vfs / vfs_fsevents.c
1 /*
2 * Copyright (c) 2004-2008 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
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.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
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.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28 #include <stdarg.h>
29 #include <sys/param.h>
30 #include <sys/systm.h>
31 #include <sys/event.h> // for kqueue related stuff
32 #include <sys/fsevents.h>
33
34 #if CONFIG_FSE
35 #include <sys/namei.h>
36 #include <sys/filedesc.h>
37 #include <sys/kernel.h>
38 #include <sys/file_internal.h>
39 #include <sys/stat.h>
40 #include <sys/vnode_internal.h>
41 #include <sys/mount_internal.h>
42 #include <sys/proc_internal.h>
43 #include <sys/kauth.h>
44 #include <sys/uio.h>
45 #include <sys/malloc.h>
46 #include <sys/dirent.h>
47 #include <sys/attr.h>
48 #include <sys/sysctl.h>
49 #include <sys/ubc.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>
60
61 #include <security/audit/audit.h>
62 #include <bsm/audit_kevents.h>
63
64 #include <pexpert/pexpert.h>
65
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
73
74 uint64_t abstime; // when this event happened (mach_absolute_time())
75 ino64_t ino;
76 dev_t dev;
77 int32_t mode;
78 uid_t uid;
79 gid_t gid;
80
81 const char *str;
82
83 struct kfs_event *dest; // if this is a two-file op
84 } kfs_event;
85
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
91
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;
95
96
97 struct fsevent_handle;
98
99 typedef struct fs_event_watcher {
100 int8_t *event_list; // the events we're interested in
101 int32_t num_events;
102 dev_t *devices_not_to_watch; // report events from devices not in this list
103 uint32_t num_devices;
104 int32_t flags;
105 kfs_event **event_queue;
106 int32_t eventq_size; // number of event pointers in queue
107 int32_t num_readers;
108 int32_t rd; // read index into the event_queue
109 int32_t wr; // write index into the event_queue
110 int32_t blockers;
111 int32_t my_id;
112 uint32_t num_dropped;
113 uint64_t max_event_id;
114 struct fsevent_handle *fseh;
115 pid_t pid;
116 char proc_name[(2 * MAXCOMLEN) + 1];
117 } fs_event_watcher;
118
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
125
126 #define MAX_WATCHERS 8
127 static fs_event_watcher *watcher_table[MAX_WATCHERS];
128
129 #define DEFAULT_MAX_KFS_EVENTS 4096
130 static int max_kfs_events = DEFAULT_MAX_KFS_EVENTS;
131
132 // we allocate kfs_event structures out of this zone
133 static zone_t event_zone;
134 static int fs_event_init = 0;
135
136 //
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
140 //
141 static int16_t fs_event_type_watchers[FSE_MAX_EVENTS];
142
143 static int watcher_add_event(fs_event_watcher *watcher, kfs_event *kfse);
144 static void fsevents_wakeup(fs_event_watcher *watcher);
145
146 //
147 // Locks
148 //
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;
152
153 static lck_grp_t * fsevent_rw_group;
154
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;
159
160
161 /* Explicitly declare qsort so compiler doesn't complain */
162 __private_extern__ void qsort(
163 void * array,
164 size_t nmembers,
165 size_t member_size,
166 int (*)(const void *, const void *));
167
168
169
170 /* From kdp_udp.c + user mode Libc - this ought to be in a library */
171 static char *
172 strnstr(char *s, const char *find, size_t slen)
173 {
174 char c, sc;
175 size_t len;
176
177 if ((c = *find++) != '\0') {
178 len = strlen(find);
179 do {
180 do {
181 if ((sc = *s++) == '\0' || slen-- < 1)
182 return (NULL);
183 } while (sc != c);
184 if (len > slen)
185 return (NULL);
186 } while (strncmp(s, find, len) != 0);
187 s--;
188 }
189 return (s);
190 }
191
192 static int
193 is_ignored_directory(const char *path) {
194
195 if (!path) {
196 return 0;
197 }
198
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/")) {
203 return 1;
204 }
205 #undef IS_TLD
206
207 return 0;
208 }
209
210 static void
211 fsevents_internal_init(void)
212 {
213 int i;
214
215 if (fs_event_init++ != 0) {
216 return;
217 }
218
219 for(i=0; i < FSE_MAX_EVENTS; i++) {
220 fs_event_type_watchers[i] = 0;
221 }
222
223 memset(watcher_table, 0, sizeof(watcher_table));
224
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);
229
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);
233
234 lck_rw_init(&event_handling_lock, fsevent_rw_group, fsevent_lock_attr);
235
236 PE_get_default("kern.maxkfsevents", &max_kfs_events, sizeof(max_kfs_events));
237
238 event_zone = zinit(sizeof(kfs_event),
239 max_kfs_events * sizeof(kfs_event),
240 max_kfs_events * sizeof(kfs_event),
241 "fs-event-buf");
242 if (event_zone == NULL) {
243 printf("fsevents: failed to initialize the event zone.\n");
244 }
245
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);
251
252 if (zfill(event_zone, max_kfs_events) < max_kfs_events) {
253 printf("fsevents: failed to pre-fill the event zone.\n");
254 }
255
256 }
257
258 static void
259 lock_watch_table(void)
260 {
261 lck_mtx_lock(&watch_table_lock);
262 }
263
264 static void
265 unlock_watch_table(void)
266 {
267 lck_mtx_unlock(&watch_table_lock);
268 }
269
270 static void
271 lock_fs_event_list(void)
272 {
273 lck_mtx_lock(&event_buf_lock);
274 }
275
276 static void
277 unlock_fs_event_list(void)
278 {
279 lck_mtx_unlock(&event_buf_lock);
280 }
281
282 // forward prototype
283 static void release_event_ref(kfs_event *kfse);
284
285 static int
286 watcher_cares_about_dev(fs_event_watcher *watcher, dev_t dev)
287 {
288 unsigned int i;
289
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) {
293 return 1;
294 }
295
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.
300 return 0;
301 }
302 }
303
304 // if we're here it's not in the devices_not_to_watch[]
305 // list so that means we do care about it
306 return 1;
307 }
308
309
310 int
311 need_fsevent(int type, vnode_t vp)
312 {
313 if (type >= 0 && type < FSE_MAX_EVENTS && fs_event_type_watchers[type] == 0)
314 return (0);
315
316 // events in /dev aren't really interesting...
317 if (vp->v_tag == VT_DEVFS) {
318 return (0);
319 }
320
321 return 1;
322 }
323
324
325 #define is_throw_away(x) ((x) == FSE_STAT_CHANGED || (x) == FSE_CONTENT_MODIFIED)
326
327
328 // Ways that an event can be reused:
329 //
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.
335 //
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.
340 //
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
345 // appropriate).
346 //
347 #define KFSE_COMBINED 0x0001
348 #define KFSE_COLLAPSED 0x0002
349 #define KFSE_RECYCLED 0x0004
350
351 int num_dropped = 0;
352 int num_parent_switch = 0;
353 int num_recycled_rename = 0;
354
355 static struct timeval last_print;
356
357 //
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
364 // get coalesced.
365 //
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 };
375
376
377 int
378 add_fsevent(int type, vfs_context_t ctx, ...)
379 {
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;
384 va_list ap;
385 int error = 0, did_alloc=0;
386 dev_t dev = 0;
387 uint64_t now, elapsed;
388 char *pathbuff=NULL;
389 int pathbuff_len;
390
391
392
393 va_start(ap, ctx);
394
395 // ignore bogus event types..
396 if (type < 0 || type >= FSE_MAX_EVENTS) {
397 return EINVAL;
398 }
399
400 // if no one cares about this type of event, bail out
401 if (fs_event_type_watchers[type] == 0) {
402 va_end(ap);
403
404 return 0;
405 }
406
407 now = mach_absolute_time();
408
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();
413
414 //
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)
418 //
419 if (type != FSE_CREATE_FILE && type != FSE_DELETE && type != FSE_RENAME && type != FSE_EXCHANGE && type != FSE_CHOWN) {
420 void *ptr=NULL;
421 int vid=0, was_str=0, nlen=0;
422
423 for(arg_type=va_arg(ap, int32_t); arg_type != FSE_ARG_DONE; arg_type=va_arg(ap, int32_t)) {
424 switch(arg_type) {
425 case FSE_ARG_VNODE: {
426 ptr = va_arg(ap, void *);
427 vid = vnode_vid((struct vnode *)ptr);
428 last_str[0] = '\0';
429 break;
430 }
431 case FSE_ARG_STRING: {
432 nlen = va_arg(ap, int32_t);
433 ptr = va_arg(ap, void *);
434 was_str = 1;
435 break;
436 }
437 }
438 if (ptr != NULL) {
439 break;
440 }
441 }
442
443 if ( sTimebaseInfo.denom == 0 ) {
444 (void) clock_timebase_info(&sTimebaseInfo);
445 }
446
447 elapsed = (now - last_coalesced_time);
448 if (sTimebaseInfo.denom != sTimebaseInfo.numer) {
449 if (sTimebaseInfo.denom == 1) {
450 elapsed *= sTimebaseInfo.numer;
451 } else {
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;
456 }
457 }
458
459 if (type == last_event_type
460 && (elapsed < 1000000000)
461 &&
462 ((vid && vid == last_vid && last_ptr == ptr)
463 ||
464 (last_str[0] && last_nlen == nlen && ptr && strcmp(last_str, ptr) == 0))
465 ) {
466
467 last_coalesced++;
468 unlock_fs_event_list();
469 va_end(ap);
470
471 return 0;
472 } else {
473 last_ptr = ptr;
474 if (was_str) {
475 strlcpy(last_str, ptr, sizeof(last_str));
476 }
477 last_nlen = nlen;
478 last_vid = vid;
479 last_event_type = type;
480 last_coalesced_time = now;
481 }
482 }
483 va_start(ap, ctx);
484
485
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) {
490 did_alloc = 1;
491 zfree(event_zone, kfse);
492 kfse = NULL;
493 }
494 }
495
496
497 if (kfse == NULL) { // yikes! no free events
498 unlock_fs_event_list();
499 lock_watch_table();
500
501 for(i=0; i < MAX_WATCHERS; i++) {
502 watcher = watcher_table[i];
503 if (watcher == NULL) {
504 continue;
505 }
506
507 watcher->flags |= WATCHER_DROPPED_EVENTS;
508 fsevents_wakeup(watcher);
509 }
510 unlock_watch_table();
511
512 {
513 struct timeval current_tv;
514
515 num_dropped++;
516
517 // only print a message at most once every 5 seconds
518 microuptime(&current_tv);
519 if ((current_tv.tv_sec - last_print.tv_sec) > 10) {
520 int ii;
521 void *junkptr=zalloc_noblock(event_zone), *listhead=kfse_list_head.lh_first;
522
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) {
529 continue;
530 }
531
532 printf("add_fsevent: watcher %s %p: rd %4d wr %4d q_size %4d flags 0x%x\n",
533 watcher_table[ii]->proc_name,
534 watcher_table[ii],
535 watcher_table[ii]->rd, watcher_table[ii]->wr,
536 watcher_table[ii]->eventq_size, watcher_table[ii]->flags);
537 }
538
539 last_print = current_tv;
540 if (junkptr) {
541 zfree(event_zone, junkptr);
542 }
543 }
544 }
545
546 if (pathbuff) {
547 release_pathbuff(pathbuff);
548 pathbuff = NULL;
549 }
550 return ENOSPC;
551 }
552
553 memset(kfse, 0, sizeof(kfs_event));
554 kfse->refcount = 1;
555 OSBitOrAtomic16(KFSE_BEING_CREATED, &kfse->flags);
556
557 last_event_ptr = kfse;
558 kfse->type = type;
559 kfse->abstime = now;
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;
568
569 kfse->dest = kfse_dest;
570 }
571
572 num_events_outstanding++;
573 if (kfse->type == FSE_RENAME) {
574 num_pending_rename++;
575 }
576 LIST_INSERT_HEAD(&kfse_list_head, kfse, kevent_list);
577
578 if (kfse->refcount < 1) {
579 panic("add_fsevent: line %d: kfse recount %d but should be at least 1\n", __LINE__, kfse->refcount);
580 }
581
582 unlock_fs_event_list(); // at this point it's safe to unlock
583
584 //
585 // now process the arguments passed in and copy them into
586 // the kfse
587 //
588
589 cur = kfse;
590 for(arg_type=va_arg(ap, int32_t); arg_type != FSE_ARG_DONE; arg_type=va_arg(ap, int32_t))
591
592 switch(arg_type) {
593 case FSE_ARG_VNODE: {
594 // this expands out into multiple arguments to the client
595 struct vnode *vp;
596 struct vnode_attr va;
597
598 if (kfse->str != NULL) {
599 cur = kfse_dest;
600 }
601
602 vp = va_arg(ap, struct vnode *);
603 if (vp == NULL) {
604 panic("add_fsevent: you can't pass me a NULL vnode ptr (type %d)!\n",
605 cur->type);
606 }
607
608 VATTR_INIT(&va);
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);
616 cur->str = NULL;
617 error = EINVAL;
618 goto clean_up;
619 }
620
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;
626
627 // if we haven't gotten the path yet, get it.
628 if (pathbuff == NULL) {
629 pathbuff = get_pathbuff();
630 pathbuff_len = MAXPATHLEN;
631
632 pathbuff[0] = '\0';
633 if ((ret = vn_getpath(vp, pathbuff, &pathbuff_len)) != 0 || pathbuff[0] == '\0') {
634
635 cur->flags |= KFSE_CONTAINS_DROPPED_EVENTS;
636
637 do {
638 if (vp->v_parent != NULL) {
639 vp = vp->v_parent;
640 } else if (vp->v_mount) {
641 strlcpy(pathbuff, vp->v_mount->mnt_vfsstat.f_mntonname, MAXPATHLEN);
642 break;
643 } else {
644 vp = NULL;
645 }
646
647 if (vp == NULL) {
648 break;
649 }
650
651 pathbuff_len = MAXPATHLEN;
652 ret = vn_getpath(vp, pathbuff, &pathbuff_len);
653 } while (ret == ENOSPC);
654
655 if (ret != 0 || vp == NULL) {
656 error = ENOENT;
657 goto clean_up;
658 }
659 }
660 }
661
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);
667 }
668
669 release_pathbuff(pathbuff);
670 pathbuff = NULL;
671
672 break;
673 }
674
675 case FSE_ARG_FINFO: {
676 fse_info *fse;
677
678 fse = va_arg(ap, fse_info *);
679
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;
688 }
689 if (cur->mode & FSE_TRUNCATED_PATH) {
690 cur->flags |= KFSE_CONTAINS_DROPPED_EVENTS;
691 cur->mode &= ~FSE_TRUNCATED_PATH;
692 }
693 break;
694 }
695
696 case FSE_ARG_STRING:
697 if (kfse->str != NULL) {
698 cur = kfse_dest;
699 }
700
701 cur->len = (int16_t)(va_arg(ap, int32_t) & 0x7fff);
702 if (cur->len >= 1) {
703 cur->str = vfs_addname(va_arg(ap, char *), cur->len, 0, 0);
704 } else {
705 printf("add_fsevent: funny looking string length: %d\n", (int)cur->len);
706 cur->len = 2;
707 cur->str = vfs_addname("/", cur->len, 0, 0);
708 }
709 if (cur->str[0] == 0) {
710 printf("add_fsevent: bogus looking string (len %d)\n", cur->len);
711 }
712 break;
713
714 default:
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);
718 }
719
720 va_end(ap);
721
722 OSBitAndAtomic16(~KFSE_BEING_CREATED, &kfse->flags);
723 if (kfse_dest) {
724 OSBitAndAtomic16(~KFSE_BEING_CREATED, &kfse_dest->flags);
725 }
726
727 //
728 // now we have to go and let everyone know that
729 // is interested in this type of event
730 //
731 lock_watch_table();
732
733 for(i=0; i < MAX_WATCHERS; i++) {
734 watcher = watcher_table[i];
735 if (watcher == NULL) {
736 continue;
737 }
738
739 if ( watcher->event_list[type] == FSE_REPORT
740 && watcher_cares_about_dev(watcher, dev)) {
741
742 if (watcher_add_event(watcher, kfse) != 0) {
743 watcher->num_dropped++;
744 continue;
745 }
746 }
747
748 // if (kfse->refcount < 1) {
749 // panic("add_fsevent: line %d: kfse recount %d but should be at least 1\n", __LINE__, kfse->refcount);
750 // }
751 }
752
753 unlock_watch_table();
754
755 clean_up:
756
757 if (pathbuff) {
758 release_pathbuff(pathbuff);
759 pathbuff = NULL;
760 }
761
762 release_event_ref(kfse);
763
764 return error;
765 }
766
767
768 static void
769 release_event_ref(kfs_event *kfse)
770 {
771 int old_refcount;
772 kfs_event copy, dest_copy;
773
774
775 old_refcount = OSAddAtomic(-1, &kfse->refcount);
776 if (old_refcount > 1) {
777 return;
778 }
779
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;
785 }
786
787 if (kfse->refcount < 0) {
788 panic("release_event_ref: bogus kfse refcount %d\n", kfse->refcount);
789 }
790
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).
803 //
804 unlock_fs_event_list();
805 return;
806 }
807
808 //
809 // make a copy of this so we can free things without
810 // holding the fs_event_buf lock
811 //
812 copy = *kfse;
813 if (kfse->dest && OSAddAtomic(-1, &kfse->dest->refcount) == 1) {
814 dest_copy = *kfse->dest;
815 } else {
816 dest_copy.str = NULL;
817 dest_copy.len = 0;
818 dest_copy.type = FSE_INVALID;
819 }
820
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();
824
825 kfse->str = (char *)0xdeadbeef; // XXXdbg - catch any cheaters...
826
827 if (dest_copy.type != FSE_INVALID) {
828 kfse->dest->str = (char *)0xbadc0de; // XXXdbg - catch any cheaters...
829 kfse->dest->type = FSE_INVALID;
830
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));
835 }
836
837 zfree(event_zone, kfse->dest);
838 }
839
840 // mark this fsevent as invalid
841 {
842 int otype;
843
844 otype = kfse->type;
845 kfse->type = FSE_INVALID;
846
847 if (kfse->kevent_list.le_prev != NULL) {
848 num_events_outstanding--;
849 if (otype == FSE_RENAME) {
850 num_pending_rename--;
851 }
852 LIST_REMOVE(kfse, kevent_list);
853 memset(&kfse->kevent_list, 0, sizeof(kfse->kevent_list));
854 }
855 }
856
857 zfree(event_zone, kfse);
858
859 unlock_fs_event_list();
860
861 // if we have a pointer in the union
862 if (copy.str) {
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);
868 }
869 }
870
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);
875 } else {
876 vfs_removename(dest_copy.str);
877 }
878 }
879 }
880
881 static int
882 add_watcher(int8_t *event_list, int32_t num_events, int32_t eventq_size, fs_event_watcher **watcher_out, void *fseh)
883 {
884 int i;
885 fs_event_watcher *watcher;
886
887 if (eventq_size <= 0 || eventq_size > 100*max_kfs_events) {
888 eventq_size = max_kfs_events;
889 }
890
891 // Note: the event_queue follows the fs_event_watcher struct
892 // in memory so we only have to do one allocation
893 MALLOC(watcher,
894 fs_event_watcher *,
895 sizeof(fs_event_watcher) + eventq_size * sizeof(kfs_event *),
896 M_TEMP, M_WAITOK);
897 if (watcher == NULL) {
898 return ENOMEM;
899 }
900
901 watcher->event_list = event_list;
902 watcher->num_events = num_events;
903 watcher->devices_not_to_watch = NULL;
904 watcher->num_devices = 0;
905 watcher->flags = 0;
906 watcher->event_queue = (kfs_event **)&watcher[1];
907 watcher->eventq_size = eventq_size;
908 watcher->rd = 0;
909 watcher->wr = 0;
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));
916
917 watcher->num_dropped = 0; // XXXdbg - debugging
918
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;
923 } else {
924 printf("fsevents: watcher %s (pid: %d) - Using /dev/fsevents directly is unsupported. Migrate to FSEventsFramework\n",
925 watcher->proc_name, watcher->pid);
926 }
927
928 lock_watch_table();
929
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]++;
935 }
936 }
937
938 for(i=0; i < MAX_WATCHERS; i++) {
939 if (watcher_table[i] == NULL) {
940 watcher->my_id = i;
941 watcher_table[i] = watcher;
942 break;
943 }
944 }
945
946 if (i > MAX_WATCHERS) {
947 printf("fsevents: too many watchers!\n");
948 unlock_watch_table();
949 return ENOSPC;
950 }
951
952 unlock_watch_table();
953
954 *watcher_out = watcher;
955
956 return 0;
957 }
958
959
960
961 static void
962 remove_watcher(fs_event_watcher *target)
963 {
964 int i, j, counter=0;
965 fs_event_watcher *watcher;
966 kfs_event *kfse;
967
968 lock_watch_table();
969
970 for(j=0; j < MAX_WATCHERS; j++) {
971 watcher = watcher_table[j];
972 if (watcher != target) {
973 continue;
974 }
975
976 watcher_table[j] = NULL;
977
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]--;
981 }
982 }
983
984 if (watcher->flags & WATCHER_CLOSING) {
985 unlock_watch_table();
986 return;
987 }
988
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);
992
993 unlock_watch_table();
994
995 while (watcher->num_readers > 1 && counter++ < 5000) {
996 lock_watch_table();
997 fsevents_wakeup(watcher); // in case they're asleep
998 unlock_watch_table();
999
1000 tsleep(watcher, PRIBIO, "fsevents-close", 1);
1001 }
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);
1005 }
1006
1007 // drain the event_queue
1008
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;
1014 OSSynchronizeIO();
1015 if (kfse != NULL && kfse->type != FSE_INVALID && kfse->refcount >= 1) {
1016 release_event_ref(kfse);
1017 }
1018 }
1019 lck_rw_unlock_exclusive(&event_handling_lock);
1020
1021 if (watcher->event_list) {
1022 FREE(watcher->event_list, M_TEMP);
1023 watcher->event_list = NULL;
1024 }
1025 if (watcher->devices_not_to_watch) {
1026 FREE(watcher->devices_not_to_watch, M_TEMP);
1027 watcher->devices_not_to_watch = NULL;
1028 }
1029 FREE(watcher, M_TEMP);
1030
1031 return;
1032 }
1033
1034 unlock_watch_table();
1035 }
1036
1037
1038 #define EVENT_DELAY_IN_MS 10
1039 static thread_call_t event_delivery_timer = NULL;
1040 static int timer_set = 0;
1041
1042
1043 static void
1044 delayed_event_delivery(__unused void *param0, __unused void *param1)
1045 {
1046 int i;
1047
1048 lock_watch_table();
1049
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]);
1053 }
1054 }
1055
1056 timer_set = 0;
1057
1058 unlock_watch_table();
1059 }
1060
1061
1062 //
1063 // The watch table must be locked before calling this function.
1064 //
1065 static void
1066 schedule_event_wakeup(void)
1067 {
1068 uint64_t deadline;
1069
1070 if (event_delivery_timer == NULL) {
1071 event_delivery_timer = thread_call_allocate((thread_call_func_t)delayed_event_delivery, NULL);
1072 }
1073
1074 clock_interval_to_deadline(EVENT_DELAY_IN_MS, 1000 * 1000, &deadline);
1075
1076 thread_call_enter_delayed(event_delivery_timer, deadline);
1077 timer_set = 1;
1078 }
1079
1080
1081
1082 #define MAX_NUM_PENDING 16
1083
1084 //
1085 // NOTE: the watch table must be locked before calling
1086 // this routine.
1087 //
1088 static int
1089 watcher_add_event(fs_event_watcher *watcher, kfs_event *kfse)
1090 {
1091 if (kfse->abstime > watcher->max_event_id) {
1092 watcher->max_event_id = kfse->abstime;
1093 }
1094
1095 if (((watcher->wr + 1) % watcher->eventq_size) == watcher->rd) {
1096 watcher->flags |= WATCHER_DROPPED_EVENTS;
1097 fsevents_wakeup(watcher);
1098 return ENOSPC;
1099 }
1100
1101 OSAddAtomic(1, &kfse->refcount);
1102 watcher->event_queue[watcher->wr] = kfse;
1103 OSSynchronizeIO();
1104 watcher->wr = (watcher->wr + 1) % watcher->eventq_size;
1105
1106 //
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.
1111 //
1112 int32_t num_pending = 0;
1113 if (watcher->rd < watcher->wr) {
1114 num_pending = watcher->wr - watcher->rd;
1115 }
1116
1117 if (watcher->rd > watcher->wr) {
1118 num_pending = watcher->wr + watcher->eventq_size - watcher->rd;
1119 }
1120
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;
1128 OSSynchronizeIO();
1129 if (kfse != NULL && kfse->type != FSE_INVALID && kfse->refcount >= 1) {
1130 release_event_ref(kfse);
1131 }
1132 }
1133 watcher->flags |= WATCHER_DROPPED_EVENTS;
1134 lck_rw_unlock_exclusive(&event_handling_lock);
1135
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);
1139
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();
1145 }
1146
1147 return 0;
1148 }
1149
1150 static int
1151 fill_buff(uint16_t type, int32_t size, const void *data,
1152 char *buff, int32_t *_buff_idx, int32_t buff_sz,
1153 struct uio *uio)
1154 {
1155 int32_t amt, error = 0, buff_idx = *_buff_idx;
1156 uint16_t tmp;
1157
1158 //
1159 // the +1 on the size is to guarantee that the main data
1160 // copy loop will always copy at least 1 byte
1161 //
1162 if ((buff_sz - buff_idx) <= (int)(2*sizeof(uint16_t) + 1)) {
1163 if (buff_idx > uio_resid(uio)) {
1164 error = ENOSPC;
1165 goto get_out;
1166 }
1167
1168 error = uiomove(buff, buff_idx, uio);
1169 if (error) {
1170 goto get_out;
1171 }
1172 buff_idx = 0;
1173 }
1174
1175 // copy out the header (type & size)
1176 memcpy(&buff[buff_idx], &type, sizeof(uint16_t));
1177 buff_idx += sizeof(uint16_t);
1178
1179 tmp = size & 0xffff;
1180 memcpy(&buff[buff_idx], &tmp, sizeof(uint16_t));
1181 buff_idx += sizeof(uint16_t);
1182
1183 // now copy the body of the data, flushing along the way
1184 // if the buffer fills up.
1185 //
1186 while(size > 0) {
1187 amt = (size < (buff_sz - buff_idx)) ? size : (buff_sz - buff_idx);
1188 memcpy(&buff[buff_idx], data, amt);
1189
1190 size -= amt;
1191 buff_idx += amt;
1192 data = (const char *)data + amt;
1193 if (size > (buff_sz - buff_idx)) {
1194 if (buff_idx > uio_resid(uio)) {
1195 error = ENOSPC;
1196 goto get_out;
1197 }
1198 error = uiomove(buff, buff_idx, uio);
1199 if (error) {
1200 goto get_out;
1201 }
1202 buff_idx = 0;
1203 }
1204
1205 if (amt == 0) { // just in case...
1206 break;
1207 }
1208 }
1209
1210 get_out:
1211 *_buff_idx = buff_idx;
1212
1213 return error;
1214 }
1215
1216
1217 static int copy_out_kfse(fs_event_watcher *watcher, kfs_event *kfse, struct uio *uio) __attribute__((noinline));
1218
1219 static int
1220 copy_out_kfse(fs_event_watcher *watcher, kfs_event *kfse, struct uio *uio)
1221 {
1222 int error;
1223 uint16_t tmp16;
1224 int32_t type;
1225 kfs_event *cur;
1226 char evbuff[512];
1227 int evbuff_idx = 0;
1228
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);
1231 }
1232
1233 if (kfse->flags & KFSE_BEING_CREATED) {
1234 return 0;
1235 }
1236
1237 if (kfse->type == FSE_RENAME && kfse->dest == NULL) {
1238 //
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
1244 // the other one)
1245 error = 0;
1246 goto get_out;
1247 }
1248
1249 if (watcher->flags & WATCHER_WANTS_EXTENDED_INFO) {
1250
1251 type = (kfse->type & 0xfff);
1252
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);
1257 }
1258
1259 } else {
1260 type = (int32_t)kfse->type;
1261 }
1262
1263 // copy out the type of the event
1264 memcpy(evbuff, &type, sizeof(int32_t));
1265 evbuff_idx += sizeof(int32_t);
1266
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);
1270
1271 cur = kfse;
1272
1273 copy_again:
1274
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);
1278 } else {
1279 error = fill_buff(FSE_ARG_STRING, cur->len, cur->str, evbuff, &evbuff_idx, sizeof(evbuff), uio);
1280 }
1281 if (error != 0) {
1282 goto get_out;
1283 }
1284
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
1290 goto done;
1291 }
1292
1293
1294 if (watcher->flags & WATCHER_WANTS_COMPACT_EVENTS) {
1295 int32_t finfo_size;
1296
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);
1299 if (error != 0) {
1300 goto get_out;
1301 }
1302 } else {
1303 ino_t ino;
1304
1305 error = fill_buff(FSE_ARG_DEV, sizeof(dev_t), &cur->dev, evbuff, &evbuff_idx, sizeof(evbuff), uio);
1306 if (error != 0) {
1307 goto get_out;
1308 }
1309
1310 ino = (ino_t)cur->ino;
1311 error = fill_buff(FSE_ARG_INO, sizeof(ino_t), &ino, evbuff, &evbuff_idx, sizeof(evbuff), uio);
1312 if (error != 0) {
1313 goto get_out;
1314 }
1315
1316 error = fill_buff(FSE_ARG_MODE, sizeof(int32_t), &cur->mode, evbuff, &evbuff_idx, sizeof(evbuff), uio);
1317 if (error != 0) {
1318 goto get_out;
1319 }
1320
1321 error = fill_buff(FSE_ARG_UID, sizeof(uid_t), &cur->uid, evbuff, &evbuff_idx, sizeof(evbuff), uio);
1322 if (error != 0) {
1323 goto get_out;
1324 }
1325
1326 error = fill_buff(FSE_ARG_GID, sizeof(gid_t), &cur->gid, evbuff, &evbuff_idx, sizeof(evbuff), uio);
1327 if (error != 0) {
1328 goto get_out;
1329 }
1330 }
1331
1332
1333 if (cur->dest) {
1334 cur = cur->dest;
1335 goto copy_again;
1336 }
1337
1338 done:
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);
1341 if (error != 0) {
1342 goto get_out;
1343 }
1344
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)) {
1348 error = ENOSPC;
1349 goto get_out;
1350 }
1351 error = uiomove(evbuff, evbuff_idx, uio);
1352 if (error) {
1353 goto get_out;
1354 }
1355 evbuff_idx = 0;
1356 }
1357
1358 tmp16 = FSE_ARG_DONE;
1359 memcpy(&evbuff[evbuff_idx], &tmp16, sizeof(uint16_t));
1360 evbuff_idx += sizeof(uint16_t);
1361
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)) {
1365 error = ENOSPC;
1366 } else {
1367 error = uiomove(evbuff, evbuff_idx, uio);
1368 }
1369
1370 get_out:
1371
1372 return error;
1373 }
1374
1375
1376
1377 static int
1378 fmod_watch(fs_event_watcher *watcher, struct uio *uio)
1379 {
1380 int error=0;
1381 user_ssize_t last_full_event_resid;
1382 kfs_event *kfse;
1383 uint16_t tmp16;
1384 int skipped;
1385
1386 last_full_event_resid = uio_resid(uio);
1387
1388 // need at least 2048 bytes of space (maxpathlen + 1 event buf)
1389 if (uio_resid(uio) < 2048 || watcher == NULL) {
1390 return EINVAL;
1391 }
1392
1393 if (watcher->flags & WATCHER_CLOSING) {
1394 return 0;
1395 }
1396
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);
1400 return EAGAIN;
1401 }
1402
1403 restart_watch:
1404 if (watcher->rd == watcher->wr) {
1405 if (watcher->flags & WATCHER_CLOSING) {
1406 OSAddAtomic(-1, &watcher->num_readers);
1407 return 0;
1408 }
1409 OSAddAtomic(1, &watcher->blockers);
1410
1411 // there's nothing to do, go to sleep
1412 error = tsleep((caddr_t)watcher, PUSER|PCATCH, "fsevents_empty", 0);
1413
1414 OSAddAtomic(-1, &watcher->blockers);
1415
1416 if (error != 0 || (watcher->flags & WATCHER_CLOSING)) {
1417 OSAddAtomic(-1, &watcher->num_readers);
1418 return error;
1419 }
1420 }
1421
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;
1425
1426 error = uiomove((caddr_t)&val, sizeof(int32_t), uio);
1427 if (error == 0) {
1428 val = 0; // a fake pid
1429 error = uiomove((caddr_t)&val, sizeof(int32_t), uio);
1430
1431 tmp16 = FSE_ARG_DONE; // makes it a consistent msg
1432 error = uiomove((caddr_t)&tmp16, sizeof(int16_t), uio);
1433
1434 last_full_event_resid = uio_resid(uio);
1435 }
1436
1437 if (error) {
1438 OSAddAtomic(-1, &watcher->num_readers);
1439 return error;
1440 }
1441
1442 watcher->flags &= ~WATCHER_DROPPED_EVENTS;
1443 }
1444
1445 skipped = 0;
1446
1447 lck_rw_lock_shared(&event_handling_lock);
1448 while (uio_resid(uio) > 0 && watcher->rd != watcher->wr) {
1449 if (watcher->flags & WATCHER_CLOSING) {
1450 break;
1451 }
1452
1453 //
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)
1457 //
1458 kfse = watcher->event_queue[watcher->rd];
1459 if (!kfse || kfse->type == FSE_INVALID || kfse->refcount < 1) {
1460 break;
1461 }
1462
1463 if (watcher->event_list[kfse->type] == FSE_REPORT && watcher_cares_about_dev(watcher, kfse->dev)) {
1464
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
1467 // radar://12034844
1468 error = 0;
1469 skipped = 1;
1470 } else {
1471
1472 skipped = 0;
1473 if (last_event_ptr == kfse) {
1474 last_event_ptr = NULL;
1475 last_event_type = -1;
1476 last_coalesced_time = 0;
1477 }
1478 error = copy_out_kfse(watcher, kfse, uio);
1479 if (error != 0) {
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);
1488 error = 0;
1489 goto get_out;
1490 }
1491 }
1492
1493 last_full_event_resid = uio_resid(uio);
1494 }
1495 }
1496
1497 watcher->event_queue[watcher->rd] = NULL;
1498 watcher->rd = (watcher->rd + 1) % watcher->eventq_size;
1499 OSSynchronizeIO();
1500 release_event_ref(kfse);
1501 }
1502 lck_rw_unlock_shared(&event_handling_lock);
1503
1504 if (skipped && error == 0) {
1505 goto restart_watch;
1506 }
1507
1508 get_out:
1509 OSAddAtomic(-1, &watcher->num_readers);
1510
1511 return error;
1512 }
1513
1514
1515 // release any references we might have on vnodes which are
1516 // the mount point passed to us (so that it can be cleanly
1517 // unmounted).
1518 //
1519 // since we don't want to lose the events we'll convert the
1520 // vnode refs to full paths.
1521 //
1522 void
1523 fsevent_unmount(__unused struct mount *mp)
1524 {
1525 // we no longer maintain pointers to vnodes so
1526 // there is nothing to do...
1527 }
1528
1529
1530 //
1531 // /dev/fsevents device code
1532 //
1533 static int fsevents_installed = 0;
1534
1535 typedef struct fsevent_handle {
1536 UInt32 flags;
1537 SInt32 active;
1538 fs_event_watcher *watcher;
1539 struct klist knotes;
1540 struct selinfo si;
1541 } fsevent_handle;
1542
1543 #define FSEH_CLOSING 0x0001
1544
1545 static int
1546 fseventsf_read(struct fileproc *fp, struct uio *uio,
1547 __unused int flags, __unused vfs_context_t ctx)
1548 {
1549 fsevent_handle *fseh = (struct fsevent_handle *)fp->f_fglob->fg_data;
1550 int error;
1551
1552 error = fmod_watch(fseh->watcher, uio);
1553
1554 return error;
1555 }
1556
1557
1558 static int
1559 fseventsf_write(__unused struct fileproc *fp, __unused struct uio *uio,
1560 __unused int flags, __unused vfs_context_t ctx)
1561 {
1562 return EIO;
1563 }
1564
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;
1570 #pragma pack(pop)
1571
1572 #define NEW_FSEVENTS_DEVICE_FILTER _IOW('s', 100, ext_fsevent_dev_filter_args)
1573
1574 typedef struct old_fsevent_dev_filter_args {
1575 uint32_t num_devices;
1576 int32_t devices;
1577 } old_fsevent_dev_filter_args;
1578
1579 #define OLD_FSEVENTS_DEVICE_FILTER _IOW('s', 100, old_fsevent_dev_filter_args)
1580
1581 #if __LP64__
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;
1585 uint32_t devices;
1586 int32_t pad1;
1587 } fsevent_dev_filter_args32;
1588 #endif
1589
1590 static int
1591 fseventsf_ioctl(struct fileproc *fp, u_long cmd, caddr_t data, vfs_context_t ctx)
1592 {
1593 fsevent_handle *fseh = (struct fsevent_handle *)fp->f_fglob->fg_data;
1594 int ret = 0;
1595 ext_fsevent_dev_filter_args *devfilt_args, _devfilt_args;
1596
1597 if (proc_is64bit(vfs_context_proc(ctx))) {
1598 devfilt_args = (ext_fsevent_dev_filter_args *)data;
1599 }
1600 else if (cmd == OLD_FSEVENTS_DEVICE_FILTER) {
1601 old_fsevent_dev_filter_args *udev_filt_args = (old_fsevent_dev_filter_args *)data;
1602
1603 devfilt_args = &_devfilt_args;
1604 memset(devfilt_args, 0, sizeof(ext_fsevent_dev_filter_args));
1605
1606 devfilt_args->num_devices = udev_filt_args->num_devices;
1607 devfilt_args->devices = CAST_USER_ADDR_T(udev_filt_args->devices);
1608 }
1609 else {
1610 #if __LP64__
1611 fsevent_dev_filter_args32 *udev_filt_args = (fsevent_dev_filter_args32 *)data;
1612 #else
1613 fsevent_dev_filter_args *udev_filt_args = (fsevent_dev_filter_args *)data;
1614 #endif
1615
1616 devfilt_args = &_devfilt_args;
1617 memset(devfilt_args, 0, sizeof(ext_fsevent_dev_filter_args));
1618
1619 devfilt_args->num_devices = udev_filt_args->num_devices;
1620 devfilt_args->devices = CAST_USER_ADDR_T(udev_filt_args->devices);
1621 }
1622
1623 OSAddAtomic(1, &fseh->active);
1624 if (fseh->flags & FSEH_CLOSING) {
1625 OSAddAtomic(-1, &fseh->active);
1626 return 0;
1627 }
1628
1629 switch (cmd) {
1630 case FIONBIO:
1631 case FIOASYNC:
1632 break;
1633
1634 case FSEVENTS_WANT_COMPACT_EVENTS: {
1635 fseh->watcher->flags |= WATCHER_WANTS_COMPACT_EVENTS;
1636 break;
1637 }
1638
1639 case FSEVENTS_WANT_EXTENDED_INFO: {
1640 fseh->watcher->flags |= WATCHER_WANTS_EXTENDED_INFO;
1641 break;
1642 }
1643
1644 case FSEVENTS_GET_CURRENT_ID: {
1645 *(uint64_t *)data = fseh->watcher->max_event_id;
1646 ret = 0;
1647 break;
1648 }
1649
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;
1654
1655 if (devfilt_args->num_devices > 256) {
1656 ret = EINVAL;
1657 break;
1658 }
1659
1660 new_num_devices = devfilt_args->num_devices;
1661 if (new_num_devices == 0) {
1662 tmp = fseh->watcher->devices_not_to_watch;
1663
1664 lock_watch_table();
1665 fseh->watcher->devices_not_to_watch = NULL;
1666 fseh->watcher->num_devices = new_num_devices;
1667 unlock_watch_table();
1668
1669 if (tmp) {
1670 FREE(tmp, M_TEMP);
1671 }
1672 break;
1673 }
1674
1675 MALLOC(devices_not_to_watch, dev_t *,
1676 new_num_devices * sizeof(dev_t),
1677 M_TEMP, M_WAITOK);
1678 if (devices_not_to_watch == NULL) {
1679 ret = ENOMEM;
1680 break;
1681 }
1682
1683 ret = copyin(devfilt_args->devices,
1684 (void *)devices_not_to_watch,
1685 new_num_devices * sizeof(dev_t));
1686 if (ret) {
1687 FREE(devices_not_to_watch, M_TEMP);
1688 break;
1689 }
1690
1691 lock_watch_table();
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();
1696
1697 if (tmp) {
1698 FREE(tmp, M_TEMP);
1699 }
1700
1701 break;
1702 }
1703
1704 default:
1705 ret = EINVAL;
1706 break;
1707 }
1708
1709 OSAddAtomic(-1, &fseh->active);
1710 return (ret);
1711 }
1712
1713
1714 static int
1715 fseventsf_select(struct fileproc *fp, int which, __unused void *wql, vfs_context_t ctx)
1716 {
1717 fsevent_handle *fseh = (struct fsevent_handle *)fp->f_fglob->fg_data;
1718 int ready = 0;
1719
1720 if ((which != FREAD) || (fseh->watcher->flags & WATCHER_CLOSING)) {
1721 return 0;
1722 }
1723
1724
1725 // if there's nothing in the queue, we're not ready
1726 if (fseh->watcher->rd != fseh->watcher->wr) {
1727 ready = 1;
1728 }
1729
1730 if (!ready) {
1731 selrecord(vfs_context_proc(ctx), &fseh->si, wql);
1732 }
1733
1734 return ready;
1735 }
1736
1737
1738 #if NOTUSED
1739 static int
1740 fseventsf_stat(__unused struct fileproc *fp, __unused struct stat *sb, __unused vfs_context_t ctx)
1741 {
1742 return ENOTSUP;
1743 }
1744 #endif
1745
1746 static int
1747 fseventsf_close(struct fileglob *fg, __unused vfs_context_t ctx)
1748 {
1749 fsevent_handle *fseh = (struct fsevent_handle *)fg->fg_data;
1750 fs_event_watcher *watcher;
1751
1752 OSBitOrAtomic(FSEH_CLOSING, &fseh->flags);
1753 while (OSAddAtomic(0, &fseh->active) > 0) {
1754 tsleep((caddr_t)fseh->watcher, PRIBIO, "fsevents-close", 1);
1755 }
1756
1757 watcher = fseh->watcher;
1758 fg->fg_data = NULL;
1759 fseh->watcher = NULL;
1760
1761 remove_watcher(watcher);
1762 FREE(fseh, M_TEMP);
1763
1764 return 0;
1765 }
1766
1767 static void
1768 filt_fsevent_detach(struct knote *kn)
1769 {
1770 fsevent_handle *fseh = (struct fsevent_handle *)kn->kn_hook;
1771
1772 lock_watch_table();
1773
1774 KNOTE_DETACH(&fseh->knotes, kn);
1775
1776 unlock_watch_table();
1777 }
1778
1779 /*
1780 * Determine whether this knote should be active
1781 *
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
1787 */
1788 static int
1789 filt_fsevent(struct knote *kn, long hint)
1790 {
1791 fsevent_handle *fseh = (struct fsevent_handle *)kn->kn_hook;
1792 int activate = 0;
1793 int32_t rd, wr, amt;
1794
1795 if (NOTE_REVOKE == hint) {
1796 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
1797 activate = 1;
1798 }
1799
1800 rd = fseh->watcher->rd;
1801 wr = fseh->watcher->wr;
1802 if (rd <= wr) {
1803 amt = wr - rd;
1804 } else {
1805 amt = fseh->watcher->eventq_size - (rd - wr);
1806 }
1807
1808 switch(kn->kn_filter) {
1809 case EVFILT_READ:
1810 kn->kn_data = amt;
1811
1812 if (kn->kn_data != 0) {
1813 activate = 1;
1814 }
1815 break;
1816 case EVFILT_VNODE:
1817 /* Check events this note matches against the hint */
1818 if (kn->kn_sfflags & hint) {
1819 kn->kn_fflags |= hint; /* Set which event occurred */
1820 }
1821 if (kn->kn_fflags != 0) {
1822 activate = 1;
1823 }
1824 break;
1825 default: {
1826 // nothing to do...
1827 break;
1828 }
1829 }
1830
1831 return (activate);
1832 }
1833
1834
1835 struct filterops fsevent_filtops = {
1836 .f_isfd = 1,
1837 .f_attach = NULL,
1838 .f_detach = filt_fsevent_detach,
1839 .f_event = filt_fsevent
1840 };
1841
1842 static int
1843 fseventsf_kqfilter(__unused struct fileproc *fp, __unused struct knote *kn, __unused vfs_context_t ctx)
1844 {
1845 fsevent_handle *fseh = (struct fsevent_handle *)fp->f_fglob->fg_data;
1846
1847 kn->kn_hook = (void*)fseh;
1848 kn->kn_hookid = 1;
1849 kn->kn_fop = &fsevent_filtops;
1850
1851 lock_watch_table();
1852
1853 KNOTE_ATTACH(&fseh->knotes, kn);
1854
1855 unlock_watch_table();
1856 return 0;
1857 }
1858
1859
1860 static int
1861 fseventsf_drain(struct fileproc *fp, __unused vfs_context_t ctx)
1862 {
1863 int counter = 0;
1864 fsevent_handle *fseh = (struct fsevent_handle *)fp->f_fglob->fg_data;
1865
1866 fseh->watcher->flags |= WATCHER_CLOSING;
1867
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
1879 lock_watch_table();
1880 fsevents_wakeup(fseh->watcher);
1881 unlock_watch_table();
1882
1883 tsleep((caddr_t)fseh->watcher, PRIBIO, "watcher-close", 1);
1884 }
1885
1886 return 0;
1887 }
1888
1889
1890 static int
1891 fseventsopen(__unused dev_t dev, __unused int flag, __unused int mode, __unused struct proc *p)
1892 {
1893 if (!is_suser()) {
1894 return EPERM;
1895 }
1896
1897 return 0;
1898 }
1899
1900 static int
1901 fseventsclose(__unused dev_t dev, __unused int flag, __unused int mode, __unused struct proc *p)
1902 {
1903 return 0;
1904 }
1905
1906 static int
1907 fseventsread(__unused dev_t dev, __unused struct uio *uio, __unused int ioflag)
1908 {
1909 return EIO;
1910 }
1911
1912
1913 static int
1914 parse_buffer_and_add_events(const char *buffer, int bufsize, vfs_context_t ctx, long *remainder)
1915 {
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;
1919
1920
1921 ptr = buffer;
1922 while ((ptr+sizeof(int)+sizeof(fse_info)+1) < buffer+bufsize) {
1923 type = *(const int *)ptr;
1924 if (type < 0 || type >= FSE_MAX_EVENTS) {
1925 err = EINVAL;
1926 break;
1927 }
1928
1929 ptr += sizeof(int);
1930
1931 finfo = (const fse_info *)ptr;
1932 ptr += sizeof(fse_info);
1933
1934 path = ptr;
1935 while(ptr < buffer+bufsize && *ptr != '\0') {
1936 ptr++;
1937 }
1938
1939 if (ptr >= buffer+bufsize) {
1940 break;
1941 }
1942
1943 ptr++; // advance over the trailing '\0'
1944
1945 path_len = ptr - path;
1946
1947 if (type != FSE_RENAME && type != FSE_EXCHANGE) {
1948 event_start = ptr; // record where the next event starts
1949
1950 err = add_fsevent(type, ctx, FSE_ARG_STRING, path_len, path, FSE_ARG_FINFO, finfo, FSE_ARG_DONE);
1951 if (err) {
1952 break;
1953 }
1954 continue;
1955 }
1956
1957 //
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.
1961 //
1962 dest_finfo = (const fse_info *)ptr;
1963 ptr += sizeof(fse_info);
1964
1965 dest_path = ptr;
1966 while(ptr < buffer+bufsize && *ptr != '\0') {
1967 ptr++;
1968 }
1969
1970 if (ptr >= buffer+bufsize) {
1971 break;
1972 }
1973
1974 ptr++; // advance over the trailing '\0'
1975 event_start = ptr; // record where the next event starts
1976
1977 dest_path_len = ptr - dest_path;
1978 //
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.
1984 //
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,
1989 FSE_ARG_DONE);
1990 } else {
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,
1994 FSE_ARG_DONE);
1995 }
1996
1997 if (err) {
1998 break;
1999 }
2000
2001 }
2002
2003 // if the last event wasn't complete, set the remainder
2004 // to be the last event start boundary.
2005 //
2006 *remainder = (long)((buffer+bufsize) - event_start);
2007
2008 return err;
2009 }
2010
2011
2012 //
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.
2018 //
2019 #define WRITE_BUFFER_SIZE 4096
2020 char *write_buffer=NULL;
2021
2022 static int
2023 fseventswrite(__unused dev_t dev, struct uio *uio, __unused int ioflag)
2024 {
2025 int error=0, count;
2026 vfs_context_t ctx = vfs_context_current();
2027 long offset=0, remainder;
2028
2029 lck_mtx_lock(&event_writer_lock);
2030
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);
2034 return ENOMEM;
2035 }
2036 }
2037
2038 //
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
2044 // after it.
2045 //
2046 while(uio_resid(uio)) {
2047 if (uio_resid(uio) > (WRITE_BUFFER_SIZE-offset)) {
2048 count = WRITE_BUFFER_SIZE - offset;
2049 } else {
2050 count = uio_resid(uio);
2051 }
2052
2053 error = uiomove(write_buffer+offset, count, uio);
2054 if (error) {
2055 break;
2056 }
2057
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);
2060 if (error) {
2061 break;
2062 }
2063
2064 //
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.
2069 //
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);
2074 offset = remainder;
2075 } else {
2076 offset = 0;
2077 }
2078 }
2079
2080 lck_mtx_unlock(&event_writer_lock);
2081
2082 return error;
2083 }
2084
2085
2086 static struct fileops fsevents_fops = {
2087 fseventsf_read,
2088 fseventsf_write,
2089 fseventsf_ioctl,
2090 fseventsf_select,
2091 fseventsf_close,
2092 fseventsf_kqfilter,
2093 fseventsf_drain
2094 };
2095
2096 typedef struct ext_fsevent_clone_args {
2097 user_addr_t event_list;
2098 int32_t num_events;
2099 int32_t event_queue_depth;
2100 user_addr_t fd;
2101 } ext_fsevent_clone_args;
2102
2103 typedef struct old_fsevent_clone_args {
2104 uint32_t event_list;
2105 int32_t num_events;
2106 int32_t event_queue_depth;
2107 uint32_t fd;
2108 } old_fsevent_clone_args;
2109
2110 #define OLD_FSEVENTS_CLONE _IOW('s', 1, old_fsevent_clone_args)
2111
2112 static int
2113 fseventsioctl(__unused dev_t dev, u_long cmd, caddr_t data, __unused int flag, struct proc *p)
2114 {
2115 struct fileproc *f;
2116 int fd, error;
2117 fsevent_handle *fseh = NULL;
2118 ext_fsevent_clone_args *fse_clone_args, _fse_clone;
2119 int8_t *event_list;
2120 int is64bit = proc_is64bit(p);
2121
2122 switch (cmd) {
2123 case OLD_FSEVENTS_CLONE: {
2124 old_fsevent_clone_args *old_args = (old_fsevent_clone_args *)data;
2125
2126 fse_clone_args = &_fse_clone;
2127 memset(fse_clone_args, 0, sizeof(ext_fsevent_clone_args));
2128
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);
2133 goto handle_clone;
2134 }
2135
2136 case FSEVENTS_CLONE:
2137 if (is64bit) {
2138 fse_clone_args = (ext_fsevent_clone_args *)data;
2139 } else {
2140 fsevent_clone_args *ufse_clone = (fsevent_clone_args *)data;
2141
2142 fse_clone_args = &_fse_clone;
2143 memset(fse_clone_args, 0, sizeof(ext_fsevent_clone_args));
2144
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);
2149 }
2150
2151 handle_clone:
2152 if (fse_clone_args->num_events < 0 || fse_clone_args->num_events > 4096) {
2153 return EINVAL;
2154 }
2155
2156 MALLOC(fseh, fsevent_handle *, sizeof(fsevent_handle),
2157 M_TEMP, M_WAITOK);
2158 if (fseh == NULL) {
2159 return ENOMEM;
2160 }
2161 memset(fseh, 0, sizeof(fsevent_handle));
2162
2163 klist_init(&fseh->knotes);
2164
2165 MALLOC(event_list, int8_t *,
2166 fse_clone_args->num_events * sizeof(int8_t),
2167 M_TEMP, M_WAITOK);
2168 if (event_list == NULL) {
2169 FREE(fseh, M_TEMP);
2170 return ENOMEM;
2171 }
2172
2173 error = copyin(fse_clone_args->event_list,
2174 (void *)event_list,
2175 fse_clone_args->num_events * sizeof(int8_t));
2176 if (error) {
2177 FREE(event_list, M_TEMP);
2178 FREE(fseh, M_TEMP);
2179 return error;
2180 }
2181
2182 error = add_watcher(event_list,
2183 fse_clone_args->num_events,
2184 fse_clone_args->event_queue_depth,
2185 &fseh->watcher,
2186 fseh);
2187 if (error) {
2188 FREE(event_list, M_TEMP);
2189 FREE(fseh, M_TEMP);
2190 return error;
2191 }
2192
2193 fseh->watcher->fseh = fseh;
2194
2195 error = falloc(p, &f, &fd, vfs_context_current());
2196 if (error) {
2197 FREE(event_list, M_TEMP);
2198 FREE(fseh, M_TEMP);
2199 return (error);
2200 }
2201 proc_fdlock(p);
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;
2206 proc_fdunlock(p);
2207 error = copyout((void *)&fd, fse_clone_args->fd, sizeof(int32_t));
2208 if (error != 0) {
2209 fp_free(p, fd, f);
2210 } else {
2211 proc_fdlock(p);
2212 procfdtbl_releasefd(p, fd, NULL);
2213 fp_drop(p, fd, f, 1);
2214 proc_fdunlock(p);
2215 }
2216 break;
2217
2218 default:
2219 error = EINVAL;
2220 break;
2221 }
2222
2223 return error;
2224 }
2225
2226 static void
2227 fsevents_wakeup(fs_event_watcher *watcher)
2228 {
2229 selwakeup(&watcher->fseh->si);
2230 KNOTE(&watcher->fseh->knotes, NOTE_WRITE|NOTE_NONE);
2231 wakeup((caddr_t)watcher);
2232 }
2233
2234
2235 /*
2236 * A struct describing which functions will get invoked for certain
2237 * actions.
2238 */
2239 static struct cdevsw fsevents_cdevsw =
2240 {
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 */
2248 NULL, /* tty's */
2249 eno_select, /* select */
2250 eno_mmap, /* mmap */
2251 eno_strat, /* strategy */
2252 eno_getc, /* getc */
2253 eno_putc, /* putc */
2254 0 /* type */
2255 };
2256
2257
2258 /*
2259 * Called to initialize our device,
2260 * and to register ourselves with devfs
2261 */
2262
2263 void
2264 fsevents_init(void)
2265 {
2266 int ret;
2267
2268 if (fsevents_installed) {
2269 return;
2270 }
2271
2272 fsevents_installed = 1;
2273
2274 ret = cdevsw_add(-1, &fsevents_cdevsw);
2275 if (ret < 0) {
2276 fsevents_installed = 0;
2277 return;
2278 }
2279
2280 devfs_make_node(makedev (ret, 0), DEVFS_CHAR,
2281 UID_ROOT, GID_WHEEL, 0644, "fsevents", 0);
2282
2283 fsevents_internal_init();
2284 }
2285
2286
2287 char *
2288 get_pathbuff(void)
2289 {
2290 char *path;
2291
2292 MALLOC_ZONE(path, char *, MAXPATHLEN, M_NAMEI, M_WAITOK);
2293 return path;
2294 }
2295
2296 void
2297 release_pathbuff(char *path)
2298 {
2299
2300 if (path == NULL) {
2301 return;
2302 }
2303 FREE_ZONE(path, MAXPATHLEN, M_NAMEI);
2304 }
2305
2306 int
2307 get_fse_info(struct vnode *vp, fse_info *fse, __unused vfs_context_t ctx)
2308 {
2309 struct vnode_attr va;
2310
2311 VATTR_INIT(&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);
2320 } else {
2321 VATTR_WANTED(&va, va_nlink);
2322 }
2323 }
2324
2325 if (vnode_getattr(vp, &va, vfs_context_kernel()) != 0) {
2326 memset(fse, 0, sizeof(fse_info));
2327 return -1;
2328 }
2329
2330 return vnode_get_fse_info_from_vap(vp, fse, &va);
2331 }
2332
2333 int
2334 vnode_get_fse_info_from_vap(vnode_t vp, fse_info *fse, struct vnode_attr *vap)
2335 {
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;
2345 } else {
2346 fse->nlink = (uint64_t)vap->va_nlink;
2347 }
2348 }
2349
2350 return 0;
2351 }
2352
2353 void
2354 create_fsevent_from_kevent(vnode_t vp, uint32_t kevents, struct vnode_attr *vap)
2355 {
2356 int fsevent_type=FSE_CONTENT_MODIFIED, len; // the default is the most pessimistic
2357 char pathbuf[MAXPATHLEN];
2358 fse_info fse;
2359
2360
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;
2373 }
2374
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)");
2376
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;
2384 } else {
2385 fse.nlink = vap->va_nlink;
2386 }
2387 }
2388
2389 if (vp->v_type == VDIR) {
2390 fse.mode |= FSE_REMOTE_DIR_EVENT;
2391 }
2392
2393
2394 fse.uid = vap->va_uid;
2395 fse.gid = vap->va_gid;
2396
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);
2400 }
2401 return;
2402 }
2403
2404 #else /* CONFIG_FSE */
2405 /*
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.
2411 */
2412 char *
2413 get_pathbuff(void)
2414 {
2415 char *path;
2416 MALLOC_ZONE(path, char *, MAXPATHLEN, M_NAMEI, M_WAITOK);
2417 return path;
2418 }
2419
2420 void
2421 release_pathbuff(char *path)
2422 {
2423 FREE_ZONE(path, MAXPATHLEN, M_NAMEI);
2424 }
2425 #endif /* CONFIG_FSE */