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