xref: /linux/drivers/firewire/core-transaction.c (revision 3e3858e479a8fc0c78afb7da8ff65ed053f8ddce)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Core IEEE1394 transaction logic
4  *
5  * Copyright (C) 2004-2006 Kristian Hoegsberg <krh@bitplanet.net>
6  */
7 
8 #include <linux/bug.h>
9 #include <linux/completion.h>
10 #include <linux/device.h>
11 #include <linux/errno.h>
12 #include <linux/firewire.h>
13 #include <linux/firewire-constants.h>
14 #include <linux/fs.h>
15 #include <linux/init.h>
16 #include <linux/jiffies.h>
17 #include <linux/kernel.h>
18 #include <linux/list.h>
19 #include <linux/module.h>
20 #include <linux/rculist.h>
21 #include <linux/slab.h>
22 #include <linux/spinlock.h>
23 #include <linux/string.h>
24 #include <linux/timer.h>
25 #include <linux/types.h>
26 #include <linux/workqueue.h>
27 #include <kunit/static_stub.h>
28 
29 #include <asm/byteorder.h>
30 
31 #include "core.h"
32 #include "packet-header-definitions.h"
33 #include "phy-packet-definitions.h"
34 #include <trace/events/firewire.h>
35 
36 #define HEADER_DESTINATION_IS_BROADCAST(header) \
37 	((async_header_get_destination(header) & 0x3f) == 0x3f)
38 
39 // Returns 0 if the split timeout handler is already running.
40 //
41 // card->transactions.lock must be acquired in advance.
42 static int try_cancel_split_timeout(struct fw_transaction *t)
43 {
44 	lockdep_assert_held(&t->card->transactions.lock);
45 
46 	if (t->is_split_transaction)
47 		return timer_delete(&t->split_timeout_timer);
48 	else
49 		return 1;
50 }
51 
52 static void remove_transaction_entry(struct fw_card *card, struct fw_transaction *entry)
53 __must_hold(&card->transactions.lock)
54 {
55 	lockdep_assert_held(&card->transactions.lock);
56 
57 	list_del_init(&entry->link);
58 	card->transactions.tlabel_mask &= ~(1ULL << entry->tlabel);
59 }
60 
61 static void invoke_callback(struct fw_transaction *t, int rcode, u32 response_tstamp, void *data,
62 			    size_t data_length)
63 {
64 	if (!t->with_tstamp) {
65 		t->callback.without_tstamp(t->card, rcode, data, data_length, t->callback_data);
66 	} else {
67 		t->callback.with_tstamp(t->card, rcode, t->packet.timestamp, response_tstamp,
68 					data, data_length, t->callback_data);
69 	}
70 }
71 
72 // card->transactions.lock must be acquired in advance.
73 #define find_and_pop_transaction_entry(card, condition)			\
74 ({									\
75 	struct fw_transaction *iter, *__t = NULL;			\
76 	list_for_each_entry(iter, &card->transactions.list, link) {	\
77 		if (condition) {					\
78 			__t = iter;					\
79 			break;						\
80 		}							\
81 	}								\
82 	if (__t) {							\
83 		if (try_cancel_split_timeout(__t))			\
84 			remove_transaction_entry(card, __t);		\
85 		else							\
86 			__t = NULL;					\
87 	}								\
88 	__t;								\
89 })
90 
91 // Ensure that the transaction is not on the pending list when scheduling this work. Cancelling
92 // the work after scheduling makes no sense, as the initiator must be notified of the transaction
93 // result.
94 static void schedule_error_callback(struct fw_card *card, struct fw_transaction *t, int rcode,
95 				    u32 response_timestamp)
96 __must_hold(&card->transactions.lock)
97 {
98 	lockdep_assert_held(&card->transactions.lock);
99 
100 	// To detect programming mistakes.
101 	WARN_ON(!list_empty(&t->link));
102 
103 	t->rcode = rcode;
104 	t->response_timestamp = response_timestamp;
105 
106 	queue_work(t->card->async_wq, &t->error_work);
107 }
108 
109 void fw_cancel_pending_transactions(struct fw_card *card)
110 __must_hold(&card->transactions.lock)
111 {
112 	struct fw_transaction *t, *tmp;
113 
114 	lockdep_assert_held(&card->transactions.lock);
115 
116 	list_for_each_entry_safe(t, tmp, &card->transactions.list, link) {
117 		if (try_cancel_split_timeout(t)) {
118 			remove_transaction_entry(card, t);
119 			schedule_error_callback(card, t, RCODE_CANCELLED, 0);
120 		}
121 	}
122 }
123 
124 /**
125  * fw_cancel_transaction: cancel transaction.
126  * @card:		interface where the transaction has been requested
127  * @transaction:	transaction instance to be cancelled
128  *
129  * Terminate the transaction by either canceling the request subaction or the response subaction
130  * of the split transaction, then schedule the transaction callback to notify the cancellation.
131  * The transaction instance should be kept until the callback will be invoked.
132  *
133  * Context: Process context.
134  * Returns: 0 on success, -ENOENT if the transaction instance is not found in the queue for the
135  * pending transaction.
136  */
137 int fw_cancel_transaction(struct fw_card *card, struct fw_transaction *transaction)
138 __must_not_hold(&card->transactions.lock)
139 {
140 	lockdep_assert_not_held(&card->transactions.lock);
141 
142 	// Allow the call of struct fw_card_driver.cancel_packet() to wait for any event.
143 	might_sleep();
144 
145 	// Cancel the packet transmission if it's still queued. That will schedule the packet
146 	// transmission callback which cancels the transaction.
147 	if (smp_load_acquire(&card->driver)->cancel_packet(card, &transaction->packet) == 0)
148 		return 0;
149 
150 	u32 curr_cycle_time = 0;
151 
152 	// Timestamping on behalf of hardware.
153 	(void)fw_card_read_cycle_time(card, &curr_cycle_time);
154 
155 	u32 tstamp = cycle_time_to_ohci_tstamp(curr_cycle_time);
156 
157 	// If the request packet has already been sent, we need to see if the transaction is still
158 	// pending and remove it in that case (e.g. the split transaction).
159 	scoped_guard(spinlock_irqsave, &card->transactions.lock) {
160 		if (!find_and_pop_transaction_entry(card, iter == transaction))
161 			return -ENOENT;
162 		schedule_error_callback(card, transaction, RCODE_CANCELLED, tstamp);
163 	}
164 
165 	return 0;
166 }
167 EXPORT_SYMBOL(fw_cancel_transaction);
168 
169 static void error_callback_work(struct work_struct *work)
170 {
171 	struct fw_transaction *t = from_work(t, work, error_work);
172 
173 	invoke_callback(t, t->rcode, t->response_timestamp, NULL, 0);
174 }
175 
176 // card->transactions.lock must be released in advance.
177 static void split_transaction_timeout_callback(struct timer_list *timer)
178 {
179 	struct fw_transaction *t = timer_container_of(t, timer, split_timeout_timer);
180 	struct fw_card *card = t->card;
181 
182 	lockdep_assert_not_held(&card->transactions.lock);
183 
184 	scoped_guard(spinlock, &card->transactions.lock) {
185 		if (list_empty(&t->link))
186 			return;
187 		remove_transaction_entry(card, t);
188 		schedule_error_callback(card, t, RCODE_CANCELLED, t->split_timeout_cycle);
189 	}
190 
191 }
192 
193 // card->transactions.lock should be acquired in advance for the linked list.
194 static void start_split_transaction_timeout(struct fw_transaction *t, unsigned int delta)
195 {
196 	lockdep_assert_held(&t->card->transactions.lock);
197 
198 	if (list_empty(&t->link) || WARN_ON(t->is_split_transaction))
199 		return;
200 
201 	t->is_split_transaction = true;
202 
203 	mod_timer(&t->split_timeout_timer, jiffies + delta);
204 }
205 
206 static u32 compute_split_timeout_timestamp(struct fw_card *card, u32 request_timestamp);
207 
208 static void transmit_complete_callback(struct fw_packet *packet,
209 				       struct fw_card *card, int status)
210 __must_not_hold(&card->split_timeout.lock)
211 __must_not_hold(&card->transactions.lock)
212 {
213 	struct fw_transaction *t =
214 	    container_of(packet, struct fw_transaction, packet);
215 
216 	lockdep_assert_not_held(&card->split_timeout.lock);
217 	lockdep_assert_not_held(&card->transactions.lock);
218 
219 	trace_async_request_outbound_complete((uintptr_t)t, card->index, packet->generation,
220 					      packet->speed, status, packet->timestamp);
221 
222 	switch (status) {
223 	case ACK_PENDING:
224 	{
225 		unsigned int delta;
226 
227 		scoped_guard(spinlock_irqsave, &card->split_timeout.lock) {
228 			t->split_timeout_cycle =
229 				compute_split_timeout_timestamp(card, packet->timestamp) & 0xffff;
230 			delta = card->split_timeout.jiffies;
231 		}
232 
233 		scoped_guard(spinlock_irqsave, &card->transactions.lock)
234 			start_split_transaction_timeout(t, delta);
235 		return;
236 	}
237 	case ACK_COMPLETE:
238 		status = RCODE_COMPLETE;
239 		break;
240 	case ACK_BUSY_X:
241 	case ACK_BUSY_A:
242 	case ACK_BUSY_B:
243 		status = RCODE_BUSY;
244 		break;
245 	case ACK_DATA_ERROR:
246 		status = RCODE_DATA_ERROR;
247 		break;
248 	case ACK_TYPE_ERROR:
249 		status = RCODE_TYPE_ERROR;
250 		break;
251 	default:
252 		// In this case the ack is really a juju specific rcode, so just forward that to
253 		// the callback.
254 		break;
255 	}
256 
257 	scoped_guard(spinlock_irqsave, &card->transactions.lock) {
258 		if (!find_and_pop_transaction_entry(card, iter == t))
259 			return;
260 	}
261 
262 	invoke_callback(t, status, packet->timestamp, NULL, 0);
263 }
264 
265 static void fw_fill_request(struct fw_packet *packet, int tcode, int tlabel,
266 		int destination_id, int source_id, int generation, int speed,
267 		unsigned long long offset, void *payload, size_t length)
268 {
269 	int ext_tcode;
270 
271 	if (tcode == TCODE_STREAM_DATA) {
272 		// The value of destination_id argument should include tag, channel, and sy fields
273 		// as isochronous packet header has.
274 		packet->header[0] = destination_id;
275 		isoc_header_set_data_length(packet->header, length);
276 		isoc_header_set_tcode(packet->header, TCODE_STREAM_DATA);
277 		packet->header_length = 4;
278 		packet->payload = payload;
279 		packet->payload_length = length;
280 
281 		goto common;
282 	}
283 
284 	if (tcode > 0x10) {
285 		ext_tcode = tcode & ~0x10;
286 		tcode = TCODE_LOCK_REQUEST;
287 	} else
288 		ext_tcode = 0;
289 
290 	async_header_set_retry(packet->header, RETRY_X);
291 	async_header_set_tlabel(packet->header, tlabel);
292 	async_header_set_tcode(packet->header, tcode);
293 	async_header_set_destination(packet->header, destination_id);
294 	async_header_set_source(packet->header, source_id);
295 	async_header_set_offset(packet->header, offset);
296 
297 	switch (tcode) {
298 	case TCODE_WRITE_QUADLET_REQUEST:
299 		async_header_set_quadlet_data(packet->header, *(u32 *)payload);
300 		packet->header_length = 16;
301 		packet->payload_length = 0;
302 		break;
303 
304 	case TCODE_LOCK_REQUEST:
305 	case TCODE_WRITE_BLOCK_REQUEST:
306 		async_header_set_data_length(packet->header, length);
307 		async_header_set_extended_tcode(packet->header, ext_tcode);
308 		packet->header_length = 16;
309 		packet->payload = payload;
310 		packet->payload_length = length;
311 		break;
312 
313 	case TCODE_READ_QUADLET_REQUEST:
314 		packet->header_length = 12;
315 		packet->payload_length = 0;
316 		break;
317 
318 	case TCODE_READ_BLOCK_REQUEST:
319 		async_header_set_data_length(packet->header, length);
320 		async_header_set_extended_tcode(packet->header, ext_tcode);
321 		packet->header_length = 16;
322 		packet->payload_length = 0;
323 		break;
324 
325 	default:
326 		WARN(1, "wrong tcode %d\n", tcode);
327 	}
328  common:
329 	packet->speed = speed;
330 	packet->generation = generation;
331 	packet->ack = 0;
332 	packet->payload_mapped = false;
333 }
334 
335 static int allocate_tlabel(struct fw_card *card)
336 __must_hold(&card->transactions.lock)
337 {
338 	int tlabel;
339 
340 	lockdep_assert_held(&card->transactions.lock);
341 
342 	tlabel = card->transactions.current_tlabel;
343 	while (card->transactions.tlabel_mask & (1ULL << tlabel)) {
344 		tlabel = (tlabel + 1) & 0x3f;
345 		if (tlabel == card->transactions.current_tlabel)
346 			return -EBUSY;
347 	}
348 
349 	card->transactions.current_tlabel = (tlabel + 1) & 0x3f;
350 	card->transactions.tlabel_mask |= 1ULL << tlabel;
351 
352 	return tlabel;
353 }
354 
355 /**
356  * __fw_send_request() - submit a request packet for transmission to generate callback for response
357  *			 subaction with or without time stamp.
358  * @card:		interface to send the request at
359  * @t:			transaction instance to which the request belongs
360  * @tcode:		transaction code
361  * @destination_id:	destination node ID, consisting of bus_ID and phy_ID
362  * @generation:		bus generation in which request and response are valid
363  * @speed:		transmission speed
364  * @offset:		48bit wide offset into destination's address space
365  * @payload:		data payload for the request subaction
366  * @length:		length of the payload, in bytes
367  * @callback:		union of two functions whether to receive time stamp or not for response
368  *			subaction.
369  * @with_tstamp:	Whether to receive time stamp or not for response subaction.
370  * @callback_data:	data to be passed to the transaction completion callback
371  *
372  * Submit a request packet into the asynchronous request transmission queue.
373  * Can be called from atomic context.  If you prefer a blocking API, use
374  * fw_run_transaction() in a context that can sleep.
375  *
376  * In case of lock requests, specify one of the firewire-core specific %TCODE_
377  * constants instead of %TCODE_LOCK_REQUEST in @tcode.
378  *
379  * Make sure that the value in @destination_id is not older than the one in
380  * @generation.  Otherwise the request is in danger to be sent to a wrong node.
381  *
382  * In case of asynchronous stream packets i.e. %TCODE_STREAM_DATA, the caller
383  * needs to synthesize @destination_id with fw_stream_packet_destination_id().
384  * It will contain tag, channel, and sy data instead of a node ID then.
385  *
386  * The payload buffer at @data is going to be DMA-mapped except in case of
387  * @length <= 8 or of local (loopback) requests.  Hence make sure that the
388  * buffer complies with the restrictions of the streaming DMA mapping API.
389  * @payload must not be freed before the @callback is called.
390  *
391  * In case of request types without payload, @data is NULL and @length is 0.
392  *
393  * After the transaction is completed successfully or unsuccessfully, the @callback will be called
394  * in process context.  Among its parameters is the response code which
395  * is either one of the rcodes per IEEE 1394 or, in case of internal errors,
396  * the firewire-core specific %RCODE_SEND_ERROR.  The other firewire-core
397  * specific rcodes (%RCODE_CANCELLED, %RCODE_BUSY, %RCODE_GENERATION,
398  * %RCODE_NO_ACK) denote transaction timeout, busy responder, stale request
399  * generation, or missing ACK respectively.
400  *
401  * Note some timing corner cases:  fw_send_request() may complete much earlier
402  * than when the request packet actually hits the wire.  On the other hand,
403  * transaction completion and hence execution of @callback may happen even
404  * before fw_send_request() returns.
405  *
406  * Context: Any context.
407  */
408 void __fw_send_request(struct fw_card *card, struct fw_transaction *t, int tcode,
409 		int destination_id, int generation, int speed, unsigned long long offset,
410 		void *payload, size_t length, union fw_transaction_callback callback,
411 		bool with_tstamp, void *callback_data)
412 __must_not_hold(&card->transactions.lock)
413 {
414 	int tlabel;
415 
416 	lockdep_assert_not_held(&card->transactions.lock);
417 
418 	t->card = card;
419 	t->callback = callback;
420 	t->with_tstamp = with_tstamp;
421 	t->callback_data = callback_data;
422 	INIT_WORK(&t->error_work, error_callback_work);
423 	INIT_LIST_HEAD(&t->link);
424 
425 	/*
426 	 * Allocate tlabel from the bitmap and put the transaction on
427 	 * the list while holding the card spinlock.
428 	 */
429 
430 	scoped_guard(spinlock_irqsave, &card->transactions.lock)
431 		tlabel = allocate_tlabel(card);
432 	if (tlabel < 0) {
433 		// Timestamping on behalf of hardware.
434 		u32 curr_cycle_time = 0;
435 		u32 tstamp;
436 
437 		(void)fw_card_read_cycle_time(card, &curr_cycle_time);
438 		tstamp = cycle_time_to_ohci_tstamp(curr_cycle_time);
439 
440 		t->packet.timestamp = tstamp;
441 		scoped_guard(spinlock_irqsave, &card->transactions.lock)
442 			schedule_error_callback(card, t, RCODE_SEND_ERROR, tstamp);
443 
444 		return;
445 	}
446 
447 	t->node_id = destination_id;
448 	t->tlabel = tlabel;
449 	t->is_split_transaction = false;
450 	timer_setup(&t->split_timeout_timer, split_transaction_timeout_callback, 0);
451 	t->packet.callback = transmit_complete_callback;
452 
453 	// The node_id field of fw_card can be updated when handling SelfIDComplete.
454 	int node_id;
455 
456 	scoped_guard(spinlock_irqsave, &card->lock)
457 		node_id = card->node_id;
458 	fw_fill_request(&t->packet, tcode, t->tlabel, destination_id, node_id, generation, speed,
459 			offset, payload, length);
460 
461 	scoped_guard(spinlock_irqsave, &card->transactions.lock)
462 		list_add_tail(&t->link, &card->transactions.list);
463 
464 	// Safe with no lock, since the index field of fw_card is immutable once assigned.
465 	trace_async_request_outbound_initiate((uintptr_t)t, card->index, generation, speed,
466 					      t->packet.header, payload,
467 					      tcode_is_read_request(tcode) ? 0 : length / 4);
468 
469 	smp_load_acquire(&card->driver)->send_request(card, &t->packet);
470 }
471 EXPORT_SYMBOL_GPL(__fw_send_request);
472 
473 struct transaction_callback_data {
474 	struct completion done;
475 	void *payload;
476 	int rcode;
477 };
478 
479 static void transaction_callback(struct fw_card *card, int rcode,
480 				 void *payload, size_t length, void *data)
481 {
482 	struct transaction_callback_data *d = data;
483 
484 	if (rcode == RCODE_COMPLETE)
485 		memcpy(d->payload, payload, length);
486 	d->rcode = rcode;
487 	complete(&d->done);
488 }
489 
490 /**
491  * fw_run_transaction() - send request and sleep until transaction is completed
492  * @card:		card interface for this request
493  * @tcode:		transaction code
494  * @destination_id:	destination node ID, consisting of bus_ID and phy_ID
495  * @generation:		bus generation in which request and response are valid
496  * @speed:		transmission speed
497  * @offset:		48bit wide offset into destination's address space
498  * @payload:		data payload for the request subaction
499  * @length:		length of the payload, in bytes
500  *
501  * Returns the RCODE.  See fw_send_request() for parameter documentation.
502  * Unlike fw_send_request(), @data points to the payload of the request or/and
503  * to the payload of the response.  DMA mapping restrictions apply to outbound
504  * request payloads of >= 8 bytes but not to inbound response payloads.
505  */
506 int fw_run_transaction(struct fw_card *card, int tcode, int destination_id,
507 		       int generation, int speed, unsigned long long offset,
508 		       void *payload, size_t length)
509 {
510 	KUNIT_STATIC_STUB_REDIRECT(fw_run_transaction, card, tcode, destination_id, generation,
511 				   speed, offset, payload, length);
512 
513 	struct transaction_callback_data d;
514 	struct fw_transaction t;
515 
516 	// Due to the call of wait_for_completion().
517 	might_sleep();
518 
519 	timer_setup_on_stack(&t.split_timeout_timer, NULL, 0);
520 	init_completion(&d.done);
521 	d.payload = payload;
522 	fw_send_request(card, &t, tcode, destination_id, generation, speed,
523 			offset, payload, length, transaction_callback, &d);
524 	wait_for_completion(&d.done);
525 	timer_destroy_on_stack(&t.split_timeout_timer);
526 
527 	return d.rcode;
528 }
529 EXPORT_SYMBOL(fw_run_transaction);
530 
531 static DEFINE_MUTEX(phy_config_mutex);
532 static DECLARE_COMPLETION(phy_config_done);
533 
534 static void transmit_phy_packet_callback(struct fw_packet *packet,
535 					 struct fw_card *card, int status)
536 {
537 	trace_async_phy_outbound_complete((uintptr_t)packet, card->index, packet->generation, status,
538 					  packet->timestamp);
539 	complete(&phy_config_done);
540 }
541 
542 static struct fw_packet phy_config_packet = {
543 	.header_length	= 12,
544 	.payload_length	= 0,
545 	.speed		= SCODE_100,
546 	.callback	= transmit_phy_packet_callback,
547 };
548 
549 void fw_send_phy_config(struct fw_card *card,
550 			int node_id, int generation, int gap_count)
551 {
552 	long timeout = msecs_to_jiffies(100);
553 	u32 data = 0;
554 
555 	// Due to the call of wait_for_completion_timeout().
556 	might_sleep();
557 
558 	phy_packet_set_packet_identifier(&data, PHY_PACKET_PACKET_IDENTIFIER_PHY_CONFIG);
559 
560 	if (node_id != FW_PHY_CONFIG_NO_NODE_ID) {
561 		phy_packet_phy_config_set_root_id(&data, node_id);
562 		phy_packet_phy_config_set_force_root_node(&data, true);
563 	}
564 
565 	if (gap_count == FW_PHY_CONFIG_CURRENT_GAP_COUNT) {
566 		gap_count = smp_load_acquire(&card->driver)->read_phy_reg(card, 1);
567 		if (gap_count < 0)
568 			return;
569 
570 		gap_count &= 63;
571 		if (gap_count == 63)
572 			return;
573 	}
574 	phy_packet_phy_config_set_gap_count(&data, gap_count);
575 	phy_packet_phy_config_set_gap_count_optimization(&data, true);
576 
577 	guard(mutex)(&phy_config_mutex);
578 
579 	async_header_set_tcode(phy_config_packet.header, TCODE_LINK_INTERNAL);
580 	phy_config_packet.header[1] = data;
581 	phy_config_packet.header[2] = ~data;
582 	phy_config_packet.generation = generation;
583 	reinit_completion(&phy_config_done);
584 
585 	trace_async_phy_outbound_initiate((uintptr_t)&phy_config_packet, card->index,
586 					  phy_config_packet.generation, phy_config_packet.header[1],
587 					  phy_config_packet.header[2]);
588 
589 	smp_load_acquire(&card->driver)->send_request(card, &phy_config_packet);
590 	wait_for_completion_timeout(&phy_config_done, timeout);
591 }
592 
593 static struct fw_address_handler *lookup_overlapping_address_handler(
594 	struct list_head *list, unsigned long long offset, size_t length)
595 {
596 	struct fw_address_handler *handler;
597 
598 	list_for_each_entry_rcu(handler, list, link) {
599 		if (handler->offset < offset + length &&
600 		    offset < handler->offset + handler->length)
601 			return handler;
602 	}
603 
604 	return NULL;
605 }
606 
607 static bool is_enclosing_handler(struct fw_address_handler *handler,
608 				 unsigned long long offset, size_t length)
609 {
610 	return handler->offset <= offset &&
611 		offset + length <= handler->offset + handler->length;
612 }
613 
614 static struct fw_address_handler *lookup_enclosing_address_handler(
615 	struct list_head *list, unsigned long long offset, size_t length)
616 {
617 	struct fw_address_handler *handler;
618 
619 	list_for_each_entry_rcu(handler, list, link) {
620 		if (is_enclosing_handler(handler, offset, length))
621 			return handler;
622 	}
623 
624 	return NULL;
625 }
626 
627 static DEFINE_SPINLOCK(address_handler_list_lock);
628 static LIST_HEAD(address_handler_list);
629 
630 /**
631  * var fw_high_memory_region - An address range for high memory.
632  *
633  * Represents an address range within the Middle Address Space defined by the 1394 OHCI
634  * specification.
635  */
636 const struct fw_address_region fw_high_memory_region =
637 	{ .start = FW_MAX_PHYSICAL_RANGE, .end = 0xffffe0000000ULL, };
638 EXPORT_SYMBOL(fw_high_memory_region);
639 
640 static const struct fw_address_region low_memory_region =
641 	{ .start = 0x000000000000ULL, .end = FW_MAX_PHYSICAL_RANGE, };
642 
643 #if 0
644 const struct fw_address_region fw_private_region =
645 	{ .start = 0xffffe0000000ULL, .end = 0xfffff0000000ULL,  };
646 const struct fw_address_region fw_csr_region =
647 	{ .start = CSR_REGISTER_BASE,
648 	  .end   = CSR_REGISTER_BASE | CSR_CONFIG_ROM_END,  };
649 const struct fw_address_region fw_unit_space_region =
650 	{ .start = 0xfffff0000900ULL, .end = 0x1000000000000ULL, };
651 #endif  /*  0  */
652 
653 static void complete_address_handler(struct kref *kref)
654 {
655 	struct fw_address_handler *handler = container_of(kref, struct fw_address_handler, kref);
656 
657 	complete(&handler->done);
658 }
659 
660 static void get_address_handler(struct fw_address_handler *handler)
661 {
662 	kref_get(&handler->kref);
663 }
664 
665 static int put_address_handler(struct fw_address_handler *handler)
666 {
667 	return kref_put(&handler->kref, complete_address_handler);
668 }
669 
670 /**
671  * fw_core_add_address_handler() - register a handler for incoming transaction requests to a
672  *				   specific address region.
673  * @handler: The handler including a callback function for an incoming transaction request.
674  * @region: The region in the IEEE 1212 node space address range.
675  *
676  * &fw_address_handler.length, &fw_address_region.start, and &fw_address_region.end are specified
677  * in bytes and must be multiples of a quadlet. &fw_address_handler.offset is available after
678  * successful registration.
679  *
680  * When a request is received that falls within the specified address range, the specified callback
681  * is invoked. The parameters passed to the callback give the details of the particular request.
682  *
683  * Address allocations are exclusive, except for the FCP registers.
684  *
685  * Returns: 0 on success, non-zero otherwise.
686  */
687 int fw_core_add_address_handler(struct fw_address_handler *handler,
688 				const struct fw_address_region *region)
689 {
690 	struct fw_address_handler *other;
691 	int ret = -EBUSY;
692 
693 	if (region->start & 0xffff000000000003ULL ||
694 	    region->start >= region->end ||
695 	    region->end   > 0x0001000000000000ULL ||
696 	    handler->length & 3 ||
697 	    handler->length == 0)
698 		return -EINVAL;
699 
700 	guard(spinlock)(&address_handler_list_lock);
701 
702 	handler->offset = region->start;
703 	while (handler->offset + handler->length <= region->end) {
704 		if (is_in_fcp_region(handler->offset, handler->length))
705 			other = NULL;
706 		else
707 			other = lookup_overlapping_address_handler
708 					(&address_handler_list,
709 					 handler->offset, handler->length);
710 		if (other != NULL) {
711 			handler->offset += other->length;
712 		} else {
713 			init_completion(&handler->done);
714 			kref_init(&handler->kref);
715 			list_add_tail_rcu(&handler->link, &address_handler_list);
716 			ret = 0;
717 			break;
718 		}
719 	}
720 
721 	return ret;
722 }
723 EXPORT_SYMBOL(fw_core_add_address_handler);
724 
725 /**
726  * fw_core_remove_address_handler() - unregister an address handler for an incoming transaction
727  *				      request.
728  * @handler: The registered handler.
729  *
730  * After this function returns, the handler's callback is guaranteed not to be running on any CPU.
731  *
732  * Context: Process context.
733  */
734 void fw_core_remove_address_handler(struct fw_address_handler *handler)
735 {
736 	// Due to synchronize_rcu().
737 	might_sleep();
738 
739 	scoped_guard(spinlock, &address_handler_list_lock)
740 		list_del_rcu(&handler->link);
741 
742 	synchronize_rcu();
743 
744 	if (!put_address_handler(handler))
745 		wait_for_completion(&handler->done);
746 }
747 EXPORT_SYMBOL(fw_core_remove_address_handler);
748 
749 struct fw_request {
750 	struct kref kref;
751 	struct fw_packet response;
752 	u32 request_header[ASYNC_HEADER_QUADLET_COUNT];
753 	int ack;
754 	u32 timestamp;
755 	u32 length;
756 	u32 data[];
757 };
758 
759 void fw_request_get(struct fw_request *request)
760 {
761 	kref_get(&request->kref);
762 }
763 
764 static void release_request(struct kref *kref)
765 {
766 	struct fw_request *request = container_of(kref, struct fw_request, kref);
767 
768 	kfree(request);
769 }
770 
771 void fw_request_put(struct fw_request *request)
772 {
773 	kref_put(&request->kref, release_request);
774 }
775 
776 static void free_response_callback(struct fw_packet *packet,
777 				   struct fw_card *card, int status)
778 {
779 	struct fw_request *request = container_of(packet, struct fw_request, response);
780 
781 	trace_async_response_outbound_complete((uintptr_t)request, card->index, packet->generation,
782 					       packet->speed, status, packet->timestamp);
783 
784 	// Decrease the reference count since not at in-flight.
785 	fw_request_put(request);
786 
787 	// Decrease the reference count to release the object.
788 	fw_request_put(request);
789 }
790 
791 int fw_get_response_length(struct fw_request *r)
792 {
793 	int tcode, ext_tcode, data_length;
794 
795 	tcode = async_header_get_tcode(r->request_header);
796 
797 	switch (tcode) {
798 	case TCODE_WRITE_QUADLET_REQUEST:
799 	case TCODE_WRITE_BLOCK_REQUEST:
800 		return 0;
801 
802 	case TCODE_READ_QUADLET_REQUEST:
803 		return 4;
804 
805 	case TCODE_READ_BLOCK_REQUEST:
806 		data_length = async_header_get_data_length(r->request_header);
807 		return data_length;
808 
809 	case TCODE_LOCK_REQUEST:
810 		ext_tcode = async_header_get_extended_tcode(r->request_header);
811 		data_length = async_header_get_data_length(r->request_header);
812 		switch (ext_tcode) {
813 		case EXTCODE_FETCH_ADD:
814 		case EXTCODE_LITTLE_ADD:
815 			return data_length;
816 		default:
817 			return data_length / 2;
818 		}
819 
820 	default:
821 		WARN(1, "wrong tcode %d\n", tcode);
822 		return 0;
823 	}
824 }
825 
826 void fw_fill_response(struct fw_packet *response, u32 *request_header,
827 		      int rcode, void *payload, size_t length)
828 {
829 	int tcode, tlabel, extended_tcode, source, destination;
830 
831 	tcode = async_header_get_tcode(request_header);
832 	tlabel = async_header_get_tlabel(request_header);
833 	source = async_header_get_destination(request_header); // Exchange.
834 	destination = async_header_get_source(request_header); // Exchange.
835 	extended_tcode = async_header_get_extended_tcode(request_header);
836 
837 	async_header_set_retry(response->header, RETRY_1);
838 	async_header_set_tlabel(response->header, tlabel);
839 	async_header_set_destination(response->header, destination);
840 	async_header_set_source(response->header, source);
841 	async_header_set_rcode(response->header, rcode);
842 	response->header[2] = 0;	// The field is reserved.
843 
844 	switch (tcode) {
845 	case TCODE_WRITE_QUADLET_REQUEST:
846 	case TCODE_WRITE_BLOCK_REQUEST:
847 		async_header_set_tcode(response->header, TCODE_WRITE_RESPONSE);
848 		response->header_length = 12;
849 		response->payload_length = 0;
850 		break;
851 
852 	case TCODE_READ_QUADLET_REQUEST:
853 		async_header_set_tcode(response->header, TCODE_READ_QUADLET_RESPONSE);
854 		if (payload != NULL)
855 			async_header_set_quadlet_data(response->header, *(u32 *)payload);
856 		else
857 			async_header_set_quadlet_data(response->header, 0);
858 		response->header_length = 16;
859 		response->payload_length = 0;
860 		break;
861 
862 	case TCODE_READ_BLOCK_REQUEST:
863 	case TCODE_LOCK_REQUEST:
864 		async_header_set_tcode(response->header, tcode + 2);
865 		async_header_set_data_length(response->header, length);
866 		async_header_set_extended_tcode(response->header, extended_tcode);
867 		response->header_length = 16;
868 		response->payload = payload;
869 		response->payload_length = length;
870 		break;
871 
872 	default:
873 		WARN(1, "wrong tcode %d\n", tcode);
874 	}
875 
876 	response->payload_mapped = false;
877 }
878 EXPORT_SYMBOL(fw_fill_response);
879 
880 static u32 compute_split_timeout_timestamp(struct fw_card *card,
881 					   u32 request_timestamp)
882 __must_hold(&card->split_timeout.lock)
883 {
884 	unsigned int cycles;
885 	u32 timestamp;
886 
887 	lockdep_assert_held(&card->split_timeout.lock);
888 
889 	cycles = card->split_timeout.cycles;
890 	cycles += request_timestamp & 0x1fff;
891 
892 	timestamp = request_timestamp & ~0x1fff;
893 	timestamp += (cycles / 8000) << 13;
894 	timestamp |= cycles % 8000;
895 
896 	return timestamp;
897 }
898 
899 static struct fw_request *allocate_request(struct fw_card *card,
900 					   struct fw_packet *p)
901 __must_not_hold(&card->split_timeout.lock)
902 {
903 	struct fw_request *request;
904 	u32 *data, length;
905 	int request_tcode;
906 
907 	lockdep_assert_not_held(&card->split_timeout.lock);
908 
909 	request_tcode = async_header_get_tcode(p->header);
910 	switch (request_tcode) {
911 	case TCODE_WRITE_QUADLET_REQUEST:
912 		data = &p->header[3];
913 		length = 4;
914 		break;
915 
916 	case TCODE_WRITE_BLOCK_REQUEST:
917 	case TCODE_LOCK_REQUEST:
918 		data = p->payload;
919 		length = async_header_get_data_length(p->header);
920 		break;
921 
922 	case TCODE_READ_QUADLET_REQUEST:
923 		data = NULL;
924 		length = 4;
925 		break;
926 
927 	case TCODE_READ_BLOCK_REQUEST:
928 		data = NULL;
929 		length = async_header_get_data_length(p->header);
930 		break;
931 
932 	default:
933 		fw_notice(card, "ERROR - corrupt request received - %08x %08x %08x\n",
934 			 p->header[0], p->header[1], p->header[2]);
935 		return NULL;
936 	}
937 
938 	request = kzalloc_flex(*request, data, DIV_ROUND_UP(length, sizeof(u32)));
939 	if (!request)
940 		return NULL;
941 	kref_init(&request->kref);
942 
943 	scoped_guard(spinlock, &card->split_timeout.lock)
944 		request->response.timestamp = compute_split_timeout_timestamp(card, p->timestamp);
945 
946 	request->response.speed = p->speed;
947 	request->response.generation = p->generation;
948 	request->response.ack = 0;
949 	request->response.callback = free_response_callback;
950 	request->ack = p->ack;
951 	request->timestamp = p->timestamp;
952 	request->length = length;
953 	if (data)
954 		memcpy(request->data, data, length);
955 
956 	memcpy(request->request_header, p->header, sizeof(p->header));
957 
958 	return request;
959 }
960 
961 /**
962  * fw_send_response: - send response packet for asynchronous transaction.
963  * @card:	interface to send the response at.
964  * @request:	firewire request data for the transaction.
965  * @rcode:	response code to send.
966  *
967  * Submit a response packet into the asynchronous response transmission queue. The contents of
968  * @request are opaque to the caller. The @request is released when the transmission finishes.
969  */
970 void fw_send_response(struct fw_card *card,
971 		      struct fw_request *request, int rcode)
972 {
973 	u32 *data = NULL;
974 	unsigned int data_length = 0;
975 
976 	/* unified transaction or broadcast transaction: don't respond */
977 	if (request->ack != ACK_PENDING ||
978 	    HEADER_DESTINATION_IS_BROADCAST(request->request_header)) {
979 		fw_request_put(request);
980 		return;
981 	}
982 
983 	if (rcode == RCODE_COMPLETE) {
984 		data = request->data;
985 		data_length = fw_get_response_length(request);
986 	}
987 
988 	fw_fill_response(&request->response, request->request_header, rcode, data, data_length);
989 
990 	// Increase the reference count so that the object is kept during in-flight.
991 	fw_request_get(request);
992 
993 	trace_async_response_outbound_initiate((uintptr_t)request, card->index,
994 					       request->response.generation, request->response.speed,
995 					       request->response.header, data,
996 					       data ? data_length / 4 : 0);
997 
998 	smp_load_acquire(&card->driver)->send_response(card, &request->response);
999 }
1000 EXPORT_SYMBOL(fw_send_response);
1001 
1002 /**
1003  * fw_get_request_speed() - returns speed at which the @request was received
1004  * @request: firewire request data
1005  */
1006 int fw_get_request_speed(struct fw_request *request)
1007 {
1008 	return request->response.speed;
1009 }
1010 EXPORT_SYMBOL(fw_get_request_speed);
1011 
1012 /**
1013  * fw_request_get_timestamp: Get timestamp of the request.
1014  * @request: The opaque pointer to request structure.
1015  *
1016  * Get timestamp when 1394 OHCI controller receives the asynchronous request subaction. The
1017  * timestamp consists of the low order 3 bits of second field and the full 13 bits of count
1018  * field of isochronous cycle time register.
1019  *
1020  * Returns: timestamp of the request.
1021  */
1022 u32 fw_request_get_timestamp(const struct fw_request *request)
1023 {
1024 	return request->timestamp;
1025 }
1026 EXPORT_SYMBOL_GPL(fw_request_get_timestamp);
1027 
1028 static void handle_exclusive_region_request(struct fw_card *card,
1029 					    struct fw_packet *p,
1030 					    struct fw_request *request,
1031 					    unsigned long long offset)
1032 {
1033 	struct fw_address_handler *handler;
1034 	int tcode, destination, source;
1035 
1036 	destination = async_header_get_destination(p->header);
1037 	source = async_header_get_source(p->header);
1038 	tcode = async_header_get_tcode(p->header);
1039 	if (tcode == TCODE_LOCK_REQUEST)
1040 		tcode = 0x10 + async_header_get_extended_tcode(p->header);
1041 
1042 	scoped_guard(rcu) {
1043 		handler = lookup_enclosing_address_handler(&address_handler_list, offset,
1044 							   request->length);
1045 		if (handler)
1046 			get_address_handler(handler);
1047 	}
1048 
1049 	if (!handler) {
1050 		fw_send_response(card, request, RCODE_ADDRESS_ERROR);
1051 		return;
1052 	}
1053 
1054 	// Outside the RCU read-side critical section. Without spinlock. With reference count.
1055 	handler->address_callback(card, request, tcode, destination, source, p->generation, offset,
1056 				  request->data, request->length, handler->callback_data);
1057 	put_address_handler(handler);
1058 }
1059 
1060 // To use kmalloc allocator efficiently, this should be power of two.
1061 #define BUFFER_ON_KERNEL_STACK_SIZE	4
1062 
1063 static void handle_fcp_region_request(struct fw_card *card,
1064 				      struct fw_packet *p,
1065 				      struct fw_request *request,
1066 				      unsigned long long offset)
1067 {
1068 	struct fw_address_handler *buffer_on_kernel_stack[BUFFER_ON_KERNEL_STACK_SIZE];
1069 	struct fw_address_handler *handler, **handlers;
1070 	int tcode, destination, source, i, count, buffer_size;
1071 
1072 	if ((offset != (CSR_REGISTER_BASE | CSR_FCP_COMMAND) &&
1073 	     offset != (CSR_REGISTER_BASE | CSR_FCP_RESPONSE)) ||
1074 	    request->length > 0x200) {
1075 		fw_send_response(card, request, RCODE_ADDRESS_ERROR);
1076 
1077 		return;
1078 	}
1079 
1080 	tcode = async_header_get_tcode(p->header);
1081 	destination = async_header_get_destination(p->header);
1082 	source = async_header_get_source(p->header);
1083 
1084 	if (tcode != TCODE_WRITE_QUADLET_REQUEST &&
1085 	    tcode != TCODE_WRITE_BLOCK_REQUEST) {
1086 		fw_send_response(card, request, RCODE_TYPE_ERROR);
1087 
1088 		return;
1089 	}
1090 
1091 	count = 0;
1092 	handlers = buffer_on_kernel_stack;
1093 	buffer_size = ARRAY_SIZE(buffer_on_kernel_stack);
1094 	scoped_guard(rcu) {
1095 		list_for_each_entry_rcu(handler, &address_handler_list, link) {
1096 			if (is_enclosing_handler(handler, offset, request->length)) {
1097 				if (count >= buffer_size) {
1098 					int next_size = buffer_size * 2;
1099 					struct fw_address_handler **buffer_on_kernel_heap;
1100 
1101 					if (handlers == buffer_on_kernel_stack)
1102 						buffer_on_kernel_heap = NULL;
1103 					else
1104 						buffer_on_kernel_heap = handlers;
1105 
1106 					buffer_on_kernel_heap =
1107 						krealloc_array(buffer_on_kernel_heap, next_size,
1108 							sizeof(*buffer_on_kernel_heap), GFP_ATOMIC);
1109 					// FCP is used for purposes unrelated to significant system
1110 					// resources (e.g. storage or networking), so allocation
1111 					// failures are not considered so critical.
1112 					if (!buffer_on_kernel_heap)
1113 						break;
1114 
1115 					if (handlers == buffer_on_kernel_stack) {
1116 						memcpy(buffer_on_kernel_heap, buffer_on_kernel_stack,
1117 						       sizeof(buffer_on_kernel_stack));
1118 					}
1119 
1120 					handlers = buffer_on_kernel_heap;
1121 					buffer_size = next_size;
1122 				}
1123 				get_address_handler(handler);
1124 				handlers[count++] = handler;
1125 			}
1126 		}
1127 	}
1128 
1129 	for (i = 0; i < count; ++i) {
1130 		handler = handlers[i];
1131 		handler->address_callback(card, request, tcode, destination, source,
1132 					  p->generation, offset, request->data,
1133 					  request->length, handler->callback_data);
1134 		put_address_handler(handler);
1135 	}
1136 
1137 	if (handlers != buffer_on_kernel_stack)
1138 		kfree(handlers);
1139 
1140 	fw_send_response(card, request, RCODE_COMPLETE);
1141 }
1142 
1143 void fw_core_handle_request(struct fw_card *card, struct fw_packet *p)
1144 {
1145 	struct fw_request *request;
1146 	unsigned long long offset;
1147 	unsigned int tcode;
1148 
1149 	// Allow the call of allocate_request() to perform object allocation with GFP_KERNEL,
1150 	// as well as the address handlers to work with mutexes.
1151 	might_sleep();
1152 
1153 	if (p->ack != ACK_PENDING && p->ack != ACK_COMPLETE)
1154 		return;
1155 
1156 	tcode = async_header_get_tcode(p->header);
1157 	if (tcode_is_link_internal(tcode)) {
1158 		trace_async_phy_inbound((uintptr_t)p, card->index, p->generation, p->ack, p->timestamp,
1159 					 p->header[1], p->header[2]);
1160 		fw_cdev_handle_phy_packet(card, p);
1161 		return;
1162 	}
1163 
1164 	request = allocate_request(card, p);
1165 	if (request == NULL) {
1166 		/* FIXME: send statically allocated busy packet. */
1167 		return;
1168 	}
1169 
1170 	trace_async_request_inbound((uintptr_t)request, card->index, p->generation, p->speed,
1171 				    p->ack, p->timestamp, p->header, request->data,
1172 				    tcode_is_read_request(tcode) ? 0 : request->length / 4);
1173 
1174 	offset = async_header_get_offset(p->header);
1175 
1176 	if (!is_in_fcp_region(offset, request->length))
1177 		handle_exclusive_region_request(card, p, request, offset);
1178 	else
1179 		handle_fcp_region_request(card, p, request, offset);
1180 
1181 }
1182 EXPORT_SYMBOL(fw_core_handle_request);
1183 
1184 void fw_core_handle_response(struct fw_card *card, struct fw_packet *p)
1185 __must_not_hold(&card->transactions.lock)
1186 {
1187 	struct fw_transaction *t = NULL;
1188 	u32 *data;
1189 	size_t data_length;
1190 	int tcode, tlabel, source, rcode;
1191 
1192 	lockdep_assert_not_held(&card->transactions.lock);
1193 
1194 	// Allow the call of struct fw_card_driver.cancel_packet() to wait for any event.
1195 	might_sleep();
1196 
1197 	tcode = async_header_get_tcode(p->header);
1198 	tlabel = async_header_get_tlabel(p->header);
1199 	source = async_header_get_source(p->header);
1200 	rcode = async_header_get_rcode(p->header);
1201 
1202 	// FIXME: sanity check packet, is length correct, does tcodes
1203 	// and addresses match to the transaction request queried later.
1204 	//
1205 	// For the tracepoints event, let us decode the header here against the concern.
1206 
1207 	switch (tcode) {
1208 	case TCODE_READ_QUADLET_RESPONSE:
1209 		data = (u32 *) &p->header[3];
1210 		data_length = 4;
1211 		break;
1212 
1213 	case TCODE_WRITE_RESPONSE:
1214 		data = NULL;
1215 		data_length = 0;
1216 		break;
1217 
1218 	case TCODE_READ_BLOCK_RESPONSE:
1219 	case TCODE_LOCK_RESPONSE:
1220 		data = p->payload;
1221 		data_length = async_header_get_data_length(p->header);
1222 		break;
1223 
1224 	default:
1225 		/* Should never happen, this is just to shut up gcc. */
1226 		data = NULL;
1227 		data_length = 0;
1228 		break;
1229 	}
1230 
1231 	scoped_guard(spinlock_irqsave, &card->transactions.lock) {
1232 		t = find_and_pop_transaction_entry(card,
1233 				iter->node_id == source && iter->tlabel == tlabel);
1234 	}
1235 
1236 	trace_async_response_inbound((uintptr_t)t, card->index, p->generation, p->speed, p->ack,
1237 				     p->timestamp, p->header, data, data_length / 4);
1238 
1239 	if (!t) {
1240 		fw_notice(card, "unsolicited response (source %x, tlabel %x)\n",
1241 			  source, tlabel);
1242 		return;
1243 	}
1244 
1245 	/*
1246 	 * The response handler may be executed while the request handler
1247 	 * is still pending.  Cancel the request handler.
1248 	 */
1249 	smp_load_acquire(&card->driver)->cancel_packet(card, &t->packet);
1250 
1251 	invoke_callback(t, rcode, p->timestamp, data, data_length);
1252 }
1253 EXPORT_SYMBOL(fw_core_handle_response);
1254 
1255 /**
1256  * fw_rcode_string - convert a firewire result code to an error description
1257  * @rcode: the result code
1258  */
1259 const char *fw_rcode_string(int rcode)
1260 {
1261 	static const char *const names[] = {
1262 		[RCODE_COMPLETE]       = "no error",
1263 		[RCODE_CONFLICT_ERROR] = "conflict error",
1264 		[RCODE_DATA_ERROR]     = "data error",
1265 		[RCODE_TYPE_ERROR]     = "type error",
1266 		[RCODE_ADDRESS_ERROR]  = "address error",
1267 		[RCODE_SEND_ERROR]     = "send error",
1268 		[RCODE_CANCELLED]      = "timeout",
1269 		[RCODE_BUSY]           = "busy",
1270 		[RCODE_GENERATION]     = "bus reset",
1271 		[RCODE_NO_ACK]         = "no ack",
1272 	};
1273 
1274 	if ((unsigned int)rcode < ARRAY_SIZE(names) && names[rcode])
1275 		return names[rcode];
1276 	else
1277 		return "unknown";
1278 }
1279 EXPORT_SYMBOL(fw_rcode_string);
1280 
1281 static const struct fw_address_region topology_map_region =
1282 	{ .start = CSR_REGISTER_BASE | CSR_TOPOLOGY_MAP,
1283 	  .end   = CSR_REGISTER_BASE | CSR_TOPOLOGY_MAP_END, };
1284 
1285 static void handle_topology_map(struct fw_card *card, struct fw_request *request,
1286 		int tcode, int destination, int source, int generation,
1287 		unsigned long long offset, void *payload, size_t length,
1288 		void *callback_data)
1289 __must_not_hold(&card->topology_map.lock)
1290 {
1291 	int start;
1292 
1293 	lockdep_assert_not_held(&card->topology_map.lock);
1294 
1295 	if (!tcode_is_read_request(tcode)) {
1296 		fw_send_response(card, request, RCODE_TYPE_ERROR);
1297 		return;
1298 	}
1299 
1300 	if ((offset & 3) > 0 || (length & 3) > 0) {
1301 		fw_send_response(card, request, RCODE_ADDRESS_ERROR);
1302 		return;
1303 	}
1304 
1305 	start = (offset - topology_map_region.start) / 4;
1306 
1307 	scoped_guard(spinlock, &card->topology_map.lock)
1308 		memcpy(payload, &card->topology_map.buffer[start], length);
1309 
1310 	fw_send_response(card, request, RCODE_COMPLETE);
1311 }
1312 
1313 static struct fw_address_handler topology_map = {
1314 	.length			= 0x400,
1315 	.address_callback	= handle_topology_map,
1316 };
1317 
1318 static const struct fw_address_region registers_region =
1319 	{ .start = CSR_REGISTER_BASE,
1320 	  .end   = CSR_REGISTER_BASE | CSR_CONFIG_ROM, };
1321 
1322 static void update_split_timeout(struct fw_card *card)
1323 __must_hold(&card->split_timeout.lock)
1324 {
1325 	unsigned int cycles;
1326 
1327 	lockdep_assert_held(&card->split_timeout.lock);
1328 
1329 	cycles = card->split_timeout.hi * 8000 + (card->split_timeout.lo >> 19);
1330 
1331 	/* minimum per IEEE 1394, maximum which doesn't overflow OHCI */
1332 	cycles = clamp(cycles, 800u, 3u * 8000u);
1333 
1334 	card->split_timeout.cycles = cycles;
1335 	card->split_timeout.jiffies = isoc_cycles_to_jiffies(cycles);
1336 }
1337 
1338 static void handle_registers(struct fw_card *card, struct fw_request *request,
1339 		int tcode, int destination, int source, int generation,
1340 		unsigned long long offset, void *payload, size_t length,
1341 		void *callback_data)
1342 {
1343 	int reg = offset & ~CSR_REGISTER_BASE;
1344 	__be32 *data = payload;
1345 	int rcode = RCODE_COMPLETE;
1346 
1347 	switch (reg) {
1348 	case CSR_PRIORITY_BUDGET:
1349 		if (!card->priority_budget_implemented) {
1350 			rcode = RCODE_ADDRESS_ERROR;
1351 			break;
1352 		}
1353 		fallthrough;
1354 
1355 	case CSR_NODE_IDS:
1356 		/*
1357 		 * per IEEE 1394-2008 8.3.22.3, not IEEE 1394.1-2004 3.2.8
1358 		 * and 9.6, but interoperable with IEEE 1394.1-2004 bridges
1359 		 */
1360 		fallthrough;
1361 
1362 	case CSR_STATE_CLEAR:
1363 	case CSR_STATE_SET:
1364 	case CSR_CYCLE_TIME:
1365 	case CSR_BUS_TIME:
1366 	case CSR_BUSY_TIMEOUT:
1367 		if (tcode == TCODE_READ_QUADLET_REQUEST)
1368 			*data = cpu_to_be32(smp_load_acquire(&card->driver)->read_csr(card, reg));
1369 		else if (tcode == TCODE_WRITE_QUADLET_REQUEST)
1370 			smp_load_acquire(&card->driver)->write_csr(card, reg, be32_to_cpu(*data));
1371 		else
1372 			rcode = RCODE_TYPE_ERROR;
1373 		break;
1374 
1375 	case CSR_RESET_START:
1376 		if (tcode == TCODE_WRITE_QUADLET_REQUEST)
1377 			smp_load_acquire(&card->driver)->write_csr(card, CSR_STATE_CLEAR,
1378 								   CSR_STATE_BIT_ABDICATE);
1379 		else
1380 			rcode = RCODE_TYPE_ERROR;
1381 		break;
1382 
1383 	case CSR_SPLIT_TIMEOUT_HI:
1384 		scoped_guard(spinlock, &card->split_timeout.lock) {
1385 			if (tcode == TCODE_READ_QUADLET_REQUEST) {
1386 				*data = cpu_to_be32(card->split_timeout.hi);
1387 			} else if (tcode == TCODE_WRITE_QUADLET_REQUEST) {
1388 				card->split_timeout.hi = be32_to_cpu(*data) & 7;
1389 				update_split_timeout(card);
1390 			} else {
1391 				rcode = RCODE_TYPE_ERROR;
1392 			}
1393 		}
1394 		break;
1395 
1396 	case CSR_SPLIT_TIMEOUT_LO:
1397 		scoped_guard(spinlock, &card->split_timeout.lock) {
1398 			if (tcode == TCODE_READ_QUADLET_REQUEST) {
1399 				*data = cpu_to_be32(card->split_timeout.lo);
1400 			} else if (tcode == TCODE_WRITE_QUADLET_REQUEST) {
1401 				card->split_timeout.lo = be32_to_cpu(*data) & 0xfff80000;
1402 				update_split_timeout(card);
1403 			} else {
1404 				rcode = RCODE_TYPE_ERROR;
1405 			}
1406 		}
1407 		break;
1408 
1409 	case CSR_MAINT_UTILITY:
1410 		if (tcode == TCODE_READ_QUADLET_REQUEST)
1411 			*data = card->maint_utility_register;
1412 		else if (tcode == TCODE_WRITE_QUADLET_REQUEST)
1413 			card->maint_utility_register = *data;
1414 		else
1415 			rcode = RCODE_TYPE_ERROR;
1416 		break;
1417 
1418 	case CSR_BROADCAST_CHANNEL:
1419 		if (tcode == TCODE_READ_QUADLET_REQUEST)
1420 			*data = cpu_to_be32(card->broadcast_channel);
1421 		else if (tcode == TCODE_WRITE_QUADLET_REQUEST)
1422 			card->broadcast_channel =
1423 			    (be32_to_cpu(*data) & BROADCAST_CHANNEL_VALID) |
1424 			    BROADCAST_CHANNEL_INITIAL;
1425 		else
1426 			rcode = RCODE_TYPE_ERROR;
1427 		break;
1428 
1429 	case CSR_BUS_MANAGER_ID:
1430 	case CSR_BANDWIDTH_AVAILABLE:
1431 	case CSR_CHANNELS_AVAILABLE_HI:
1432 	case CSR_CHANNELS_AVAILABLE_LO:
1433 		/*
1434 		 * FIXME: these are handled by the OHCI hardware and
1435 		 * the stack never sees these request. If we add
1436 		 * support for a new type of controller that doesn't
1437 		 * handle this in hardware we need to deal with these
1438 		 * transactions.
1439 		 */
1440 		BUG();
1441 		break;
1442 
1443 	default:
1444 		rcode = RCODE_ADDRESS_ERROR;
1445 		break;
1446 	}
1447 
1448 	fw_send_response(card, request, rcode);
1449 }
1450 
1451 static struct fw_address_handler registers = {
1452 	.length			= 0x400,
1453 	.address_callback	= handle_registers,
1454 };
1455 
1456 static void handle_low_memory(struct fw_card *card, struct fw_request *request,
1457 		int tcode, int destination, int source, int generation,
1458 		unsigned long long offset, void *payload, size_t length,
1459 		void *callback_data)
1460 {
1461 	/*
1462 	 * This catches requests not handled by the physical DMA unit,
1463 	 * i.e., wrong transaction types or unauthorized source nodes.
1464 	 */
1465 	fw_send_response(card, request, RCODE_TYPE_ERROR);
1466 }
1467 
1468 static struct fw_address_handler low_memory = {
1469 	.length			= FW_MAX_PHYSICAL_RANGE,
1470 	.address_callback	= handle_low_memory,
1471 };
1472 
1473 MODULE_AUTHOR("Kristian Hoegsberg <krh@bitplanet.net>");
1474 MODULE_DESCRIPTION("Core IEEE1394 transaction logic");
1475 MODULE_LICENSE("GPL");
1476 
1477 static const u32 vendor_textual_descriptor[] = {
1478 	/* textual descriptor leaf () */
1479 	0x00060000,
1480 	0x00000000,
1481 	0x00000000,
1482 	0x4c696e75,		/* L i n u */
1483 	0x78204669,		/* x   F i */
1484 	0x72657769,		/* r e w i */
1485 	0x72650000,		/* r e     */
1486 };
1487 
1488 static const u32 model_textual_descriptor[] = {
1489 	/* model descriptor leaf () */
1490 	0x00030000,
1491 	0x00000000,
1492 	0x00000000,
1493 	0x4a756a75,		/* J u j u */
1494 };
1495 
1496 static struct fw_descriptor vendor_id_descriptor = {
1497 	.length = ARRAY_SIZE(vendor_textual_descriptor),
1498 	.immediate = 0x03001f11,
1499 	.key = 0x81000000,
1500 	.data = vendor_textual_descriptor,
1501 };
1502 
1503 static struct fw_descriptor model_id_descriptor = {
1504 	.length = ARRAY_SIZE(model_textual_descriptor),
1505 	.immediate = 0x17023901,
1506 	.key = 0x81000000,
1507 	.data = model_textual_descriptor,
1508 };
1509 
1510 static int __init fw_core_init(void)
1511 {
1512 	int ret;
1513 
1514 	fw_workqueue = alloc_workqueue("firewire", WQ_MEM_RECLAIM | WQ_UNBOUND,
1515 				       0);
1516 	if (!fw_workqueue)
1517 		return -ENOMEM;
1518 
1519 	ret = bus_register(&fw_bus_type);
1520 	if (ret < 0) {
1521 		destroy_workqueue(fw_workqueue);
1522 		return ret;
1523 	}
1524 
1525 	fw_cdev_major = register_chrdev(0, "firewire", &fw_device_ops);
1526 	if (fw_cdev_major < 0) {
1527 		bus_unregister(&fw_bus_type);
1528 		destroy_workqueue(fw_workqueue);
1529 		return fw_cdev_major;
1530 	}
1531 
1532 	fw_core_add_address_handler(&topology_map, &topology_map_region);
1533 	fw_core_add_address_handler(&registers, &registers_region);
1534 	fw_core_add_address_handler(&low_memory, &low_memory_region);
1535 	fw_core_add_descriptor(&vendor_id_descriptor);
1536 	fw_core_add_descriptor(&model_id_descriptor);
1537 
1538 	return 0;
1539 }
1540 
1541 static void __exit fw_core_cleanup(void)
1542 {
1543 	unregister_chrdev(fw_cdev_major, "firewire");
1544 	bus_unregister(&fw_bus_type);
1545 	destroy_workqueue(fw_workqueue);
1546 	xa_destroy(&fw_device_xa);
1547 }
1548 
1549 module_init(fw_core_init);
1550 module_exit(fw_core_cleanup);
1551