xref: /linux-6.15/drivers/firewire/core-cdev.c (revision cf123b01)
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 	guard(spinlock_irq)(&client->lock);
1067 
1068 	if (client->iso_context != NULL) {
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 			fw_iso_context_destroy(context);
1079 
1080 			return ret;
1081 		}
1082 		client->buffer_is_mapped = true;
1083 	}
1084 	client->iso_closure = a->closure;
1085 	client->iso_context = context;
1086 
1087 	a->handle = 0;
1088 
1089 	return 0;
1090 }
1091 
1092 static int ioctl_set_iso_channels(struct client *client, union ioctl_arg *arg)
1093 {
1094 	struct fw_cdev_set_iso_channels *a = &arg->set_iso_channels;
1095 	struct fw_iso_context *ctx = client->iso_context;
1096 
1097 	if (ctx == NULL || a->handle != 0)
1098 		return -EINVAL;
1099 
1100 	return fw_iso_context_set_channels(ctx, &a->channels);
1101 }
1102 
1103 /* Macros for decoding the iso packet control header. */
1104 #define GET_PAYLOAD_LENGTH(v)	((v) & 0xffff)
1105 #define GET_INTERRUPT(v)	(((v) >> 16) & 0x01)
1106 #define GET_SKIP(v)		(((v) >> 17) & 0x01)
1107 #define GET_TAG(v)		(((v) >> 18) & 0x03)
1108 #define GET_SY(v)		(((v) >> 20) & 0x0f)
1109 #define GET_HEADER_LENGTH(v)	(((v) >> 24) & 0xff)
1110 
1111 static int ioctl_queue_iso(struct client *client, union ioctl_arg *arg)
1112 {
1113 	struct fw_cdev_queue_iso *a = &arg->queue_iso;
1114 	struct fw_cdev_iso_packet __user *p, *end, *next;
1115 	struct fw_iso_context *ctx = client->iso_context;
1116 	unsigned long payload, buffer_end, transmit_header_bytes = 0;
1117 	u32 control;
1118 	int count;
1119 	struct {
1120 		struct fw_iso_packet packet;
1121 		u8 header[256];
1122 	} u;
1123 
1124 	if (ctx == NULL || a->handle != 0)
1125 		return -EINVAL;
1126 
1127 	/*
1128 	 * If the user passes a non-NULL data pointer, has mmap()'ed
1129 	 * the iso buffer, and the pointer points inside the buffer,
1130 	 * we setup the payload pointers accordingly.  Otherwise we
1131 	 * set them both to 0, which will still let packets with
1132 	 * payload_length == 0 through.  In other words, if no packets
1133 	 * use the indirect payload, the iso buffer need not be mapped
1134 	 * and the a->data pointer is ignored.
1135 	 */
1136 	payload = (unsigned long)a->data - client->vm_start;
1137 	buffer_end = client->buffer.page_count << PAGE_SHIFT;
1138 	if (a->data == 0 || client->buffer.pages == NULL ||
1139 	    payload >= buffer_end) {
1140 		payload = 0;
1141 		buffer_end = 0;
1142 	}
1143 
1144 	if (ctx->type == FW_ISO_CONTEXT_RECEIVE_MULTICHANNEL && payload & 3)
1145 		return -EINVAL;
1146 
1147 	p = (struct fw_cdev_iso_packet __user *)u64_to_uptr(a->packets);
1148 
1149 	end = (void __user *)p + a->size;
1150 	count = 0;
1151 	while (p < end) {
1152 		if (get_user(control, &p->control))
1153 			return -EFAULT;
1154 		u.packet.payload_length = GET_PAYLOAD_LENGTH(control);
1155 		u.packet.interrupt = GET_INTERRUPT(control);
1156 		u.packet.skip = GET_SKIP(control);
1157 		u.packet.tag = GET_TAG(control);
1158 		u.packet.sy = GET_SY(control);
1159 		u.packet.header_length = GET_HEADER_LENGTH(control);
1160 
1161 		switch (ctx->type) {
1162 		case FW_ISO_CONTEXT_TRANSMIT:
1163 			if (u.packet.header_length & 3)
1164 				return -EINVAL;
1165 			transmit_header_bytes = u.packet.header_length;
1166 			break;
1167 
1168 		case FW_ISO_CONTEXT_RECEIVE:
1169 			if (u.packet.header_length == 0 ||
1170 			    u.packet.header_length % ctx->header_size != 0)
1171 				return -EINVAL;
1172 			break;
1173 
1174 		case FW_ISO_CONTEXT_RECEIVE_MULTICHANNEL:
1175 			if (u.packet.payload_length == 0 ||
1176 			    u.packet.payload_length & 3)
1177 				return -EINVAL;
1178 			break;
1179 		}
1180 
1181 		next = (struct fw_cdev_iso_packet __user *)
1182 			&p->header[transmit_header_bytes / 4];
1183 		if (next > end)
1184 			return -EINVAL;
1185 		if (copy_from_user
1186 		    (u.packet.header, p->header, transmit_header_bytes))
1187 			return -EFAULT;
1188 		if (u.packet.skip && ctx->type == FW_ISO_CONTEXT_TRANSMIT &&
1189 		    u.packet.header_length + u.packet.payload_length > 0)
1190 			return -EINVAL;
1191 		if (payload + u.packet.payload_length > buffer_end)
1192 			return -EINVAL;
1193 
1194 		if (fw_iso_context_queue(ctx, &u.packet,
1195 					 &client->buffer, payload))
1196 			break;
1197 
1198 		p = next;
1199 		payload += u.packet.payload_length;
1200 		count++;
1201 	}
1202 	fw_iso_context_queue_flush(ctx);
1203 
1204 	a->size    -= uptr_to_u64(p) - a->packets;
1205 	a->packets  = uptr_to_u64(p);
1206 	a->data     = client->vm_start + payload;
1207 
1208 	return count;
1209 }
1210 
1211 static int ioctl_start_iso(struct client *client, union ioctl_arg *arg)
1212 {
1213 	struct fw_cdev_start_iso *a = &arg->start_iso;
1214 
1215 	BUILD_BUG_ON(
1216 	    FW_CDEV_ISO_CONTEXT_MATCH_TAG0 != FW_ISO_CONTEXT_MATCH_TAG0 ||
1217 	    FW_CDEV_ISO_CONTEXT_MATCH_TAG1 != FW_ISO_CONTEXT_MATCH_TAG1 ||
1218 	    FW_CDEV_ISO_CONTEXT_MATCH_TAG2 != FW_ISO_CONTEXT_MATCH_TAG2 ||
1219 	    FW_CDEV_ISO_CONTEXT_MATCH_TAG3 != FW_ISO_CONTEXT_MATCH_TAG3 ||
1220 	    FW_CDEV_ISO_CONTEXT_MATCH_ALL_TAGS != FW_ISO_CONTEXT_MATCH_ALL_TAGS);
1221 
1222 	if (client->iso_context == NULL || a->handle != 0)
1223 		return -EINVAL;
1224 
1225 	if (client->iso_context->type == FW_ISO_CONTEXT_RECEIVE &&
1226 	    (a->tags == 0 || a->tags > 15 || a->sync > 15))
1227 		return -EINVAL;
1228 
1229 	return fw_iso_context_start(client->iso_context,
1230 				    a->cycle, a->sync, a->tags);
1231 }
1232 
1233 static int ioctl_stop_iso(struct client *client, union ioctl_arg *arg)
1234 {
1235 	struct fw_cdev_stop_iso *a = &arg->stop_iso;
1236 
1237 	if (client->iso_context == NULL || a->handle != 0)
1238 		return -EINVAL;
1239 
1240 	return fw_iso_context_stop(client->iso_context);
1241 }
1242 
1243 static int ioctl_flush_iso(struct client *client, union ioctl_arg *arg)
1244 {
1245 	struct fw_cdev_flush_iso *a = &arg->flush_iso;
1246 
1247 	if (client->iso_context == NULL || a->handle != 0)
1248 		return -EINVAL;
1249 
1250 	return fw_iso_context_flush_completions(client->iso_context);
1251 }
1252 
1253 static int ioctl_get_cycle_timer2(struct client *client, union ioctl_arg *arg)
1254 {
1255 	struct fw_cdev_get_cycle_timer2 *a = &arg->get_cycle_timer2;
1256 	struct fw_card *card = client->device->card;
1257 	struct timespec64 ts = {0, 0};
1258 	u32 cycle_time = 0;
1259 	int ret;
1260 
1261 	guard(irq)();
1262 
1263 	ret = fw_card_read_cycle_time(card, &cycle_time);
1264 	if (ret < 0)
1265 		return ret;
1266 
1267 	switch (a->clk_id) {
1268 	case CLOCK_REALTIME:      ktime_get_real_ts64(&ts);	break;
1269 	case CLOCK_MONOTONIC:     ktime_get_ts64(&ts);		break;
1270 	case CLOCK_MONOTONIC_RAW: ktime_get_raw_ts64(&ts);	break;
1271 	default:
1272 		return -EINVAL;
1273 	}
1274 
1275 	a->tv_sec      = ts.tv_sec;
1276 	a->tv_nsec     = ts.tv_nsec;
1277 	a->cycle_timer = cycle_time;
1278 
1279 	return 0;
1280 }
1281 
1282 static int ioctl_get_cycle_timer(struct client *client, union ioctl_arg *arg)
1283 {
1284 	struct fw_cdev_get_cycle_timer *a = &arg->get_cycle_timer;
1285 	struct fw_cdev_get_cycle_timer2 ct2;
1286 
1287 	ct2.clk_id = CLOCK_REALTIME;
1288 	ioctl_get_cycle_timer2(client, (union ioctl_arg *)&ct2);
1289 
1290 	a->local_time = ct2.tv_sec * USEC_PER_SEC + ct2.tv_nsec / NSEC_PER_USEC;
1291 	a->cycle_timer = ct2.cycle_timer;
1292 
1293 	return 0;
1294 }
1295 
1296 static void iso_resource_work(struct work_struct *work)
1297 {
1298 	struct iso_resource_event *e;
1299 	struct iso_resource *r =
1300 			container_of(work, struct iso_resource, work.work);
1301 	struct client *client = r->client;
1302 	int generation, channel, bandwidth, todo;
1303 	bool skip, free, success;
1304 
1305 	scoped_guard(spinlock_irq, &client->lock) {
1306 		generation = client->device->generation;
1307 		todo = r->todo;
1308 		// Allow 1000ms grace period for other reallocations.
1309 		if (todo == ISO_RES_ALLOC &&
1310 		    time_before64(get_jiffies_64(), client->device->card->reset_jiffies + HZ)) {
1311 			schedule_iso_resource(r, DIV_ROUND_UP(HZ, 3));
1312 			skip = true;
1313 		} else {
1314 			// We could be called twice within the same generation.
1315 			skip = todo == ISO_RES_REALLOC &&
1316 			       r->generation == generation;
1317 		}
1318 		free = todo == ISO_RES_DEALLOC ||
1319 		       todo == ISO_RES_ALLOC_ONCE ||
1320 		       todo == ISO_RES_DEALLOC_ONCE;
1321 		r->generation = generation;
1322 	}
1323 
1324 	if (skip)
1325 		goto out;
1326 
1327 	bandwidth = r->bandwidth;
1328 
1329 	fw_iso_resource_manage(client->device->card, generation,
1330 			r->channels, &channel, &bandwidth,
1331 			todo == ISO_RES_ALLOC ||
1332 			todo == ISO_RES_REALLOC ||
1333 			todo == ISO_RES_ALLOC_ONCE);
1334 	/*
1335 	 * Is this generation outdated already?  As long as this resource sticks
1336 	 * in the idr, it will be scheduled again for a newer generation or at
1337 	 * shutdown.
1338 	 */
1339 	if (channel == -EAGAIN &&
1340 	    (todo == ISO_RES_ALLOC || todo == ISO_RES_REALLOC))
1341 		goto out;
1342 
1343 	success = channel >= 0 || bandwidth > 0;
1344 
1345 	scoped_guard(spinlock_irq, &client->lock) {
1346 		// Transit from allocation to reallocation, except if the client
1347 		// requested deallocation in the meantime.
1348 		if (r->todo == ISO_RES_ALLOC)
1349 			r->todo = ISO_RES_REALLOC;
1350 		// Allocation or reallocation failure?  Pull this resource out of the
1351 		// idr and prepare for deletion, unless the client is shutting down.
1352 		if (r->todo == ISO_RES_REALLOC && !success &&
1353 		    !client->in_shutdown &&
1354 		    idr_remove(&client->resource_idr, r->resource.handle)) {
1355 			client_put(client);
1356 			free = true;
1357 		}
1358 	}
1359 
1360 	if (todo == ISO_RES_ALLOC && channel >= 0)
1361 		r->channels = 1ULL << channel;
1362 
1363 	if (todo == ISO_RES_REALLOC && success)
1364 		goto out;
1365 
1366 	if (todo == ISO_RES_ALLOC || todo == ISO_RES_ALLOC_ONCE) {
1367 		e = r->e_alloc;
1368 		r->e_alloc = NULL;
1369 	} else {
1370 		e = r->e_dealloc;
1371 		r->e_dealloc = NULL;
1372 	}
1373 	e->iso_resource.handle    = r->resource.handle;
1374 	e->iso_resource.channel   = channel;
1375 	e->iso_resource.bandwidth = bandwidth;
1376 
1377 	queue_event(client, &e->event,
1378 		    &e->iso_resource, sizeof(e->iso_resource), NULL, 0);
1379 
1380 	if (free) {
1381 		cancel_delayed_work(&r->work);
1382 		kfree(r->e_alloc);
1383 		kfree(r->e_dealloc);
1384 		kfree(r);
1385 	}
1386  out:
1387 	client_put(client);
1388 }
1389 
1390 static void release_iso_resource(struct client *client,
1391 				 struct client_resource *resource)
1392 {
1393 	struct iso_resource *r =
1394 		container_of(resource, struct iso_resource, resource);
1395 
1396 	guard(spinlock_irq)(&client->lock);
1397 
1398 	r->todo = ISO_RES_DEALLOC;
1399 	schedule_iso_resource(r, 0);
1400 }
1401 
1402 static int init_iso_resource(struct client *client,
1403 		struct fw_cdev_allocate_iso_resource *request, int todo)
1404 {
1405 	struct iso_resource_event *e1, *e2;
1406 	struct iso_resource *r;
1407 	int ret;
1408 
1409 	if ((request->channels == 0 && request->bandwidth == 0) ||
1410 	    request->bandwidth > BANDWIDTH_AVAILABLE_INITIAL)
1411 		return -EINVAL;
1412 
1413 	r  = kmalloc(sizeof(*r), GFP_KERNEL);
1414 	e1 = kmalloc(sizeof(*e1), GFP_KERNEL);
1415 	e2 = kmalloc(sizeof(*e2), GFP_KERNEL);
1416 	if (r == NULL || e1 == NULL || e2 == NULL) {
1417 		ret = -ENOMEM;
1418 		goto fail;
1419 	}
1420 
1421 	INIT_DELAYED_WORK(&r->work, iso_resource_work);
1422 	r->client	= client;
1423 	r->todo		= todo;
1424 	r->generation	= -1;
1425 	r->channels	= request->channels;
1426 	r->bandwidth	= request->bandwidth;
1427 	r->e_alloc	= e1;
1428 	r->e_dealloc	= e2;
1429 
1430 	e1->iso_resource.closure = request->closure;
1431 	e1->iso_resource.type    = FW_CDEV_EVENT_ISO_RESOURCE_ALLOCATED;
1432 	e2->iso_resource.closure = request->closure;
1433 	e2->iso_resource.type    = FW_CDEV_EVENT_ISO_RESOURCE_DEALLOCATED;
1434 
1435 	if (todo == ISO_RES_ALLOC) {
1436 		r->resource.release = release_iso_resource;
1437 		ret = add_client_resource(client, &r->resource, GFP_KERNEL);
1438 		if (ret < 0)
1439 			goto fail;
1440 	} else {
1441 		r->resource.release = NULL;
1442 		r->resource.handle = -1;
1443 		schedule_iso_resource(r, 0);
1444 	}
1445 	request->handle = r->resource.handle;
1446 
1447 	return 0;
1448  fail:
1449 	kfree(r);
1450 	kfree(e1);
1451 	kfree(e2);
1452 
1453 	return ret;
1454 }
1455 
1456 static int ioctl_allocate_iso_resource(struct client *client,
1457 				       union ioctl_arg *arg)
1458 {
1459 	return init_iso_resource(client,
1460 			&arg->allocate_iso_resource, ISO_RES_ALLOC);
1461 }
1462 
1463 static int ioctl_deallocate_iso_resource(struct client *client,
1464 					 union ioctl_arg *arg)
1465 {
1466 	return release_client_resource(client,
1467 			arg->deallocate.handle, release_iso_resource, NULL);
1468 }
1469 
1470 static int ioctl_allocate_iso_resource_once(struct client *client,
1471 					    union ioctl_arg *arg)
1472 {
1473 	return init_iso_resource(client,
1474 			&arg->allocate_iso_resource, ISO_RES_ALLOC_ONCE);
1475 }
1476 
1477 static int ioctl_deallocate_iso_resource_once(struct client *client,
1478 					      union ioctl_arg *arg)
1479 {
1480 	return init_iso_resource(client,
1481 			&arg->allocate_iso_resource, ISO_RES_DEALLOC_ONCE);
1482 }
1483 
1484 /*
1485  * Returns a speed code:  Maximum speed to or from this device,
1486  * limited by the device's link speed, the local node's link speed,
1487  * and all PHY port speeds between the two links.
1488  */
1489 static int ioctl_get_speed(struct client *client, union ioctl_arg *arg)
1490 {
1491 	return client->device->max_speed;
1492 }
1493 
1494 static int ioctl_send_broadcast_request(struct client *client,
1495 					union ioctl_arg *arg)
1496 {
1497 	struct fw_cdev_send_request *a = &arg->send_request;
1498 
1499 	switch (a->tcode) {
1500 	case TCODE_WRITE_QUADLET_REQUEST:
1501 	case TCODE_WRITE_BLOCK_REQUEST:
1502 		break;
1503 	default:
1504 		return -EINVAL;
1505 	}
1506 
1507 	/* Security policy: Only allow accesses to Units Space. */
1508 	if (a->offset < CSR_REGISTER_BASE + CSR_CONFIG_ROM_END)
1509 		return -EACCES;
1510 
1511 	return init_request(client, a, LOCAL_BUS | 0x3f, SCODE_100);
1512 }
1513 
1514 static int ioctl_send_stream_packet(struct client *client, union ioctl_arg *arg)
1515 {
1516 	struct fw_cdev_send_stream_packet *a = &arg->send_stream_packet;
1517 	struct fw_cdev_send_request request;
1518 	int dest;
1519 
1520 	if (a->speed > client->device->card->link_speed ||
1521 	    a->length > 1024 << a->speed)
1522 		return -EIO;
1523 
1524 	if (a->tag > 3 || a->channel > 63 || a->sy > 15)
1525 		return -EINVAL;
1526 
1527 	dest = fw_stream_packet_destination_id(a->tag, a->channel, a->sy);
1528 	request.tcode		= TCODE_STREAM_DATA;
1529 	request.length		= a->length;
1530 	request.closure		= a->closure;
1531 	request.data		= a->data;
1532 	request.generation	= a->generation;
1533 
1534 	return init_request(client, &request, dest, a->speed);
1535 }
1536 
1537 static void outbound_phy_packet_callback(struct fw_packet *packet,
1538 					 struct fw_card *card, int status)
1539 {
1540 	struct outbound_phy_packet_event *e =
1541 		container_of(packet, struct outbound_phy_packet_event, p);
1542 	struct client *e_client = e->client;
1543 	u32 rcode;
1544 
1545 	trace_async_phy_outbound_complete((uintptr_t)packet, card->index, status, packet->generation,
1546 					  packet->timestamp);
1547 
1548 	switch (status) {
1549 	// expected:
1550 	case ACK_COMPLETE:
1551 		rcode = RCODE_COMPLETE;
1552 		break;
1553 	// should never happen with PHY packets:
1554 	case ACK_PENDING:
1555 		rcode = RCODE_COMPLETE;
1556 		break;
1557 	case ACK_BUSY_X:
1558 	case ACK_BUSY_A:
1559 	case ACK_BUSY_B:
1560 		rcode = RCODE_BUSY;
1561 		break;
1562 	case ACK_DATA_ERROR:
1563 		rcode = RCODE_DATA_ERROR;
1564 		break;
1565 	case ACK_TYPE_ERROR:
1566 		rcode = RCODE_TYPE_ERROR;
1567 		break;
1568 	// stale generation; cancelled; on certain controllers: no ack
1569 	default:
1570 		rcode = status;
1571 		break;
1572 	}
1573 
1574 	switch (e->phy_packet.without_tstamp.type) {
1575 	case FW_CDEV_EVENT_PHY_PACKET_SENT:
1576 	{
1577 		struct fw_cdev_event_phy_packet *pp = &e->phy_packet.without_tstamp;
1578 
1579 		pp->rcode = rcode;
1580 		pp->data[0] = packet->timestamp;
1581 		queue_event(e->client, &e->event, &e->phy_packet, sizeof(*pp) + pp->length,
1582 			    NULL, 0);
1583 		break;
1584 	}
1585 	case FW_CDEV_EVENT_PHY_PACKET_SENT2:
1586 	{
1587 		struct fw_cdev_event_phy_packet2 *pp = &e->phy_packet.with_tstamp;
1588 
1589 		pp->rcode = rcode;
1590 		pp->tstamp = packet->timestamp;
1591 		queue_event(e->client, &e->event, &e->phy_packet, sizeof(*pp) + pp->length,
1592 			    NULL, 0);
1593 		break;
1594 	}
1595 	default:
1596 		WARN_ON(1);
1597 		break;
1598 	}
1599 
1600 	client_put(e_client);
1601 }
1602 
1603 static int ioctl_send_phy_packet(struct client *client, union ioctl_arg *arg)
1604 {
1605 	struct fw_cdev_send_phy_packet *a = &arg->send_phy_packet;
1606 	struct fw_card *card = client->device->card;
1607 	struct outbound_phy_packet_event *e;
1608 
1609 	/* Access policy: Allow this ioctl only on local nodes' device files. */
1610 	if (!client->device->is_local)
1611 		return -ENOSYS;
1612 
1613 	e = kzalloc(sizeof(*e) + sizeof(a->data), GFP_KERNEL);
1614 	if (e == NULL)
1615 		return -ENOMEM;
1616 
1617 	client_get(client);
1618 	e->client		= client;
1619 	e->p.speed		= SCODE_100;
1620 	e->p.generation		= a->generation;
1621 	async_header_set_tcode(e->p.header, TCODE_LINK_INTERNAL);
1622 	e->p.header[1]		= a->data[0];
1623 	e->p.header[2]		= a->data[1];
1624 	e->p.header_length	= 12;
1625 	e->p.callback		= outbound_phy_packet_callback;
1626 
1627 	if (client->version < FW_CDEV_VERSION_EVENT_ASYNC_TSTAMP) {
1628 		struct fw_cdev_event_phy_packet *pp = &e->phy_packet.without_tstamp;
1629 
1630 		pp->closure = a->closure;
1631 		pp->type = FW_CDEV_EVENT_PHY_PACKET_SENT;
1632 		if (is_ping_packet(a->data))
1633 			pp->length = 4;
1634 	} else {
1635 		struct fw_cdev_event_phy_packet2 *pp = &e->phy_packet.with_tstamp;
1636 
1637 		pp->closure = a->closure;
1638 		pp->type = FW_CDEV_EVENT_PHY_PACKET_SENT2;
1639 		// Keep the data field so that application can match the response event to the
1640 		// request.
1641 		pp->length = sizeof(a->data);
1642 		memcpy(pp->data, a->data, sizeof(a->data));
1643 	}
1644 
1645 	trace_async_phy_outbound_initiate((uintptr_t)&e->p, card->index, e->p.generation,
1646 					  e->p.header[1], e->p.header[2]);
1647 
1648 	card->driver->send_request(card, &e->p);
1649 
1650 	return 0;
1651 }
1652 
1653 static int ioctl_receive_phy_packets(struct client *client, union ioctl_arg *arg)
1654 {
1655 	struct fw_cdev_receive_phy_packets *a = &arg->receive_phy_packets;
1656 	struct fw_card *card = client->device->card;
1657 
1658 	/* Access policy: Allow this ioctl only on local nodes' device files. */
1659 	if (!client->device->is_local)
1660 		return -ENOSYS;
1661 
1662 	spin_lock_irq(&card->lock);
1663 
1664 	list_move_tail(&client->phy_receiver_link, &card->phy_receiver_list);
1665 	client->phy_receiver_closure = a->closure;
1666 
1667 	spin_unlock_irq(&card->lock);
1668 
1669 	return 0;
1670 }
1671 
1672 void fw_cdev_handle_phy_packet(struct fw_card *card, struct fw_packet *p)
1673 {
1674 	struct client *client;
1675 	struct inbound_phy_packet_event *e;
1676 	unsigned long flags;
1677 
1678 	spin_lock_irqsave(&card->lock, flags);
1679 
1680 	list_for_each_entry(client, &card->phy_receiver_list, phy_receiver_link) {
1681 		e = kmalloc(sizeof(*e) + 8, GFP_ATOMIC);
1682 		if (e == NULL)
1683 			break;
1684 
1685 		if (client->version < FW_CDEV_VERSION_EVENT_ASYNC_TSTAMP) {
1686 			struct fw_cdev_event_phy_packet *pp = &e->phy_packet.without_tstamp;
1687 
1688 			pp->closure = client->phy_receiver_closure;
1689 			pp->type = FW_CDEV_EVENT_PHY_PACKET_RECEIVED;
1690 			pp->rcode = RCODE_COMPLETE;
1691 			pp->length = 8;
1692 			pp->data[0] = p->header[1];
1693 			pp->data[1] = p->header[2];
1694 			queue_event(client, &e->event, &e->phy_packet, sizeof(*pp) + 8, NULL, 0);
1695 		} else {
1696 			struct fw_cdev_event_phy_packet2 *pp = &e->phy_packet.with_tstamp;
1697 
1698 			pp = &e->phy_packet.with_tstamp;
1699 			pp->closure = client->phy_receiver_closure;
1700 			pp->type = FW_CDEV_EVENT_PHY_PACKET_RECEIVED2;
1701 			pp->rcode = RCODE_COMPLETE;
1702 			pp->length = 8;
1703 			pp->tstamp = p->timestamp;
1704 			pp->data[0] = p->header[1];
1705 			pp->data[1] = p->header[2];
1706 			queue_event(client, &e->event, &e->phy_packet, sizeof(*pp) + 8, NULL, 0);
1707 		}
1708 	}
1709 
1710 	spin_unlock_irqrestore(&card->lock, flags);
1711 }
1712 
1713 static int (* const ioctl_handlers[])(struct client *, union ioctl_arg *) = {
1714 	[0x00] = ioctl_get_info,
1715 	[0x01] = ioctl_send_request,
1716 	[0x02] = ioctl_allocate,
1717 	[0x03] = ioctl_deallocate,
1718 	[0x04] = ioctl_send_response,
1719 	[0x05] = ioctl_initiate_bus_reset,
1720 	[0x06] = ioctl_add_descriptor,
1721 	[0x07] = ioctl_remove_descriptor,
1722 	[0x08] = ioctl_create_iso_context,
1723 	[0x09] = ioctl_queue_iso,
1724 	[0x0a] = ioctl_start_iso,
1725 	[0x0b] = ioctl_stop_iso,
1726 	[0x0c] = ioctl_get_cycle_timer,
1727 	[0x0d] = ioctl_allocate_iso_resource,
1728 	[0x0e] = ioctl_deallocate_iso_resource,
1729 	[0x0f] = ioctl_allocate_iso_resource_once,
1730 	[0x10] = ioctl_deallocate_iso_resource_once,
1731 	[0x11] = ioctl_get_speed,
1732 	[0x12] = ioctl_send_broadcast_request,
1733 	[0x13] = ioctl_send_stream_packet,
1734 	[0x14] = ioctl_get_cycle_timer2,
1735 	[0x15] = ioctl_send_phy_packet,
1736 	[0x16] = ioctl_receive_phy_packets,
1737 	[0x17] = ioctl_set_iso_channels,
1738 	[0x18] = ioctl_flush_iso,
1739 };
1740 
1741 static int dispatch_ioctl(struct client *client,
1742 			  unsigned int cmd, void __user *arg)
1743 {
1744 	union ioctl_arg buffer;
1745 	int ret;
1746 
1747 	if (fw_device_is_shutdown(client->device))
1748 		return -ENODEV;
1749 
1750 	if (_IOC_TYPE(cmd) != '#' ||
1751 	    _IOC_NR(cmd) >= ARRAY_SIZE(ioctl_handlers) ||
1752 	    _IOC_SIZE(cmd) > sizeof(buffer))
1753 		return -ENOTTY;
1754 
1755 	memset(&buffer, 0, sizeof(buffer));
1756 
1757 	if (_IOC_DIR(cmd) & _IOC_WRITE)
1758 		if (copy_from_user(&buffer, arg, _IOC_SIZE(cmd)))
1759 			return -EFAULT;
1760 
1761 	ret = ioctl_handlers[_IOC_NR(cmd)](client, &buffer);
1762 	if (ret < 0)
1763 		return ret;
1764 
1765 	if (_IOC_DIR(cmd) & _IOC_READ)
1766 		if (copy_to_user(arg, &buffer, _IOC_SIZE(cmd)))
1767 			return -EFAULT;
1768 
1769 	return ret;
1770 }
1771 
1772 static long fw_device_op_ioctl(struct file *file,
1773 			       unsigned int cmd, unsigned long arg)
1774 {
1775 	return dispatch_ioctl(file->private_data, cmd, (void __user *)arg);
1776 }
1777 
1778 static int fw_device_op_mmap(struct file *file, struct vm_area_struct *vma)
1779 {
1780 	struct client *client = file->private_data;
1781 	unsigned long size;
1782 	int page_count, ret;
1783 
1784 	if (fw_device_is_shutdown(client->device))
1785 		return -ENODEV;
1786 
1787 	/* FIXME: We could support multiple buffers, but we don't. */
1788 	if (client->buffer.pages != NULL)
1789 		return -EBUSY;
1790 
1791 	if (!(vma->vm_flags & VM_SHARED))
1792 		return -EINVAL;
1793 
1794 	if (vma->vm_start & ~PAGE_MASK)
1795 		return -EINVAL;
1796 
1797 	client->vm_start = vma->vm_start;
1798 	size = vma->vm_end - vma->vm_start;
1799 	page_count = size >> PAGE_SHIFT;
1800 	if (size & ~PAGE_MASK)
1801 		return -EINVAL;
1802 
1803 	ret = fw_iso_buffer_alloc(&client->buffer, page_count);
1804 	if (ret < 0)
1805 		return ret;
1806 
1807 	scoped_guard(spinlock_irq, &client->lock) {
1808 		if (client->iso_context) {
1809 			ret = fw_iso_buffer_map_dma(&client->buffer, client->device->card,
1810 						    iso_dma_direction(client->iso_context));
1811 			if (ret < 0)
1812 				goto fail;
1813 			client->buffer_is_mapped = true;
1814 		}
1815 	}
1816 
1817 	ret = vm_map_pages_zero(vma, client->buffer.pages,
1818 				client->buffer.page_count);
1819 	if (ret < 0)
1820 		goto fail;
1821 
1822 	return 0;
1823  fail:
1824 	fw_iso_buffer_destroy(&client->buffer, client->device->card);
1825 	return ret;
1826 }
1827 
1828 static int is_outbound_transaction_resource(int id, void *p, void *data)
1829 {
1830 	struct client_resource *resource = p;
1831 
1832 	return resource->release == release_transaction;
1833 }
1834 
1835 static int has_outbound_transactions(struct client *client)
1836 {
1837 	guard(spinlock_irq)(&client->lock);
1838 
1839 	return idr_for_each(&client->resource_idr, is_outbound_transaction_resource, NULL);
1840 }
1841 
1842 static int shutdown_resource(int id, void *p, void *data)
1843 {
1844 	struct client_resource *resource = p;
1845 	struct client *client = data;
1846 
1847 	resource->release(client, resource);
1848 	client_put(client);
1849 
1850 	return 0;
1851 }
1852 
1853 static int fw_device_op_release(struct inode *inode, struct file *file)
1854 {
1855 	struct client *client = file->private_data;
1856 	struct event *event, *next_event;
1857 
1858 	spin_lock_irq(&client->device->card->lock);
1859 	list_del(&client->phy_receiver_link);
1860 	spin_unlock_irq(&client->device->card->lock);
1861 
1862 	scoped_guard(mutex, &client->device->client_list_mutex)
1863 		list_del(&client->link);
1864 
1865 	if (client->iso_context)
1866 		fw_iso_context_destroy(client->iso_context);
1867 
1868 	if (client->buffer.pages)
1869 		fw_iso_buffer_destroy(&client->buffer, client->device->card);
1870 
1871 	/* Freeze client->resource_idr and client->event_list */
1872 	scoped_guard(spinlock_irq, &client->lock)
1873 		client->in_shutdown = true;
1874 
1875 	wait_event(client->tx_flush_wait, !has_outbound_transactions(client));
1876 
1877 	idr_for_each(&client->resource_idr, shutdown_resource, client);
1878 	idr_destroy(&client->resource_idr);
1879 
1880 	list_for_each_entry_safe(event, next_event, &client->event_list, link)
1881 		kfree(event);
1882 
1883 	client_put(client);
1884 
1885 	return 0;
1886 }
1887 
1888 static __poll_t fw_device_op_poll(struct file *file, poll_table * pt)
1889 {
1890 	struct client *client = file->private_data;
1891 	__poll_t mask = 0;
1892 
1893 	poll_wait(file, &client->wait, pt);
1894 
1895 	if (fw_device_is_shutdown(client->device))
1896 		mask |= EPOLLHUP | EPOLLERR;
1897 	if (!list_empty(&client->event_list))
1898 		mask |= EPOLLIN | EPOLLRDNORM;
1899 
1900 	return mask;
1901 }
1902 
1903 const struct file_operations fw_device_ops = {
1904 	.owner		= THIS_MODULE,
1905 	.llseek		= no_llseek,
1906 	.open		= fw_device_op_open,
1907 	.read		= fw_device_op_read,
1908 	.unlocked_ioctl	= fw_device_op_ioctl,
1909 	.mmap		= fw_device_op_mmap,
1910 	.release	= fw_device_op_release,
1911 	.poll		= fw_device_op_poll,
1912 	.compat_ioctl	= compat_ptr_ioctl,
1913 };
1914