]> git.saurik.com Git - apple/xnu.git/blob - bsd/vfs/vfs_fsevents.c
xnu-3789.1.32.tar.gz
[apple/xnu.git] / bsd / vfs / vfs_fsevents.c
1 /*
2 * Copyright (c) 2004-2014 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 static int
169 is_ignored_directory(const char *path) {
170
171 if (!path) {
172 return 0;
173 }
174
175 #define IS_TLD(x) strnstr(__DECONST(char *, path), x, MAXPATHLEN)
176 if (IS_TLD("/.Spotlight-V100/") ||
177 IS_TLD("/.MobileBackups/") ||
178 IS_TLD("/Backups.backupdb/")) {
179 return 1;
180 }
181 #undef IS_TLD
182
183 return 0;
184 }
185
186 static void
187 fsevents_internal_init(void)
188 {
189 int i;
190
191 if (fs_event_init++ != 0) {
192 return;
193 }
194
195 for(i=0; i < FSE_MAX_EVENTS; i++) {
196 fs_event_type_watchers[i] = 0;
197 }
198
199 memset(watcher_table, 0, sizeof(watcher_table));
200
201 fsevent_lock_attr = lck_attr_alloc_init();
202 fsevent_group_attr = lck_grp_attr_alloc_init();
203 fsevent_mutex_group = lck_grp_alloc_init("fsevent-mutex", fsevent_group_attr);
204 fsevent_rw_group = lck_grp_alloc_init("fsevent-rw", fsevent_group_attr);
205
206 lck_mtx_init(&watch_table_lock, fsevent_mutex_group, fsevent_lock_attr);
207 lck_mtx_init(&event_buf_lock, fsevent_mutex_group, fsevent_lock_attr);
208 lck_mtx_init(&event_writer_lock, fsevent_mutex_group, fsevent_lock_attr);
209
210 lck_rw_init(&event_handling_lock, fsevent_rw_group, fsevent_lock_attr);
211
212 PE_get_default("kern.maxkfsevents", &max_kfs_events, sizeof(max_kfs_events));
213
214 event_zone = zinit(sizeof(kfs_event),
215 max_kfs_events * sizeof(kfs_event),
216 max_kfs_events * sizeof(kfs_event),
217 "fs-event-buf");
218 if (event_zone == NULL) {
219 printf("fsevents: failed to initialize the event zone.\n");
220 }
221
222 // mark the zone as exhaustible so that it will not
223 // ever grow beyond what we initially filled it with
224 zone_change(event_zone, Z_EXHAUST, TRUE);
225 zone_change(event_zone, Z_COLLECT, FALSE);
226 zone_change(event_zone, Z_CALLERACCT, FALSE);
227
228 if (zfill(event_zone, max_kfs_events) < max_kfs_events) {
229 printf("fsevents: failed to pre-fill the event zone.\n");
230 }
231
232 }
233
234 static void
235 lock_watch_table(void)
236 {
237 lck_mtx_lock(&watch_table_lock);
238 }
239
240 static void
241 unlock_watch_table(void)
242 {
243 lck_mtx_unlock(&watch_table_lock);
244 }
245
246 static void
247 lock_fs_event_list(void)
248 {
249 lck_mtx_lock(&event_buf_lock);
250 }
251
252 static void
253 unlock_fs_event_list(void)
254 {
255 lck_mtx_unlock(&event_buf_lock);
256 }
257
258 // forward prototype
259 static void release_event_ref(kfs_event *kfse);
260
261 static int
262 watcher_cares_about_dev(fs_event_watcher *watcher, dev_t dev)
263 {
264 unsigned int i;
265
266 // if devices_not_to_watch is NULL then we care about all
267 // events from all devices
268 if (watcher->devices_not_to_watch == NULL) {
269 return 1;
270 }
271
272 for(i=0; i < watcher->num_devices; i++) {
273 if (dev == watcher->devices_not_to_watch[i]) {
274 // found a match! that means we do not
275 // want events from this device.
276 return 0;
277 }
278 }
279
280 // if we're here it's not in the devices_not_to_watch[]
281 // list so that means we do care about it
282 return 1;
283 }
284
285
286 int
287 need_fsevent(int type, vnode_t vp)
288 {
289 if (type >= 0 && type < FSE_MAX_EVENTS && fs_event_type_watchers[type] == 0)
290 return (0);
291
292 // events in /dev aren't really interesting...
293 if (vp->v_tag == VT_DEVFS) {
294 return (0);
295 }
296
297 return 1;
298 }
299
300
301 #define is_throw_away(x) ((x) == FSE_STAT_CHANGED || (x) == FSE_CONTENT_MODIFIED)
302
303
304 // Ways that an event can be reused:
305 //
306 // "combined" events mean that there were two events for
307 // the same vnode or path and we're combining both events
308 // into a single event. The primary event gets a bit that
309 // marks it as having been combined. The secondary event
310 // is essentially dropped and the kfse structure reused.
311 //
312 // "collapsed" means that multiple events below a given
313 // directory are collapsed into a single event. in this
314 // case, the directory that we collapse into and all of
315 // its children must be re-scanned.
316 //
317 // "recycled" means that we're completely blowing away
318 // the event since there are other events that have info
319 // about the same vnode or path (and one of those other
320 // events will be marked as combined or collapsed as
321 // appropriate).
322 //
323 #define KFSE_COMBINED 0x0001
324 #define KFSE_COLLAPSED 0x0002
325 #define KFSE_RECYCLED 0x0004
326
327 int num_dropped = 0;
328 int num_parent_switch = 0;
329 int num_recycled_rename = 0;
330
331 static struct timeval last_print;
332
333 //
334 // These variables are used to track coalescing multiple identical
335 // events for the same vnode/pathname. If we get the same event
336 // type and same vnode/pathname as the previous event, we just drop
337 // the event since it's superfluous. This improves some micro-
338 // benchmarks considerably and actually has a real-world impact on
339 // tests like a Finder copy where multiple stat-changed events can
340 // get coalesced.
341 //
342 static int last_event_type=-1;
343 static void *last_ptr=NULL;
344 static char last_str[MAXPATHLEN];
345 static int last_nlen=0;
346 static int last_vid=-1;
347 static uint64_t last_coalesced_time=0;
348 static void *last_event_ptr=NULL;
349 int last_coalesced = 0;
350 static mach_timebase_info_data_t sTimebaseInfo = { 0, 0 };
351
352
353 int
354 add_fsevent(int type, vfs_context_t ctx, ...)
355 {
356 struct proc *p = vfs_context_proc(ctx);
357 int i, arg_type, ret;
358 kfs_event *kfse, *kfse_dest=NULL, *cur;
359 fs_event_watcher *watcher;
360 va_list ap;
361 int error = 0, did_alloc=0;
362 dev_t dev = 0;
363 uint64_t now, elapsed;
364 char *pathbuff=NULL;
365 int pathbuff_len;
366
367
368
369 va_start(ap, ctx);
370
371 // ignore bogus event types..
372 if (type < 0 || type >= FSE_MAX_EVENTS) {
373 return EINVAL;
374 }
375
376 // if no one cares about this type of event, bail out
377 if (fs_event_type_watchers[type] == 0) {
378 va_end(ap);
379
380 return 0;
381 }
382
383 now = mach_absolute_time();
384
385 // find a free event and snag it for our use
386 // NOTE: do not do anything that would block until
387 // the lock is dropped.
388 lock_fs_event_list();
389
390 //
391 // check if this event is identical to the previous one...
392 // (as long as it's not an event type that can never be the
393 // same as a previous event)
394 //
395 if (type != FSE_CREATE_FILE && type != FSE_DELETE && type != FSE_RENAME && type != FSE_EXCHANGE && type != FSE_CHOWN && type != FSE_DOCID_CHANGED && type != FSE_DOCID_CREATED) {
396 void *ptr=NULL;
397 int vid=0, was_str=0, nlen=0;
398
399 for(arg_type=va_arg(ap, int32_t); arg_type != FSE_ARG_DONE; arg_type=va_arg(ap, int32_t)) {
400 switch(arg_type) {
401 case FSE_ARG_VNODE: {
402 ptr = va_arg(ap, void *);
403 vid = vnode_vid((struct vnode *)ptr);
404 last_str[0] = '\0';
405 break;
406 }
407 case FSE_ARG_STRING: {
408 nlen = va_arg(ap, int32_t);
409 ptr = va_arg(ap, void *);
410 was_str = 1;
411 break;
412 }
413 }
414 if (ptr != NULL) {
415 break;
416 }
417 }
418
419 if ( sTimebaseInfo.denom == 0 ) {
420 (void) clock_timebase_info(&sTimebaseInfo);
421 }
422
423 elapsed = (now - last_coalesced_time);
424 if (sTimebaseInfo.denom != sTimebaseInfo.numer) {
425 if (sTimebaseInfo.denom == 1) {
426 elapsed *= sTimebaseInfo.numer;
427 } else {
428 // this could overflow... the worst that will happen is that we'll
429 // send (or not send) an extra event so I'm not going to worry about
430 // doing the math right like dtrace_abs_to_nano() does.
431 elapsed = (elapsed * sTimebaseInfo.numer) / (uint64_t)sTimebaseInfo.denom;
432 }
433 }
434
435 if (type == last_event_type
436 && (elapsed < 1000000000)
437 &&
438 ((vid && vid == last_vid && last_ptr == ptr)
439 ||
440 (last_str[0] && last_nlen == nlen && ptr && strcmp(last_str, ptr) == 0))
441 ) {
442
443 last_coalesced++;
444 unlock_fs_event_list();
445 va_end(ap);
446
447 return 0;
448 } else {
449 last_ptr = ptr;
450 if (was_str) {
451 strlcpy(last_str, ptr, sizeof(last_str));
452 }
453 last_nlen = nlen;
454 last_vid = vid;
455 last_event_type = type;
456 last_coalesced_time = now;
457 }
458 }
459 va_start(ap, ctx);
460
461
462 kfse = zalloc_noblock(event_zone);
463 if (kfse && (type == FSE_RENAME || type == FSE_EXCHANGE)) {
464 kfse_dest = zalloc_noblock(event_zone);
465 if (kfse_dest == NULL) {
466 did_alloc = 1;
467 zfree(event_zone, kfse);
468 kfse = NULL;
469 }
470 }
471
472
473 if (kfse == NULL) { // yikes! no free events
474 unlock_fs_event_list();
475 lock_watch_table();
476
477 for(i=0; i < MAX_WATCHERS; i++) {
478 watcher = watcher_table[i];
479 if (watcher == NULL) {
480 continue;
481 }
482
483 watcher->flags |= WATCHER_DROPPED_EVENTS;
484 fsevents_wakeup(watcher);
485 }
486 unlock_watch_table();
487
488 {
489 struct timeval current_tv;
490
491 num_dropped++;
492
493 // only print a message at most once every 5 seconds
494 microuptime(&current_tv);
495 if ((current_tv.tv_sec - last_print.tv_sec) > 10) {
496 int ii;
497 void *junkptr=zalloc_noblock(event_zone), *listhead=kfse_list_head.lh_first;
498
499 printf("add_fsevent: event queue is full! dropping events (num dropped events: %d; num events outstanding: %d).\n", num_dropped, num_events_outstanding);
500 printf("add_fsevent: kfse_list head %p ; num_pending_rename %d\n", listhead, num_pending_rename);
501 printf("add_fsevent: zalloc sez: %p\n", junkptr);
502 printf("add_fsevent: event_zone info: %d 0x%x\n", ((int *)event_zone)[0], ((int *)event_zone)[1]);
503 lock_watch_table();
504 for(ii=0; ii < MAX_WATCHERS; ii++) {
505 if (watcher_table[ii] == NULL) {
506 continue;
507 }
508
509 printf("add_fsevent: watcher %s %p: rd %4d wr %4d q_size %4d flags 0x%x\n",
510 watcher_table[ii]->proc_name,
511 watcher_table[ii],
512 watcher_table[ii]->rd, watcher_table[ii]->wr,
513 watcher_table[ii]->eventq_size, watcher_table[ii]->flags);
514 }
515 unlock_watch_table();
516
517 last_print = current_tv;
518 if (junkptr) {
519 zfree(event_zone, junkptr);
520 }
521 }
522 }
523
524 if (pathbuff) {
525 release_pathbuff(pathbuff);
526 pathbuff = NULL;
527 }
528 return ENOSPC;
529 }
530
531 memset(kfse, 0, sizeof(kfs_event));
532 kfse->refcount = 1;
533 OSBitOrAtomic16(KFSE_BEING_CREATED, &kfse->flags);
534
535 last_event_ptr = kfse;
536 kfse->type = type;
537 kfse->abstime = now;
538 kfse->pid = p->p_pid;
539 if (type == FSE_RENAME || type == FSE_EXCHANGE) {
540 memset(kfse_dest, 0, sizeof(kfs_event));
541 kfse_dest->refcount = 1;
542 OSBitOrAtomic16(KFSE_BEING_CREATED, &kfse_dest->flags);
543 kfse_dest->type = type;
544 kfse_dest->pid = p->p_pid;
545 kfse_dest->abstime = now;
546
547 kfse->dest = kfse_dest;
548 }
549
550 num_events_outstanding++;
551 if (kfse->type == FSE_RENAME) {
552 num_pending_rename++;
553 }
554 LIST_INSERT_HEAD(&kfse_list_head, kfse, kevent_list);
555
556 if (kfse->refcount < 1) {
557 panic("add_fsevent: line %d: kfse recount %d but should be at least 1\n", __LINE__, kfse->refcount);
558 }
559
560 unlock_fs_event_list(); // at this point it's safe to unlock
561
562 //
563 // now process the arguments passed in and copy them into
564 // the kfse
565 //
566
567 cur = kfse;
568
569 if (type == FSE_DOCID_CREATED || type == FSE_DOCID_CHANGED) {
570 uint64_t val;
571
572 //
573 // These events are special and not like the other events. They only
574 // have a dev_t, src inode #, dest inode #, and a doc-id. We use the
575 // fields that we can in the kfse but have to overlay the dest inode
576 // number and the doc-id on the other fields.
577 //
578
579 // First the dev_t
580 arg_type = va_arg(ap, int32_t);
581 if (arg_type == FSE_ARG_DEV) {
582 cur->dev = (dev_t)(va_arg(ap, dev_t));
583 } else {
584 cur->dev = (dev_t)0xbadc0de1;
585 }
586
587 // next the source inode #
588 arg_type = va_arg(ap, int32_t);
589 if (arg_type == FSE_ARG_INO) {
590 cur->ino = (ino64_t)(va_arg(ap, ino64_t));
591 } else {
592 cur->ino = 0xbadc0de2;
593 }
594
595 // now the dest inode #
596 arg_type = va_arg(ap, int32_t);
597 if (arg_type == FSE_ARG_INO) {
598 val = (ino64_t)(va_arg(ap, ino64_t));
599 } else {
600 val = 0xbadc0de2;
601 }
602 // overlay the dest inode number on the str/dest pointer fields
603 memcpy(&cur->str, &val, sizeof(ino64_t));
604
605
606 // and last the document-id
607 arg_type = va_arg(ap, int32_t);
608 if (arg_type == FSE_ARG_INT32) {
609 val = (uint64_t)va_arg(ap, uint32_t);
610 } else if (arg_type == FSE_ARG_INT64) {
611 val = (uint64_t)va_arg(ap, uint64_t);
612 } else {
613 val = 0xbadc0de3;
614 }
615
616 // the docid is 64-bit and overlays the uid/gid fields
617 memcpy(&cur->uid, &val, sizeof(uint64_t));
618
619 goto done_with_args;
620 }
621
622 for(arg_type=va_arg(ap, int32_t); arg_type != FSE_ARG_DONE; arg_type=va_arg(ap, int32_t))
623
624 switch(arg_type) {
625 case FSE_ARG_VNODE: {
626 // this expands out into multiple arguments to the client
627 struct vnode *vp;
628 struct vnode_attr va;
629
630 if (kfse->str != NULL) {
631 cur = kfse_dest;
632 }
633
634 vp = va_arg(ap, struct vnode *);
635 if (vp == NULL) {
636 panic("add_fsevent: you can't pass me a NULL vnode ptr (type %d)!\n",
637 cur->type);
638 }
639
640 VATTR_INIT(&va);
641 VATTR_WANTED(&va, va_fsid);
642 VATTR_WANTED(&va, va_fileid);
643 VATTR_WANTED(&va, va_mode);
644 VATTR_WANTED(&va, va_uid);
645 VATTR_WANTED(&va, va_gid);
646 VATTR_WANTED(&va, va_nlink);
647 if ((ret = vnode_getattr(vp, &va, vfs_context_kernel())) != 0) {
648 // printf("add_fsevent: failed to getattr on vp %p (%d)\n", cur->fref.vp, ret);
649 cur->str = NULL;
650 error = EINVAL;
651 goto clean_up;
652 }
653
654 cur->dev = dev = (dev_t)va.va_fsid;
655 cur->ino = (ino64_t)va.va_fileid;
656 cur->mode = (int32_t)vnode_vttoif(vnode_vtype(vp)) | va.va_mode;
657 cur->uid = va.va_uid;
658 cur->gid = va.va_gid;
659 if (vp->v_flag & VISHARDLINK) {
660 cur->mode |= FSE_MODE_HLINK;
661 if ((vp->v_type == VDIR && va.va_dirlinkcount == 0) || (vp->v_type == VREG && va.va_nlink == 0)) {
662 cur->mode |= FSE_MODE_LAST_HLINK;
663 }
664 }
665
666 // if we haven't gotten the path yet, get it.
667 if (pathbuff == NULL) {
668 pathbuff = get_pathbuff();
669 pathbuff_len = MAXPATHLEN;
670
671 pathbuff[0] = '\0';
672 if ((ret = vn_getpath(vp, pathbuff, &pathbuff_len)) != 0 || pathbuff[0] == '\0') {
673
674 cur->flags |= KFSE_CONTAINS_DROPPED_EVENTS;
675
676 do {
677 if (vp->v_parent != NULL) {
678 vp = vp->v_parent;
679 } else if (vp->v_mount) {
680 strlcpy(pathbuff, vp->v_mount->mnt_vfsstat.f_mntonname, MAXPATHLEN);
681 break;
682 } else {
683 vp = NULL;
684 }
685
686 if (vp == NULL) {
687 break;
688 }
689
690 pathbuff_len = MAXPATHLEN;
691 ret = vn_getpath(vp, pathbuff, &pathbuff_len);
692 } while (ret == ENOSPC);
693
694 if (ret != 0 || vp == NULL) {
695 error = ENOENT;
696 goto clean_up;
697 }
698 }
699 }
700
701 // store the path by adding it to the global string table
702 cur->len = pathbuff_len;
703 cur->str = vfs_addname(pathbuff, pathbuff_len, 0, 0);
704 if (cur->str == NULL || cur->str[0] == '\0') {
705 panic("add_fsevent: was not able to add path %s to event %p.\n", pathbuff, cur);
706 }
707
708 release_pathbuff(pathbuff);
709 pathbuff = NULL;
710
711 break;
712 }
713
714 case FSE_ARG_FINFO: {
715 fse_info *fse;
716
717 fse = va_arg(ap, fse_info *);
718
719 cur->dev = dev = (dev_t)fse->dev;
720 cur->ino = (ino64_t)fse->ino;
721 cur->mode = (int32_t)fse->mode;
722 cur->uid = (uid_t)fse->uid;
723 cur->gid = (uid_t)fse->gid;
724 // if it's a hard-link and this is the last link, flag it
725 if ((fse->mode & FSE_MODE_HLINK) && fse->nlink == 0) {
726 cur->mode |= FSE_MODE_LAST_HLINK;
727 }
728 if (cur->mode & FSE_TRUNCATED_PATH) {
729 cur->flags |= KFSE_CONTAINS_DROPPED_EVENTS;
730 cur->mode &= ~FSE_TRUNCATED_PATH;
731 }
732 break;
733 }
734
735 case FSE_ARG_STRING:
736 if (kfse->str != NULL) {
737 cur = kfse_dest;
738 }
739
740 cur->len = (int16_t)(va_arg(ap, int32_t) & 0x7fff);
741 if (cur->len >= 1) {
742 cur->str = vfs_addname(va_arg(ap, char *), cur->len, 0, 0);
743 } else {
744 printf("add_fsevent: funny looking string length: %d\n", (int)cur->len);
745 cur->len = 2;
746 cur->str = vfs_addname("/", cur->len, 0, 0);
747 }
748 if (cur->str[0] == 0) {
749 printf("add_fsevent: bogus looking string (len %d)\n", cur->len);
750 }
751 break;
752
753 case FSE_ARG_INT32: {
754 uint32_t ival = (uint32_t)va_arg(ap, int32_t);
755 kfse->uid = (ino64_t)ival;
756 break;
757 }
758
759 default:
760 printf("add_fsevent: unknown type %d\n", arg_type);
761 // just skip one 32-bit word and hope we sync up...
762 (void)va_arg(ap, int32_t);
763 }
764
765 done_with_args:
766 va_end(ap);
767
768 OSBitAndAtomic16(~KFSE_BEING_CREATED, &kfse->flags);
769 if (kfse_dest) {
770 OSBitAndAtomic16(~KFSE_BEING_CREATED, &kfse_dest->flags);
771 }
772
773 //
774 // now we have to go and let everyone know that
775 // is interested in this type of event
776 //
777 lock_watch_table();
778
779 for(i=0; i < MAX_WATCHERS; i++) {
780 watcher = watcher_table[i];
781 if (watcher == NULL) {
782 continue;
783 }
784
785 if ( type < watcher->num_events
786 && watcher->event_list[type] == FSE_REPORT
787 && watcher_cares_about_dev(watcher, dev)) {
788
789 if (watcher_add_event(watcher, kfse) != 0) {
790 watcher->num_dropped++;
791 continue;
792 }
793 }
794
795 // if (kfse->refcount < 1) {
796 // panic("add_fsevent: line %d: kfse recount %d but should be at least 1\n", __LINE__, kfse->refcount);
797 // }
798 }
799
800 unlock_watch_table();
801
802 clean_up:
803
804 if (pathbuff) {
805 release_pathbuff(pathbuff);
806 pathbuff = NULL;
807 }
808
809 release_event_ref(kfse);
810
811 return error;
812 }
813
814
815 static void
816 release_event_ref(kfs_event *kfse)
817 {
818 int old_refcount;
819 kfs_event copy, dest_copy;
820
821
822 old_refcount = OSAddAtomic(-1, &kfse->refcount);
823 if (old_refcount > 1) {
824 return;
825 }
826
827 lock_fs_event_list();
828 if (last_event_ptr == kfse) {
829 last_event_ptr = NULL;
830 last_event_type = -1;
831 last_coalesced_time = 0;
832 }
833
834 if (kfse->refcount < 0) {
835 panic("release_event_ref: bogus kfse refcount %d\n", kfse->refcount);
836 }
837
838 if (kfse->refcount > 0 || kfse->type == FSE_INVALID) {
839 // This is very subtle. Either of these conditions can
840 // be true if an event got recycled while we were waiting
841 // on the fs_event_list lock or the event got recycled,
842 // delivered, _and_ free'd by someone else while we were
843 // waiting on the fs event list lock. In either case
844 // we need to just unlock the list and return without
845 // doing anything because if the refcount is > 0 then
846 // someone else will take care of free'ing it and when
847 // the kfse->type is invalid then someone else already
848 // has handled free'ing the event (while we were blocked
849 // on the event list lock).
850 //
851 unlock_fs_event_list();
852 return;
853 }
854
855 //
856 // make a copy of this so we can free things without
857 // holding the fs_event_buf lock
858 //
859 copy = *kfse;
860 if (kfse->dest && OSAddAtomic(-1, &kfse->dest->refcount) == 1) {
861 dest_copy = *kfse->dest;
862 } else {
863 dest_copy.str = NULL;
864 dest_copy.len = 0;
865 dest_copy.type = FSE_INVALID;
866 }
867
868 kfse->pid = kfse->type; // save this off for debugging...
869 kfse->uid = (uid_t)(long)kfse->str; // save this off for debugging...
870 kfse->gid = (gid_t)(long)current_thread();
871
872 kfse->str = (char *)0xdeadbeef; // XXXdbg - catch any cheaters...
873
874 if (dest_copy.type != FSE_INVALID) {
875 kfse->dest->str = (char *)0xbadc0de; // XXXdbg - catch any cheaters...
876 kfse->dest->type = FSE_INVALID;
877
878 if (kfse->dest->kevent_list.le_prev != NULL) {
879 num_events_outstanding--;
880 LIST_REMOVE(kfse->dest, kevent_list);
881 memset(&kfse->dest->kevent_list, 0xa5, sizeof(kfse->dest->kevent_list));
882 }
883
884 zfree(event_zone, kfse->dest);
885 }
886
887 // mark this fsevent as invalid
888 {
889 int otype;
890
891 otype = kfse->type;
892 kfse->type = FSE_INVALID;
893
894 if (kfse->kevent_list.le_prev != NULL) {
895 num_events_outstanding--;
896 if (otype == FSE_RENAME) {
897 num_pending_rename--;
898 }
899 LIST_REMOVE(kfse, kevent_list);
900 memset(&kfse->kevent_list, 0, sizeof(kfse->kevent_list));
901 }
902 }
903
904 zfree(event_zone, kfse);
905
906 unlock_fs_event_list();
907
908 // if we have a pointer in the union
909 if (copy.str && copy.type != FSE_DOCID_CHANGED) {
910 if (copy.len == 0) { // and it's not a string
911 panic("%s:%d: no more fref.vp!\n", __FILE__, __LINE__);
912 // vnode_rele_ext(copy.fref.vp, O_EVTONLY, 0);
913 } else { // else it's a string
914 vfs_removename(copy.str);
915 }
916 }
917
918 if (dest_copy.type != FSE_INVALID && dest_copy.str) {
919 if (dest_copy.len == 0) {
920 panic("%s:%d: no more fref.vp!\n", __FILE__, __LINE__);
921 // vnode_rele_ext(dest_copy.fref.vp, O_EVTONLY, 0);
922 } else {
923 vfs_removename(dest_copy.str);
924 }
925 }
926 }
927
928 static int
929 add_watcher(int8_t *event_list, int32_t num_events, int32_t eventq_size, fs_event_watcher **watcher_out, void *fseh)
930 {
931 int i;
932 fs_event_watcher *watcher;
933
934 if (eventq_size <= 0 || eventq_size > 100*max_kfs_events) {
935 eventq_size = max_kfs_events;
936 }
937
938 // Note: the event_queue follows the fs_event_watcher struct
939 // in memory so we only have to do one allocation
940 MALLOC(watcher,
941 fs_event_watcher *,
942 sizeof(fs_event_watcher) + eventq_size * sizeof(kfs_event *),
943 M_TEMP, M_WAITOK);
944 if (watcher == NULL) {
945 return ENOMEM;
946 }
947
948 watcher->event_list = event_list;
949 watcher->num_events = num_events;
950 watcher->devices_not_to_watch = NULL;
951 watcher->num_devices = 0;
952 watcher->flags = 0;
953 watcher->event_queue = (kfs_event **)&watcher[1];
954 watcher->eventq_size = eventq_size;
955 watcher->rd = 0;
956 watcher->wr = 0;
957 watcher->blockers = 0;
958 watcher->num_readers = 0;
959 watcher->max_event_id = 0;
960 watcher->fseh = fseh;
961 watcher->pid = proc_selfpid();
962 proc_selfname(watcher->proc_name, sizeof(watcher->proc_name));
963
964 watcher->num_dropped = 0; // XXXdbg - debugging
965
966 if (!strncmp(watcher->proc_name, "fseventsd", sizeof(watcher->proc_name)) ||
967 !strncmp(watcher->proc_name, "coreservicesd", sizeof(watcher->proc_name)) ||
968 !strncmp(watcher->proc_name, "mds", sizeof(watcher->proc_name))) {
969 watcher->flags |= WATCHER_APPLE_SYSTEM_SERVICE;
970 } else {
971 printf("fsevents: watcher %s (pid: %d) - Using /dev/fsevents directly is unsupported. Migrate to FSEventsFramework\n",
972 watcher->proc_name, watcher->pid);
973 }
974
975 lock_watch_table();
976
977 // find a slot for the new watcher
978 for(i=0; i < MAX_WATCHERS; i++) {
979 if (watcher_table[i] == NULL) {
980 watcher->my_id = i;
981 watcher_table[i] = watcher;
982 break;
983 }
984 }
985
986 if (i >= MAX_WATCHERS) {
987 printf("fsevents: too many watchers!\n");
988 unlock_watch_table();
989 FREE(watcher, M_TEMP);
990 return ENOSPC;
991 }
992
993 // now update the global list of who's interested in
994 // events of a particular type...
995 for(i=0; i < num_events; i++) {
996 if (event_list[i] != FSE_IGNORE && i < FSE_MAX_EVENTS) {
997 fs_event_type_watchers[i]++;
998 }
999 }
1000
1001 unlock_watch_table();
1002
1003 *watcher_out = watcher;
1004
1005 return 0;
1006 }
1007
1008
1009
1010 static void
1011 remove_watcher(fs_event_watcher *target)
1012 {
1013 int i, j, counter=0;
1014 fs_event_watcher *watcher;
1015 kfs_event *kfse;
1016
1017 lock_watch_table();
1018
1019 for(j=0; j < MAX_WATCHERS; j++) {
1020 watcher = watcher_table[j];
1021 if (watcher != target) {
1022 continue;
1023 }
1024
1025 watcher_table[j] = NULL;
1026
1027 for(i=0; i < watcher->num_events; i++) {
1028 if (watcher->event_list[i] != FSE_IGNORE && i < FSE_MAX_EVENTS) {
1029 fs_event_type_watchers[i]--;
1030 }
1031 }
1032
1033 if (watcher->flags & WATCHER_CLOSING) {
1034 unlock_watch_table();
1035 return;
1036 }
1037
1038 // 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);
1039 watcher->flags |= WATCHER_CLOSING;
1040 OSAddAtomic(1, &watcher->num_readers);
1041
1042 unlock_watch_table();
1043
1044 while (watcher->num_readers > 1 && counter++ < 5000) {
1045 lock_watch_table();
1046 fsevents_wakeup(watcher); // in case they're asleep
1047 unlock_watch_table();
1048
1049 tsleep(watcher, PRIBIO, "fsevents-close", 1);
1050 }
1051 if (counter++ >= 5000) {
1052 // printf("fsevents: close: still have readers! (%d)\n", watcher->num_readers);
1053 panic("fsevents: close: still have readers! (%d)\n", watcher->num_readers);
1054 }
1055
1056 // drain the event_queue
1057
1058 lck_rw_lock_exclusive(&event_handling_lock);
1059 while(watcher->rd != watcher->wr) {
1060 kfse = watcher->event_queue[watcher->rd];
1061 watcher->event_queue[watcher->rd] = NULL;
1062 watcher->rd = (watcher->rd+1) % watcher->eventq_size;
1063 OSSynchronizeIO();
1064 if (kfse != NULL && kfse->type != FSE_INVALID && kfse->refcount >= 1) {
1065 release_event_ref(kfse);
1066 }
1067 }
1068 lck_rw_unlock_exclusive(&event_handling_lock);
1069
1070 if (watcher->event_list) {
1071 FREE(watcher->event_list, M_TEMP);
1072 watcher->event_list = NULL;
1073 }
1074 if (watcher->devices_not_to_watch) {
1075 FREE(watcher->devices_not_to_watch, M_TEMP);
1076 watcher->devices_not_to_watch = NULL;
1077 }
1078 FREE(watcher, M_TEMP);
1079
1080 return;
1081 }
1082
1083 unlock_watch_table();
1084 }
1085
1086
1087 #define EVENT_DELAY_IN_MS 10
1088 static thread_call_t event_delivery_timer = NULL;
1089 static int timer_set = 0;
1090
1091
1092 static void
1093 delayed_event_delivery(__unused void *param0, __unused void *param1)
1094 {
1095 int i;
1096
1097 lock_watch_table();
1098
1099 for(i=0; i < MAX_WATCHERS; i++) {
1100 if (watcher_table[i] != NULL && watcher_table[i]->rd != watcher_table[i]->wr) {
1101 fsevents_wakeup(watcher_table[i]);
1102 }
1103 }
1104
1105 timer_set = 0;
1106
1107 unlock_watch_table();
1108 }
1109
1110
1111 //
1112 // The watch table must be locked before calling this function.
1113 //
1114 static void
1115 schedule_event_wakeup(void)
1116 {
1117 uint64_t deadline;
1118
1119 if (event_delivery_timer == NULL) {
1120 event_delivery_timer = thread_call_allocate((thread_call_func_t)delayed_event_delivery, NULL);
1121 }
1122
1123 clock_interval_to_deadline(EVENT_DELAY_IN_MS, 1000 * 1000, &deadline);
1124
1125 thread_call_enter_delayed(event_delivery_timer, deadline);
1126 timer_set = 1;
1127 }
1128
1129
1130
1131 #define MAX_NUM_PENDING 16
1132
1133 //
1134 // NOTE: the watch table must be locked before calling
1135 // this routine.
1136 //
1137 static int
1138 watcher_add_event(fs_event_watcher *watcher, kfs_event *kfse)
1139 {
1140 if (kfse->abstime > watcher->max_event_id) {
1141 watcher->max_event_id = kfse->abstime;
1142 }
1143
1144 if (((watcher->wr + 1) % watcher->eventq_size) == watcher->rd) {
1145 watcher->flags |= WATCHER_DROPPED_EVENTS;
1146 fsevents_wakeup(watcher);
1147 return ENOSPC;
1148 }
1149
1150 OSAddAtomic(1, &kfse->refcount);
1151 watcher->event_queue[watcher->wr] = kfse;
1152 OSSynchronizeIO();
1153 watcher->wr = (watcher->wr + 1) % watcher->eventq_size;
1154
1155 //
1156 // wake up the watcher if there are more than MAX_NUM_PENDING events.
1157 // otherwise schedule a timer (if one isn't already set) which will
1158 // send any pending events if no more are received in the next
1159 // EVENT_DELAY_IN_MS milli-seconds.
1160 //
1161 int32_t num_pending = 0;
1162 if (watcher->rd < watcher->wr) {
1163 num_pending = watcher->wr - watcher->rd;
1164 }
1165
1166 if (watcher->rd > watcher->wr) {
1167 num_pending = watcher->wr + watcher->eventq_size - watcher->rd;
1168 }
1169
1170 if (num_pending > (watcher->eventq_size*3/4) && !(watcher->flags & WATCHER_APPLE_SYSTEM_SERVICE)) {
1171 /* Non-Apple Service is falling behind, start dropping events for this process */
1172 lck_rw_lock_exclusive(&event_handling_lock);
1173 while (watcher->rd != watcher->wr) {
1174 kfse = watcher->event_queue[watcher->rd];
1175 watcher->event_queue[watcher->rd] = NULL;
1176 watcher->rd = (watcher->rd+1) % watcher->eventq_size;
1177 OSSynchronizeIO();
1178 if (kfse != NULL && kfse->type != FSE_INVALID && kfse->refcount >= 1) {
1179 release_event_ref(kfse);
1180 }
1181 }
1182 watcher->flags |= WATCHER_DROPPED_EVENTS;
1183 lck_rw_unlock_exclusive(&event_handling_lock);
1184
1185 printf("fsevents: watcher falling behind: %s (pid: %d) rd: %4d wr: %4d q_size: %4d flags: 0x%x\n",
1186 watcher->proc_name, watcher->pid, watcher->rd, watcher->wr,
1187 watcher->eventq_size, watcher->flags);
1188
1189 fsevents_wakeup(watcher);
1190 } else if (num_pending > MAX_NUM_PENDING) {
1191 fsevents_wakeup(watcher);
1192 } else if (timer_set == 0) {
1193 schedule_event_wakeup();
1194 }
1195
1196 return 0;
1197 }
1198
1199 static int
1200 fill_buff(uint16_t type, int32_t size, const void *data,
1201 char *buff, int32_t *_buff_idx, int32_t buff_sz,
1202 struct uio *uio)
1203 {
1204 int32_t amt, error = 0, buff_idx = *_buff_idx;
1205 uint16_t tmp;
1206
1207 //
1208 // the +1 on the size is to guarantee that the main data
1209 // copy loop will always copy at least 1 byte
1210 //
1211 if ((buff_sz - buff_idx) <= (int)(2*sizeof(uint16_t) + 1)) {
1212 if (buff_idx > uio_resid(uio)) {
1213 error = ENOSPC;
1214 goto get_out;
1215 }
1216
1217 error = uiomove(buff, buff_idx, uio);
1218 if (error) {
1219 goto get_out;
1220 }
1221 buff_idx = 0;
1222 }
1223
1224 // copy out the header (type & size)
1225 memcpy(&buff[buff_idx], &type, sizeof(uint16_t));
1226 buff_idx += sizeof(uint16_t);
1227
1228 tmp = size & 0xffff;
1229 memcpy(&buff[buff_idx], &tmp, sizeof(uint16_t));
1230 buff_idx += sizeof(uint16_t);
1231
1232 // now copy the body of the data, flushing along the way
1233 // if the buffer fills up.
1234 //
1235 while(size > 0) {
1236 amt = (size < (buff_sz - buff_idx)) ? size : (buff_sz - buff_idx);
1237 memcpy(&buff[buff_idx], data, amt);
1238
1239 size -= amt;
1240 buff_idx += amt;
1241 data = (const char *)data + amt;
1242 if (size > (buff_sz - buff_idx)) {
1243 if (buff_idx > uio_resid(uio)) {
1244 error = ENOSPC;
1245 goto get_out;
1246 }
1247 error = uiomove(buff, buff_idx, uio);
1248 if (error) {
1249 goto get_out;
1250 }
1251 buff_idx = 0;
1252 }
1253
1254 if (amt == 0) { // just in case...
1255 break;
1256 }
1257 }
1258
1259 get_out:
1260 *_buff_idx = buff_idx;
1261
1262 return error;
1263 }
1264
1265
1266 static int copy_out_kfse(fs_event_watcher *watcher, kfs_event *kfse, struct uio *uio) __attribute__((noinline));
1267
1268 static int
1269 copy_out_kfse(fs_event_watcher *watcher, kfs_event *kfse, struct uio *uio)
1270 {
1271 int error;
1272 uint16_t tmp16;
1273 int32_t type;
1274 kfs_event *cur;
1275 char evbuff[512];
1276 int evbuff_idx = 0;
1277
1278 if (kfse->type == FSE_INVALID) {
1279 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);
1280 }
1281
1282 if (kfse->flags & KFSE_BEING_CREATED) {
1283 return 0;
1284 }
1285
1286 if (kfse->type == FSE_RENAME && kfse->dest == NULL) {
1287 //
1288 // This can happen if an event gets recycled but we had a
1289 // pointer to it in our event queue. The event is the
1290 // destination of a rename which we'll process separately
1291 // (that is, another kfse points to this one so it's ok
1292 // to skip this guy because we'll process it when we process
1293 // the other one)
1294 error = 0;
1295 goto get_out;
1296 }
1297
1298 if (watcher->flags & WATCHER_WANTS_EXTENDED_INFO) {
1299
1300 type = (kfse->type & 0xfff);
1301
1302 if (kfse->flags & KFSE_CONTAINS_DROPPED_EVENTS) {
1303 type |= (FSE_CONTAINS_DROPPED_EVENTS << FSE_FLAG_SHIFT);
1304 } else if (kfse->flags & KFSE_COMBINED_EVENTS) {
1305 type |= (FSE_COMBINED_EVENTS << FSE_FLAG_SHIFT);
1306 }
1307
1308 } else {
1309 type = (int32_t)kfse->type;
1310 }
1311
1312 // copy out the type of the event
1313 memcpy(evbuff, &type, sizeof(int32_t));
1314 evbuff_idx += sizeof(int32_t);
1315
1316 // copy out the pid of the person that generated the event
1317 memcpy(&evbuff[evbuff_idx], &kfse->pid, sizeof(pid_t));
1318 evbuff_idx += sizeof(pid_t);
1319
1320 cur = kfse;
1321
1322 copy_again:
1323
1324 if (kfse->type == FSE_DOCID_CHANGED || kfse->type == FSE_DOCID_CREATED) {
1325 dev_t dev = cur->dev;
1326 ino_t ino = cur->ino;
1327 uint64_t ival;
1328
1329 error = fill_buff(FSE_ARG_DEV, sizeof(dev_t), &dev, evbuff, &evbuff_idx, sizeof(evbuff), uio);
1330 if (error != 0) {
1331 goto get_out;
1332 }
1333
1334 error = fill_buff(FSE_ARG_INO, sizeof(ino_t), &ino, evbuff, &evbuff_idx, sizeof(evbuff), uio);
1335 if (error != 0) {
1336 goto get_out;
1337 }
1338
1339 memcpy(&ino, &cur->str, sizeof(ino_t));
1340 error = fill_buff(FSE_ARG_INO, sizeof(ino_t), &ino, evbuff, &evbuff_idx, sizeof(evbuff), uio);
1341 if (error != 0) {
1342 goto get_out;
1343 }
1344
1345 memcpy(&ival, &cur->uid, sizeof(uint64_t)); // the docid gets stuffed into the ino field
1346 error = fill_buff(FSE_ARG_INT64, sizeof(uint64_t), &ival, evbuff, &evbuff_idx, sizeof(evbuff), uio);
1347 if (error != 0) {
1348 goto get_out;
1349 }
1350
1351 goto done;
1352 }
1353
1354 if (cur->str == NULL || cur->str[0] == '\0') {
1355 printf("copy_out_kfse:2: empty/short path (%s)\n", cur->str);
1356 error = fill_buff(FSE_ARG_STRING, 2, "/", evbuff, &evbuff_idx, sizeof(evbuff), uio);
1357 } else {
1358 error = fill_buff(FSE_ARG_STRING, cur->len, cur->str, evbuff, &evbuff_idx, sizeof(evbuff), uio);
1359 }
1360 if (error != 0) {
1361 goto get_out;
1362 }
1363
1364 if (cur->dev == 0 && cur->ino == 0) {
1365 // this happens when a rename event happens and the
1366 // destination of the rename did not previously exist.
1367 // it thus has no other file info so skip copying out
1368 // the stuff below since it isn't initialized
1369 goto done;
1370 }
1371
1372
1373 if (watcher->flags & WATCHER_WANTS_COMPACT_EVENTS) {
1374 int32_t finfo_size;
1375
1376 finfo_size = sizeof(dev_t) + sizeof(ino64_t) + sizeof(int32_t) + sizeof(uid_t) + sizeof(gid_t);
1377 error = fill_buff(FSE_ARG_FINFO, finfo_size, &cur->ino, evbuff, &evbuff_idx, sizeof(evbuff), uio);
1378 if (error != 0) {
1379 goto get_out;
1380 }
1381 } else {
1382 ino_t ino;
1383
1384 error = fill_buff(FSE_ARG_DEV, sizeof(dev_t), &cur->dev, evbuff, &evbuff_idx, sizeof(evbuff), uio);
1385 if (error != 0) {
1386 goto get_out;
1387 }
1388
1389 ino = (ino_t)cur->ino;
1390 error = fill_buff(FSE_ARG_INO, sizeof(ino_t), &ino, evbuff, &evbuff_idx, sizeof(evbuff), uio);
1391 if (error != 0) {
1392 goto get_out;
1393 }
1394
1395 error = fill_buff(FSE_ARG_MODE, sizeof(int32_t), &cur->mode, evbuff, &evbuff_idx, sizeof(evbuff), uio);
1396 if (error != 0) {
1397 goto get_out;
1398 }
1399
1400 error = fill_buff(FSE_ARG_UID, sizeof(uid_t), &cur->uid, evbuff, &evbuff_idx, sizeof(evbuff), uio);
1401 if (error != 0) {
1402 goto get_out;
1403 }
1404
1405 error = fill_buff(FSE_ARG_GID, sizeof(gid_t), &cur->gid, evbuff, &evbuff_idx, sizeof(evbuff), uio);
1406 if (error != 0) {
1407 goto get_out;
1408 }
1409 }
1410
1411
1412 if (cur->dest) {
1413 cur = cur->dest;
1414 goto copy_again;
1415 }
1416
1417 done:
1418 // very last thing: the time stamp
1419 error = fill_buff(FSE_ARG_INT64, sizeof(uint64_t), &cur->abstime, evbuff, &evbuff_idx, sizeof(evbuff), uio);
1420 if (error != 0) {
1421 goto get_out;
1422 }
1423
1424 // check if the FSE_ARG_DONE will fit
1425 if (sizeof(uint16_t) > sizeof(evbuff) - evbuff_idx) {
1426 if (evbuff_idx > uio_resid(uio)) {
1427 error = ENOSPC;
1428 goto get_out;
1429 }
1430 error = uiomove(evbuff, evbuff_idx, uio);
1431 if (error) {
1432 goto get_out;
1433 }
1434 evbuff_idx = 0;
1435 }
1436
1437 tmp16 = FSE_ARG_DONE;
1438 memcpy(&evbuff[evbuff_idx], &tmp16, sizeof(uint16_t));
1439 evbuff_idx += sizeof(uint16_t);
1440
1441 // flush any remaining data in the buffer (and hopefully
1442 // in most cases this is the only uiomove we'll do)
1443 if (evbuff_idx > uio_resid(uio)) {
1444 error = ENOSPC;
1445 } else {
1446 error = uiomove(evbuff, evbuff_idx, uio);
1447 }
1448
1449 get_out:
1450
1451 return error;
1452 }
1453
1454
1455
1456 static int
1457 fmod_watch(fs_event_watcher *watcher, struct uio *uio)
1458 {
1459 int error=0;
1460 user_ssize_t last_full_event_resid;
1461 kfs_event *kfse;
1462 uint16_t tmp16;
1463 int skipped;
1464
1465 last_full_event_resid = uio_resid(uio);
1466
1467 // need at least 2048 bytes of space (maxpathlen + 1 event buf)
1468 if (uio_resid(uio) < 2048 || watcher == NULL) {
1469 return EINVAL;
1470 }
1471
1472 if (watcher->flags & WATCHER_CLOSING) {
1473 return 0;
1474 }
1475
1476 if (OSAddAtomic(1, &watcher->num_readers) != 0) {
1477 // don't allow multiple threads to read from the fd at the same time
1478 OSAddAtomic(-1, &watcher->num_readers);
1479 return EAGAIN;
1480 }
1481
1482 restart_watch:
1483 if (watcher->rd == watcher->wr) {
1484 if (watcher->flags & WATCHER_CLOSING) {
1485 OSAddAtomic(-1, &watcher->num_readers);
1486 return 0;
1487 }
1488 OSAddAtomic(1, &watcher->blockers);
1489
1490 // there's nothing to do, go to sleep
1491 error = tsleep((caddr_t)watcher, PUSER|PCATCH, "fsevents_empty", 0);
1492
1493 OSAddAtomic(-1, &watcher->blockers);
1494
1495 if (error != 0 || (watcher->flags & WATCHER_CLOSING)) {
1496 OSAddAtomic(-1, &watcher->num_readers);
1497 return error;
1498 }
1499 }
1500
1501 // if we dropped events, return that as an event first
1502 if (watcher->flags & WATCHER_DROPPED_EVENTS) {
1503 int32_t val = FSE_EVENTS_DROPPED;
1504
1505 error = uiomove((caddr_t)&val, sizeof(int32_t), uio);
1506 if (error == 0) {
1507 val = 0; // a fake pid
1508 error = uiomove((caddr_t)&val, sizeof(int32_t), uio);
1509
1510 tmp16 = FSE_ARG_DONE; // makes it a consistent msg
1511 error = uiomove((caddr_t)&tmp16, sizeof(int16_t), uio);
1512
1513 last_full_event_resid = uio_resid(uio);
1514 }
1515
1516 if (error) {
1517 OSAddAtomic(-1, &watcher->num_readers);
1518 return error;
1519 }
1520
1521 watcher->flags &= ~WATCHER_DROPPED_EVENTS;
1522 }
1523
1524 skipped = 0;
1525
1526 lck_rw_lock_shared(&event_handling_lock);
1527 while (uio_resid(uio) > 0 && watcher->rd != watcher->wr) {
1528 if (watcher->flags & WATCHER_CLOSING) {
1529 break;
1530 }
1531
1532 //
1533 // check if the event is something of interest to us
1534 // (since it may have been recycled/reused and changed
1535 // its type or which device it is for)
1536 //
1537 kfse = watcher->event_queue[watcher->rd];
1538 if (!kfse || kfse->type == FSE_INVALID || kfse->type >= watcher->num_events || kfse->refcount < 1) {
1539 break;
1540 }
1541
1542 if (watcher->event_list[kfse->type] == FSE_REPORT && watcher_cares_about_dev(watcher, kfse->dev)) {
1543
1544 if (!(watcher->flags & WATCHER_APPLE_SYSTEM_SERVICE) && kfse->type != FSE_DOCID_CHANGED && is_ignored_directory(kfse->str)) {
1545 // If this is not an Apple System Service, skip specified directories
1546 // radar://12034844
1547 error = 0;
1548 skipped = 1;
1549 } else {
1550
1551 skipped = 0;
1552 if (last_event_ptr == kfse) {
1553 last_event_ptr = NULL;
1554 last_event_type = -1;
1555 last_coalesced_time = 0;
1556 }
1557 error = copy_out_kfse(watcher, kfse, uio);
1558 if (error != 0) {
1559 // if an event won't fit or encountered an error while
1560 // we were copying it out, then backup to the last full
1561 // event and just bail out. if the error was ENOENT
1562 // then we can continue regular processing, otherwise
1563 // we should unlock things and return.
1564 uio_setresid(uio, last_full_event_resid);
1565 if (error != ENOENT) {
1566 lck_rw_unlock_shared(&event_handling_lock);
1567 error = 0;
1568 goto get_out;
1569 }
1570 }
1571
1572 last_full_event_resid = uio_resid(uio);
1573 }
1574 }
1575
1576 watcher->event_queue[watcher->rd] = NULL;
1577 watcher->rd = (watcher->rd + 1) % watcher->eventq_size;
1578 OSSynchronizeIO();
1579 release_event_ref(kfse);
1580 }
1581 lck_rw_unlock_shared(&event_handling_lock);
1582
1583 if (skipped && error == 0) {
1584 goto restart_watch;
1585 }
1586
1587 get_out:
1588 OSAddAtomic(-1, &watcher->num_readers);
1589
1590 return error;
1591 }
1592
1593
1594 // release any references we might have on vnodes which are
1595 // the mount point passed to us (so that it can be cleanly
1596 // unmounted).
1597 //
1598 // since we don't want to lose the events we'll convert the
1599 // vnode refs to full paths.
1600 //
1601 void
1602 fsevent_unmount(__unused struct mount *mp)
1603 {
1604 // we no longer maintain pointers to vnodes so
1605 // there is nothing to do...
1606 }
1607
1608
1609 //
1610 // /dev/fsevents device code
1611 //
1612 static int fsevents_installed = 0;
1613
1614 typedef struct fsevent_handle {
1615 UInt32 flags;
1616 SInt32 active;
1617 fs_event_watcher *watcher;
1618 struct klist knotes;
1619 struct selinfo si;
1620 } fsevent_handle;
1621
1622 #define FSEH_CLOSING 0x0001
1623
1624 static int
1625 fseventsf_read(struct fileproc *fp, struct uio *uio,
1626 __unused int flags, __unused vfs_context_t ctx)
1627 {
1628 fsevent_handle *fseh = (struct fsevent_handle *)fp->f_fglob->fg_data;
1629 int error;
1630
1631 error = fmod_watch(fseh->watcher, uio);
1632
1633 return error;
1634 }
1635
1636
1637 static int
1638 fseventsf_write(__unused struct fileproc *fp, __unused struct uio *uio,
1639 __unused int flags, __unused vfs_context_t ctx)
1640 {
1641 return EIO;
1642 }
1643
1644 #pragma pack(push, 4)
1645 typedef struct fsevent_dev_filter_args32 {
1646 uint32_t num_devices;
1647 user32_addr_t devices;
1648 } fsevent_dev_filter_args32;
1649 typedef struct fsevent_dev_filter_args64 {
1650 uint32_t num_devices;
1651 user64_addr_t devices;
1652 } fsevent_dev_filter_args64;
1653 #pragma pack(pop)
1654
1655 #define FSEVENTS_DEVICE_FILTER_32 _IOW('s', 100, fsevent_dev_filter_args32)
1656 #define FSEVENTS_DEVICE_FILTER_64 _IOW('s', 100, fsevent_dev_filter_args64)
1657
1658 static int
1659 fseventsf_ioctl(struct fileproc *fp, u_long cmd, caddr_t data, vfs_context_t ctx)
1660 {
1661 fsevent_handle *fseh = (struct fsevent_handle *)fp->f_fglob->fg_data;
1662 int ret = 0;
1663 fsevent_dev_filter_args64 *devfilt_args, _devfilt_args;
1664
1665 OSAddAtomic(1, &fseh->active);
1666 if (fseh->flags & FSEH_CLOSING) {
1667 OSAddAtomic(-1, &fseh->active);
1668 return 0;
1669 }
1670
1671 switch (cmd) {
1672 case FIONBIO:
1673 case FIOASYNC:
1674 break;
1675
1676 case FSEVENTS_WANT_COMPACT_EVENTS: {
1677 fseh->watcher->flags |= WATCHER_WANTS_COMPACT_EVENTS;
1678 break;
1679 }
1680
1681 case FSEVENTS_WANT_EXTENDED_INFO: {
1682 fseh->watcher->flags |= WATCHER_WANTS_EXTENDED_INFO;
1683 break;
1684 }
1685
1686 case FSEVENTS_GET_CURRENT_ID: {
1687 *(uint64_t *)data = fseh->watcher->max_event_id;
1688 ret = 0;
1689 break;
1690 }
1691
1692 case FSEVENTS_DEVICE_FILTER_32: {
1693 if (proc_is64bit(vfs_context_proc(ctx))) {
1694 ret = EINVAL;
1695 break;
1696 }
1697 fsevent_dev_filter_args32 *devfilt_args32 = (fsevent_dev_filter_args32 *)data;
1698
1699 devfilt_args = &_devfilt_args;
1700 memset(devfilt_args, 0, sizeof(fsevent_dev_filter_args64));
1701 devfilt_args->num_devices = devfilt_args32->num_devices;
1702 devfilt_args->devices = CAST_USER_ADDR_T(devfilt_args32->devices);
1703 goto handle_dev_filter;
1704 }
1705
1706 case FSEVENTS_DEVICE_FILTER_64:
1707 if (!proc_is64bit(vfs_context_proc(ctx))) {
1708 ret = EINVAL;
1709 break;
1710 }
1711 devfilt_args = (fsevent_dev_filter_args64 *)data;
1712
1713 handle_dev_filter:
1714 {
1715 int new_num_devices;
1716 dev_t *devices_not_to_watch, *tmp=NULL;
1717
1718 if (devfilt_args->num_devices > 256) {
1719 ret = EINVAL;
1720 break;
1721 }
1722
1723 new_num_devices = devfilt_args->num_devices;
1724 if (new_num_devices == 0) {
1725 tmp = fseh->watcher->devices_not_to_watch;
1726
1727 lock_watch_table();
1728 fseh->watcher->devices_not_to_watch = NULL;
1729 fseh->watcher->num_devices = new_num_devices;
1730 unlock_watch_table();
1731
1732 if (tmp) {
1733 FREE(tmp, M_TEMP);
1734 }
1735 break;
1736 }
1737
1738 MALLOC(devices_not_to_watch, dev_t *,
1739 new_num_devices * sizeof(dev_t),
1740 M_TEMP, M_WAITOK);
1741 if (devices_not_to_watch == NULL) {
1742 ret = ENOMEM;
1743 break;
1744 }
1745
1746 ret = copyin(devfilt_args->devices,
1747 (void *)devices_not_to_watch,
1748 new_num_devices * sizeof(dev_t));
1749 if (ret) {
1750 FREE(devices_not_to_watch, M_TEMP);
1751 break;
1752 }
1753
1754 lock_watch_table();
1755 fseh->watcher->num_devices = new_num_devices;
1756 tmp = fseh->watcher->devices_not_to_watch;
1757 fseh->watcher->devices_not_to_watch = devices_not_to_watch;
1758 unlock_watch_table();
1759
1760 if (tmp) {
1761 FREE(tmp, M_TEMP);
1762 }
1763
1764 break;
1765 }
1766
1767 default:
1768 ret = EINVAL;
1769 break;
1770 }
1771
1772 OSAddAtomic(-1, &fseh->active);
1773 return (ret);
1774 }
1775
1776
1777 static int
1778 fseventsf_select(struct fileproc *fp, int which, __unused void *wql, vfs_context_t ctx)
1779 {
1780 fsevent_handle *fseh = (struct fsevent_handle *)fp->f_fglob->fg_data;
1781 int ready = 0;
1782
1783 if ((which != FREAD) || (fseh->watcher->flags & WATCHER_CLOSING)) {
1784 return 0;
1785 }
1786
1787
1788 // if there's nothing in the queue, we're not ready
1789 if (fseh->watcher->rd != fseh->watcher->wr) {
1790 ready = 1;
1791 }
1792
1793 if (!ready) {
1794 selrecord(vfs_context_proc(ctx), &fseh->si, wql);
1795 }
1796
1797 return ready;
1798 }
1799
1800
1801 #if NOTUSED
1802 static int
1803 fseventsf_stat(__unused struct fileproc *fp, __unused struct stat *sb, __unused vfs_context_t ctx)
1804 {
1805 return ENOTSUP;
1806 }
1807 #endif
1808
1809 static int
1810 fseventsf_close(struct fileglob *fg, __unused vfs_context_t ctx)
1811 {
1812 fsevent_handle *fseh = (struct fsevent_handle *)fg->fg_data;
1813 fs_event_watcher *watcher;
1814
1815 OSBitOrAtomic(FSEH_CLOSING, &fseh->flags);
1816 while (OSAddAtomic(0, &fseh->active) > 0) {
1817 tsleep((caddr_t)fseh->watcher, PRIBIO, "fsevents-close", 1);
1818 }
1819
1820 watcher = fseh->watcher;
1821 fg->fg_data = NULL;
1822 fseh->watcher = NULL;
1823
1824 remove_watcher(watcher);
1825 FREE(fseh, M_TEMP);
1826
1827 return 0;
1828 }
1829
1830 static void
1831 filt_fsevent_detach(struct knote *kn)
1832 {
1833 fsevent_handle *fseh = (struct fsevent_handle *)kn->kn_hook;
1834
1835 lock_watch_table();
1836
1837 KNOTE_DETACH(&fseh->knotes, kn);
1838
1839 unlock_watch_table();
1840 }
1841
1842 /*
1843 * Determine whether this knote should be active
1844 *
1845 * This is kind of subtle.
1846 * --First, notice if the vnode has been revoked: in so, override hint
1847 * --EVFILT_READ knotes are checked no matter what the hint is
1848 * --Other knotes activate based on hint.
1849 * --If hint is revoke, set special flags and activate
1850 */
1851 static int
1852 filt_fsevent(struct knote *kn, long hint)
1853 {
1854 fsevent_handle *fseh = (struct fsevent_handle *)kn->kn_hook;
1855 int activate = 0;
1856 int32_t rd, wr, amt;
1857
1858 if (NOTE_REVOKE == hint) {
1859 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
1860 activate = 1;
1861 }
1862
1863 rd = fseh->watcher->rd;
1864 wr = fseh->watcher->wr;
1865 if (rd <= wr) {
1866 amt = wr - rd;
1867 } else {
1868 amt = fseh->watcher->eventq_size - (rd - wr);
1869 }
1870
1871 switch(kn->kn_filter) {
1872 case EVFILT_READ:
1873 kn->kn_data = amt;
1874
1875 if (kn->kn_data != 0) {
1876 activate = 1;
1877 }
1878 break;
1879 case EVFILT_VNODE:
1880 /* Check events this note matches against the hint */
1881 if (kn->kn_sfflags & hint) {
1882 kn->kn_fflags |= hint; /* Set which event occurred */
1883 }
1884 if (kn->kn_fflags != 0) {
1885 activate = 1;
1886 }
1887 break;
1888 default: {
1889 // nothing to do...
1890 break;
1891 }
1892 }
1893
1894 return (activate);
1895 }
1896
1897
1898 static int
1899 filt_fsevent_touch(struct knote *kn, struct kevent_internal_s *kev)
1900 {
1901 int res;
1902
1903 lock_watch_table();
1904
1905 /* accept new fflags/data as saved */
1906 kn->kn_sfflags = kev->fflags;
1907 kn->kn_sdata = kev->data;
1908 if ((kn->kn_status & KN_UDATA_SPECIFIC) == 0)
1909 kn->kn_udata = kev->udata;
1910
1911 /* restrict the current results to the (smaller?) set of new interest */
1912 /*
1913 * For compatibility with previous implementations, we leave kn_fflags
1914 * as they were before.
1915 */
1916 //kn->kn_fflags &= kev->fflags;
1917
1918 /* determine if the filter is now fired */
1919 res = filt_fsevent(kn, 0);
1920
1921 unlock_watch_table();
1922
1923 return res;
1924 }
1925
1926 static int
1927 filt_fsevent_process(struct knote *kn, struct filt_process_s *data, struct kevent_internal_s *kev)
1928 {
1929 #pragma unused(data)
1930 int res;
1931
1932 lock_watch_table();
1933
1934 res = filt_fsevent(kn, 0);
1935 if (res) {
1936 *kev = kn->kn_kevent;
1937 if (kev->flags & EV_CLEAR) {
1938 kn->kn_data = 0;
1939 kn->kn_fflags = 0;
1940 }
1941 }
1942
1943 unlock_watch_table();
1944 return res;
1945 }
1946
1947 struct filterops fsevent_filtops = {
1948 .f_isfd = 1,
1949 .f_attach = NULL,
1950 .f_detach = filt_fsevent_detach,
1951 .f_event = filt_fsevent,
1952 .f_touch = filt_fsevent_touch,
1953 .f_process = filt_fsevent_process,
1954 };
1955
1956 static int
1957 fseventsf_kqfilter(__unused struct fileproc *fp, __unused struct knote *kn, __unused vfs_context_t ctx)
1958 {
1959 fsevent_handle *fseh = (struct fsevent_handle *)fp->f_fglob->fg_data;
1960 int res;
1961
1962 kn->kn_hook = (void*)fseh;
1963 kn->kn_hookid = 1;
1964 kn->kn_filtid = EVFILTID_FSEVENT;
1965
1966 lock_watch_table();
1967
1968 KNOTE_ATTACH(&fseh->knotes, kn);
1969
1970 /* check to see if it is fired already */
1971 res = filt_fsevent(kn, 0);
1972
1973 unlock_watch_table();
1974
1975 return res;
1976 }
1977
1978
1979 static int
1980 fseventsf_drain(struct fileproc *fp, __unused vfs_context_t ctx)
1981 {
1982 int counter = 0;
1983 fsevent_handle *fseh = (struct fsevent_handle *)fp->f_fglob->fg_data;
1984
1985 fseh->watcher->flags |= WATCHER_CLOSING;
1986
1987 // if there are people still waiting, sleep for 10ms to
1988 // let them clean up and get out of there. however we
1989 // also don't want to get stuck forever so if they don't
1990 // exit after 5 seconds we're tearing things down anyway.
1991 while(fseh->watcher->blockers && counter++ < 500) {
1992 // issue wakeup in case anyone is blocked waiting for an event
1993 // do this each time we wakeup in case the blocker missed
1994 // the wakeup due to the unprotected test of WATCHER_CLOSING
1995 // and decision to tsleep in fmod_watch... this bit of
1996 // latency is a decent tradeoff against not having to
1997 // take and drop a lock in fmod_watch
1998 lock_watch_table();
1999 fsevents_wakeup(fseh->watcher);
2000 unlock_watch_table();
2001
2002 tsleep((caddr_t)fseh->watcher, PRIBIO, "watcher-close", 1);
2003 }
2004
2005 return 0;
2006 }
2007
2008
2009 static int
2010 fseventsopen(__unused dev_t dev, __unused int flag, __unused int mode, __unused struct proc *p)
2011 {
2012 if (!kauth_cred_issuser(kauth_cred_get())) {
2013 return EPERM;
2014 }
2015
2016 return 0;
2017 }
2018
2019 static int
2020 fseventsclose(__unused dev_t dev, __unused int flag, __unused int mode, __unused struct proc *p)
2021 {
2022 return 0;
2023 }
2024
2025 static int
2026 fseventsread(__unused dev_t dev, __unused struct uio *uio, __unused int ioflag)
2027 {
2028 return EIO;
2029 }
2030
2031
2032 static int
2033 parse_buffer_and_add_events(const char *buffer, int bufsize, vfs_context_t ctx, long *remainder)
2034 {
2035 const fse_info *finfo, *dest_finfo;
2036 const char *path, *ptr, *dest_path, *event_start=buffer;
2037 int path_len, type, dest_path_len, err = 0;
2038
2039
2040 ptr = buffer;
2041 while ((ptr+sizeof(int)+sizeof(fse_info)+1) < buffer+bufsize) {
2042 type = *(const int *)ptr;
2043 if (type < 0 || type >= FSE_MAX_EVENTS) {
2044 err = EINVAL;
2045 break;
2046 }
2047
2048 ptr += sizeof(int);
2049
2050 finfo = (const fse_info *)ptr;
2051 ptr += sizeof(fse_info);
2052
2053 path = ptr;
2054 while(ptr < buffer+bufsize && *ptr != '\0') {
2055 ptr++;
2056 }
2057
2058 if (ptr >= buffer+bufsize) {
2059 break;
2060 }
2061
2062 ptr++; // advance over the trailing '\0'
2063
2064 path_len = ptr - path;
2065
2066 if (type != FSE_RENAME && type != FSE_EXCHANGE) {
2067 event_start = ptr; // record where the next event starts
2068
2069 err = add_fsevent(type, ctx, FSE_ARG_STRING, path_len, path, FSE_ARG_FINFO, finfo, FSE_ARG_DONE);
2070 if (err) {
2071 break;
2072 }
2073 continue;
2074 }
2075
2076 //
2077 // if we're here we have to slurp up the destination finfo
2078 // and path so that we can pass them to the add_fsevent()
2079 // call. basically it's a copy of the above code.
2080 //
2081 dest_finfo = (const fse_info *)ptr;
2082 ptr += sizeof(fse_info);
2083
2084 dest_path = ptr;
2085 while(ptr < buffer+bufsize && *ptr != '\0') {
2086 ptr++;
2087 }
2088
2089 if (ptr >= buffer+bufsize) {
2090 break;
2091 }
2092
2093 ptr++; // advance over the trailing '\0'
2094 event_start = ptr; // record where the next event starts
2095
2096 dest_path_len = ptr - dest_path;
2097 //
2098 // If the destination inode number is non-zero, generate a rename
2099 // with both source and destination FSE_ARG_FINFO. Otherwise generate
2100 // a rename with only one FSE_ARG_FINFO. If you need to inject an
2101 // exchange with an inode of zero, just make that inode (and its path)
2102 // come in as the first one, not the second.
2103 //
2104 if (dest_finfo->ino) {
2105 err = add_fsevent(type, ctx,
2106 FSE_ARG_STRING, path_len, path, FSE_ARG_FINFO, finfo,
2107 FSE_ARG_STRING, dest_path_len, dest_path, FSE_ARG_FINFO, dest_finfo,
2108 FSE_ARG_DONE);
2109 } else {
2110 err = add_fsevent(type, ctx,
2111 FSE_ARG_STRING, path_len, path, FSE_ARG_FINFO, finfo,
2112 FSE_ARG_STRING, dest_path_len, dest_path,
2113 FSE_ARG_DONE);
2114 }
2115
2116 if (err) {
2117 break;
2118 }
2119
2120 }
2121
2122 // if the last event wasn't complete, set the remainder
2123 // to be the last event start boundary.
2124 //
2125 *remainder = (long)((buffer+bufsize) - event_start);
2126
2127 return err;
2128 }
2129
2130
2131 //
2132 // Note: this buffer size can not ever be less than
2133 // 2*MAXPATHLEN + 2*sizeof(fse_info) + sizeof(int)
2134 // because that is the max size for a single event.
2135 // I made it 4k to be a "nice" size. making it
2136 // smaller is not a good idea.
2137 //
2138 #define WRITE_BUFFER_SIZE 4096
2139 char *write_buffer=NULL;
2140
2141 static int
2142 fseventswrite(__unused dev_t dev, struct uio *uio, __unused int ioflag)
2143 {
2144 int error=0, count;
2145 vfs_context_t ctx = vfs_context_current();
2146 long offset=0, remainder;
2147
2148 lck_mtx_lock(&event_writer_lock);
2149
2150 if (write_buffer == NULL) {
2151 if (kmem_alloc(kernel_map, (vm_offset_t *)&write_buffer, WRITE_BUFFER_SIZE, VM_KERN_MEMORY_FILE)) {
2152 lck_mtx_unlock(&event_writer_lock);
2153 return ENOMEM;
2154 }
2155 }
2156
2157 //
2158 // this loop copies in and processes the events written.
2159 // it takes care to copy in reasonable size chunks and
2160 // process them. if there is an event that spans a chunk
2161 // boundary we're careful to copy those bytes down to the
2162 // beginning of the buffer and read the next chunk in just
2163 // after it.
2164 //
2165 while(uio_resid(uio)) {
2166 if (uio_resid(uio) > (WRITE_BUFFER_SIZE-offset)) {
2167 count = WRITE_BUFFER_SIZE - offset;
2168 } else {
2169 count = uio_resid(uio);
2170 }
2171
2172 error = uiomove(write_buffer+offset, count, uio);
2173 if (error) {
2174 break;
2175 }
2176
2177 // printf("fsevents: write: copied in %d bytes (offset: %ld)\n", count, offset);
2178 error = parse_buffer_and_add_events(write_buffer, offset+count, ctx, &remainder);
2179 if (error) {
2180 break;
2181 }
2182
2183 //
2184 // if there's any remainder, copy it down to the beginning
2185 // of the buffer so that it will get processed the next time
2186 // through the loop. note that the remainder always starts
2187 // at an event boundary.
2188 //
2189 if (remainder != 0) {
2190 // printf("fsevents: write: an event spanned a %d byte boundary. remainder: %ld\n",
2191 // WRITE_BUFFER_SIZE, remainder);
2192 memmove(write_buffer, (write_buffer+count+offset) - remainder, remainder);
2193 offset = remainder;
2194 } else {
2195 offset = 0;
2196 }
2197 }
2198
2199 lck_mtx_unlock(&event_writer_lock);
2200
2201 return error;
2202 }
2203
2204
2205 static const struct fileops fsevents_fops = {
2206 .fo_type = DTYPE_FSEVENTS,
2207 .fo_read = fseventsf_read,
2208 .fo_write = fseventsf_write,
2209 .fo_ioctl = fseventsf_ioctl,
2210 .fo_select = fseventsf_select,
2211 .fo_close = fseventsf_close,
2212 .fo_kqfilter = fseventsf_kqfilter,
2213 .fo_drain = fseventsf_drain,
2214 };
2215
2216 typedef struct fsevent_clone_args32 {
2217 user32_addr_t event_list;
2218 int32_t num_events;
2219 int32_t event_queue_depth;
2220 user32_addr_t fd;
2221 } fsevent_clone_args32;
2222
2223 typedef struct fsevent_clone_args64 {
2224 user64_addr_t event_list;
2225 int32_t num_events;
2226 int32_t event_queue_depth;
2227 user64_addr_t fd;
2228 } fsevent_clone_args64;
2229
2230 #define FSEVENTS_CLONE_32 _IOW('s', 1, fsevent_clone_args32)
2231 #define FSEVENTS_CLONE_64 _IOW('s', 1, fsevent_clone_args64)
2232
2233 static int
2234 fseventsioctl(__unused dev_t dev, u_long cmd, caddr_t data, __unused int flag, struct proc *p)
2235 {
2236 struct fileproc *f;
2237 int fd, error;
2238 fsevent_handle *fseh = NULL;
2239 fsevent_clone_args64 *fse_clone_args, _fse_clone;
2240 int8_t *event_list;
2241 int is64bit = proc_is64bit(p);
2242
2243 switch (cmd) {
2244 case FSEVENTS_CLONE_32: {
2245 if (is64bit) {
2246 return EINVAL;
2247 }
2248 fsevent_clone_args32 *args32 = (fsevent_clone_args32 *)data;
2249
2250 fse_clone_args = &_fse_clone;
2251 memset(fse_clone_args, 0, sizeof(fsevent_clone_args64));
2252
2253 fse_clone_args->event_list = CAST_USER_ADDR_T(args32->event_list);
2254 fse_clone_args->num_events = args32->num_events;
2255 fse_clone_args->event_queue_depth = args32->event_queue_depth;
2256 fse_clone_args->fd = CAST_USER_ADDR_T(args32->fd);
2257 goto handle_clone;
2258 }
2259
2260 case FSEVENTS_CLONE_64:
2261 if (!is64bit) {
2262 return EINVAL;
2263 }
2264 fse_clone_args = (fsevent_clone_args64 *)data;
2265
2266 handle_clone:
2267 if (fse_clone_args->num_events < 0 || fse_clone_args->num_events > 4096) {
2268 return EINVAL;
2269 }
2270
2271 MALLOC(fseh, fsevent_handle *, sizeof(fsevent_handle),
2272 M_TEMP, M_WAITOK);
2273 if (fseh == NULL) {
2274 return ENOMEM;
2275 }
2276 memset(fseh, 0, sizeof(fsevent_handle));
2277
2278 klist_init(&fseh->knotes);
2279
2280 MALLOC(event_list, int8_t *,
2281 fse_clone_args->num_events * sizeof(int8_t),
2282 M_TEMP, M_WAITOK);
2283 if (event_list == NULL) {
2284 FREE(fseh, M_TEMP);
2285 return ENOMEM;
2286 }
2287
2288 error = copyin(fse_clone_args->event_list,
2289 (void *)event_list,
2290 fse_clone_args->num_events * sizeof(int8_t));
2291 if (error) {
2292 FREE(event_list, M_TEMP);
2293 FREE(fseh, M_TEMP);
2294 return error;
2295 }
2296
2297 error = add_watcher(event_list,
2298 fse_clone_args->num_events,
2299 fse_clone_args->event_queue_depth,
2300 &fseh->watcher,
2301 fseh);
2302 if (error) {
2303 FREE(event_list, M_TEMP);
2304 FREE(fseh, M_TEMP);
2305 return error;
2306 }
2307
2308 fseh->watcher->fseh = fseh;
2309
2310 error = falloc(p, &f, &fd, vfs_context_current());
2311 if (error) {
2312 remove_watcher(fseh->watcher);
2313 FREE(event_list, M_TEMP);
2314 FREE(fseh, M_TEMP);
2315 return (error);
2316 }
2317 proc_fdlock(p);
2318 f->f_fglob->fg_flag = FREAD | FWRITE;
2319 f->f_fglob->fg_ops = &fsevents_fops;
2320 f->f_fglob->fg_data = (caddr_t) fseh;
2321 proc_fdunlock(p);
2322 error = copyout((void *)&fd, fse_clone_args->fd, sizeof(int32_t));
2323 if (error != 0) {
2324 fp_free(p, fd, f);
2325 } else {
2326 proc_fdlock(p);
2327 procfdtbl_releasefd(p, fd, NULL);
2328 fp_drop(p, fd, f, 1);
2329 proc_fdunlock(p);
2330 }
2331 break;
2332
2333 default:
2334 error = EINVAL;
2335 break;
2336 }
2337
2338 return error;
2339 }
2340
2341 static void
2342 fsevents_wakeup(fs_event_watcher *watcher)
2343 {
2344 selwakeup(&watcher->fseh->si);
2345 KNOTE(&watcher->fseh->knotes, NOTE_WRITE|NOTE_NONE);
2346 wakeup((caddr_t)watcher);
2347 }
2348
2349
2350 /*
2351 * A struct describing which functions will get invoked for certain
2352 * actions.
2353 */
2354 static struct cdevsw fsevents_cdevsw =
2355 {
2356 fseventsopen, /* open */
2357 fseventsclose, /* close */
2358 fseventsread, /* read */
2359 fseventswrite, /* write */
2360 fseventsioctl, /* ioctl */
2361 (stop_fcn_t *)&nulldev, /* stop */
2362 (reset_fcn_t *)&nulldev, /* reset */
2363 NULL, /* tty's */
2364 eno_select, /* select */
2365 eno_mmap, /* mmap */
2366 eno_strat, /* strategy */
2367 eno_getc, /* getc */
2368 eno_putc, /* putc */
2369 0 /* type */
2370 };
2371
2372
2373 /*
2374 * Called to initialize our device,
2375 * and to register ourselves with devfs
2376 */
2377
2378 void
2379 fsevents_init(void)
2380 {
2381 int ret;
2382
2383 if (fsevents_installed) {
2384 return;
2385 }
2386
2387 fsevents_installed = 1;
2388
2389 ret = cdevsw_add(-1, &fsevents_cdevsw);
2390 if (ret < 0) {
2391 fsevents_installed = 0;
2392 return;
2393 }
2394
2395 devfs_make_node(makedev (ret, 0), DEVFS_CHAR,
2396 UID_ROOT, GID_WHEEL, 0644, "fsevents", 0);
2397
2398 fsevents_internal_init();
2399 }
2400
2401
2402 char *
2403 get_pathbuff(void)
2404 {
2405 char *path;
2406
2407 MALLOC_ZONE(path, char *, MAXPATHLEN, M_NAMEI, M_WAITOK);
2408 return path;
2409 }
2410
2411 void
2412 release_pathbuff(char *path)
2413 {
2414
2415 if (path == NULL) {
2416 return;
2417 }
2418 FREE_ZONE(path, MAXPATHLEN, M_NAMEI);
2419 }
2420
2421 int
2422 get_fse_info(struct vnode *vp, fse_info *fse, __unused vfs_context_t ctx)
2423 {
2424 struct vnode_attr va;
2425
2426 VATTR_INIT(&va);
2427 VATTR_WANTED(&va, va_fsid);
2428 VATTR_WANTED(&va, va_fileid);
2429 VATTR_WANTED(&va, va_mode);
2430 VATTR_WANTED(&va, va_uid);
2431 VATTR_WANTED(&va, va_gid);
2432 if (vp->v_flag & VISHARDLINK) {
2433 if (vp->v_type == VDIR) {
2434 VATTR_WANTED(&va, va_dirlinkcount);
2435 } else {
2436 VATTR_WANTED(&va, va_nlink);
2437 }
2438 }
2439
2440 if (vnode_getattr(vp, &va, vfs_context_kernel()) != 0) {
2441 memset(fse, 0, sizeof(fse_info));
2442 return -1;
2443 }
2444
2445 return vnode_get_fse_info_from_vap(vp, fse, &va);
2446 }
2447
2448 int
2449 vnode_get_fse_info_from_vap(vnode_t vp, fse_info *fse, struct vnode_attr *vap)
2450 {
2451 fse->ino = (ino64_t)vap->va_fileid;
2452 fse->dev = (dev_t)vap->va_fsid;
2453 fse->mode = (int32_t)vnode_vttoif(vnode_vtype(vp)) | vap->va_mode;
2454 fse->uid = (uid_t)vap->va_uid;
2455 fse->gid = (gid_t)vap->va_gid;
2456 if (vp->v_flag & VISHARDLINK) {
2457 fse->mode |= FSE_MODE_HLINK;
2458 if (vp->v_type == VDIR) {
2459 fse->nlink = (uint64_t)vap->va_dirlinkcount;
2460 } else {
2461 fse->nlink = (uint64_t)vap->va_nlink;
2462 }
2463 }
2464
2465 return 0;
2466 }
2467
2468 void
2469 create_fsevent_from_kevent(vnode_t vp, uint32_t kevents, struct vnode_attr *vap)
2470 {
2471 int fsevent_type=FSE_CONTENT_MODIFIED, len; // the default is the most pessimistic
2472 char pathbuf[MAXPATHLEN];
2473 fse_info fse;
2474
2475
2476 if (kevents & VNODE_EVENT_DELETE) {
2477 fsevent_type = FSE_DELETE;
2478 } else if (kevents & (VNODE_EVENT_EXTEND|VNODE_EVENT_WRITE)) {
2479 fsevent_type = FSE_CONTENT_MODIFIED;
2480 } else if (kevents & VNODE_EVENT_LINK) {
2481 fsevent_type = FSE_CREATE_FILE;
2482 } else if (kevents & VNODE_EVENT_RENAME) {
2483 fsevent_type = FSE_CREATE_FILE; // XXXdbg - should use FSE_RENAME but we don't have the destination info;
2484 } else if (kevents & (VNODE_EVENT_FILE_CREATED|VNODE_EVENT_FILE_REMOVED|VNODE_EVENT_DIR_CREATED|VNODE_EVENT_DIR_REMOVED)) {
2485 fsevent_type = FSE_STAT_CHANGED; // XXXdbg - because vp is a dir and the thing created/removed lived inside it
2486 } else { // a catch all for VNODE_EVENT_PERMS, VNODE_EVENT_ATTRIB and anything else
2487 fsevent_type = FSE_STAT_CHANGED;
2488 }
2489
2490 // printf("convert_kevent: kevents 0x%x fsevent type 0x%x (for %s)\n", kevents, fsevent_type, vp->v_name ? vp->v_name : "(no-name)");
2491
2492 fse.dev = vap->va_fsid;
2493 fse.ino = vap->va_fileid;
2494 fse.mode = vnode_vttoif(vnode_vtype(vp)) | (uint32_t)vap->va_mode;
2495 if (vp->v_flag & VISHARDLINK) {
2496 fse.mode |= FSE_MODE_HLINK;
2497 if (vp->v_type == VDIR) {
2498 fse.nlink = vap->va_dirlinkcount;
2499 } else {
2500 fse.nlink = vap->va_nlink;
2501 }
2502 }
2503
2504 if (vp->v_type == VDIR) {
2505 fse.mode |= FSE_REMOTE_DIR_EVENT;
2506 }
2507
2508
2509 fse.uid = vap->va_uid;
2510 fse.gid = vap->va_gid;
2511
2512 len = sizeof(pathbuf);
2513 if (vn_getpath(vp, pathbuf, &len) == 0) {
2514 add_fsevent(fsevent_type, vfs_context_current(), FSE_ARG_STRING, len, pathbuf, FSE_ARG_FINFO, &fse, FSE_ARG_DONE);
2515 }
2516 return;
2517 }
2518
2519 #else /* CONFIG_FSE */
2520
2521 #include <sys/fsevents.h>
2522
2523 /*
2524 * The get_pathbuff and release_pathbuff routines are used in places not
2525 * related to fsevents, and it's a handy abstraction, so define trivial
2526 * versions that don't cache a pool of buffers. This way, we don't have
2527 * to conditionalize the callers, and they still get the advantage of the
2528 * pool of buffers if CONFIG_FSE is turned on.
2529 */
2530 char *
2531 get_pathbuff(void)
2532 {
2533 char *path;
2534 MALLOC_ZONE(path, char *, MAXPATHLEN, M_NAMEI, M_WAITOK);
2535 return path;
2536 }
2537
2538 void
2539 release_pathbuff(char *path)
2540 {
2541 FREE_ZONE(path, MAXPATHLEN, M_NAMEI);
2542 }
2543
2544 int
2545 add_fsevent(__unused int type, __unused vfs_context_t ctx, ...)
2546 {
2547 return 0;
2548 }
2549
2550 int need_fsevent(__unused int type, __unused vnode_t vp)
2551 {
2552 return 0;
2553 }
2554
2555 #endif /* CONFIG_FSE */