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