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