xref: /linux-6.15/drivers/firewire/core-cdev.c (revision ebb9d3ca)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Char device for device raw access
4  *
5  * Copyright (C) 2005-2007  Kristian Hoegsberg <[email protected]>
6  */
7 
8 #include <linux/bug.h>
9 #include <linux/compat.h>
10 #include <linux/delay.h>
11 #include <linux/device.h>
12 #include <linux/dma-mapping.h>
13 #include <linux/err.h>
14 #include <linux/errno.h>
15 #include <linux/firewire.h>
16 #include <linux/firewire-cdev.h>
17 #include <linux/idr.h>
18 #include <linux/irqflags.h>
19 #include <linux/jiffies.h>
20 #include <linux/kernel.h>
21 #include <linux/kref.h>
22 #include <linux/mm.h>
23 #include <linux/module.h>
24 #include <linux/mutex.h>
25 #include <linux/poll.h>
26 #include <linux/sched.h> /* required for linux/wait.h */
27 #include <linux/slab.h>
28 #include <linux/spinlock.h>
29 #include <linux/string.h>
30 #include <linux/time.h>
31 #include <linux/uaccess.h>
32 #include <linux/vmalloc.h>
33 #include <linux/wait.h>
34 #include <linux/workqueue.h>
35 
36 
37 #include "core.h"
38 #include <trace/events/firewire.h>
39 
40 #include "packet-header-definitions.h"
41 
42 /*
43  * ABI version history is documented in linux/firewire-cdev.h.
44  */
45 #define FW_CDEV_KERNEL_VERSION			5
46 #define FW_CDEV_VERSION_EVENT_REQUEST2		4
47 #define FW_CDEV_VERSION_ALLOCATE_REGION_END	4
48 #define FW_CDEV_VERSION_AUTO_FLUSH_ISO_OVERFLOW	5
49 #define FW_CDEV_VERSION_EVENT_ASYNC_TSTAMP	6
50 
51 struct client {
52 	u32 version;
53 	struct fw_device *device;
54 
55 	spinlock_t lock;
56 	bool in_shutdown;
57 	struct idr resource_idr;
58 	struct list_head event_list;
59 	wait_queue_head_t wait;
60 	wait_queue_head_t tx_flush_wait;
61 	u64 bus_reset_closure;
62 
63 	struct fw_iso_context *iso_context;
64 	u64 iso_closure;
65 	struct fw_iso_buffer buffer;
66 	unsigned long vm_start;
67 	bool buffer_is_mapped;
68 
69 	struct list_head phy_receiver_link;
70 	u64 phy_receiver_closure;
71 
72 	struct list_head link;
73 	struct kref kref;
74 };
75 
76 static inline void client_get(struct client *client)
77 {
78 	kref_get(&client->kref);
79 }
80 
81 static void client_release(struct kref *kref)
82 {
83 	struct client *client = container_of(kref, struct client, kref);
84 
85 	fw_device_put(client->device);
86 	kfree(client);
87 }
88 
89 static void client_put(struct client *client)
90 {
91 	kref_put(&client->kref, client_release);
92 }
93 
94 struct client_resource;
95 typedef void (*client_resource_release_fn_t)(struct client *,
96 					     struct client_resource *);
97 struct client_resource {
98 	client_resource_release_fn_t release;
99 	int handle;
100 };
101 
102 struct address_handler_resource {
103 	struct client_resource resource;
104 	struct fw_address_handler handler;
105 	__u64 closure;
106 	struct client *client;
107 };
108 
109 struct outbound_transaction_resource {
110 	struct client_resource resource;
111 	struct fw_transaction transaction;
112 };
113 
114 struct inbound_transaction_resource {
115 	struct client_resource resource;
116 	struct fw_card *card;
117 	struct fw_request *request;
118 	bool is_fcp;
119 	void *data;
120 	size_t length;
121 };
122 
123 struct descriptor_resource {
124 	struct client_resource resource;
125 	struct fw_descriptor descriptor;
126 	u32 data[];
127 };
128 
129 struct iso_resource {
130 	struct client_resource resource;
131 	struct client *client;
132 	/* Schedule work and access todo only with client->lock held. */
133 	struct delayed_work work;
134 	enum {ISO_RES_ALLOC, ISO_RES_REALLOC, ISO_RES_DEALLOC,
135 	      ISO_RES_ALLOC_ONCE, ISO_RES_DEALLOC_ONCE,} todo;
136 	int generation;
137 	u64 channels;
138 	s32 bandwidth;
139 	struct iso_resource_event *e_alloc, *e_dealloc;
140 };
141 
142 static void release_iso_resource(struct client *, struct client_resource *);
143 
144 static void schedule_iso_resource(struct iso_resource *r, unsigned long delay)
145 {
146 	client_get(r->client);
147 	if (!queue_delayed_work(fw_workqueue, &r->work, delay))
148 		client_put(r->client);
149 }
150 
151 static void schedule_if_iso_resource(struct client_resource *resource)
152 {
153 	if (resource->release == release_iso_resource)
154 		schedule_iso_resource(container_of(resource,
155 					struct iso_resource, resource), 0);
156 }
157 
158 /*
159  * dequeue_event() just kfree()'s the event, so the event has to be
160  * the first field in a struct XYZ_event.
161  */
162 struct event {
163 	struct { void *data; size_t size; } v[2];
164 	struct list_head link;
165 };
166 
167 struct bus_reset_event {
168 	struct event event;
169 	struct fw_cdev_event_bus_reset reset;
170 };
171 
172 struct outbound_transaction_event {
173 	struct event event;
174 	struct client *client;
175 	struct outbound_transaction_resource r;
176 	union {
177 		struct fw_cdev_event_response without_tstamp;
178 		struct fw_cdev_event_response2 with_tstamp;
179 	} rsp;
180 };
181 
182 struct inbound_transaction_event {
183 	struct event event;
184 	union {
185 		struct fw_cdev_event_request request;
186 		struct fw_cdev_event_request2 request2;
187 		struct fw_cdev_event_request3 with_tstamp;
188 	} req;
189 };
190 
191 struct iso_interrupt_event {
192 	struct event event;
193 	struct fw_cdev_event_iso_interrupt interrupt;
194 };
195 
196 struct iso_interrupt_mc_event {
197 	struct event event;
198 	struct fw_cdev_event_iso_interrupt_mc interrupt;
199 };
200 
201 struct iso_resource_event {
202 	struct event event;
203 	struct fw_cdev_event_iso_resource iso_resource;
204 };
205 
206 struct outbound_phy_packet_event {
207 	struct event event;
208 	struct client *client;
209 	struct fw_packet p;
210 	union {
211 		struct fw_cdev_event_phy_packet without_tstamp;
212 		struct fw_cdev_event_phy_packet2 with_tstamp;
213 	} phy_packet;
214 };
215 
216 struct inbound_phy_packet_event {
217 	struct event event;
218 	union {
219 		struct fw_cdev_event_phy_packet without_tstamp;
220 		struct fw_cdev_event_phy_packet2 with_tstamp;
221 	} phy_packet;
222 };
223 
224 #ifdef CONFIG_COMPAT
225 static void __user *u64_to_uptr(u64 value)
226 {
227 	if (in_compat_syscall())
228 		return compat_ptr(value);
229 	else
230 		return (void __user *)(unsigned long)value;
231 }
232 
233 static u64 uptr_to_u64(void __user *ptr)
234 {
235 	if (in_compat_syscall())
236 		return ptr_to_compat(ptr);
237 	else
238 		return (u64)(unsigned long)ptr;
239 }
240 #else
241 static inline void __user *u64_to_uptr(u64 value)
242 {
243 	return (void __user *)(unsigned long)value;
244 }
245 
246 static inline u64 uptr_to_u64(void __user *ptr)
247 {
248 	return (u64)(unsigned long)ptr;
249 }
250 #endif /* CONFIG_COMPAT */
251 
252 static int fw_device_op_open(struct inode *inode, struct file *file)
253 {
254 	struct fw_device *device;
255 	struct client *client;
256 
257 	device = fw_device_get_by_devt(inode->i_rdev);
258 	if (device == NULL)
259 		return -ENODEV;
260 
261 	if (fw_device_is_shutdown(device)) {
262 		fw_device_put(device);
263 		return -ENODEV;
264 	}
265 
266 	client = kzalloc(sizeof(*client), GFP_KERNEL);
267 	if (client == NULL) {
268 		fw_device_put(device);
269 		return -ENOMEM;
270 	}
271 
272 	client->device = device;
273 	spin_lock_init(&client->lock);
274 	idr_init(&client->resource_idr);
275 	INIT_LIST_HEAD(&client->event_list);
276 	init_waitqueue_head(&client->wait);
277 	init_waitqueue_head(&client->tx_flush_wait);
278 	INIT_LIST_HEAD(&client->phy_receiver_link);
279 	INIT_LIST_HEAD(&client->link);
280 	kref_init(&client->kref);
281 
282 	file->private_data = client;
283 
284 	return nonseekable_open(inode, file);
285 }
286 
287 static void queue_event(struct client *client, struct event *event,
288 			void *data0, size_t size0, void *data1, size_t size1)
289 {
290 	event->v[0].data = data0;
291 	event->v[0].size = size0;
292 	event->v[1].data = data1;
293 	event->v[1].size = size1;
294 
295 	scoped_guard(spinlock_irqsave, &client->lock) {
296 		if (client->in_shutdown)
297 			kfree(event);
298 		else
299 			list_add_tail(&event->link, &client->event_list);
300 	}
301 
302 	wake_up_interruptible(&client->wait);
303 }
304 
305 static int dequeue_event(struct client *client,
306 			 char __user *buffer, size_t count)
307 {
308 	struct event *event;
309 	size_t size, total;
310 	int i, ret;
311 
312 	ret = wait_event_interruptible(client->wait,
313 			!list_empty(&client->event_list) ||
314 			fw_device_is_shutdown(client->device));
315 	if (ret < 0)
316 		return ret;
317 
318 	if (list_empty(&client->event_list) &&
319 		       fw_device_is_shutdown(client->device))
320 		return -ENODEV;
321 
322 	scoped_guard(spinlock_irq, &client->lock) {
323 		event = list_first_entry(&client->event_list, struct event, link);
324 		list_del(&event->link);
325 	}
326 
327 	total = 0;
328 	for (i = 0; i < ARRAY_SIZE(event->v) && total < count; i++) {
329 		size = min(event->v[i].size, count - total);
330 		if (copy_to_user(buffer + total, event->v[i].data, size)) {
331 			ret = -EFAULT;
332 			goto out;
333 		}
334 		total += size;
335 	}
336 	ret = total;
337 
338  out:
339 	kfree(event);
340 
341 	return ret;
342 }
343 
344 static ssize_t fw_device_op_read(struct file *file, char __user *buffer,
345 				 size_t count, loff_t *offset)
346 {
347 	struct client *client = file->private_data;
348 
349 	return dequeue_event(client, buffer, count);
350 }
351 
352 static void fill_bus_reset_event(struct fw_cdev_event_bus_reset *event,
353 				 struct client *client)
354 {
355 	struct fw_card *card = client->device->card;
356 
357 	guard(spinlock_irq)(&card->lock);
358 
359 	event->closure	     = client->bus_reset_closure;
360 	event->type          = FW_CDEV_EVENT_BUS_RESET;
361 	event->generation    = client->device->generation;
362 	event->node_id       = client->device->node_id;
363 	event->local_node_id = card->local_node->node_id;
364 	event->bm_node_id    = card->bm_node_id;
365 	event->irm_node_id   = card->irm_node->node_id;
366 	event->root_node_id  = card->root_node->node_id;
367 }
368 
369 static void for_each_client(struct fw_device *device,
370 			    void (*callback)(struct client *client))
371 {
372 	struct client *c;
373 
374 	guard(mutex)(&device->client_list_mutex);
375 
376 	list_for_each_entry(c, &device->client_list, link)
377 		callback(c);
378 }
379 
380 static int schedule_reallocations(int id, void *p, void *data)
381 {
382 	schedule_if_iso_resource(p);
383 
384 	return 0;
385 }
386 
387 static void queue_bus_reset_event(struct client *client)
388 {
389 	struct bus_reset_event *e;
390 
391 	e = kzalloc(sizeof(*e), GFP_KERNEL);
392 	if (e == NULL)
393 		return;
394 
395 	fill_bus_reset_event(&e->reset, client);
396 
397 	queue_event(client, &e->event,
398 		    &e->reset, sizeof(e->reset), NULL, 0);
399 
400 	guard(spinlock_irq)(&client->lock);
401 
402 	idr_for_each(&client->resource_idr, schedule_reallocations, client);
403 }
404 
405 void fw_device_cdev_update(struct fw_device *device)
406 {
407 	for_each_client(device, queue_bus_reset_event);
408 }
409 
410 static void wake_up_client(struct client *client)
411 {
412 	wake_up_interruptible(&client->wait);
413 }
414 
415 void fw_device_cdev_remove(struct fw_device *device)
416 {
417 	for_each_client(device, wake_up_client);
418 }
419 
420 union ioctl_arg {
421 	struct fw_cdev_get_info			get_info;
422 	struct fw_cdev_send_request		send_request;
423 	struct fw_cdev_allocate			allocate;
424 	struct fw_cdev_deallocate		deallocate;
425 	struct fw_cdev_send_response		send_response;
426 	struct fw_cdev_initiate_bus_reset	initiate_bus_reset;
427 	struct fw_cdev_add_descriptor		add_descriptor;
428 	struct fw_cdev_remove_descriptor	remove_descriptor;
429 	struct fw_cdev_create_iso_context	create_iso_context;
430 	struct fw_cdev_queue_iso		queue_iso;
431 	struct fw_cdev_start_iso		start_iso;
432 	struct fw_cdev_stop_iso			stop_iso;
433 	struct fw_cdev_get_cycle_timer		get_cycle_timer;
434 	struct fw_cdev_allocate_iso_resource	allocate_iso_resource;
435 	struct fw_cdev_send_stream_packet	send_stream_packet;
436 	struct fw_cdev_get_cycle_timer2		get_cycle_timer2;
437 	struct fw_cdev_send_phy_packet		send_phy_packet;
438 	struct fw_cdev_receive_phy_packets	receive_phy_packets;
439 	struct fw_cdev_set_iso_channels		set_iso_channels;
440 	struct fw_cdev_flush_iso		flush_iso;
441 };
442 
443 static int ioctl_get_info(struct client *client, union ioctl_arg *arg)
444 {
445 	struct fw_cdev_get_info *a = &arg->get_info;
446 	struct fw_cdev_event_bus_reset bus_reset;
447 	unsigned long ret = 0;
448 
449 	client->version = a->version;
450 	a->version = FW_CDEV_KERNEL_VERSION;
451 	a->card = client->device->card->index;
452 
453 	scoped_guard(rwsem_read, &fw_device_rwsem) {
454 		if (a->rom != 0) {
455 			size_t want = a->rom_length;
456 			size_t have = client->device->config_rom_length * 4;
457 
458 			ret = copy_to_user(u64_to_uptr(a->rom), client->device->config_rom,
459 					   min(want, have));
460 			if (ret != 0)
461 				return -EFAULT;
462 		}
463 		a->rom_length = client->device->config_rom_length * 4;
464 	}
465 
466 	guard(mutex)(&client->device->client_list_mutex);
467 
468 	client->bus_reset_closure = a->bus_reset_closure;
469 	if (a->bus_reset != 0) {
470 		fill_bus_reset_event(&bus_reset, client);
471 		/* unaligned size of bus_reset is 36 bytes */
472 		ret = copy_to_user(u64_to_uptr(a->bus_reset), &bus_reset, 36);
473 	}
474 	if (ret == 0 && list_empty(&client->link))
475 		list_add_tail(&client->link, &client->device->client_list);
476 
477 	return ret ? -EFAULT : 0;
478 }
479 
480 static int add_client_resource(struct client *client,
481 			       struct client_resource *resource, gfp_t gfp_mask)
482 {
483 	bool preload = gfpflags_allow_blocking(gfp_mask);
484 	int ret;
485 
486 	if (preload)
487 		idr_preload(gfp_mask);
488 
489 	scoped_guard(spinlock_irqsave, &client->lock) {
490 		if (client->in_shutdown)
491 			ret = -ECANCELED;
492 		else
493 			ret = idr_alloc(&client->resource_idr, resource, 0, 0, GFP_NOWAIT);
494 		if (ret >= 0) {
495 			resource->handle = ret;
496 			client_get(client);
497 			schedule_if_iso_resource(resource);
498 		}
499 	}
500 
501 	if (preload)
502 		idr_preload_end();
503 
504 	return ret < 0 ? ret : 0;
505 }
506 
507 static int release_client_resource(struct client *client, u32 handle,
508 				   client_resource_release_fn_t release,
509 				   struct client_resource **return_resource)
510 {
511 	struct client_resource *resource;
512 
513 	scoped_guard(spinlock_irq, &client->lock) {
514 		if (client->in_shutdown)
515 			resource = NULL;
516 		else
517 			resource = idr_find(&client->resource_idr, handle);
518 		if (resource && resource->release == release)
519 			idr_remove(&client->resource_idr, handle);
520 	}
521 
522 	if (!(resource && resource->release == release))
523 		return -EINVAL;
524 
525 	if (return_resource)
526 		*return_resource = resource;
527 	else
528 		resource->release(client, resource);
529 
530 	client_put(client);
531 
532 	return 0;
533 }
534 
535 static void release_transaction(struct client *client,
536 				struct client_resource *resource)
537 {
538 }
539 
540 static void complete_transaction(struct fw_card *card, int rcode, u32 request_tstamp,
541 				 u32 response_tstamp, void *payload, size_t length, void *data)
542 {
543 	struct outbound_transaction_event *e = data;
544 	struct client *client = e->client;
545 
546 	scoped_guard(spinlock_irqsave, &client->lock) {
547 		idr_remove(&client->resource_idr, e->r.resource.handle);
548 		if (client->in_shutdown)
549 			wake_up(&client->tx_flush_wait);
550 	}
551 
552 	switch (e->rsp.without_tstamp.type) {
553 	case FW_CDEV_EVENT_RESPONSE:
554 	{
555 		struct fw_cdev_event_response *rsp = &e->rsp.without_tstamp;
556 
557 		if (length < rsp->length)
558 			rsp->length = length;
559 		if (rcode == RCODE_COMPLETE)
560 			memcpy(rsp->data, payload, rsp->length);
561 
562 		rsp->rcode = rcode;
563 
564 		// In the case that sizeof(*rsp) doesn't align with the position of the
565 		// data, and the read is short, preserve an extra copy of the data
566 		// to stay compatible with a pre-2.6.27 bug.  Since the bug is harmless
567 		// for short reads and some apps depended on it, this is both safe
568 		// and prudent for compatibility.
569 		if (rsp->length <= sizeof(*rsp) - offsetof(typeof(*rsp), data))
570 			queue_event(client, &e->event, rsp, sizeof(*rsp), rsp->data, rsp->length);
571 		else
572 			queue_event(client, &e->event, rsp, sizeof(*rsp) + rsp->length, NULL, 0);
573 
574 		break;
575 	}
576 	case FW_CDEV_EVENT_RESPONSE2:
577 	{
578 		struct fw_cdev_event_response2 *rsp = &e->rsp.with_tstamp;
579 
580 		if (length < rsp->length)
581 			rsp->length = length;
582 		if (rcode == RCODE_COMPLETE)
583 			memcpy(rsp->data, payload, rsp->length);
584 
585 		rsp->rcode = rcode;
586 		rsp->request_tstamp = request_tstamp;
587 		rsp->response_tstamp = response_tstamp;
588 
589 		queue_event(client, &e->event, rsp, sizeof(*rsp) + rsp->length, NULL, 0);
590 
591 		break;
592 	}
593 	default:
594 		WARN_ON(1);
595 		break;
596 	}
597 
598 	/* Drop the idr's reference */
599 	client_put(client);
600 }
601 
602 static int init_request(struct client *client,
603 			struct fw_cdev_send_request *request,
604 			int destination_id, int speed)
605 {
606 	struct outbound_transaction_event *e;
607 	void *payload;
608 	int ret;
609 
610 	if (request->tcode != TCODE_STREAM_DATA &&
611 	    (request->length > 4096 || request->length > 512 << speed))
612 		return -EIO;
613 
614 	if (request->tcode == TCODE_WRITE_QUADLET_REQUEST &&
615 	    request->length < 4)
616 		return -EINVAL;
617 
618 	e = kmalloc(sizeof(*e) + request->length, GFP_KERNEL);
619 	if (e == NULL)
620 		return -ENOMEM;
621 	e->client = client;
622 
623 	if (client->version < FW_CDEV_VERSION_EVENT_ASYNC_TSTAMP) {
624 		struct fw_cdev_event_response *rsp = &e->rsp.without_tstamp;
625 
626 		rsp->type = FW_CDEV_EVENT_RESPONSE;
627 		rsp->length = request->length;
628 		rsp->closure = request->closure;
629 		payload = rsp->data;
630 	} else {
631 		struct fw_cdev_event_response2 *rsp = &e->rsp.with_tstamp;
632 
633 		rsp->type = FW_CDEV_EVENT_RESPONSE2;
634 		rsp->length = request->length;
635 		rsp->closure = request->closure;
636 		payload = rsp->data;
637 	}
638 
639 	if (request->data && copy_from_user(payload, u64_to_uptr(request->data), request->length)) {
640 		ret = -EFAULT;
641 		goto failed;
642 	}
643 
644 	e->r.resource.release = release_transaction;
645 	ret = add_client_resource(client, &e->r.resource, GFP_KERNEL);
646 	if (ret < 0)
647 		goto failed;
648 
649 	fw_send_request_with_tstamp(client->device->card, &e->r.transaction, request->tcode,
650 				    destination_id, request->generation, speed, request->offset,
651 				    payload, request->length, complete_transaction, e);
652 	return 0;
653 
654  failed:
655 	kfree(e);
656 
657 	return ret;
658 }
659 
660 static int ioctl_send_request(struct client *client, union ioctl_arg *arg)
661 {
662 	switch (arg->send_request.tcode) {
663 	case TCODE_WRITE_QUADLET_REQUEST:
664 	case TCODE_WRITE_BLOCK_REQUEST:
665 	case TCODE_READ_QUADLET_REQUEST:
666 	case TCODE_READ_BLOCK_REQUEST:
667 	case TCODE_LOCK_MASK_SWAP:
668 	case TCODE_LOCK_COMPARE_SWAP:
669 	case TCODE_LOCK_FETCH_ADD:
670 	case TCODE_LOCK_LITTLE_ADD:
671 	case TCODE_LOCK_BOUNDED_ADD:
672 	case TCODE_LOCK_WRAP_ADD:
673 	case TCODE_LOCK_VENDOR_DEPENDENT:
674 		break;
675 	default:
676 		return -EINVAL;
677 	}
678 
679 	return init_request(client, &arg->send_request, client->device->node_id,
680 			    client->device->max_speed);
681 }
682 
683 static void release_request(struct client *client,
684 			    struct client_resource *resource)
685 {
686 	struct inbound_transaction_resource *r = container_of(resource,
687 			struct inbound_transaction_resource, resource);
688 
689 	if (r->is_fcp)
690 		fw_request_put(r->request);
691 	else
692 		fw_send_response(r->card, r->request, RCODE_CONFLICT_ERROR);
693 
694 	fw_card_put(r->card);
695 	kfree(r);
696 }
697 
698 static void handle_request(struct fw_card *card, struct fw_request *request,
699 			   int tcode, int destination, int source,
700 			   int generation, unsigned long long offset,
701 			   void *payload, size_t length, void *callback_data)
702 {
703 	struct address_handler_resource *handler = callback_data;
704 	bool is_fcp = is_in_fcp_region(offset, length);
705 	struct inbound_transaction_resource *r;
706 	struct inbound_transaction_event *e;
707 	size_t event_size0;
708 	int ret;
709 
710 	/* card may be different from handler->client->device->card */
711 	fw_card_get(card);
712 
713 	// Extend the lifetime of data for request so that its payload is safely accessible in
714 	// the process context for the client.
715 	if (is_fcp)
716 		fw_request_get(request);
717 
718 	r = kmalloc(sizeof(*r), GFP_ATOMIC);
719 	e = kmalloc(sizeof(*e), GFP_ATOMIC);
720 	if (r == NULL || e == NULL)
721 		goto failed;
722 
723 	r->card    = card;
724 	r->request = request;
725 	r->is_fcp  = is_fcp;
726 	r->data    = payload;
727 	r->length  = length;
728 
729 	r->resource.release = release_request;
730 	ret = add_client_resource(handler->client, &r->resource, GFP_ATOMIC);
731 	if (ret < 0)
732 		goto failed;
733 
734 	if (handler->client->version < FW_CDEV_VERSION_EVENT_REQUEST2) {
735 		struct fw_cdev_event_request *req = &e->req.request;
736 
737 		if (tcode & 0x10)
738 			tcode = TCODE_LOCK_REQUEST;
739 
740 		req->type	= FW_CDEV_EVENT_REQUEST;
741 		req->tcode	= tcode;
742 		req->offset	= offset;
743 		req->length	= length;
744 		req->handle	= r->resource.handle;
745 		req->closure	= handler->closure;
746 		event_size0	= sizeof(*req);
747 	} else if (handler->client->version < FW_CDEV_VERSION_EVENT_ASYNC_TSTAMP) {
748 		struct fw_cdev_event_request2 *req = &e->req.request2;
749 
750 		req->type	= FW_CDEV_EVENT_REQUEST2;
751 		req->tcode	= tcode;
752 		req->offset	= offset;
753 		req->source_node_id = source;
754 		req->destination_node_id = destination;
755 		req->card	= card->index;
756 		req->generation	= generation;
757 		req->length	= length;
758 		req->handle	= r->resource.handle;
759 		req->closure	= handler->closure;
760 		event_size0	= sizeof(*req);
761 	} else {
762 		struct fw_cdev_event_request3 *req = &e->req.with_tstamp;
763 
764 		req->type	= FW_CDEV_EVENT_REQUEST3;
765 		req->tcode	= tcode;
766 		req->offset	= offset;
767 		req->source_node_id = source;
768 		req->destination_node_id = destination;
769 		req->card	= card->index;
770 		req->generation	= generation;
771 		req->length	= length;
772 		req->handle	= r->resource.handle;
773 		req->closure	= handler->closure;
774 		req->tstamp	= fw_request_get_timestamp(request);
775 		event_size0	= sizeof(*req);
776 	}
777 
778 	queue_event(handler->client, &e->event,
779 		    &e->req, event_size0, r->data, length);
780 	return;
781 
782  failed:
783 	kfree(r);
784 	kfree(e);
785 
786 	if (!is_fcp)
787 		fw_send_response(card, request, RCODE_CONFLICT_ERROR);
788 	else
789 		fw_request_put(request);
790 
791 	fw_card_put(card);
792 }
793 
794 static void release_address_handler(struct client *client,
795 				    struct client_resource *resource)
796 {
797 	struct address_handler_resource *r =
798 	    container_of(resource, struct address_handler_resource, resource);
799 
800 	fw_core_remove_address_handler(&r->handler);
801 	kfree(r);
802 }
803 
804 static int ioctl_allocate(struct client *client, union ioctl_arg *arg)
805 {
806 	struct fw_cdev_allocate *a = &arg->allocate;
807 	struct address_handler_resource *r;
808 	struct fw_address_region region;
809 	int ret;
810 
811 	r = kmalloc(sizeof(*r), GFP_KERNEL);
812 	if (r == NULL)
813 		return -ENOMEM;
814 
815 	region.start = a->offset;
816 	if (client->version < FW_CDEV_VERSION_ALLOCATE_REGION_END)
817 		region.end = a->offset + a->length;
818 	else
819 		region.end = a->region_end;
820 
821 	r->handler.length           = a->length;
822 	r->handler.address_callback = handle_request;
823 	r->handler.callback_data    = r;
824 	r->closure   = a->closure;
825 	r->client    = client;
826 
827 	ret = fw_core_add_address_handler(&r->handler, &region);
828 	if (ret < 0) {
829 		kfree(r);
830 		return ret;
831 	}
832 	a->offset = r->handler.offset;
833 
834 	r->resource.release = release_address_handler;
835 	ret = add_client_resource(client, &r->resource, GFP_KERNEL);
836 	if (ret < 0) {
837 		release_address_handler(client, &r->resource);
838 		return ret;
839 	}
840 	a->handle = r->resource.handle;
841 
842 	return 0;
843 }
844 
845 static int ioctl_deallocate(struct client *client, union ioctl_arg *arg)
846 {
847 	return release_client_resource(client, arg->deallocate.handle,
848 				       release_address_handler, NULL);
849 }
850 
851 static int ioctl_send_response(struct client *client, union ioctl_arg *arg)
852 {
853 	struct fw_cdev_send_response *a = &arg->send_response;
854 	struct client_resource *resource;
855 	struct inbound_transaction_resource *r;
856 	int ret = 0;
857 
858 	if (release_client_resource(client, a->handle,
859 				    release_request, &resource) < 0)
860 		return -EINVAL;
861 
862 	r = container_of(resource, struct inbound_transaction_resource,
863 			 resource);
864 	if (r->is_fcp) {
865 		fw_request_put(r->request);
866 		goto out;
867 	}
868 
869 	if (a->length != fw_get_response_length(r->request)) {
870 		ret = -EINVAL;
871 		fw_request_put(r->request);
872 		goto out;
873 	}
874 	if (copy_from_user(r->data, u64_to_uptr(a->data), a->length)) {
875 		ret = -EFAULT;
876 		fw_request_put(r->request);
877 		goto out;
878 	}
879 	fw_send_response(r->card, r->request, a->rcode);
880  out:
881 	fw_card_put(r->card);
882 	kfree(r);
883 
884 	return ret;
885 }
886 
887 static int ioctl_initiate_bus_reset(struct client *client, union ioctl_arg *arg)
888 {
889 	fw_schedule_bus_reset(client->device->card, true,
890 			arg->initiate_bus_reset.type == FW_CDEV_SHORT_RESET);
891 	return 0;
892 }
893 
894 static void release_descriptor(struct client *client,
895 			       struct client_resource *resource)
896 {
897 	struct descriptor_resource *r =
898 		container_of(resource, struct descriptor_resource, resource);
899 
900 	fw_core_remove_descriptor(&r->descriptor);
901 	kfree(r);
902 }
903 
904 static int ioctl_add_descriptor(struct client *client, union ioctl_arg *arg)
905 {
906 	struct fw_cdev_add_descriptor *a = &arg->add_descriptor;
907 	struct descriptor_resource *r;
908 	int ret;
909 
910 	/* Access policy: Allow this ioctl only on local nodes' device files. */
911 	if (!client->device->is_local)
912 		return -ENOSYS;
913 
914 	if (a->length > 256)
915 		return -EINVAL;
916 
917 	r = kmalloc(sizeof(*r) + a->length * 4, GFP_KERNEL);
918 	if (r == NULL)
919 		return -ENOMEM;
920 
921 	if (copy_from_user(r->data, u64_to_uptr(a->data), a->length * 4)) {
922 		ret = -EFAULT;
923 		goto failed;
924 	}
925 
926 	r->descriptor.length    = a->length;
927 	r->descriptor.immediate = a->immediate;
928 	r->descriptor.key       = a->key;
929 	r->descriptor.data      = r->data;
930 
931 	ret = fw_core_add_descriptor(&r->descriptor);
932 	if (ret < 0)
933 		goto failed;
934 
935 	r->resource.release = release_descriptor;
936 	ret = add_client_resource(client, &r->resource, GFP_KERNEL);
937 	if (ret < 0) {
938 		fw_core_remove_descriptor(&r->descriptor);
939 		goto failed;
940 	}
941 	a->handle = r->resource.handle;
942 
943 	return 0;
944  failed:
945 	kfree(r);
946 
947 	return ret;
948 }
949 
950 static int ioctl_remove_descriptor(struct client *client, union ioctl_arg *arg)
951 {
952 	return release_client_resource(client, arg->remove_descriptor.handle,
953 				       release_descriptor, NULL);
954 }
955 
956 static void iso_callback(struct fw_iso_context *context, u32 cycle,
957 			 size_t header_length, void *header, void *data)
958 {
959 	struct client *client = data;
960 	struct iso_interrupt_event *e;
961 
962 	e = kmalloc(sizeof(*e) + header_length, GFP_ATOMIC);
963 	if (e == NULL)
964 		return;
965 
966 	e->interrupt.type      = FW_CDEV_EVENT_ISO_INTERRUPT;
967 	e->interrupt.closure   = client->iso_closure;
968 	e->interrupt.cycle     = cycle;
969 	e->interrupt.header_length = header_length;
970 	memcpy(e->interrupt.header, header, header_length);
971 	queue_event(client, &e->event, &e->interrupt,
972 		    sizeof(e->interrupt) + header_length, NULL, 0);
973 }
974 
975 static void iso_mc_callback(struct fw_iso_context *context,
976 			    dma_addr_t completed, void *data)
977 {
978 	struct client *client = data;
979 	struct iso_interrupt_mc_event *e;
980 
981 	e = kmalloc(sizeof(*e), GFP_ATOMIC);
982 	if (e == NULL)
983 		return;
984 
985 	e->interrupt.type      = FW_CDEV_EVENT_ISO_INTERRUPT_MULTICHANNEL;
986 	e->interrupt.closure   = client->iso_closure;
987 	e->interrupt.completed = fw_iso_buffer_lookup(&client->buffer,
988 						      completed);
989 	queue_event(client, &e->event, &e->interrupt,
990 		    sizeof(e->interrupt), NULL, 0);
991 }
992 
993 static enum dma_data_direction iso_dma_direction(struct fw_iso_context *context)
994 {
995 		if (context->type == FW_ISO_CONTEXT_TRANSMIT)
996 			return DMA_TO_DEVICE;
997 		else
998 			return DMA_FROM_DEVICE;
999 }
1000 
1001 static struct fw_iso_context *fw_iso_mc_context_create(struct fw_card *card,
1002 						fw_iso_mc_callback_t callback,
1003 						void *callback_data)
1004 {
1005 	struct fw_iso_context *ctx;
1006 
1007 	ctx = fw_iso_context_create(card, FW_ISO_CONTEXT_RECEIVE_MULTICHANNEL,
1008 				    0, 0, 0, NULL, callback_data);
1009 	if (!IS_ERR(ctx))
1010 		ctx->callback.mc = callback;
1011 
1012 	return ctx;
1013 }
1014 
1015 static int ioctl_create_iso_context(struct client *client, union ioctl_arg *arg)
1016 {
1017 	struct fw_cdev_create_iso_context *a = &arg->create_iso_context;
1018 	struct fw_iso_context *context;
1019 	union fw_iso_callback cb;
1020 	int ret;
1021 
1022 	BUILD_BUG_ON(FW_CDEV_ISO_CONTEXT_TRANSMIT != FW_ISO_CONTEXT_TRANSMIT ||
1023 		     FW_CDEV_ISO_CONTEXT_RECEIVE  != FW_ISO_CONTEXT_RECEIVE  ||
1024 		     FW_CDEV_ISO_CONTEXT_RECEIVE_MULTICHANNEL !=
1025 					FW_ISO_CONTEXT_RECEIVE_MULTICHANNEL);
1026 
1027 	switch (a->type) {
1028 	case FW_ISO_CONTEXT_TRANSMIT:
1029 		if (a->speed > SCODE_3200 || a->channel > 63)
1030 			return -EINVAL;
1031 
1032 		cb.sc = iso_callback;
1033 		break;
1034 
1035 	case FW_ISO_CONTEXT_RECEIVE:
1036 		if (a->header_size < 4 || (a->header_size & 3) ||
1037 		    a->channel > 63)
1038 			return -EINVAL;
1039 
1040 		cb.sc = iso_callback;
1041 		break;
1042 
1043 	case FW_ISO_CONTEXT_RECEIVE_MULTICHANNEL:
1044 		cb.mc = iso_mc_callback;
1045 		break;
1046 
1047 	default:
1048 		return -EINVAL;
1049 	}
1050 
1051 	if (a->type == FW_ISO_CONTEXT_RECEIVE_MULTICHANNEL)
1052 		context = fw_iso_mc_context_create(client->device->card, cb.mc,
1053 						   client);
1054 	else
1055 		context = fw_iso_context_create(client->device->card, a->type,
1056 						a->channel, a->speed,
1057 						a->header_size, cb.sc, client);
1058 	if (IS_ERR(context))
1059 		return PTR_ERR(context);
1060 	if (client->version < FW_CDEV_VERSION_AUTO_FLUSH_ISO_OVERFLOW)
1061 		context->drop_overflow_headers = true;
1062 
1063 	// We only support one context at this time.
1064 	guard(spinlock_irq)(&client->lock);
1065 
1066 	if (client->iso_context != NULL) {
1067 		fw_iso_context_destroy(context);
1068 
1069 		return -EBUSY;
1070 	}
1071 	if (!client->buffer_is_mapped) {
1072 		ret = fw_iso_buffer_map_dma(&client->buffer,
1073 					    client->device->card,
1074 					    iso_dma_direction(context));
1075 		if (ret < 0) {
1076 			fw_iso_context_destroy(context);
1077 
1078 			return ret;
1079 		}
1080 		client->buffer_is_mapped = true;
1081 	}
1082 	client->iso_closure = a->closure;
1083 	client->iso_context = context;
1084 
1085 	a->handle = 0;
1086 
1087 	return 0;
1088 }
1089 
1090 static int ioctl_set_iso_channels(struct client *client, union ioctl_arg *arg)
1091 {
1092 	struct fw_cdev_set_iso_channels *a = &arg->set_iso_channels;
1093 	struct fw_iso_context *ctx = client->iso_context;
1094 
1095 	if (ctx == NULL || a->handle != 0)
1096 		return -EINVAL;
1097 
1098 	return fw_iso_context_set_channels(ctx, &a->channels);
1099 }
1100 
1101 /* Macros for decoding the iso packet control header. */
1102 #define GET_PAYLOAD_LENGTH(v)	((v) & 0xffff)
1103 #define GET_INTERRUPT(v)	(((v) >> 16) & 0x01)
1104 #define GET_SKIP(v)		(((v) >> 17) & 0x01)
1105 #define GET_TAG(v)		(((v) >> 18) & 0x03)
1106 #define GET_SY(v)		(((v) >> 20) & 0x0f)
1107 #define GET_HEADER_LENGTH(v)	(((v) >> 24) & 0xff)
1108 
1109 static int ioctl_queue_iso(struct client *client, union ioctl_arg *arg)
1110 {
1111 	struct fw_cdev_queue_iso *a = &arg->queue_iso;
1112 	struct fw_cdev_iso_packet __user *p, *end, *next;
1113 	struct fw_iso_context *ctx = client->iso_context;
1114 	unsigned long payload, buffer_end, transmit_header_bytes = 0;
1115 	u32 control;
1116 	int count;
1117 	struct {
1118 		struct fw_iso_packet packet;
1119 		u8 header[256];
1120 	} u;
1121 
1122 	if (ctx == NULL || a->handle != 0)
1123 		return -EINVAL;
1124 
1125 	/*
1126 	 * If the user passes a non-NULL data pointer, has mmap()'ed
1127 	 * the iso buffer, and the pointer points inside the buffer,
1128 	 * we setup the payload pointers accordingly.  Otherwise we
1129 	 * set them both to 0, which will still let packets with
1130 	 * payload_length == 0 through.  In other words, if no packets
1131 	 * use the indirect payload, the iso buffer need not be mapped
1132 	 * and the a->data pointer is ignored.
1133 	 */
1134 	payload = (unsigned long)a->data - client->vm_start;
1135 	buffer_end = client->buffer.page_count << PAGE_SHIFT;
1136 	if (a->data == 0 || client->buffer.pages == NULL ||
1137 	    payload >= buffer_end) {
1138 		payload = 0;
1139 		buffer_end = 0;
1140 	}
1141 
1142 	if (ctx->type == FW_ISO_CONTEXT_RECEIVE_MULTICHANNEL && payload & 3)
1143 		return -EINVAL;
1144 
1145 	p = (struct fw_cdev_iso_packet __user *)u64_to_uptr(a->packets);
1146 
1147 	end = (void __user *)p + a->size;
1148 	count = 0;
1149 	while (p < end) {
1150 		if (get_user(control, &p->control))
1151 			return -EFAULT;
1152 		u.packet.payload_length = GET_PAYLOAD_LENGTH(control);
1153 		u.packet.interrupt = GET_INTERRUPT(control);
1154 		u.packet.skip = GET_SKIP(control);
1155 		u.packet.tag = GET_TAG(control);
1156 		u.packet.sy = GET_SY(control);
1157 		u.packet.header_length = GET_HEADER_LENGTH(control);
1158 
1159 		switch (ctx->type) {
1160 		case FW_ISO_CONTEXT_TRANSMIT:
1161 			if (u.packet.header_length & 3)
1162 				return -EINVAL;
1163 			transmit_header_bytes = u.packet.header_length;
1164 			break;
1165 
1166 		case FW_ISO_CONTEXT_RECEIVE:
1167 			if (u.packet.header_length == 0 ||
1168 			    u.packet.header_length % ctx->header_size != 0)
1169 				return -EINVAL;
1170 			break;
1171 
1172 		case FW_ISO_CONTEXT_RECEIVE_MULTICHANNEL:
1173 			if (u.packet.payload_length == 0 ||
1174 			    u.packet.payload_length & 3)
1175 				return -EINVAL;
1176 			break;
1177 		}
1178 
1179 		next = (struct fw_cdev_iso_packet __user *)
1180 			&p->header[transmit_header_bytes / 4];
1181 		if (next > end)
1182 			return -EINVAL;
1183 		if (copy_from_user
1184 		    (u.packet.header, p->header, transmit_header_bytes))
1185 			return -EFAULT;
1186 		if (u.packet.skip && ctx->type == FW_ISO_CONTEXT_TRANSMIT &&
1187 		    u.packet.header_length + u.packet.payload_length > 0)
1188 			return -EINVAL;
1189 		if (payload + u.packet.payload_length > buffer_end)
1190 			return -EINVAL;
1191 
1192 		if (fw_iso_context_queue(ctx, &u.packet,
1193 					 &client->buffer, payload))
1194 			break;
1195 
1196 		p = next;
1197 		payload += u.packet.payload_length;
1198 		count++;
1199 	}
1200 	fw_iso_context_queue_flush(ctx);
1201 
1202 	a->size    -= uptr_to_u64(p) - a->packets;
1203 	a->packets  = uptr_to_u64(p);
1204 	a->data     = client->vm_start + payload;
1205 
1206 	return count;
1207 }
1208 
1209 static int ioctl_start_iso(struct client *client, union ioctl_arg *arg)
1210 {
1211 	struct fw_cdev_start_iso *a = &arg->start_iso;
1212 
1213 	BUILD_BUG_ON(
1214 	    FW_CDEV_ISO_CONTEXT_MATCH_TAG0 != FW_ISO_CONTEXT_MATCH_TAG0 ||
1215 	    FW_CDEV_ISO_CONTEXT_MATCH_TAG1 != FW_ISO_CONTEXT_MATCH_TAG1 ||
1216 	    FW_CDEV_ISO_CONTEXT_MATCH_TAG2 != FW_ISO_CONTEXT_MATCH_TAG2 ||
1217 	    FW_CDEV_ISO_CONTEXT_MATCH_TAG3 != FW_ISO_CONTEXT_MATCH_TAG3 ||
1218 	    FW_CDEV_ISO_CONTEXT_MATCH_ALL_TAGS != FW_ISO_CONTEXT_MATCH_ALL_TAGS);
1219 
1220 	if (client->iso_context == NULL || a->handle != 0)
1221 		return -EINVAL;
1222 
1223 	if (client->iso_context->type == FW_ISO_CONTEXT_RECEIVE &&
1224 	    (a->tags == 0 || a->tags > 15 || a->sync > 15))
1225 		return -EINVAL;
1226 
1227 	return fw_iso_context_start(client->iso_context,
1228 				    a->cycle, a->sync, a->tags);
1229 }
1230 
1231 static int ioctl_stop_iso(struct client *client, union ioctl_arg *arg)
1232 {
1233 	struct fw_cdev_stop_iso *a = &arg->stop_iso;
1234 
1235 	if (client->iso_context == NULL || a->handle != 0)
1236 		return -EINVAL;
1237 
1238 	return fw_iso_context_stop(client->iso_context);
1239 }
1240 
1241 static int ioctl_flush_iso(struct client *client, union ioctl_arg *arg)
1242 {
1243 	struct fw_cdev_flush_iso *a = &arg->flush_iso;
1244 
1245 	if (client->iso_context == NULL || a->handle != 0)
1246 		return -EINVAL;
1247 
1248 	return fw_iso_context_flush_completions(client->iso_context);
1249 }
1250 
1251 static int ioctl_get_cycle_timer2(struct client *client, union ioctl_arg *arg)
1252 {
1253 	struct fw_cdev_get_cycle_timer2 *a = &arg->get_cycle_timer2;
1254 	struct fw_card *card = client->device->card;
1255 	struct timespec64 ts = {0, 0};
1256 	u32 cycle_time = 0;
1257 	int ret;
1258 
1259 	guard(irq)();
1260 
1261 	ret = fw_card_read_cycle_time(card, &cycle_time);
1262 	if (ret < 0)
1263 		return ret;
1264 
1265 	switch (a->clk_id) {
1266 	case CLOCK_REALTIME:      ktime_get_real_ts64(&ts);	break;
1267 	case CLOCK_MONOTONIC:     ktime_get_ts64(&ts);		break;
1268 	case CLOCK_MONOTONIC_RAW: ktime_get_raw_ts64(&ts);	break;
1269 	default:
1270 		return -EINVAL;
1271 	}
1272 
1273 	a->tv_sec      = ts.tv_sec;
1274 	a->tv_nsec     = ts.tv_nsec;
1275 	a->cycle_timer = cycle_time;
1276 
1277 	return 0;
1278 }
1279 
1280 static int ioctl_get_cycle_timer(struct client *client, union ioctl_arg *arg)
1281 {
1282 	struct fw_cdev_get_cycle_timer *a = &arg->get_cycle_timer;
1283 	struct fw_cdev_get_cycle_timer2 ct2;
1284 
1285 	ct2.clk_id = CLOCK_REALTIME;
1286 	ioctl_get_cycle_timer2(client, (union ioctl_arg *)&ct2);
1287 
1288 	a->local_time = ct2.tv_sec * USEC_PER_SEC + ct2.tv_nsec / NSEC_PER_USEC;
1289 	a->cycle_timer = ct2.cycle_timer;
1290 
1291 	return 0;
1292 }
1293 
1294 static void iso_resource_work(struct work_struct *work)
1295 {
1296 	struct iso_resource_event *e;
1297 	struct iso_resource *r =
1298 			container_of(work, struct iso_resource, work.work);
1299 	struct client *client = r->client;
1300 	int generation, channel, bandwidth, todo;
1301 	bool skip, free, success;
1302 
1303 	scoped_guard(spinlock_irq, &client->lock) {
1304 		generation = client->device->generation;
1305 		todo = r->todo;
1306 		// Allow 1000ms grace period for other reallocations.
1307 		if (todo == ISO_RES_ALLOC &&
1308 		    time_before64(get_jiffies_64(), client->device->card->reset_jiffies + HZ)) {
1309 			schedule_iso_resource(r, DIV_ROUND_UP(HZ, 3));
1310 			skip = true;
1311 		} else {
1312 			// We could be called twice within the same generation.
1313 			skip = todo == ISO_RES_REALLOC &&
1314 			       r->generation == generation;
1315 		}
1316 		free = todo == ISO_RES_DEALLOC ||
1317 		       todo == ISO_RES_ALLOC_ONCE ||
1318 		       todo == ISO_RES_DEALLOC_ONCE;
1319 		r->generation = generation;
1320 	}
1321 
1322 	if (skip)
1323 		goto out;
1324 
1325 	bandwidth = r->bandwidth;
1326 
1327 	fw_iso_resource_manage(client->device->card, generation,
1328 			r->channels, &channel, &bandwidth,
1329 			todo == ISO_RES_ALLOC ||
1330 			todo == ISO_RES_REALLOC ||
1331 			todo == ISO_RES_ALLOC_ONCE);
1332 	/*
1333 	 * Is this generation outdated already?  As long as this resource sticks
1334 	 * in the idr, it will be scheduled again for a newer generation or at
1335 	 * shutdown.
1336 	 */
1337 	if (channel == -EAGAIN &&
1338 	    (todo == ISO_RES_ALLOC || todo == ISO_RES_REALLOC))
1339 		goto out;
1340 
1341 	success = channel >= 0 || bandwidth > 0;
1342 
1343 	scoped_guard(spinlock_irq, &client->lock) {
1344 		// Transit from allocation to reallocation, except if the client
1345 		// requested deallocation in the meantime.
1346 		if (r->todo == ISO_RES_ALLOC)
1347 			r->todo = ISO_RES_REALLOC;
1348 		// Allocation or reallocation failure?  Pull this resource out of the
1349 		// idr and prepare for deletion, unless the client is shutting down.
1350 		if (r->todo == ISO_RES_REALLOC && !success &&
1351 		    !client->in_shutdown &&
1352 		    idr_remove(&client->resource_idr, r->resource.handle)) {
1353 			client_put(client);
1354 			free = true;
1355 		}
1356 	}
1357 
1358 	if (todo == ISO_RES_ALLOC && channel >= 0)
1359 		r->channels = 1ULL << channel;
1360 
1361 	if (todo == ISO_RES_REALLOC && success)
1362 		goto out;
1363 
1364 	if (todo == ISO_RES_ALLOC || todo == ISO_RES_ALLOC_ONCE) {
1365 		e = r->e_alloc;
1366 		r->e_alloc = NULL;
1367 	} else {
1368 		e = r->e_dealloc;
1369 		r->e_dealloc = NULL;
1370 	}
1371 	e->iso_resource.handle    = r->resource.handle;
1372 	e->iso_resource.channel   = channel;
1373 	e->iso_resource.bandwidth = bandwidth;
1374 
1375 	queue_event(client, &e->event,
1376 		    &e->iso_resource, sizeof(e->iso_resource), NULL, 0);
1377 
1378 	if (free) {
1379 		cancel_delayed_work(&r->work);
1380 		kfree(r->e_alloc);
1381 		kfree(r->e_dealloc);
1382 		kfree(r);
1383 	}
1384  out:
1385 	client_put(client);
1386 }
1387 
1388 static void release_iso_resource(struct client *client,
1389 				 struct client_resource *resource)
1390 {
1391 	struct iso_resource *r =
1392 		container_of(resource, struct iso_resource, resource);
1393 
1394 	guard(spinlock_irq)(&client->lock);
1395 
1396 	r->todo = ISO_RES_DEALLOC;
1397 	schedule_iso_resource(r, 0);
1398 }
1399 
1400 static int init_iso_resource(struct client *client,
1401 		struct fw_cdev_allocate_iso_resource *request, int todo)
1402 {
1403 	struct iso_resource_event *e1, *e2;
1404 	struct iso_resource *r;
1405 	int ret;
1406 
1407 	if ((request->channels == 0 && request->bandwidth == 0) ||
1408 	    request->bandwidth > BANDWIDTH_AVAILABLE_INITIAL)
1409 		return -EINVAL;
1410 
1411 	r  = kmalloc(sizeof(*r), GFP_KERNEL);
1412 	e1 = kmalloc(sizeof(*e1), GFP_KERNEL);
1413 	e2 = kmalloc(sizeof(*e2), GFP_KERNEL);
1414 	if (r == NULL || e1 == NULL || e2 == NULL) {
1415 		ret = -ENOMEM;
1416 		goto fail;
1417 	}
1418 
1419 	INIT_DELAYED_WORK(&r->work, iso_resource_work);
1420 	r->client	= client;
1421 	r->todo		= todo;
1422 	r->generation	= -1;
1423 	r->channels	= request->channels;
1424 	r->bandwidth	= request->bandwidth;
1425 	r->e_alloc	= e1;
1426 	r->e_dealloc	= e2;
1427 
1428 	e1->iso_resource.closure = request->closure;
1429 	e1->iso_resource.type    = FW_CDEV_EVENT_ISO_RESOURCE_ALLOCATED;
1430 	e2->iso_resource.closure = request->closure;
1431 	e2->iso_resource.type    = FW_CDEV_EVENT_ISO_RESOURCE_DEALLOCATED;
1432 
1433 	if (todo == ISO_RES_ALLOC) {
1434 		r->resource.release = release_iso_resource;
1435 		ret = add_client_resource(client, &r->resource, GFP_KERNEL);
1436 		if (ret < 0)
1437 			goto fail;
1438 	} else {
1439 		r->resource.release = NULL;
1440 		r->resource.handle = -1;
1441 		schedule_iso_resource(r, 0);
1442 	}
1443 	request->handle = r->resource.handle;
1444 
1445 	return 0;
1446  fail:
1447 	kfree(r);
1448 	kfree(e1);
1449 	kfree(e2);
1450 
1451 	return ret;
1452 }
1453 
1454 static int ioctl_allocate_iso_resource(struct client *client,
1455 				       union ioctl_arg *arg)
1456 {
1457 	return init_iso_resource(client,
1458 			&arg->allocate_iso_resource, ISO_RES_ALLOC);
1459 }
1460 
1461 static int ioctl_deallocate_iso_resource(struct client *client,
1462 					 union ioctl_arg *arg)
1463 {
1464 	return release_client_resource(client,
1465 			arg->deallocate.handle, release_iso_resource, NULL);
1466 }
1467 
1468 static int ioctl_allocate_iso_resource_once(struct client *client,
1469 					    union ioctl_arg *arg)
1470 {
1471 	return init_iso_resource(client,
1472 			&arg->allocate_iso_resource, ISO_RES_ALLOC_ONCE);
1473 }
1474 
1475 static int ioctl_deallocate_iso_resource_once(struct client *client,
1476 					      union ioctl_arg *arg)
1477 {
1478 	return init_iso_resource(client,
1479 			&arg->allocate_iso_resource, ISO_RES_DEALLOC_ONCE);
1480 }
1481 
1482 /*
1483  * Returns a speed code:  Maximum speed to or from this device,
1484  * limited by the device's link speed, the local node's link speed,
1485  * and all PHY port speeds between the two links.
1486  */
1487 static int ioctl_get_speed(struct client *client, union ioctl_arg *arg)
1488 {
1489 	return client->device->max_speed;
1490 }
1491 
1492 static int ioctl_send_broadcast_request(struct client *client,
1493 					union ioctl_arg *arg)
1494 {
1495 	struct fw_cdev_send_request *a = &arg->send_request;
1496 
1497 	switch (a->tcode) {
1498 	case TCODE_WRITE_QUADLET_REQUEST:
1499 	case TCODE_WRITE_BLOCK_REQUEST:
1500 		break;
1501 	default:
1502 		return -EINVAL;
1503 	}
1504 
1505 	/* Security policy: Only allow accesses to Units Space. */
1506 	if (a->offset < CSR_REGISTER_BASE + CSR_CONFIG_ROM_END)
1507 		return -EACCES;
1508 
1509 	return init_request(client, a, LOCAL_BUS | 0x3f, SCODE_100);
1510 }
1511 
1512 static int ioctl_send_stream_packet(struct client *client, union ioctl_arg *arg)
1513 {
1514 	struct fw_cdev_send_stream_packet *a = &arg->send_stream_packet;
1515 	struct fw_cdev_send_request request;
1516 	int dest;
1517 
1518 	if (a->speed > client->device->card->link_speed ||
1519 	    a->length > 1024 << a->speed)
1520 		return -EIO;
1521 
1522 	if (a->tag > 3 || a->channel > 63 || a->sy > 15)
1523 		return -EINVAL;
1524 
1525 	dest = fw_stream_packet_destination_id(a->tag, a->channel, a->sy);
1526 	request.tcode		= TCODE_STREAM_DATA;
1527 	request.length		= a->length;
1528 	request.closure		= a->closure;
1529 	request.data		= a->data;
1530 	request.generation	= a->generation;
1531 
1532 	return init_request(client, &request, dest, a->speed);
1533 }
1534 
1535 static void outbound_phy_packet_callback(struct fw_packet *packet,
1536 					 struct fw_card *card, int status)
1537 {
1538 	struct outbound_phy_packet_event *e =
1539 		container_of(packet, struct outbound_phy_packet_event, p);
1540 	struct client *e_client = e->client;
1541 	u32 rcode;
1542 
1543 	trace_async_phy_outbound_complete((uintptr_t)packet, card->index, status, packet->generation,
1544 					  packet->timestamp);
1545 
1546 	switch (status) {
1547 	// expected:
1548 	case ACK_COMPLETE:
1549 		rcode = RCODE_COMPLETE;
1550 		break;
1551 	// should never happen with PHY packets:
1552 	case ACK_PENDING:
1553 		rcode = RCODE_COMPLETE;
1554 		break;
1555 	case ACK_BUSY_X:
1556 	case ACK_BUSY_A:
1557 	case ACK_BUSY_B:
1558 		rcode = RCODE_BUSY;
1559 		break;
1560 	case ACK_DATA_ERROR:
1561 		rcode = RCODE_DATA_ERROR;
1562 		break;
1563 	case ACK_TYPE_ERROR:
1564 		rcode = RCODE_TYPE_ERROR;
1565 		break;
1566 	// stale generation; cancelled; on certain controllers: no ack
1567 	default:
1568 		rcode = status;
1569 		break;
1570 	}
1571 
1572 	switch (e->phy_packet.without_tstamp.type) {
1573 	case FW_CDEV_EVENT_PHY_PACKET_SENT:
1574 	{
1575 		struct fw_cdev_event_phy_packet *pp = &e->phy_packet.without_tstamp;
1576 
1577 		pp->rcode = rcode;
1578 		pp->data[0] = packet->timestamp;
1579 		queue_event(e->client, &e->event, &e->phy_packet, sizeof(*pp) + pp->length,
1580 			    NULL, 0);
1581 		break;
1582 	}
1583 	case FW_CDEV_EVENT_PHY_PACKET_SENT2:
1584 	{
1585 		struct fw_cdev_event_phy_packet2 *pp = &e->phy_packet.with_tstamp;
1586 
1587 		pp->rcode = rcode;
1588 		pp->tstamp = packet->timestamp;
1589 		queue_event(e->client, &e->event, &e->phy_packet, sizeof(*pp) + pp->length,
1590 			    NULL, 0);
1591 		break;
1592 	}
1593 	default:
1594 		WARN_ON(1);
1595 		break;
1596 	}
1597 
1598 	client_put(e_client);
1599 }
1600 
1601 static int ioctl_send_phy_packet(struct client *client, union ioctl_arg *arg)
1602 {
1603 	struct fw_cdev_send_phy_packet *a = &arg->send_phy_packet;
1604 	struct fw_card *card = client->device->card;
1605 	struct outbound_phy_packet_event *e;
1606 
1607 	/* Access policy: Allow this ioctl only on local nodes' device files. */
1608 	if (!client->device->is_local)
1609 		return -ENOSYS;
1610 
1611 	e = kzalloc(sizeof(*e) + sizeof(a->data), GFP_KERNEL);
1612 	if (e == NULL)
1613 		return -ENOMEM;
1614 
1615 	client_get(client);
1616 	e->client		= client;
1617 	e->p.speed		= SCODE_100;
1618 	e->p.generation		= a->generation;
1619 	async_header_set_tcode(e->p.header, TCODE_LINK_INTERNAL);
1620 	e->p.header[1]		= a->data[0];
1621 	e->p.header[2]		= a->data[1];
1622 	e->p.header_length	= 12;
1623 	e->p.callback		= outbound_phy_packet_callback;
1624 
1625 	if (client->version < FW_CDEV_VERSION_EVENT_ASYNC_TSTAMP) {
1626 		struct fw_cdev_event_phy_packet *pp = &e->phy_packet.without_tstamp;
1627 
1628 		pp->closure = a->closure;
1629 		pp->type = FW_CDEV_EVENT_PHY_PACKET_SENT;
1630 		if (is_ping_packet(a->data))
1631 			pp->length = 4;
1632 	} else {
1633 		struct fw_cdev_event_phy_packet2 *pp = &e->phy_packet.with_tstamp;
1634 
1635 		pp->closure = a->closure;
1636 		pp->type = FW_CDEV_EVENT_PHY_PACKET_SENT2;
1637 		// Keep the data field so that application can match the response event to the
1638 		// request.
1639 		pp->length = sizeof(a->data);
1640 		memcpy(pp->data, a->data, sizeof(a->data));
1641 	}
1642 
1643 	trace_async_phy_outbound_initiate((uintptr_t)&e->p, card->index, e->p.generation,
1644 					  e->p.header[1], e->p.header[2]);
1645 
1646 	card->driver->send_request(card, &e->p);
1647 
1648 	return 0;
1649 }
1650 
1651 static int ioctl_receive_phy_packets(struct client *client, union ioctl_arg *arg)
1652 {
1653 	struct fw_cdev_receive_phy_packets *a = &arg->receive_phy_packets;
1654 	struct fw_card *card = client->device->card;
1655 
1656 	/* Access policy: Allow this ioctl only on local nodes' device files. */
1657 	if (!client->device->is_local)
1658 		return -ENOSYS;
1659 
1660 	guard(spinlock_irq)(&card->lock);
1661 
1662 	list_move_tail(&client->phy_receiver_link, &card->phy_receiver_list);
1663 	client->phy_receiver_closure = a->closure;
1664 
1665 	return 0;
1666 }
1667 
1668 void fw_cdev_handle_phy_packet(struct fw_card *card, struct fw_packet *p)
1669 {
1670 	struct client *client;
1671 
1672 	guard(spinlock_irqsave)(&card->lock);
1673 
1674 	list_for_each_entry(client, &card->phy_receiver_list, phy_receiver_link) {
1675 		struct inbound_phy_packet_event *e = kmalloc(sizeof(*e) + 8, GFP_ATOMIC);
1676 		if (e == NULL)
1677 			break;
1678 
1679 		if (client->version < FW_CDEV_VERSION_EVENT_ASYNC_TSTAMP) {
1680 			struct fw_cdev_event_phy_packet *pp = &e->phy_packet.without_tstamp;
1681 
1682 			pp->closure = client->phy_receiver_closure;
1683 			pp->type = FW_CDEV_EVENT_PHY_PACKET_RECEIVED;
1684 			pp->rcode = RCODE_COMPLETE;
1685 			pp->length = 8;
1686 			pp->data[0] = p->header[1];
1687 			pp->data[1] = p->header[2];
1688 			queue_event(client, &e->event, &e->phy_packet, sizeof(*pp) + 8, NULL, 0);
1689 		} else {
1690 			struct fw_cdev_event_phy_packet2 *pp = &e->phy_packet.with_tstamp;
1691 
1692 			pp = &e->phy_packet.with_tstamp;
1693 			pp->closure = client->phy_receiver_closure;
1694 			pp->type = FW_CDEV_EVENT_PHY_PACKET_RECEIVED2;
1695 			pp->rcode = RCODE_COMPLETE;
1696 			pp->length = 8;
1697 			pp->tstamp = p->timestamp;
1698 			pp->data[0] = p->header[1];
1699 			pp->data[1] = p->header[2];
1700 			queue_event(client, &e->event, &e->phy_packet, sizeof(*pp) + 8, NULL, 0);
1701 		}
1702 	}
1703 }
1704 
1705 static int (* const ioctl_handlers[])(struct client *, union ioctl_arg *) = {
1706 	[0x00] = ioctl_get_info,
1707 	[0x01] = ioctl_send_request,
1708 	[0x02] = ioctl_allocate,
1709 	[0x03] = ioctl_deallocate,
1710 	[0x04] = ioctl_send_response,
1711 	[0x05] = ioctl_initiate_bus_reset,
1712 	[0x06] = ioctl_add_descriptor,
1713 	[0x07] = ioctl_remove_descriptor,
1714 	[0x08] = ioctl_create_iso_context,
1715 	[0x09] = ioctl_queue_iso,
1716 	[0x0a] = ioctl_start_iso,
1717 	[0x0b] = ioctl_stop_iso,
1718 	[0x0c] = ioctl_get_cycle_timer,
1719 	[0x0d] = ioctl_allocate_iso_resource,
1720 	[0x0e] = ioctl_deallocate_iso_resource,
1721 	[0x0f] = ioctl_allocate_iso_resource_once,
1722 	[0x10] = ioctl_deallocate_iso_resource_once,
1723 	[0x11] = ioctl_get_speed,
1724 	[0x12] = ioctl_send_broadcast_request,
1725 	[0x13] = ioctl_send_stream_packet,
1726 	[0x14] = ioctl_get_cycle_timer2,
1727 	[0x15] = ioctl_send_phy_packet,
1728 	[0x16] = ioctl_receive_phy_packets,
1729 	[0x17] = ioctl_set_iso_channels,
1730 	[0x18] = ioctl_flush_iso,
1731 };
1732 
1733 static int dispatch_ioctl(struct client *client,
1734 			  unsigned int cmd, void __user *arg)
1735 {
1736 	union ioctl_arg buffer;
1737 	int ret;
1738 
1739 	if (fw_device_is_shutdown(client->device))
1740 		return -ENODEV;
1741 
1742 	if (_IOC_TYPE(cmd) != '#' ||
1743 	    _IOC_NR(cmd) >= ARRAY_SIZE(ioctl_handlers) ||
1744 	    _IOC_SIZE(cmd) > sizeof(buffer))
1745 		return -ENOTTY;
1746 
1747 	memset(&buffer, 0, sizeof(buffer));
1748 
1749 	if (_IOC_DIR(cmd) & _IOC_WRITE)
1750 		if (copy_from_user(&buffer, arg, _IOC_SIZE(cmd)))
1751 			return -EFAULT;
1752 
1753 	ret = ioctl_handlers[_IOC_NR(cmd)](client, &buffer);
1754 	if (ret < 0)
1755 		return ret;
1756 
1757 	if (_IOC_DIR(cmd) & _IOC_READ)
1758 		if (copy_to_user(arg, &buffer, _IOC_SIZE(cmd)))
1759 			return -EFAULT;
1760 
1761 	return ret;
1762 }
1763 
1764 static long fw_device_op_ioctl(struct file *file,
1765 			       unsigned int cmd, unsigned long arg)
1766 {
1767 	return dispatch_ioctl(file->private_data, cmd, (void __user *)arg);
1768 }
1769 
1770 static int fw_device_op_mmap(struct file *file, struct vm_area_struct *vma)
1771 {
1772 	struct client *client = file->private_data;
1773 	unsigned long size;
1774 	int page_count, ret;
1775 
1776 	if (fw_device_is_shutdown(client->device))
1777 		return -ENODEV;
1778 
1779 	/* FIXME: We could support multiple buffers, but we don't. */
1780 	if (client->buffer.pages != NULL)
1781 		return -EBUSY;
1782 
1783 	if (!(vma->vm_flags & VM_SHARED))
1784 		return -EINVAL;
1785 
1786 	if (vma->vm_start & ~PAGE_MASK)
1787 		return -EINVAL;
1788 
1789 	client->vm_start = vma->vm_start;
1790 	size = vma->vm_end - vma->vm_start;
1791 	page_count = size >> PAGE_SHIFT;
1792 	if (size & ~PAGE_MASK)
1793 		return -EINVAL;
1794 
1795 	ret = fw_iso_buffer_alloc(&client->buffer, page_count);
1796 	if (ret < 0)
1797 		return ret;
1798 
1799 	scoped_guard(spinlock_irq, &client->lock) {
1800 		if (client->iso_context) {
1801 			ret = fw_iso_buffer_map_dma(&client->buffer, client->device->card,
1802 						    iso_dma_direction(client->iso_context));
1803 			if (ret < 0)
1804 				goto fail;
1805 			client->buffer_is_mapped = true;
1806 		}
1807 	}
1808 
1809 	ret = vm_map_pages_zero(vma, client->buffer.pages,
1810 				client->buffer.page_count);
1811 	if (ret < 0)
1812 		goto fail;
1813 
1814 	return 0;
1815  fail:
1816 	fw_iso_buffer_destroy(&client->buffer, client->device->card);
1817 	return ret;
1818 }
1819 
1820 static int is_outbound_transaction_resource(int id, void *p, void *data)
1821 {
1822 	struct client_resource *resource = p;
1823 
1824 	return resource->release == release_transaction;
1825 }
1826 
1827 static int has_outbound_transactions(struct client *client)
1828 {
1829 	guard(spinlock_irq)(&client->lock);
1830 
1831 	return idr_for_each(&client->resource_idr, is_outbound_transaction_resource, NULL);
1832 }
1833 
1834 static int shutdown_resource(int id, void *p, void *data)
1835 {
1836 	struct client_resource *resource = p;
1837 	struct client *client = data;
1838 
1839 	resource->release(client, resource);
1840 	client_put(client);
1841 
1842 	return 0;
1843 }
1844 
1845 static int fw_device_op_release(struct inode *inode, struct file *file)
1846 {
1847 	struct client *client = file->private_data;
1848 	struct event *event, *next_event;
1849 
1850 	scoped_guard(spinlock_irq, &client->device->card->lock)
1851 		list_del(&client->phy_receiver_link);
1852 
1853 	scoped_guard(mutex, &client->device->client_list_mutex)
1854 		list_del(&client->link);
1855 
1856 	if (client->iso_context)
1857 		fw_iso_context_destroy(client->iso_context);
1858 
1859 	if (client->buffer.pages)
1860 		fw_iso_buffer_destroy(&client->buffer, client->device->card);
1861 
1862 	/* Freeze client->resource_idr and client->event_list */
1863 	scoped_guard(spinlock_irq, &client->lock)
1864 		client->in_shutdown = true;
1865 
1866 	wait_event(client->tx_flush_wait, !has_outbound_transactions(client));
1867 
1868 	idr_for_each(&client->resource_idr, shutdown_resource, client);
1869 	idr_destroy(&client->resource_idr);
1870 
1871 	list_for_each_entry_safe(event, next_event, &client->event_list, link)
1872 		kfree(event);
1873 
1874 	client_put(client);
1875 
1876 	return 0;
1877 }
1878 
1879 static __poll_t fw_device_op_poll(struct file *file, poll_table * pt)
1880 {
1881 	struct client *client = file->private_data;
1882 	__poll_t mask = 0;
1883 
1884 	poll_wait(file, &client->wait, pt);
1885 
1886 	if (fw_device_is_shutdown(client->device))
1887 		mask |= EPOLLHUP | EPOLLERR;
1888 	if (!list_empty(&client->event_list))
1889 		mask |= EPOLLIN | EPOLLRDNORM;
1890 
1891 	return mask;
1892 }
1893 
1894 const struct file_operations fw_device_ops = {
1895 	.owner		= THIS_MODULE,
1896 	.llseek		= no_llseek,
1897 	.open		= fw_device_op_open,
1898 	.read		= fw_device_op_read,
1899 	.unlocked_ioctl	= fw_device_op_ioctl,
1900 	.mmap		= fw_device_op_mmap,
1901 	.release	= fw_device_op_release,
1902 	.poll		= fw_device_op_poll,
1903 	.compat_ioctl	= compat_ptr_ioctl,
1904 };
1905