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