]> git.saurik.com Git - apple/xnu.git/blob - bsd/vfs/vfs_fsevents.c
5c816aad5ce1bfcd5287932cea258381f2fa9237
[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 static int
169 is_ignored_directory(const char *path) {
170
171 if (!path) {
172 return 0;
173 }
174
175 #define IS_TLD(x) strnstr((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) {
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 for(ii=0; ii < MAX_WATCHERS; ii++) {
504 if (watcher_table[ii] == NULL) {
505 continue;
506 }
507
508 printf("add_fsevent: watcher %s %p: rd %4d wr %4d q_size %4d flags 0x%x\n",
509 watcher_table[ii]->proc_name,
510 watcher_table[ii],
511 watcher_table[ii]->rd, watcher_table[ii]->wr,
512 watcher_table[ii]->eventq_size, watcher_table[ii]->flags);
513 }
514
515 last_print = current_tv;
516 if (junkptr) {
517 zfree(event_zone, junkptr);
518 }
519 }
520 }
521
522 if (pathbuff) {
523 release_pathbuff(pathbuff);
524 pathbuff = NULL;
525 }
526 return ENOSPC;
527 }
528
529 memset(kfse, 0, sizeof(kfs_event));
530 kfse->refcount = 1;
531 OSBitOrAtomic16(KFSE_BEING_CREATED, &kfse->flags);
532
533 last_event_ptr = kfse;
534 kfse->type = type;
535 kfse->abstime = now;
536 kfse->pid = p->p_pid;
537 if (type == FSE_RENAME || type == FSE_EXCHANGE) {
538 memset(kfse_dest, 0, sizeof(kfs_event));
539 kfse_dest->refcount = 1;
540 OSBitOrAtomic16(KFSE_BEING_CREATED, &kfse_dest->flags);
541 kfse_dest->type = type;
542 kfse_dest->pid = p->p_pid;
543 kfse_dest->abstime = now;
544
545 kfse->dest = kfse_dest;
546 }
547
548 num_events_outstanding++;
549 if (kfse->type == FSE_RENAME) {
550 num_pending_rename++;
551 }
552 LIST_INSERT_HEAD(&kfse_list_head, kfse, kevent_list);
553
554 if (kfse->refcount < 1) {
555 panic("add_fsevent: line %d: kfse recount %d but should be at least 1\n", __LINE__, kfse->refcount);
556 }
557
558 unlock_fs_event_list(); // at this point it's safe to unlock
559
560 //
561 // now process the arguments passed in and copy them into
562 // the kfse
563 //
564
565 cur = kfse;
566 for(arg_type=va_arg(ap, int32_t); arg_type != FSE_ARG_DONE; arg_type=va_arg(ap, int32_t))
567
568 switch(arg_type) {
569 case FSE_ARG_VNODE: {
570 // this expands out into multiple arguments to the client
571 struct vnode *vp;
572 struct vnode_attr va;
573
574 if (kfse->str != NULL) {
575 cur = kfse_dest;
576 }
577
578 vp = va_arg(ap, struct vnode *);
579 if (vp == NULL) {
580 panic("add_fsevent: you can't pass me a NULL vnode ptr (type %d)!\n",
581 cur->type);
582 }
583
584 VATTR_INIT(&va);
585 VATTR_WANTED(&va, va_fsid);
586 VATTR_WANTED(&va, va_fileid);
587 VATTR_WANTED(&va, va_mode);
588 VATTR_WANTED(&va, va_uid);
589 VATTR_WANTED(&va, va_gid);
590 if ((ret = vnode_getattr(vp, &va, vfs_context_kernel())) != 0) {
591 // printf("add_fsevent: failed to getattr on vp %p (%d)\n", cur->fref.vp, ret);
592 cur->str = NULL;
593 error = EINVAL;
594 goto clean_up;
595 }
596
597 cur->dev = dev = (dev_t)va.va_fsid;
598 cur->ino = (ino64_t)va.va_fileid;
599 cur->mode = (int32_t)vnode_vttoif(vnode_vtype(vp)) | va.va_mode;
600 cur->uid = va.va_uid;
601 cur->gid = va.va_gid;
602
603 // if we haven't gotten the path yet, get it.
604 if (pathbuff == NULL) {
605 pathbuff = get_pathbuff();
606 pathbuff_len = MAXPATHLEN;
607
608 pathbuff[0] = '\0';
609 if ((ret = vn_getpath(vp, pathbuff, &pathbuff_len)) != 0 || pathbuff[0] == '\0') {
610
611 cur->flags |= KFSE_CONTAINS_DROPPED_EVENTS;
612
613 do {
614 if (vp->v_parent != NULL) {
615 vp = vp->v_parent;
616 } else if (vp->v_mount) {
617 strlcpy(pathbuff, vp->v_mount->mnt_vfsstat.f_mntonname, MAXPATHLEN);
618 break;
619 } else {
620 vp = NULL;
621 }
622
623 if (vp == NULL) {
624 break;
625 }
626
627 pathbuff_len = MAXPATHLEN;
628 ret = vn_getpath(vp, pathbuff, &pathbuff_len);
629 } while (ret == ENOSPC);
630
631 if (ret != 0 || vp == NULL) {
632 error = ENOENT;
633 goto clean_up;
634 }
635 }
636 }
637
638 // store the path by adding it to the global string table
639 cur->len = pathbuff_len;
640 cur->str = vfs_addname(pathbuff, pathbuff_len, 0, 0);
641 if (cur->str == NULL || cur->str[0] == '\0') {
642 panic("add_fsevent: was not able to add path %s to event %p.\n", pathbuff, cur);
643 }
644
645 release_pathbuff(pathbuff);
646 pathbuff = NULL;
647
648 break;
649 }
650
651 case FSE_ARG_FINFO: {
652 fse_info *fse;
653
654 fse = va_arg(ap, fse_info *);
655
656 cur->dev = dev = (dev_t)fse->dev;
657 cur->ino = (ino64_t)fse->ino;
658 cur->mode = (int32_t)fse->mode;
659 cur->uid = (uid_t)fse->uid;
660 cur->gid = (uid_t)fse->gid;
661 // if it's a hard-link and this is the last link, flag it
662 if ((fse->mode & FSE_MODE_HLINK) && fse->nlink == 0) {
663 cur->mode |= FSE_MODE_LAST_HLINK;
664 }
665 if (cur->mode & FSE_TRUNCATED_PATH) {
666 cur->flags |= KFSE_CONTAINS_DROPPED_EVENTS;
667 cur->mode &= ~FSE_TRUNCATED_PATH;
668 }
669 break;
670 }
671
672 case FSE_ARG_STRING:
673 if (kfse->str != NULL) {
674 cur = kfse_dest;
675 }
676
677 cur->len = (int16_t)(va_arg(ap, int32_t) & 0x7fff);
678 if (cur->len >= 1) {
679 cur->str = vfs_addname(va_arg(ap, char *), cur->len, 0, 0);
680 } else {
681 printf("add_fsevent: funny looking string length: %d\n", (int)cur->len);
682 cur->len = 2;
683 cur->str = vfs_addname("/", cur->len, 0, 0);
684 }
685 if (cur->str[0] == 0) {
686 printf("add_fsevent: bogus looking string (len %d)\n", cur->len);
687 }
688 break;
689
690 default:
691 printf("add_fsevent: unknown type %d\n", arg_type);
692 // just skip one 32-bit word and hope we sync up...
693 (void)va_arg(ap, int32_t);
694 }
695
696 va_end(ap);
697
698 OSBitAndAtomic16(~KFSE_BEING_CREATED, &kfse->flags);
699 if (kfse_dest) {
700 OSBitAndAtomic16(~KFSE_BEING_CREATED, &kfse_dest->flags);
701 }
702
703 //
704 // now we have to go and let everyone know that
705 // is interested in this type of event
706 //
707 lock_watch_table();
708
709 for(i=0; i < MAX_WATCHERS; i++) {
710 watcher = watcher_table[i];
711 if (watcher == NULL) {
712 continue;
713 }
714
715 if ( watcher->event_list[type] == FSE_REPORT
716 && watcher_cares_about_dev(watcher, dev)) {
717
718 if (watcher_add_event(watcher, kfse) != 0) {
719 watcher->num_dropped++;
720 continue;
721 }
722 }
723
724 // if (kfse->refcount < 1) {
725 // panic("add_fsevent: line %d: kfse recount %d but should be at least 1\n", __LINE__, kfse->refcount);
726 // }
727 }
728
729 unlock_watch_table();
730
731 clean_up:
732
733 if (pathbuff) {
734 release_pathbuff(pathbuff);
735 pathbuff = NULL;
736 }
737
738 release_event_ref(kfse);
739
740 return error;
741 }
742
743
744 static void
745 release_event_ref(kfs_event *kfse)
746 {
747 int old_refcount;
748 kfs_event copy, dest_copy;
749
750
751 old_refcount = OSAddAtomic(-1, &kfse->refcount);
752 if (old_refcount > 1) {
753 return;
754 }
755
756 lock_fs_event_list();
757 if (last_event_ptr == kfse) {
758 last_event_ptr = NULL;
759 last_event_type = -1;
760 last_coalesced_time = 0;
761 }
762
763 if (kfse->refcount < 0) {
764 panic("release_event_ref: bogus kfse refcount %d\n", kfse->refcount);
765 }
766
767 if (kfse->refcount > 0 || kfse->type == FSE_INVALID) {
768 // This is very subtle. Either of these conditions can
769 // be true if an event got recycled while we were waiting
770 // on the fs_event_list lock or the event got recycled,
771 // delivered, _and_ free'd by someone else while we were
772 // waiting on the fs event list lock. In either case
773 // we need to just unlock the list and return without
774 // doing anything because if the refcount is > 0 then
775 // someone else will take care of free'ing it and when
776 // the kfse->type is invalid then someone else already
777 // has handled free'ing the event (while we were blocked
778 // on the event list lock).
779 //
780 unlock_fs_event_list();
781 return;
782 }
783
784 //
785 // make a copy of this so we can free things without
786 // holding the fs_event_buf lock
787 //
788 copy = *kfse;
789 if (kfse->dest && OSAddAtomic(-1, &kfse->dest->refcount) == 1) {
790 dest_copy = *kfse->dest;
791 } else {
792 dest_copy.str = NULL;
793 dest_copy.len = 0;
794 dest_copy.type = FSE_INVALID;
795 }
796
797 kfse->pid = kfse->type; // save this off for debugging...
798 kfse->uid = (uid_t)(long)kfse->str; // save this off for debugging...
799 kfse->gid = (gid_t)(long)current_thread();
800
801 kfse->str = (char *)0xdeadbeef; // XXXdbg - catch any cheaters...
802
803 if (dest_copy.type != FSE_INVALID) {
804 kfse->dest->str = (char *)0xbadc0de; // XXXdbg - catch any cheaters...
805 kfse->dest->type = FSE_INVALID;
806
807 if (kfse->dest->kevent_list.le_prev != NULL) {
808 num_events_outstanding--;
809 LIST_REMOVE(kfse->dest, kevent_list);
810 memset(&kfse->dest->kevent_list, 0xa5, sizeof(kfse->dest->kevent_list));
811 }
812
813 zfree(event_zone, kfse->dest);
814 }
815
816 // mark this fsevent as invalid
817 {
818 int otype;
819
820 otype = kfse->type;
821 kfse->type = FSE_INVALID;
822
823 if (kfse->kevent_list.le_prev != NULL) {
824 num_events_outstanding--;
825 if (otype == FSE_RENAME) {
826 num_pending_rename--;
827 }
828 LIST_REMOVE(kfse, kevent_list);
829 memset(&kfse->kevent_list, 0, sizeof(kfse->kevent_list));
830 }
831 }
832
833 zfree(event_zone, kfse);
834
835 unlock_fs_event_list();
836
837 // if we have a pointer in the union
838 if (copy.str) {
839 if (copy.len == 0) { // and it's not a string
840 panic("%s:%d: no more fref.vp!\n", __FILE__, __LINE__);
841 // vnode_rele_ext(copy.fref.vp, O_EVTONLY, 0);
842 } else { // else it's a string
843 vfs_removename(copy.str);
844 }
845 }
846
847 if (dest_copy.type != FSE_INVALID && dest_copy.str) {
848 if (dest_copy.len == 0) {
849 panic("%s:%d: no more fref.vp!\n", __FILE__, __LINE__);
850 // vnode_rele_ext(dest_copy.fref.vp, O_EVTONLY, 0);
851 } else {
852 vfs_removename(dest_copy.str);
853 }
854 }
855 }
856
857 static int
858 add_watcher(int8_t *event_list, int32_t num_events, int32_t eventq_size, fs_event_watcher **watcher_out, void *fseh)
859 {
860 int i;
861 fs_event_watcher *watcher;
862
863 if (eventq_size <= 0 || eventq_size > 100*max_kfs_events) {
864 eventq_size = max_kfs_events;
865 }
866
867 // Note: the event_queue follows the fs_event_watcher struct
868 // in memory so we only have to do one allocation
869 MALLOC(watcher,
870 fs_event_watcher *,
871 sizeof(fs_event_watcher) + eventq_size * sizeof(kfs_event *),
872 M_TEMP, M_WAITOK);
873 if (watcher == NULL) {
874 return ENOMEM;
875 }
876
877 watcher->event_list = event_list;
878 watcher->num_events = num_events;
879 watcher->devices_not_to_watch = NULL;
880 watcher->num_devices = 0;
881 watcher->flags = 0;
882 watcher->event_queue = (kfs_event **)&watcher[1];
883 watcher->eventq_size = eventq_size;
884 watcher->rd = 0;
885 watcher->wr = 0;
886 watcher->blockers = 0;
887 watcher->num_readers = 0;
888 watcher->max_event_id = 0;
889 watcher->fseh = fseh;
890 watcher->pid = proc_selfpid();
891 proc_selfname(watcher->proc_name, sizeof(watcher->proc_name));
892
893 watcher->num_dropped = 0; // XXXdbg - debugging
894
895 if (!strncmp(watcher->proc_name, "fseventsd", sizeof(watcher->proc_name)) ||
896 !strncmp(watcher->proc_name, "coreservicesd", sizeof(watcher->proc_name)) ||
897 !strncmp(watcher->proc_name, "mds", sizeof(watcher->proc_name))) {
898 watcher->flags |= WATCHER_APPLE_SYSTEM_SERVICE;
899 } else {
900 printf("fsevents: watcher %s (pid: %d) - Using /dev/fsevents directly is unsupported. Migrate to FSEventsFramework\n",
901 watcher->proc_name, watcher->pid);
902 }
903
904 lock_watch_table();
905
906 // now update the global list of who's interested in
907 // events of a particular type...
908 for(i=0; i < num_events; i++) {
909 if (event_list[i] != FSE_IGNORE && i < FSE_MAX_EVENTS) {
910 fs_event_type_watchers[i]++;
911 }
912 }
913
914 for(i=0; i < MAX_WATCHERS; i++) {
915 if (watcher_table[i] == NULL) {
916 watcher->my_id = i;
917 watcher_table[i] = watcher;
918 break;
919 }
920 }
921
922 if (i > MAX_WATCHERS) {
923 printf("fsevents: too many watchers!\n");
924 unlock_watch_table();
925 return ENOSPC;
926 }
927
928 unlock_watch_table();
929
930 *watcher_out = watcher;
931
932 return 0;
933 }
934
935
936
937 static void
938 remove_watcher(fs_event_watcher *target)
939 {
940 int i, j, counter=0;
941 fs_event_watcher *watcher;
942 kfs_event *kfse;
943
944 lock_watch_table();
945
946 for(j=0; j < MAX_WATCHERS; j++) {
947 watcher = watcher_table[j];
948 if (watcher != target) {
949 continue;
950 }
951
952 watcher_table[j] = NULL;
953
954 for(i=0; i < watcher->num_events; i++) {
955 if (watcher->event_list[i] != FSE_IGNORE && i < FSE_MAX_EVENTS) {
956 fs_event_type_watchers[i]--;
957 }
958 }
959
960 if (watcher->flags & WATCHER_CLOSING) {
961 unlock_watch_table();
962 return;
963 }
964
965 // 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);
966 watcher->flags |= WATCHER_CLOSING;
967 OSAddAtomic(1, &watcher->num_readers);
968
969 unlock_watch_table();
970
971 while (watcher->num_readers > 1 && counter++ < 5000) {
972 lock_watch_table();
973 fsevents_wakeup(watcher); // in case they're asleep
974 unlock_watch_table();
975
976 tsleep(watcher, PRIBIO, "fsevents-close", 1);
977 }
978 if (counter++ >= 5000) {
979 // printf("fsevents: close: still have readers! (%d)\n", watcher->num_readers);
980 panic("fsevents: close: still have readers! (%d)\n", watcher->num_readers);
981 }
982
983 // drain the event_queue
984
985 lck_rw_lock_exclusive(&event_handling_lock);
986 while(watcher->rd != watcher->wr) {
987 kfse = watcher->event_queue[watcher->rd];
988 watcher->event_queue[watcher->rd] = NULL;
989 watcher->rd = (watcher->rd+1) % watcher->eventq_size;
990 OSSynchronizeIO();
991 if (kfse != NULL && kfse->type != FSE_INVALID && kfse->refcount >= 1) {
992 release_event_ref(kfse);
993 }
994 }
995 lck_rw_unlock_exclusive(&event_handling_lock);
996
997 if (watcher->event_list) {
998 FREE(watcher->event_list, M_TEMP);
999 watcher->event_list = NULL;
1000 }
1001 if (watcher->devices_not_to_watch) {
1002 FREE(watcher->devices_not_to_watch, M_TEMP);
1003 watcher->devices_not_to_watch = NULL;
1004 }
1005 FREE(watcher, M_TEMP);
1006
1007 return;
1008 }
1009
1010 unlock_watch_table();
1011 }
1012
1013
1014 #define EVENT_DELAY_IN_MS 10
1015 static thread_call_t event_delivery_timer = NULL;
1016 static int timer_set = 0;
1017
1018
1019 static void
1020 delayed_event_delivery(__unused void *param0, __unused void *param1)
1021 {
1022 int i;
1023
1024 lock_watch_table();
1025
1026 for(i=0; i < MAX_WATCHERS; i++) {
1027 if (watcher_table[i] != NULL && watcher_table[i]->rd != watcher_table[i]->wr) {
1028 fsevents_wakeup(watcher_table[i]);
1029 }
1030 }
1031
1032 timer_set = 0;
1033
1034 unlock_watch_table();
1035 }
1036
1037
1038 //
1039 // The watch table must be locked before calling this function.
1040 //
1041 static void
1042 schedule_event_wakeup(void)
1043 {
1044 uint64_t deadline;
1045
1046 if (event_delivery_timer == NULL) {
1047 event_delivery_timer = thread_call_allocate((thread_call_func_t)delayed_event_delivery, NULL);
1048 }
1049
1050 clock_interval_to_deadline(EVENT_DELAY_IN_MS, 1000 * 1000, &deadline);
1051
1052 thread_call_enter_delayed(event_delivery_timer, deadline);
1053 timer_set = 1;
1054 }
1055
1056
1057
1058 #define MAX_NUM_PENDING 16
1059
1060 //
1061 // NOTE: the watch table must be locked before calling
1062 // this routine.
1063 //
1064 static int
1065 watcher_add_event(fs_event_watcher *watcher, kfs_event *kfse)
1066 {
1067 if (kfse->abstime > watcher->max_event_id) {
1068 watcher->max_event_id = kfse->abstime;
1069 }
1070
1071 if (((watcher->wr + 1) % watcher->eventq_size) == watcher->rd) {
1072 watcher->flags |= WATCHER_DROPPED_EVENTS;
1073 fsevents_wakeup(watcher);
1074 return ENOSPC;
1075 }
1076
1077 OSAddAtomic(1, &kfse->refcount);
1078 watcher->event_queue[watcher->wr] = kfse;
1079 OSSynchronizeIO();
1080 watcher->wr = (watcher->wr + 1) % watcher->eventq_size;
1081
1082 //
1083 // wake up the watcher if there are more than MAX_NUM_PENDING events.
1084 // otherwise schedule a timer (if one isn't already set) which will
1085 // send any pending events if no more are received in the next
1086 // EVENT_DELAY_IN_MS milli-seconds.
1087 //
1088 int32_t num_pending = 0;
1089 if (watcher->rd < watcher->wr) {
1090 num_pending = watcher->wr - watcher->rd;
1091 }
1092
1093 if (watcher->rd > watcher->wr) {
1094 num_pending = watcher->wr + watcher->eventq_size - watcher->rd;
1095 }
1096
1097 if (num_pending > (watcher->eventq_size*3/4) && !(watcher->flags & WATCHER_APPLE_SYSTEM_SERVICE)) {
1098 /* Non-Apple Service is falling behind, start dropping events for this process */
1099 lck_rw_lock_exclusive(&event_handling_lock);
1100 while (watcher->rd != watcher->wr) {
1101 kfse = watcher->event_queue[watcher->rd];
1102 watcher->event_queue[watcher->rd] = NULL;
1103 watcher->rd = (watcher->rd+1) % watcher->eventq_size;
1104 OSSynchronizeIO();
1105 if (kfse != NULL && kfse->type != FSE_INVALID && kfse->refcount >= 1) {
1106 release_event_ref(kfse);
1107 }
1108 }
1109 watcher->flags |= WATCHER_DROPPED_EVENTS;
1110 lck_rw_unlock_exclusive(&event_handling_lock);
1111
1112 printf("fsevents: watcher falling behind: %s (pid: %d) rd: %4d wr: %4d q_size: %4d flags: 0x%x\n",
1113 watcher->proc_name, watcher->pid, watcher->rd, watcher->wr,
1114 watcher->eventq_size, watcher->flags);
1115
1116 fsevents_wakeup(watcher);
1117 } else if (num_pending > MAX_NUM_PENDING) {
1118 fsevents_wakeup(watcher);
1119 } else if (timer_set == 0) {
1120 schedule_event_wakeup();
1121 }
1122
1123 return 0;
1124 }
1125
1126 static int
1127 fill_buff(uint16_t type, int32_t size, const void *data,
1128 char *buff, int32_t *_buff_idx, int32_t buff_sz,
1129 struct uio *uio)
1130 {
1131 int32_t amt, error = 0, buff_idx = *_buff_idx;
1132 uint16_t tmp;
1133
1134 //
1135 // the +1 on the size is to guarantee that the main data
1136 // copy loop will always copy at least 1 byte
1137 //
1138 if ((buff_sz - buff_idx) <= (int)(2*sizeof(uint16_t) + 1)) {
1139 if (buff_idx > uio_resid(uio)) {
1140 error = ENOSPC;
1141 goto get_out;
1142 }
1143
1144 error = uiomove(buff, buff_idx, uio);
1145 if (error) {
1146 goto get_out;
1147 }
1148 buff_idx = 0;
1149 }
1150
1151 // copy out the header (type & size)
1152 memcpy(&buff[buff_idx], &type, sizeof(uint16_t));
1153 buff_idx += sizeof(uint16_t);
1154
1155 tmp = size & 0xffff;
1156 memcpy(&buff[buff_idx], &tmp, sizeof(uint16_t));
1157 buff_idx += sizeof(uint16_t);
1158
1159 // now copy the body of the data, flushing along the way
1160 // if the buffer fills up.
1161 //
1162 while(size > 0) {
1163 amt = (size < (buff_sz - buff_idx)) ? size : (buff_sz - buff_idx);
1164 memcpy(&buff[buff_idx], data, amt);
1165
1166 size -= amt;
1167 buff_idx += amt;
1168 data = (const char *)data + amt;
1169 if (size > (buff_sz - buff_idx)) {
1170 if (buff_idx > uio_resid(uio)) {
1171 error = ENOSPC;
1172 goto get_out;
1173 }
1174 error = uiomove(buff, buff_idx, uio);
1175 if (error) {
1176 goto get_out;
1177 }
1178 buff_idx = 0;
1179 }
1180
1181 if (amt == 0) { // just in case...
1182 break;
1183 }
1184 }
1185
1186 get_out:
1187 *_buff_idx = buff_idx;
1188
1189 return error;
1190 }
1191
1192
1193 static int copy_out_kfse(fs_event_watcher *watcher, kfs_event *kfse, struct uio *uio) __attribute__((noinline));
1194
1195 static int
1196 copy_out_kfse(fs_event_watcher *watcher, kfs_event *kfse, struct uio *uio)
1197 {
1198 int error;
1199 uint16_t tmp16;
1200 int32_t type;
1201 kfs_event *cur;
1202 char evbuff[512];
1203 int evbuff_idx = 0;
1204
1205 if (kfse->type == FSE_INVALID) {
1206 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);
1207 }
1208
1209 if (kfse->flags & KFSE_BEING_CREATED) {
1210 return 0;
1211 }
1212
1213 if (kfse->type == FSE_RENAME && kfse->dest == NULL) {
1214 //
1215 // This can happen if an event gets recycled but we had a
1216 // pointer to it in our event queue. The event is the
1217 // destination of a rename which we'll process separately
1218 // (that is, another kfse points to this one so it's ok
1219 // to skip this guy because we'll process it when we process
1220 // the other one)
1221 error = 0;
1222 goto get_out;
1223 }
1224
1225 if (watcher->flags & WATCHER_WANTS_EXTENDED_INFO) {
1226
1227 type = (kfse->type & 0xfff);
1228
1229 if (kfse->flags & KFSE_CONTAINS_DROPPED_EVENTS) {
1230 type |= (FSE_CONTAINS_DROPPED_EVENTS << FSE_FLAG_SHIFT);
1231 } else if (kfse->flags & KFSE_COMBINED_EVENTS) {
1232 type |= (FSE_COMBINED_EVENTS << FSE_FLAG_SHIFT);
1233 }
1234
1235 } else {
1236 type = (int32_t)kfse->type;
1237 }
1238
1239 // copy out the type of the event
1240 memcpy(evbuff, &type, sizeof(int32_t));
1241 evbuff_idx += sizeof(int32_t);
1242
1243 // copy out the pid of the person that generated the event
1244 memcpy(&evbuff[evbuff_idx], &kfse->pid, sizeof(pid_t));
1245 evbuff_idx += sizeof(pid_t);
1246
1247 cur = kfse;
1248
1249 copy_again:
1250
1251 if (cur->str == NULL || cur->str[0] == '\0') {
1252 printf("copy_out_kfse:2: empty/short path (%s)\n", cur->str);
1253 error = fill_buff(FSE_ARG_STRING, 2, "/", evbuff, &evbuff_idx, sizeof(evbuff), uio);
1254 } else {
1255 error = fill_buff(FSE_ARG_STRING, cur->len, cur->str, evbuff, &evbuff_idx, sizeof(evbuff), uio);
1256 }
1257 if (error != 0) {
1258 goto get_out;
1259 }
1260
1261 if (cur->dev == 0 && cur->ino == 0) {
1262 // this happens when a rename event happens and the
1263 // destination of the rename did not previously exist.
1264 // it thus has no other file info so skip copying out
1265 // the stuff below since it isn't initialized
1266 goto done;
1267 }
1268
1269
1270 if (watcher->flags & WATCHER_WANTS_COMPACT_EVENTS) {
1271 int32_t finfo_size;
1272
1273 finfo_size = sizeof(dev_t) + sizeof(ino64_t) + sizeof(int32_t) + sizeof(uid_t) + sizeof(gid_t);
1274 error = fill_buff(FSE_ARG_FINFO, finfo_size, &cur->ino, evbuff, &evbuff_idx, sizeof(evbuff), uio);
1275 if (error != 0) {
1276 goto get_out;
1277 }
1278 } else {
1279 ino_t ino;
1280
1281 error = fill_buff(FSE_ARG_DEV, sizeof(dev_t), &cur->dev, evbuff, &evbuff_idx, sizeof(evbuff), uio);
1282 if (error != 0) {
1283 goto get_out;
1284 }
1285
1286 ino = (ino_t)cur->ino;
1287 error = fill_buff(FSE_ARG_INO, sizeof(ino_t), &ino, evbuff, &evbuff_idx, sizeof(evbuff), uio);
1288 if (error != 0) {
1289 goto get_out;
1290 }
1291
1292 error = fill_buff(FSE_ARG_MODE, sizeof(int32_t), &cur->mode, evbuff, &evbuff_idx, sizeof(evbuff), uio);
1293 if (error != 0) {
1294 goto get_out;
1295 }
1296
1297 error = fill_buff(FSE_ARG_UID, sizeof(uid_t), &cur->uid, evbuff, &evbuff_idx, sizeof(evbuff), uio);
1298 if (error != 0) {
1299 goto get_out;
1300 }
1301
1302 error = fill_buff(FSE_ARG_GID, sizeof(gid_t), &cur->gid, evbuff, &evbuff_idx, sizeof(evbuff), uio);
1303 if (error != 0) {
1304 goto get_out;
1305 }
1306 }
1307
1308
1309 if (cur->dest) {
1310 cur = cur->dest;
1311 goto copy_again;
1312 }
1313
1314 done:
1315 // very last thing: the time stamp
1316 error = fill_buff(FSE_ARG_INT64, sizeof(uint64_t), &cur->abstime, evbuff, &evbuff_idx, sizeof(evbuff), uio);
1317 if (error != 0) {
1318 goto get_out;
1319 }
1320
1321 // check if the FSE_ARG_DONE will fit
1322 if (sizeof(uint16_t) > sizeof(evbuff) - evbuff_idx) {
1323 if (evbuff_idx > uio_resid(uio)) {
1324 error = ENOSPC;
1325 goto get_out;
1326 }
1327 error = uiomove(evbuff, evbuff_idx, uio);
1328 if (error) {
1329 goto get_out;
1330 }
1331 evbuff_idx = 0;
1332 }
1333
1334 tmp16 = FSE_ARG_DONE;
1335 memcpy(&evbuff[evbuff_idx], &tmp16, sizeof(uint16_t));
1336 evbuff_idx += sizeof(uint16_t);
1337
1338 // flush any remaining data in the buffer (and hopefully
1339 // in most cases this is the only uiomove we'll do)
1340 if (evbuff_idx > uio_resid(uio)) {
1341 error = ENOSPC;
1342 } else {
1343 error = uiomove(evbuff, evbuff_idx, uio);
1344 }
1345
1346 get_out:
1347
1348 return error;
1349 }
1350
1351
1352
1353 static int
1354 fmod_watch(fs_event_watcher *watcher, struct uio *uio)
1355 {
1356 int error=0;
1357 user_ssize_t last_full_event_resid;
1358 kfs_event *kfse;
1359 uint16_t tmp16;
1360 int skipped;
1361
1362 last_full_event_resid = uio_resid(uio);
1363
1364 // need at least 2048 bytes of space (maxpathlen + 1 event buf)
1365 if (uio_resid(uio) < 2048 || watcher == NULL) {
1366 return EINVAL;
1367 }
1368
1369 if (watcher->flags & WATCHER_CLOSING) {
1370 return 0;
1371 }
1372
1373 if (OSAddAtomic(1, &watcher->num_readers) != 0) {
1374 // don't allow multiple threads to read from the fd at the same time
1375 OSAddAtomic(-1, &watcher->num_readers);
1376 return EAGAIN;
1377 }
1378
1379 restart_watch:
1380 if (watcher->rd == watcher->wr) {
1381 if (watcher->flags & WATCHER_CLOSING) {
1382 OSAddAtomic(-1, &watcher->num_readers);
1383 return 0;
1384 }
1385 OSAddAtomic(1, &watcher->blockers);
1386
1387 // there's nothing to do, go to sleep
1388 error = tsleep((caddr_t)watcher, PUSER|PCATCH, "fsevents_empty", 0);
1389
1390 OSAddAtomic(-1, &watcher->blockers);
1391
1392 if (error != 0 || (watcher->flags & WATCHER_CLOSING)) {
1393 OSAddAtomic(-1, &watcher->num_readers);
1394 return error;
1395 }
1396 }
1397
1398 // if we dropped events, return that as an event first
1399 if (watcher->flags & WATCHER_DROPPED_EVENTS) {
1400 int32_t val = FSE_EVENTS_DROPPED;
1401
1402 error = uiomove((caddr_t)&val, sizeof(int32_t), uio);
1403 if (error == 0) {
1404 val = 0; // a fake pid
1405 error = uiomove((caddr_t)&val, sizeof(int32_t), uio);
1406
1407 tmp16 = FSE_ARG_DONE; // makes it a consistent msg
1408 error = uiomove((caddr_t)&tmp16, sizeof(int16_t), uio);
1409
1410 last_full_event_resid = uio_resid(uio);
1411 }
1412
1413 if (error) {
1414 OSAddAtomic(-1, &watcher->num_readers);
1415 return error;
1416 }
1417
1418 watcher->flags &= ~WATCHER_DROPPED_EVENTS;
1419 }
1420
1421 skipped = 0;
1422
1423 lck_rw_lock_shared(&event_handling_lock);
1424 while (uio_resid(uio) > 0 && watcher->rd != watcher->wr) {
1425 if (watcher->flags & WATCHER_CLOSING) {
1426 break;
1427 }
1428
1429 //
1430 // check if the event is something of interest to us
1431 // (since it may have been recycled/reused and changed
1432 // its type or which device it is for)
1433 //
1434 kfse = watcher->event_queue[watcher->rd];
1435 if (!kfse || kfse->type == FSE_INVALID || kfse->refcount < 1) {
1436 break;
1437 }
1438
1439 if (watcher->event_list[kfse->type] == FSE_REPORT && watcher_cares_about_dev(watcher, kfse->dev)) {
1440
1441 if (!(watcher->flags & WATCHER_APPLE_SYSTEM_SERVICE) & is_ignored_directory(kfse->str)) {
1442 // If this is not an Apple System Service, skip specified directories
1443 // radar://12034844
1444 error = 0;
1445 skipped = 1;
1446 } else {
1447
1448 skipped = 0;
1449 if (last_event_ptr == kfse) {
1450 last_event_ptr = NULL;
1451 last_event_type = -1;
1452 last_coalesced_time = 0;
1453 }
1454 error = copy_out_kfse(watcher, kfse, uio);
1455 if (error != 0) {
1456 // if an event won't fit or encountered an error while
1457 // we were copying it out, then backup to the last full
1458 // event and just bail out. if the error was ENOENT
1459 // then we can continue regular processing, otherwise
1460 // we should unlock things and return.
1461 uio_setresid(uio, last_full_event_resid);
1462 if (error != ENOENT) {
1463 lck_rw_unlock_shared(&event_handling_lock);
1464 error = 0;
1465 goto get_out;
1466 }
1467 }
1468
1469 last_full_event_resid = uio_resid(uio);
1470 }
1471 }
1472
1473 watcher->event_queue[watcher->rd] = NULL;
1474 watcher->rd = (watcher->rd + 1) % watcher->eventq_size;
1475 OSSynchronizeIO();
1476 release_event_ref(kfse);
1477 }
1478 lck_rw_unlock_shared(&event_handling_lock);
1479
1480 if (skipped && error == 0) {
1481 goto restart_watch;
1482 }
1483
1484 get_out:
1485 OSAddAtomic(-1, &watcher->num_readers);
1486
1487 return error;
1488 }
1489
1490
1491 // release any references we might have on vnodes which are
1492 // the mount point passed to us (so that it can be cleanly
1493 // unmounted).
1494 //
1495 // since we don't want to lose the events we'll convert the
1496 // vnode refs to full paths.
1497 //
1498 void
1499 fsevent_unmount(__unused struct mount *mp)
1500 {
1501 // we no longer maintain pointers to vnodes so
1502 // there is nothing to do...
1503 }
1504
1505
1506 //
1507 // /dev/fsevents device code
1508 //
1509 static int fsevents_installed = 0;
1510
1511 typedef struct fsevent_handle {
1512 UInt32 flags;
1513 SInt32 active;
1514 fs_event_watcher *watcher;
1515 struct klist knotes;
1516 struct selinfo si;
1517 } fsevent_handle;
1518
1519 #define FSEH_CLOSING 0x0001
1520
1521 static int
1522 fseventsf_read(struct fileproc *fp, struct uio *uio,
1523 __unused int flags, __unused vfs_context_t ctx)
1524 {
1525 fsevent_handle *fseh = (struct fsevent_handle *)fp->f_fglob->fg_data;
1526 int error;
1527
1528 error = fmod_watch(fseh->watcher, uio);
1529
1530 return error;
1531 }
1532
1533
1534 static int
1535 fseventsf_write(__unused struct fileproc *fp, __unused struct uio *uio,
1536 __unused int flags, __unused vfs_context_t ctx)
1537 {
1538 return EIO;
1539 }
1540
1541 #pragma pack(push, 4)
1542 typedef struct ext_fsevent_dev_filter_args {
1543 uint32_t num_devices;
1544 user_addr_t devices;
1545 } ext_fsevent_dev_filter_args;
1546 #pragma pack(pop)
1547
1548 #define NEW_FSEVENTS_DEVICE_FILTER _IOW('s', 100, ext_fsevent_dev_filter_args)
1549
1550 typedef struct old_fsevent_dev_filter_args {
1551 uint32_t num_devices;
1552 int32_t devices;
1553 } old_fsevent_dev_filter_args;
1554
1555 #define OLD_FSEVENTS_DEVICE_FILTER _IOW('s', 100, old_fsevent_dev_filter_args)
1556
1557 #if __LP64__
1558 /* need this in spite of the padding due to alignment of devices */
1559 typedef struct fsevent_dev_filter_args32 {
1560 uint32_t num_devices;
1561 uint32_t devices;
1562 int32_t pad1;
1563 } fsevent_dev_filter_args32;
1564 #endif
1565
1566 static int
1567 fseventsf_ioctl(struct fileproc *fp, u_long cmd, caddr_t data, vfs_context_t ctx)
1568 {
1569 fsevent_handle *fseh = (struct fsevent_handle *)fp->f_fglob->fg_data;
1570 int ret = 0;
1571 ext_fsevent_dev_filter_args *devfilt_args, _devfilt_args;
1572
1573 if (proc_is64bit(vfs_context_proc(ctx))) {
1574 devfilt_args = (ext_fsevent_dev_filter_args *)data;
1575 }
1576 else if (cmd == OLD_FSEVENTS_DEVICE_FILTER) {
1577 old_fsevent_dev_filter_args *udev_filt_args = (old_fsevent_dev_filter_args *)data;
1578
1579 devfilt_args = &_devfilt_args;
1580 memset(devfilt_args, 0, sizeof(ext_fsevent_dev_filter_args));
1581
1582 devfilt_args->num_devices = udev_filt_args->num_devices;
1583 devfilt_args->devices = CAST_USER_ADDR_T(udev_filt_args->devices);
1584 }
1585 else {
1586 #if __LP64__
1587 fsevent_dev_filter_args32 *udev_filt_args = (fsevent_dev_filter_args32 *)data;
1588 #else
1589 fsevent_dev_filter_args *udev_filt_args = (fsevent_dev_filter_args *)data;
1590 #endif
1591
1592 devfilt_args = &_devfilt_args;
1593 memset(devfilt_args, 0, sizeof(ext_fsevent_dev_filter_args));
1594
1595 devfilt_args->num_devices = udev_filt_args->num_devices;
1596 devfilt_args->devices = CAST_USER_ADDR_T(udev_filt_args->devices);
1597 }
1598
1599 OSAddAtomic(1, &fseh->active);
1600 if (fseh->flags & FSEH_CLOSING) {
1601 OSAddAtomic(-1, &fseh->active);
1602 return 0;
1603 }
1604
1605 switch (cmd) {
1606 case FIONBIO:
1607 case FIOASYNC:
1608 break;
1609
1610 case FSEVENTS_WANT_COMPACT_EVENTS: {
1611 fseh->watcher->flags |= WATCHER_WANTS_COMPACT_EVENTS;
1612 break;
1613 }
1614
1615 case FSEVENTS_WANT_EXTENDED_INFO: {
1616 fseh->watcher->flags |= WATCHER_WANTS_EXTENDED_INFO;
1617 break;
1618 }
1619
1620 case FSEVENTS_GET_CURRENT_ID: {
1621 *(uint64_t *)data = fseh->watcher->max_event_id;
1622 ret = 0;
1623 break;
1624 }
1625
1626 case OLD_FSEVENTS_DEVICE_FILTER:
1627 case NEW_FSEVENTS_DEVICE_FILTER: {
1628 int new_num_devices;
1629 dev_t *devices_not_to_watch, *tmp=NULL;
1630
1631 if (devfilt_args->num_devices > 256) {
1632 ret = EINVAL;
1633 break;
1634 }
1635
1636 new_num_devices = devfilt_args->num_devices;
1637 if (new_num_devices == 0) {
1638 tmp = fseh->watcher->devices_not_to_watch;
1639
1640 lock_watch_table();
1641 fseh->watcher->devices_not_to_watch = NULL;
1642 fseh->watcher->num_devices = new_num_devices;
1643 unlock_watch_table();
1644
1645 if (tmp) {
1646 FREE(tmp, M_TEMP);
1647 }
1648 break;
1649 }
1650
1651 MALLOC(devices_not_to_watch, dev_t *,
1652 new_num_devices * sizeof(dev_t),
1653 M_TEMP, M_WAITOK);
1654 if (devices_not_to_watch == NULL) {
1655 ret = ENOMEM;
1656 break;
1657 }
1658
1659 ret = copyin(devfilt_args->devices,
1660 (void *)devices_not_to_watch,
1661 new_num_devices * sizeof(dev_t));
1662 if (ret) {
1663 FREE(devices_not_to_watch, M_TEMP);
1664 break;
1665 }
1666
1667 lock_watch_table();
1668 fseh->watcher->num_devices = new_num_devices;
1669 tmp = fseh->watcher->devices_not_to_watch;
1670 fseh->watcher->devices_not_to_watch = devices_not_to_watch;
1671 unlock_watch_table();
1672
1673 if (tmp) {
1674 FREE(tmp, M_TEMP);
1675 }
1676
1677 break;
1678 }
1679
1680 default:
1681 ret = EINVAL;
1682 break;
1683 }
1684
1685 OSAddAtomic(-1, &fseh->active);
1686 return (ret);
1687 }
1688
1689
1690 static int
1691 fseventsf_select(struct fileproc *fp, int which, __unused void *wql, vfs_context_t ctx)
1692 {
1693 fsevent_handle *fseh = (struct fsevent_handle *)fp->f_fglob->fg_data;
1694 int ready = 0;
1695
1696 if ((which != FREAD) || (fseh->watcher->flags & WATCHER_CLOSING)) {
1697 return 0;
1698 }
1699
1700
1701 // if there's nothing in the queue, we're not ready
1702 if (fseh->watcher->rd != fseh->watcher->wr) {
1703 ready = 1;
1704 }
1705
1706 if (!ready) {
1707 selrecord(vfs_context_proc(ctx), &fseh->si, wql);
1708 }
1709
1710 return ready;
1711 }
1712
1713
1714 #if NOTUSED
1715 static int
1716 fseventsf_stat(__unused struct fileproc *fp, __unused struct stat *sb, __unused vfs_context_t ctx)
1717 {
1718 return ENOTSUP;
1719 }
1720 #endif
1721
1722 static int
1723 fseventsf_close(struct fileglob *fg, __unused vfs_context_t ctx)
1724 {
1725 fsevent_handle *fseh = (struct fsevent_handle *)fg->fg_data;
1726 fs_event_watcher *watcher;
1727
1728 OSBitOrAtomic(FSEH_CLOSING, &fseh->flags);
1729 while (OSAddAtomic(0, &fseh->active) > 0) {
1730 tsleep((caddr_t)fseh->watcher, PRIBIO, "fsevents-close", 1);
1731 }
1732
1733 watcher = fseh->watcher;
1734 fg->fg_data = NULL;
1735 fseh->watcher = NULL;
1736
1737 remove_watcher(watcher);
1738 FREE(fseh, M_TEMP);
1739
1740 return 0;
1741 }
1742
1743 static void
1744 filt_fsevent_detach(struct knote *kn)
1745 {
1746 fsevent_handle *fseh = (struct fsevent_handle *)kn->kn_hook;
1747
1748 lock_watch_table();
1749
1750 KNOTE_DETACH(&fseh->knotes, kn);
1751
1752 unlock_watch_table();
1753 }
1754
1755 /*
1756 * Determine whether this knote should be active
1757 *
1758 * This is kind of subtle.
1759 * --First, notice if the vnode has been revoked: in so, override hint
1760 * --EVFILT_READ knotes are checked no matter what the hint is
1761 * --Other knotes activate based on hint.
1762 * --If hint is revoke, set special flags and activate
1763 */
1764 static int
1765 filt_fsevent(struct knote *kn, long hint)
1766 {
1767 fsevent_handle *fseh = (struct fsevent_handle *)kn->kn_hook;
1768 int activate = 0;
1769 int32_t rd, wr, amt;
1770
1771 if (NOTE_REVOKE == hint) {
1772 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
1773 activate = 1;
1774 }
1775
1776 rd = fseh->watcher->rd;
1777 wr = fseh->watcher->wr;
1778 if (rd <= wr) {
1779 amt = wr - rd;
1780 } else {
1781 amt = fseh->watcher->eventq_size - (rd - wr);
1782 }
1783
1784 switch(kn->kn_filter) {
1785 case EVFILT_READ:
1786 kn->kn_data = amt;
1787
1788 if (kn->kn_data != 0) {
1789 activate = 1;
1790 }
1791 break;
1792 case EVFILT_VNODE:
1793 /* Check events this note matches against the hint */
1794 if (kn->kn_sfflags & hint) {
1795 kn->kn_fflags |= hint; /* Set which event occurred */
1796 }
1797 if (kn->kn_fflags != 0) {
1798 activate = 1;
1799 }
1800 break;
1801 default: {
1802 // nothing to do...
1803 break;
1804 }
1805 }
1806
1807 return (activate);
1808 }
1809
1810
1811 struct filterops fsevent_filtops = {
1812 .f_isfd = 1,
1813 .f_attach = NULL,
1814 .f_detach = filt_fsevent_detach,
1815 .f_event = filt_fsevent
1816 };
1817
1818 static int
1819 fseventsf_kqfilter(__unused struct fileproc *fp, __unused struct knote *kn, __unused vfs_context_t ctx)
1820 {
1821 fsevent_handle *fseh = (struct fsevent_handle *)fp->f_fglob->fg_data;
1822
1823 kn->kn_hook = (void*)fseh;
1824 kn->kn_hookid = 1;
1825 kn->kn_fop = &fsevent_filtops;
1826
1827 lock_watch_table();
1828
1829 KNOTE_ATTACH(&fseh->knotes, kn);
1830
1831 unlock_watch_table();
1832 return 0;
1833 }
1834
1835
1836 static int
1837 fseventsf_drain(struct fileproc *fp, __unused vfs_context_t ctx)
1838 {
1839 int counter = 0;
1840 fsevent_handle *fseh = (struct fsevent_handle *)fp->f_fglob->fg_data;
1841
1842 fseh->watcher->flags |= WATCHER_CLOSING;
1843
1844 // if there are people still waiting, sleep for 10ms to
1845 // let them clean up and get out of there. however we
1846 // also don't want to get stuck forever so if they don't
1847 // exit after 5 seconds we're tearing things down anyway.
1848 while(fseh->watcher->blockers && counter++ < 500) {
1849 // issue wakeup in case anyone is blocked waiting for an event
1850 // do this each time we wakeup in case the blocker missed
1851 // the wakeup due to the unprotected test of WATCHER_CLOSING
1852 // and decision to tsleep in fmod_watch... this bit of
1853 // latency is a decent tradeoff against not having to
1854 // take and drop a lock in fmod_watch
1855 lock_watch_table();
1856 fsevents_wakeup(fseh->watcher);
1857 unlock_watch_table();
1858
1859 tsleep((caddr_t)fseh->watcher, PRIBIO, "watcher-close", 1);
1860 }
1861
1862 return 0;
1863 }
1864
1865
1866 static int
1867 fseventsopen(__unused dev_t dev, __unused int flag, __unused int mode, __unused struct proc *p)
1868 {
1869 if (!kauth_cred_issuser(kauth_cred_get())) {
1870 return EPERM;
1871 }
1872
1873 return 0;
1874 }
1875
1876 static int
1877 fseventsclose(__unused dev_t dev, __unused int flag, __unused int mode, __unused struct proc *p)
1878 {
1879 return 0;
1880 }
1881
1882 static int
1883 fseventsread(__unused dev_t dev, __unused struct uio *uio, __unused int ioflag)
1884 {
1885 return EIO;
1886 }
1887
1888
1889 static int
1890 parse_buffer_and_add_events(const char *buffer, int bufsize, vfs_context_t ctx, long *remainder)
1891 {
1892 const fse_info *finfo, *dest_finfo;
1893 const char *path, *ptr, *dest_path, *event_start=buffer;
1894 int path_len, type, dest_path_len, err = 0;
1895
1896
1897 ptr = buffer;
1898 while ((ptr+sizeof(int)+sizeof(fse_info)+1) < buffer+bufsize) {
1899 type = *(const int *)ptr;
1900 if (type < 0 || type >= FSE_MAX_EVENTS) {
1901 err = EINVAL;
1902 break;
1903 }
1904
1905 ptr += sizeof(int);
1906
1907 finfo = (const fse_info *)ptr;
1908 ptr += sizeof(fse_info);
1909
1910 path = ptr;
1911 while(ptr < buffer+bufsize && *ptr != '\0') {
1912 ptr++;
1913 }
1914
1915 if (ptr >= buffer+bufsize) {
1916 break;
1917 }
1918
1919 ptr++; // advance over the trailing '\0'
1920
1921 path_len = ptr - path;
1922
1923 if (type != FSE_RENAME && type != FSE_EXCHANGE) {
1924 event_start = ptr; // record where the next event starts
1925
1926 err = add_fsevent(type, ctx, FSE_ARG_STRING, path_len, path, FSE_ARG_FINFO, finfo, FSE_ARG_DONE);
1927 if (err) {
1928 break;
1929 }
1930 continue;
1931 }
1932
1933 //
1934 // if we're here we have to slurp up the destination finfo
1935 // and path so that we can pass them to the add_fsevent()
1936 // call. basically it's a copy of the above code.
1937 //
1938 dest_finfo = (const fse_info *)ptr;
1939 ptr += sizeof(fse_info);
1940
1941 dest_path = ptr;
1942 while(ptr < buffer+bufsize && *ptr != '\0') {
1943 ptr++;
1944 }
1945
1946 if (ptr >= buffer+bufsize) {
1947 break;
1948 }
1949
1950 ptr++; // advance over the trailing '\0'
1951 event_start = ptr; // record where the next event starts
1952
1953 dest_path_len = ptr - dest_path;
1954 //
1955 // If the destination inode number is non-zero, generate a rename
1956 // with both source and destination FSE_ARG_FINFO. Otherwise generate
1957 // a rename with only one FSE_ARG_FINFO. If you need to inject an
1958 // exchange with an inode of zero, just make that inode (and its path)
1959 // come in as the first one, not the second.
1960 //
1961 if (dest_finfo->ino) {
1962 err = add_fsevent(type, ctx,
1963 FSE_ARG_STRING, path_len, path, FSE_ARG_FINFO, finfo,
1964 FSE_ARG_STRING, dest_path_len, dest_path, FSE_ARG_FINFO, dest_finfo,
1965 FSE_ARG_DONE);
1966 } else {
1967 err = add_fsevent(type, ctx,
1968 FSE_ARG_STRING, path_len, path, FSE_ARG_FINFO, finfo,
1969 FSE_ARG_STRING, dest_path_len, dest_path,
1970 FSE_ARG_DONE);
1971 }
1972
1973 if (err) {
1974 break;
1975 }
1976
1977 }
1978
1979 // if the last event wasn't complete, set the remainder
1980 // to be the last event start boundary.
1981 //
1982 *remainder = (long)((buffer+bufsize) - event_start);
1983
1984 return err;
1985 }
1986
1987
1988 //
1989 // Note: this buffer size can not ever be less than
1990 // 2*MAXPATHLEN + 2*sizeof(fse_info) + sizeof(int)
1991 // because that is the max size for a single event.
1992 // I made it 4k to be a "nice" size. making it
1993 // smaller is not a good idea.
1994 //
1995 #define WRITE_BUFFER_SIZE 4096
1996 char *write_buffer=NULL;
1997
1998 static int
1999 fseventswrite(__unused dev_t dev, struct uio *uio, __unused int ioflag)
2000 {
2001 int error=0, count;
2002 vfs_context_t ctx = vfs_context_current();
2003 long offset=0, remainder;
2004
2005 lck_mtx_lock(&event_writer_lock);
2006
2007 if (write_buffer == NULL) {
2008 if (kmem_alloc(kernel_map, (vm_offset_t *)&write_buffer, WRITE_BUFFER_SIZE)) {
2009 lck_mtx_unlock(&event_writer_lock);
2010 return ENOMEM;
2011 }
2012 }
2013
2014 //
2015 // this loop copies in and processes the events written.
2016 // it takes care to copy in reasonable size chunks and
2017 // process them. if there is an event that spans a chunk
2018 // boundary we're careful to copy those bytes down to the
2019 // beginning of the buffer and read the next chunk in just
2020 // after it.
2021 //
2022 while(uio_resid(uio)) {
2023 if (uio_resid(uio) > (WRITE_BUFFER_SIZE-offset)) {
2024 count = WRITE_BUFFER_SIZE - offset;
2025 } else {
2026 count = uio_resid(uio);
2027 }
2028
2029 error = uiomove(write_buffer+offset, count, uio);
2030 if (error) {
2031 break;
2032 }
2033
2034 // printf("fsevents: write: copied in %d bytes (offset: %ld)\n", count, offset);
2035 error = parse_buffer_and_add_events(write_buffer, offset+count, ctx, &remainder);
2036 if (error) {
2037 break;
2038 }
2039
2040 //
2041 // if there's any remainder, copy it down to the beginning
2042 // of the buffer so that it will get processed the next time
2043 // through the loop. note that the remainder always starts
2044 // at an event boundary.
2045 //
2046 if (remainder != 0) {
2047 // printf("fsevents: write: an event spanned a %d byte boundary. remainder: %ld\n",
2048 // WRITE_BUFFER_SIZE, remainder);
2049 memmove(write_buffer, (write_buffer+count+offset) - remainder, remainder);
2050 offset = remainder;
2051 } else {
2052 offset = 0;
2053 }
2054 }
2055
2056 lck_mtx_unlock(&event_writer_lock);
2057
2058 return error;
2059 }
2060
2061
2062 static const struct fileops fsevents_fops = {
2063 DTYPE_FSEVENTS,
2064 fseventsf_read,
2065 fseventsf_write,
2066 fseventsf_ioctl,
2067 fseventsf_select,
2068 fseventsf_close,
2069 fseventsf_kqfilter,
2070 fseventsf_drain
2071 };
2072
2073 typedef struct ext_fsevent_clone_args {
2074 user_addr_t event_list;
2075 int32_t num_events;
2076 int32_t event_queue_depth;
2077 user_addr_t fd;
2078 } ext_fsevent_clone_args;
2079
2080 typedef struct old_fsevent_clone_args {
2081 uint32_t event_list;
2082 int32_t num_events;
2083 int32_t event_queue_depth;
2084 uint32_t fd;
2085 } old_fsevent_clone_args;
2086
2087 #define OLD_FSEVENTS_CLONE _IOW('s', 1, old_fsevent_clone_args)
2088
2089 static int
2090 fseventsioctl(__unused dev_t dev, u_long cmd, caddr_t data, __unused int flag, struct proc *p)
2091 {
2092 struct fileproc *f;
2093 int fd, error;
2094 fsevent_handle *fseh = NULL;
2095 ext_fsevent_clone_args *fse_clone_args, _fse_clone;
2096 int8_t *event_list;
2097 int is64bit = proc_is64bit(p);
2098
2099 switch (cmd) {
2100 case OLD_FSEVENTS_CLONE: {
2101 old_fsevent_clone_args *old_args = (old_fsevent_clone_args *)data;
2102
2103 fse_clone_args = &_fse_clone;
2104 memset(fse_clone_args, 0, sizeof(ext_fsevent_clone_args));
2105
2106 fse_clone_args->event_list = CAST_USER_ADDR_T(old_args->event_list);
2107 fse_clone_args->num_events = old_args->num_events;
2108 fse_clone_args->event_queue_depth = old_args->event_queue_depth;
2109 fse_clone_args->fd = CAST_USER_ADDR_T(old_args->fd);
2110 goto handle_clone;
2111 }
2112
2113 case FSEVENTS_CLONE:
2114 if (is64bit) {
2115 fse_clone_args = (ext_fsevent_clone_args *)data;
2116 } else {
2117 fsevent_clone_args *ufse_clone = (fsevent_clone_args *)data;
2118
2119 fse_clone_args = &_fse_clone;
2120 memset(fse_clone_args, 0, sizeof(ext_fsevent_clone_args));
2121
2122 fse_clone_args->event_list = CAST_USER_ADDR_T(ufse_clone->event_list);
2123 fse_clone_args->num_events = ufse_clone->num_events;
2124 fse_clone_args->event_queue_depth = ufse_clone->event_queue_depth;
2125 fse_clone_args->fd = CAST_USER_ADDR_T(ufse_clone->fd);
2126 }
2127
2128 handle_clone:
2129 if (fse_clone_args->num_events < 0 || fse_clone_args->num_events > 4096) {
2130 return EINVAL;
2131 }
2132
2133 MALLOC(fseh, fsevent_handle *, sizeof(fsevent_handle),
2134 M_TEMP, M_WAITOK);
2135 if (fseh == NULL) {
2136 return ENOMEM;
2137 }
2138 memset(fseh, 0, sizeof(fsevent_handle));
2139
2140 klist_init(&fseh->knotes);
2141
2142 MALLOC(event_list, int8_t *,
2143 fse_clone_args->num_events * sizeof(int8_t),
2144 M_TEMP, M_WAITOK);
2145 if (event_list == NULL) {
2146 FREE(fseh, M_TEMP);
2147 return ENOMEM;
2148 }
2149
2150 error = copyin(fse_clone_args->event_list,
2151 (void *)event_list,
2152 fse_clone_args->num_events * sizeof(int8_t));
2153 if (error) {
2154 FREE(event_list, M_TEMP);
2155 FREE(fseh, M_TEMP);
2156 return error;
2157 }
2158
2159 error = add_watcher(event_list,
2160 fse_clone_args->num_events,
2161 fse_clone_args->event_queue_depth,
2162 &fseh->watcher,
2163 fseh);
2164 if (error) {
2165 FREE(event_list, M_TEMP);
2166 FREE(fseh, M_TEMP);
2167 return error;
2168 }
2169
2170 fseh->watcher->fseh = fseh;
2171
2172 error = falloc(p, &f, &fd, vfs_context_current());
2173 if (error) {
2174 FREE(event_list, M_TEMP);
2175 FREE(fseh, M_TEMP);
2176 return (error);
2177 }
2178 proc_fdlock(p);
2179 f->f_fglob->fg_flag = FREAD | FWRITE;
2180 f->f_fglob->fg_ops = &fsevents_fops;
2181 f->f_fglob->fg_data = (caddr_t) fseh;
2182 proc_fdunlock(p);
2183 error = copyout((void *)&fd, fse_clone_args->fd, sizeof(int32_t));
2184 if (error != 0) {
2185 fp_free(p, fd, f);
2186 } else {
2187 proc_fdlock(p);
2188 procfdtbl_releasefd(p, fd, NULL);
2189 fp_drop(p, fd, f, 1);
2190 proc_fdunlock(p);
2191 }
2192 break;
2193
2194 default:
2195 error = EINVAL;
2196 break;
2197 }
2198
2199 return error;
2200 }
2201
2202 static void
2203 fsevents_wakeup(fs_event_watcher *watcher)
2204 {
2205 selwakeup(&watcher->fseh->si);
2206 KNOTE(&watcher->fseh->knotes, NOTE_WRITE|NOTE_NONE);
2207 wakeup((caddr_t)watcher);
2208 }
2209
2210
2211 /*
2212 * A struct describing which functions will get invoked for certain
2213 * actions.
2214 */
2215 static struct cdevsw fsevents_cdevsw =
2216 {
2217 fseventsopen, /* open */
2218 fseventsclose, /* close */
2219 fseventsread, /* read */
2220 fseventswrite, /* write */
2221 fseventsioctl, /* ioctl */
2222 (stop_fcn_t *)&nulldev, /* stop */
2223 (reset_fcn_t *)&nulldev, /* reset */
2224 NULL, /* tty's */
2225 eno_select, /* select */
2226 eno_mmap, /* mmap */
2227 eno_strat, /* strategy */
2228 eno_getc, /* getc */
2229 eno_putc, /* putc */
2230 0 /* type */
2231 };
2232
2233
2234 /*
2235 * Called to initialize our device,
2236 * and to register ourselves with devfs
2237 */
2238
2239 void
2240 fsevents_init(void)
2241 {
2242 int ret;
2243
2244 if (fsevents_installed) {
2245 return;
2246 }
2247
2248 fsevents_installed = 1;
2249
2250 ret = cdevsw_add(-1, &fsevents_cdevsw);
2251 if (ret < 0) {
2252 fsevents_installed = 0;
2253 return;
2254 }
2255
2256 devfs_make_node(makedev (ret, 0), DEVFS_CHAR,
2257 UID_ROOT, GID_WHEEL, 0644, "fsevents", 0);
2258
2259 fsevents_internal_init();
2260 }
2261
2262
2263 char *
2264 get_pathbuff(void)
2265 {
2266 char *path;
2267
2268 MALLOC_ZONE(path, char *, MAXPATHLEN, M_NAMEI, M_WAITOK);
2269 return path;
2270 }
2271
2272 void
2273 release_pathbuff(char *path)
2274 {
2275
2276 if (path == NULL) {
2277 return;
2278 }
2279 FREE_ZONE(path, MAXPATHLEN, M_NAMEI);
2280 }
2281
2282 int
2283 get_fse_info(struct vnode *vp, fse_info *fse, __unused vfs_context_t ctx)
2284 {
2285 struct vnode_attr va;
2286
2287 VATTR_INIT(&va);
2288 VATTR_WANTED(&va, va_fsid);
2289 VATTR_WANTED(&va, va_fileid);
2290 VATTR_WANTED(&va, va_mode);
2291 VATTR_WANTED(&va, va_uid);
2292 VATTR_WANTED(&va, va_gid);
2293 if (vp->v_flag & VISHARDLINK) {
2294 if (vp->v_type == VDIR) {
2295 VATTR_WANTED(&va, va_dirlinkcount);
2296 } else {
2297 VATTR_WANTED(&va, va_nlink);
2298 }
2299 }
2300
2301 if (vnode_getattr(vp, &va, vfs_context_kernel()) != 0) {
2302 memset(fse, 0, sizeof(fse_info));
2303 return -1;
2304 }
2305
2306 return vnode_get_fse_info_from_vap(vp, fse, &va);
2307 }
2308
2309 int
2310 vnode_get_fse_info_from_vap(vnode_t vp, fse_info *fse, struct vnode_attr *vap)
2311 {
2312 fse->ino = (ino64_t)vap->va_fileid;
2313 fse->dev = (dev_t)vap->va_fsid;
2314 fse->mode = (int32_t)vnode_vttoif(vnode_vtype(vp)) | vap->va_mode;
2315 fse->uid = (uid_t)vap->va_uid;
2316 fse->gid = (gid_t)vap->va_gid;
2317 if (vp->v_flag & VISHARDLINK) {
2318 fse->mode |= FSE_MODE_HLINK;
2319 if (vp->v_type == VDIR) {
2320 fse->nlink = (uint64_t)vap->va_dirlinkcount;
2321 } else {
2322 fse->nlink = (uint64_t)vap->va_nlink;
2323 }
2324 }
2325
2326 return 0;
2327 }
2328
2329 void
2330 create_fsevent_from_kevent(vnode_t vp, uint32_t kevents, struct vnode_attr *vap)
2331 {
2332 int fsevent_type=FSE_CONTENT_MODIFIED, len; // the default is the most pessimistic
2333 char pathbuf[MAXPATHLEN];
2334 fse_info fse;
2335
2336
2337 if (kevents & VNODE_EVENT_DELETE) {
2338 fsevent_type = FSE_DELETE;
2339 } else if (kevents & (VNODE_EVENT_EXTEND|VNODE_EVENT_WRITE)) {
2340 fsevent_type = FSE_CONTENT_MODIFIED;
2341 } else if (kevents & VNODE_EVENT_LINK) {
2342 fsevent_type = FSE_CREATE_FILE;
2343 } else if (kevents & VNODE_EVENT_RENAME) {
2344 fsevent_type = FSE_CREATE_FILE; // XXXdbg - should use FSE_RENAME but we don't have the destination info;
2345 } else if (kevents & (VNODE_EVENT_FILE_CREATED|VNODE_EVENT_FILE_REMOVED|VNODE_EVENT_DIR_CREATED|VNODE_EVENT_DIR_REMOVED)) {
2346 fsevent_type = FSE_STAT_CHANGED; // XXXdbg - because vp is a dir and the thing created/removed lived inside it
2347 } else { // a catch all for VNODE_EVENT_PERMS, VNODE_EVENT_ATTRIB and anything else
2348 fsevent_type = FSE_STAT_CHANGED;
2349 }
2350
2351 // printf("convert_kevent: kevents 0x%x fsevent type 0x%x (for %s)\n", kevents, fsevent_type, vp->v_name ? vp->v_name : "(no-name)");
2352
2353 fse.dev = vap->va_fsid;
2354 fse.ino = vap->va_fileid;
2355 fse.mode = vnode_vttoif(vnode_vtype(vp)) | (uint32_t)vap->va_mode;
2356 if (vp->v_flag & VISHARDLINK) {
2357 fse.mode |= FSE_MODE_HLINK;
2358 if (vp->v_type == VDIR) {
2359 fse.nlink = vap->va_dirlinkcount;
2360 } else {
2361 fse.nlink = vap->va_nlink;
2362 }
2363 }
2364
2365 if (vp->v_type == VDIR) {
2366 fse.mode |= FSE_REMOTE_DIR_EVENT;
2367 }
2368
2369
2370 fse.uid = vap->va_uid;
2371 fse.gid = vap->va_gid;
2372
2373 len = sizeof(pathbuf);
2374 if (vn_getpath(vp, pathbuf, &len) == 0) {
2375 add_fsevent(fsevent_type, vfs_context_current(), FSE_ARG_STRING, len, pathbuf, FSE_ARG_FINFO, &fse, FSE_ARG_DONE);
2376 }
2377 return;
2378 }
2379
2380 #else /* CONFIG_FSE */
2381 /*
2382 * The get_pathbuff and release_pathbuff routines are used in places not
2383 * related to fsevents, and it's a handy abstraction, so define trivial
2384 * versions that don't cache a pool of buffers. This way, we don't have
2385 * to conditionalize the callers, and they still get the advantage of the
2386 * pool of buffers if CONFIG_FSE is turned on.
2387 */
2388 char *
2389 get_pathbuff(void)
2390 {
2391 char *path;
2392 MALLOC_ZONE(path, char *, MAXPATHLEN, M_NAMEI, M_WAITOK);
2393 return path;
2394 }
2395
2396 void
2397 release_pathbuff(char *path)
2398 {
2399 FREE_ZONE(path, MAXPATHLEN, M_NAMEI);
2400 }
2401 #endif /* CONFIG_FSE */