firewire: cdev: add ioctls for isochronous resource management
[linux-2.6] / drivers / firewire / fw-cdev.c
1 /*
2  * Char device for device raw access
3  *
4  * Copyright (C) 2005-2007  Kristian Hoegsberg <krh@bitplanet.net>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19  */
20
21 #include <linux/compat.h>
22 #include <linux/delay.h>
23 #include <linux/device.h>
24 #include <linux/errno.h>
25 #include <linux/firewire-cdev.h>
26 #include <linux/idr.h>
27 #include <linux/jiffies.h>
28 #include <linux/kernel.h>
29 #include <linux/kref.h>
30 #include <linux/mm.h>
31 #include <linux/module.h>
32 #include <linux/mutex.h>
33 #include <linux/poll.h>
34 #include <linux/preempt.h>
35 #include <linux/spinlock.h>
36 #include <linux/time.h>
37 #include <linux/vmalloc.h>
38 #include <linux/wait.h>
39 #include <linux/workqueue.h>
40
41 #include <asm/system.h>
42 #include <asm/uaccess.h>
43
44 #include "fw-device.h"
45 #include "fw-topology.h"
46 #include "fw-transaction.h"
47
48 struct client {
49         u32 version;
50         struct fw_device *device;
51
52         spinlock_t lock;
53         bool in_shutdown;
54         struct idr resource_idr;
55         struct list_head event_list;
56         wait_queue_head_t wait;
57         u64 bus_reset_closure;
58
59         struct fw_iso_context *iso_context;
60         u64 iso_closure;
61         struct fw_iso_buffer buffer;
62         unsigned long vm_start;
63
64         struct list_head link;
65         struct kref kref;
66 };
67
68 static inline void client_get(struct client *client)
69 {
70         kref_get(&client->kref);
71 }
72
73 static void client_release(struct kref *kref)
74 {
75         struct client *client = container_of(kref, struct client, kref);
76
77         fw_device_put(client->device);
78         kfree(client);
79 }
80
81 static void client_put(struct client *client)
82 {
83         kref_put(&client->kref, client_release);
84 }
85
86 struct client_resource;
87 typedef void (*client_resource_release_fn_t)(struct client *,
88                                              struct client_resource *);
89 struct client_resource {
90         client_resource_release_fn_t release;
91         int handle;
92 };
93
94 struct address_handler_resource {
95         struct client_resource resource;
96         struct fw_address_handler handler;
97         __u64 closure;
98         struct client *client;
99 };
100
101 struct outbound_transaction_resource {
102         struct client_resource resource;
103         struct fw_transaction transaction;
104 };
105
106 struct inbound_transaction_resource {
107         struct client_resource resource;
108         struct fw_request *request;
109         void *data;
110         size_t length;
111 };
112
113 struct descriptor_resource {
114         struct client_resource resource;
115         struct fw_descriptor descriptor;
116         u32 data[0];
117 };
118
119 struct iso_resource {
120         struct client_resource resource;
121         struct client *client;
122         /* Schedule work and access todo only with client->lock held. */
123         struct delayed_work work;
124         enum {ISO_RES_ALLOC, ISO_RES_REALLOC, ISO_RES_DEALLOC,} todo;
125         int generation;
126         u64 channels;
127         s32 bandwidth;
128         struct iso_resource_event *e_alloc, *e_dealloc;
129 };
130
131 static void schedule_iso_resource(struct iso_resource *);
132 static void release_iso_resource(struct client *, struct client_resource *);
133
134 /*
135  * dequeue_event() just kfree()'s the event, so the event has to be
136  * the first field in a struct XYZ_event.
137  */
138 struct event {
139         struct { void *data; size_t size; } v[2];
140         struct list_head link;
141 };
142
143 struct bus_reset_event {
144         struct event event;
145         struct fw_cdev_event_bus_reset reset;
146 };
147
148 struct outbound_transaction_event {
149         struct event event;
150         struct client *client;
151         struct outbound_transaction_resource r;
152         struct fw_cdev_event_response response;
153 };
154
155 struct inbound_transaction_event {
156         struct event event;
157         struct fw_cdev_event_request request;
158 };
159
160 struct iso_interrupt_event {
161         struct event event;
162         struct fw_cdev_event_iso_interrupt interrupt;
163 };
164
165 struct iso_resource_event {
166         struct event event;
167         struct fw_cdev_event_iso_resource resource;
168 };
169
170 static inline void __user *u64_to_uptr(__u64 value)
171 {
172         return (void __user *)(unsigned long)value;
173 }
174
175 static inline __u64 uptr_to_u64(void __user *ptr)
176 {
177         return (__u64)(unsigned long)ptr;
178 }
179
180 static int fw_device_op_open(struct inode *inode, struct file *file)
181 {
182         struct fw_device *device;
183         struct client *client;
184
185         device = fw_device_get_by_devt(inode->i_rdev);
186         if (device == NULL)
187                 return -ENODEV;
188
189         if (fw_device_is_shutdown(device)) {
190                 fw_device_put(device);
191                 return -ENODEV;
192         }
193
194         client = kzalloc(sizeof(*client), GFP_KERNEL);
195         if (client == NULL) {
196                 fw_device_put(device);
197                 return -ENOMEM;
198         }
199
200         client->device = device;
201         spin_lock_init(&client->lock);
202         idr_init(&client->resource_idr);
203         INIT_LIST_HEAD(&client->event_list);
204         init_waitqueue_head(&client->wait);
205         kref_init(&client->kref);
206
207         file->private_data = client;
208
209         mutex_lock(&device->client_list_mutex);
210         list_add_tail(&client->link, &device->client_list);
211         mutex_unlock(&device->client_list_mutex);
212
213         return 0;
214 }
215
216 static void queue_event(struct client *client, struct event *event,
217                         void *data0, size_t size0, void *data1, size_t size1)
218 {
219         unsigned long flags;
220
221         event->v[0].data = data0;
222         event->v[0].size = size0;
223         event->v[1].data = data1;
224         event->v[1].size = size1;
225
226         spin_lock_irqsave(&client->lock, flags);
227         if (client->in_shutdown)
228                 kfree(event);
229         else
230                 list_add_tail(&event->link, &client->event_list);
231         spin_unlock_irqrestore(&client->lock, flags);
232
233         wake_up_interruptible(&client->wait);
234 }
235
236 static int dequeue_event(struct client *client,
237                          char __user *buffer, size_t count)
238 {
239         unsigned long flags;
240         struct event *event;
241         size_t size, total;
242         int i, ret;
243
244         ret = wait_event_interruptible(client->wait,
245                         !list_empty(&client->event_list) ||
246                         fw_device_is_shutdown(client->device));
247         if (ret < 0)
248                 return ret;
249
250         if (list_empty(&client->event_list) &&
251                        fw_device_is_shutdown(client->device))
252                 return -ENODEV;
253
254         spin_lock_irqsave(&client->lock, flags);
255         event = list_first_entry(&client->event_list, struct event, link);
256         list_del(&event->link);
257         spin_unlock_irqrestore(&client->lock, flags);
258
259         total = 0;
260         for (i = 0; i < ARRAY_SIZE(event->v) && total < count; i++) {
261                 size = min(event->v[i].size, count - total);
262                 if (copy_to_user(buffer + total, event->v[i].data, size)) {
263                         ret = -EFAULT;
264                         goto out;
265                 }
266                 total += size;
267         }
268         ret = total;
269
270  out:
271         kfree(event);
272
273         return ret;
274 }
275
276 static ssize_t fw_device_op_read(struct file *file, char __user *buffer,
277                                  size_t count, loff_t *offset)
278 {
279         struct client *client = file->private_data;
280
281         return dequeue_event(client, buffer, count);
282 }
283
284 static void fill_bus_reset_event(struct fw_cdev_event_bus_reset *event,
285                                  struct client *client)
286 {
287         struct fw_card *card = client->device->card;
288         unsigned long flags;
289
290         spin_lock_irqsave(&card->lock, flags);
291
292         event->closure       = client->bus_reset_closure;
293         event->type          = FW_CDEV_EVENT_BUS_RESET;
294         event->generation    = client->device->generation;
295         event->node_id       = client->device->node_id;
296         event->local_node_id = card->local_node->node_id;
297         event->bm_node_id    = 0; /* FIXME: We don't track the BM. */
298         event->irm_node_id   = card->irm_node->node_id;
299         event->root_node_id  = card->root_node->node_id;
300
301         spin_unlock_irqrestore(&card->lock, flags);
302 }
303
304 static void for_each_client(struct fw_device *device,
305                             void (*callback)(struct client *client))
306 {
307         struct client *c;
308
309         mutex_lock(&device->client_list_mutex);
310         list_for_each_entry(c, &device->client_list, link)
311                 callback(c);
312         mutex_unlock(&device->client_list_mutex);
313 }
314
315 static int schedule_reallocations(int id, void *p, void *data)
316 {
317         struct client_resource *r = p;
318
319         if (r->release == release_iso_resource)
320                 schedule_iso_resource(container_of(r,
321                                         struct iso_resource, resource));
322         return 0;
323 }
324
325 static void queue_bus_reset_event(struct client *client)
326 {
327         struct bus_reset_event *e;
328
329         e = kzalloc(sizeof(*e), GFP_KERNEL);
330         if (e == NULL) {
331                 fw_notify("Out of memory when allocating bus reset event\n");
332                 return;
333         }
334
335         fill_bus_reset_event(&e->reset, client);
336
337         queue_event(client, &e->event,
338                     &e->reset, sizeof(e->reset), NULL, 0);
339
340         spin_lock_irq(&client->lock);
341         idr_for_each(&client->resource_idr, schedule_reallocations, client);
342         spin_unlock_irq(&client->lock);
343 }
344
345 void fw_device_cdev_update(struct fw_device *device)
346 {
347         for_each_client(device, queue_bus_reset_event);
348 }
349
350 static void wake_up_client(struct client *client)
351 {
352         wake_up_interruptible(&client->wait);
353 }
354
355 void fw_device_cdev_remove(struct fw_device *device)
356 {
357         for_each_client(device, wake_up_client);
358 }
359
360 static int ioctl_get_info(struct client *client, void *buffer)
361 {
362         struct fw_cdev_get_info *get_info = buffer;
363         struct fw_cdev_event_bus_reset bus_reset;
364         unsigned long ret = 0;
365
366         client->version = get_info->version;
367         get_info->version = FW_CDEV_VERSION;
368         get_info->card = client->device->card->index;
369
370         down_read(&fw_device_rwsem);
371
372         if (get_info->rom != 0) {
373                 void __user *uptr = u64_to_uptr(get_info->rom);
374                 size_t want = get_info->rom_length;
375                 size_t have = client->device->config_rom_length * 4;
376
377                 ret = copy_to_user(uptr, client->device->config_rom,
378                                    min(want, have));
379         }
380         get_info->rom_length = client->device->config_rom_length * 4;
381
382         up_read(&fw_device_rwsem);
383
384         if (ret != 0)
385                 return -EFAULT;
386
387         client->bus_reset_closure = get_info->bus_reset_closure;
388         if (get_info->bus_reset != 0) {
389                 void __user *uptr = u64_to_uptr(get_info->bus_reset);
390
391                 fill_bus_reset_event(&bus_reset, client);
392                 if (copy_to_user(uptr, &bus_reset, sizeof(bus_reset)))
393                         return -EFAULT;
394         }
395
396         return 0;
397 }
398
399 static int add_client_resource(struct client *client,
400                                struct client_resource *resource, gfp_t gfp_mask)
401 {
402         unsigned long flags;
403         int ret;
404
405  retry:
406         if (idr_pre_get(&client->resource_idr, gfp_mask) == 0)
407                 return -ENOMEM;
408
409         spin_lock_irqsave(&client->lock, flags);
410         if (client->in_shutdown)
411                 ret = -ECANCELED;
412         else
413                 ret = idr_get_new(&client->resource_idr, resource,
414                                   &resource->handle);
415         if (ret >= 0) {
416                 client_get(client);
417                 if (resource->release == release_iso_resource)
418                         schedule_iso_resource(container_of(resource,
419                                                 struct iso_resource, resource));
420         }
421         spin_unlock_irqrestore(&client->lock, flags);
422
423         if (ret == -EAGAIN)
424                 goto retry;
425
426         return ret < 0 ? ret : 0;
427 }
428
429 static int release_client_resource(struct client *client, u32 handle,
430                                    client_resource_release_fn_t release,
431                                    struct client_resource **resource)
432 {
433         struct client_resource *r;
434         unsigned long flags;
435
436         spin_lock_irqsave(&client->lock, flags);
437         if (client->in_shutdown)
438                 r = NULL;
439         else
440                 r = idr_find(&client->resource_idr, handle);
441         if (r && r->release == release)
442                 idr_remove(&client->resource_idr, handle);
443         spin_unlock_irqrestore(&client->lock, flags);
444
445         if (!(r && r->release == release))
446                 return -EINVAL;
447
448         if (resource)
449                 *resource = r;
450         else
451                 r->release(client, r);
452
453         client_put(client);
454
455         return 0;
456 }
457
458 static void release_transaction(struct client *client,
459                                 struct client_resource *resource)
460 {
461         struct outbound_transaction_resource *r = container_of(resource,
462                         struct outbound_transaction_resource, resource);
463
464         fw_cancel_transaction(client->device->card, &r->transaction);
465 }
466
467 static void complete_transaction(struct fw_card *card, int rcode,
468                                  void *payload, size_t length, void *data)
469 {
470         struct outbound_transaction_event *e = data;
471         struct fw_cdev_event_response *rsp = &e->response;
472         struct client *client = e->client;
473         unsigned long flags;
474
475         if (length < rsp->length)
476                 rsp->length = length;
477         if (rcode == RCODE_COMPLETE)
478                 memcpy(rsp->data, payload, rsp->length);
479
480         spin_lock_irqsave(&client->lock, flags);
481         /*
482          * 1. If called while in shutdown, the idr tree must be left untouched.
483          *    The idr handle will be removed and the client reference will be
484          *    dropped later.
485          * 2. If the call chain was release_client_resource ->
486          *    release_transaction -> complete_transaction (instead of a normal
487          *    conclusion of the transaction), i.e. if this resource was already
488          *    unregistered from the idr, the client reference will be dropped
489          *    by release_client_resource and we must not drop it here.
490          */
491         if (!client->in_shutdown &&
492             idr_find(&client->resource_idr, e->r.resource.handle)) {
493                 idr_remove(&client->resource_idr, e->r.resource.handle);
494                 /* Drop the idr's reference */
495                 client_put(client);
496         }
497         spin_unlock_irqrestore(&client->lock, flags);
498
499         rsp->type = FW_CDEV_EVENT_RESPONSE;
500         rsp->rcode = rcode;
501
502         /*
503          * In the case that sizeof(*rsp) doesn't align with the position of the
504          * data, and the read is short, preserve an extra copy of the data
505          * to stay compatible with a pre-2.6.27 bug.  Since the bug is harmless
506          * for short reads and some apps depended on it, this is both safe
507          * and prudent for compatibility.
508          */
509         if (rsp->length <= sizeof(*rsp) - offsetof(typeof(*rsp), data))
510                 queue_event(client, &e->event, rsp, sizeof(*rsp),
511                             rsp->data, rsp->length);
512         else
513                 queue_event(client, &e->event, rsp, sizeof(*rsp) + rsp->length,
514                             NULL, 0);
515
516         /* Drop the transaction callback's reference */
517         client_put(client);
518 }
519
520 static int ioctl_send_request(struct client *client, void *buffer)
521 {
522         struct fw_device *device = client->device;
523         struct fw_cdev_send_request *request = buffer;
524         struct outbound_transaction_event *e;
525         int ret;
526
527         /* What is the biggest size we'll accept, really? */
528         if (request->length > 4096)
529                 return -EINVAL;
530
531         e = kmalloc(sizeof(*e) + request->length, GFP_KERNEL);
532         if (e == NULL)
533                 return -ENOMEM;
534
535         e->client = client;
536         e->response.length = request->length;
537         e->response.closure = request->closure;
538
539         if (request->data &&
540             copy_from_user(e->response.data,
541                            u64_to_uptr(request->data), request->length)) {
542                 ret = -EFAULT;
543                 goto failed;
544         }
545
546         switch (request->tcode) {
547         case TCODE_WRITE_QUADLET_REQUEST:
548         case TCODE_WRITE_BLOCK_REQUEST:
549         case TCODE_READ_QUADLET_REQUEST:
550         case TCODE_READ_BLOCK_REQUEST:
551         case TCODE_LOCK_MASK_SWAP:
552         case TCODE_LOCK_COMPARE_SWAP:
553         case TCODE_LOCK_FETCH_ADD:
554         case TCODE_LOCK_LITTLE_ADD:
555         case TCODE_LOCK_BOUNDED_ADD:
556         case TCODE_LOCK_WRAP_ADD:
557         case TCODE_LOCK_VENDOR_DEPENDENT:
558                 break;
559         default:
560                 ret = -EINVAL;
561                 goto failed;
562         }
563
564         e->r.resource.release = release_transaction;
565         ret = add_client_resource(client, &e->r.resource, GFP_KERNEL);
566         if (ret < 0)
567                 goto failed;
568
569         /* Get a reference for the transaction callback */
570         client_get(client);
571
572         fw_send_request(device->card, &e->r.transaction,
573                         request->tcode & 0x1f,
574                         device->node->node_id,
575                         request->generation,
576                         device->max_speed,
577                         request->offset,
578                         e->response.data, request->length,
579                         complete_transaction, e);
580
581         if (request->data)
582                 return sizeof(request) + request->length;
583         else
584                 return sizeof(request);
585  failed:
586         kfree(e);
587
588         return ret;
589 }
590
591 static void release_request(struct client *client,
592                             struct client_resource *resource)
593 {
594         struct inbound_transaction_resource *r = container_of(resource,
595                         struct inbound_transaction_resource, resource);
596
597         fw_send_response(client->device->card, r->request,
598                          RCODE_CONFLICT_ERROR);
599         kfree(r);
600 }
601
602 static void handle_request(struct fw_card *card, struct fw_request *request,
603                            int tcode, int destination, int source,
604                            int generation, int speed,
605                            unsigned long long offset,
606                            void *payload, size_t length, void *callback_data)
607 {
608         struct address_handler_resource *handler = callback_data;
609         struct inbound_transaction_resource *r;
610         struct inbound_transaction_event *e;
611         int ret;
612
613         r = kmalloc(sizeof(*r), GFP_ATOMIC);
614         e = kmalloc(sizeof(*e), GFP_ATOMIC);
615         if (r == NULL || e == NULL)
616                 goto failed;
617
618         r->request = request;
619         r->data    = payload;
620         r->length  = length;
621
622         r->resource.release = release_request;
623         ret = add_client_resource(handler->client, &r->resource, GFP_ATOMIC);
624         if (ret < 0)
625                 goto failed;
626
627         e->request.type    = FW_CDEV_EVENT_REQUEST;
628         e->request.tcode   = tcode;
629         e->request.offset  = offset;
630         e->request.length  = length;
631         e->request.handle  = r->resource.handle;
632         e->request.closure = handler->closure;
633
634         queue_event(handler->client, &e->event,
635                     &e->request, sizeof(e->request), payload, length);
636         return;
637
638  failed:
639         kfree(r);
640         kfree(e);
641         fw_send_response(card, request, RCODE_CONFLICT_ERROR);
642 }
643
644 static void release_address_handler(struct client *client,
645                                     struct client_resource *resource)
646 {
647         struct address_handler_resource *r =
648             container_of(resource, struct address_handler_resource, resource);
649
650         fw_core_remove_address_handler(&r->handler);
651         kfree(r);
652 }
653
654 static int ioctl_allocate(struct client *client, void *buffer)
655 {
656         struct fw_cdev_allocate *request = buffer;
657         struct address_handler_resource *r;
658         struct fw_address_region region;
659         int ret;
660
661         r = kmalloc(sizeof(*r), GFP_KERNEL);
662         if (r == NULL)
663                 return -ENOMEM;
664
665         region.start = request->offset;
666         region.end = request->offset + request->length;
667         r->handler.length = request->length;
668         r->handler.address_callback = handle_request;
669         r->handler.callback_data = r;
670         r->closure = request->closure;
671         r->client = client;
672
673         ret = fw_core_add_address_handler(&r->handler, &region);
674         if (ret < 0) {
675                 kfree(r);
676                 return ret;
677         }
678
679         r->resource.release = release_address_handler;
680         ret = add_client_resource(client, &r->resource, GFP_KERNEL);
681         if (ret < 0) {
682                 release_address_handler(client, &r->resource);
683                 return ret;
684         }
685         request->handle = r->resource.handle;
686
687         return 0;
688 }
689
690 static int ioctl_deallocate(struct client *client, void *buffer)
691 {
692         struct fw_cdev_deallocate *request = buffer;
693
694         return release_client_resource(client, request->handle,
695                                        release_address_handler, NULL);
696 }
697
698 static int ioctl_send_response(struct client *client, void *buffer)
699 {
700         struct fw_cdev_send_response *request = buffer;
701         struct client_resource *resource;
702         struct inbound_transaction_resource *r;
703
704         if (release_client_resource(client, request->handle,
705                                     release_request, &resource) < 0)
706                 return -EINVAL;
707
708         r = container_of(resource, struct inbound_transaction_resource,
709                          resource);
710         if (request->length < r->length)
711                 r->length = request->length;
712         if (copy_from_user(r->data, u64_to_uptr(request->data), r->length))
713                 return -EFAULT;
714
715         fw_send_response(client->device->card, r->request, request->rcode);
716         kfree(r);
717
718         return 0;
719 }
720
721 static int ioctl_initiate_bus_reset(struct client *client, void *buffer)
722 {
723         struct fw_cdev_initiate_bus_reset *request = buffer;
724         int short_reset;
725
726         short_reset = (request->type == FW_CDEV_SHORT_RESET);
727
728         return fw_core_initiate_bus_reset(client->device->card, short_reset);
729 }
730
731 static void release_descriptor(struct client *client,
732                                struct client_resource *resource)
733 {
734         struct descriptor_resource *r =
735                 container_of(resource, struct descriptor_resource, resource);
736
737         fw_core_remove_descriptor(&r->descriptor);
738         kfree(r);
739 }
740
741 static int ioctl_add_descriptor(struct client *client, void *buffer)
742 {
743         struct fw_cdev_add_descriptor *request = buffer;
744         struct descriptor_resource *r;
745         int ret;
746
747         if (request->length > 256)
748                 return -EINVAL;
749
750         r = kmalloc(sizeof(*r) + request->length * 4, GFP_KERNEL);
751         if (r == NULL)
752                 return -ENOMEM;
753
754         if (copy_from_user(r->data,
755                            u64_to_uptr(request->data), request->length * 4)) {
756                 ret = -EFAULT;
757                 goto failed;
758         }
759
760         r->descriptor.length    = request->length;
761         r->descriptor.immediate = request->immediate;
762         r->descriptor.key       = request->key;
763         r->descriptor.data      = r->data;
764
765         ret = fw_core_add_descriptor(&r->descriptor);
766         if (ret < 0)
767                 goto failed;
768
769         r->resource.release = release_descriptor;
770         ret = add_client_resource(client, &r->resource, GFP_KERNEL);
771         if (ret < 0) {
772                 fw_core_remove_descriptor(&r->descriptor);
773                 goto failed;
774         }
775         request->handle = r->resource.handle;
776
777         return 0;
778  failed:
779         kfree(r);
780
781         return ret;
782 }
783
784 static int ioctl_remove_descriptor(struct client *client, void *buffer)
785 {
786         struct fw_cdev_remove_descriptor *request = buffer;
787
788         return release_client_resource(client, request->handle,
789                                        release_descriptor, NULL);
790 }
791
792 static void iso_callback(struct fw_iso_context *context, u32 cycle,
793                          size_t header_length, void *header, void *data)
794 {
795         struct client *client = data;
796         struct iso_interrupt_event *e;
797
798         e = kzalloc(sizeof(*e) + header_length, GFP_ATOMIC);
799         if (e == NULL)
800                 return;
801
802         e->interrupt.type      = FW_CDEV_EVENT_ISO_INTERRUPT;
803         e->interrupt.closure   = client->iso_closure;
804         e->interrupt.cycle     = cycle;
805         e->interrupt.header_length = header_length;
806         memcpy(e->interrupt.header, header, header_length);
807         queue_event(client, &e->event, &e->interrupt,
808                     sizeof(e->interrupt) + header_length, NULL, 0);
809 }
810
811 static int ioctl_create_iso_context(struct client *client, void *buffer)
812 {
813         struct fw_cdev_create_iso_context *request = buffer;
814         struct fw_iso_context *context;
815
816         /* We only support one context at this time. */
817         if (client->iso_context != NULL)
818                 return -EBUSY;
819
820         if (request->channel > 63)
821                 return -EINVAL;
822
823         switch (request->type) {
824         case FW_ISO_CONTEXT_RECEIVE:
825                 if (request->header_size < 4 || (request->header_size & 3))
826                         return -EINVAL;
827
828                 break;
829
830         case FW_ISO_CONTEXT_TRANSMIT:
831                 if (request->speed > SCODE_3200)
832                         return -EINVAL;
833
834                 break;
835
836         default:
837                 return -EINVAL;
838         }
839
840         context =  fw_iso_context_create(client->device->card,
841                                          request->type,
842                                          request->channel,
843                                          request->speed,
844                                          request->header_size,
845                                          iso_callback, client);
846         if (IS_ERR(context))
847                 return PTR_ERR(context);
848
849         client->iso_closure = request->closure;
850         client->iso_context = context;
851
852         /* We only support one context at this time. */
853         request->handle = 0;
854
855         return 0;
856 }
857
858 /* Macros for decoding the iso packet control header. */
859 #define GET_PAYLOAD_LENGTH(v)   ((v) & 0xffff)
860 #define GET_INTERRUPT(v)        (((v) >> 16) & 0x01)
861 #define GET_SKIP(v)             (((v) >> 17) & 0x01)
862 #define GET_TAG(v)              (((v) >> 18) & 0x03)
863 #define GET_SY(v)               (((v) >> 20) & 0x0f)
864 #define GET_HEADER_LENGTH(v)    (((v) >> 24) & 0xff)
865
866 static int ioctl_queue_iso(struct client *client, void *buffer)
867 {
868         struct fw_cdev_queue_iso *request = buffer;
869         struct fw_cdev_iso_packet __user *p, *end, *next;
870         struct fw_iso_context *ctx = client->iso_context;
871         unsigned long payload, buffer_end, header_length;
872         u32 control;
873         int count;
874         struct {
875                 struct fw_iso_packet packet;
876                 u8 header[256];
877         } u;
878
879         if (ctx == NULL || request->handle != 0)
880                 return -EINVAL;
881
882         /*
883          * If the user passes a non-NULL data pointer, has mmap()'ed
884          * the iso buffer, and the pointer points inside the buffer,
885          * we setup the payload pointers accordingly.  Otherwise we
886          * set them both to 0, which will still let packets with
887          * payload_length == 0 through.  In other words, if no packets
888          * use the indirect payload, the iso buffer need not be mapped
889          * and the request->data pointer is ignored.
890          */
891
892         payload = (unsigned long)request->data - client->vm_start;
893         buffer_end = client->buffer.page_count << PAGE_SHIFT;
894         if (request->data == 0 || client->buffer.pages == NULL ||
895             payload >= buffer_end) {
896                 payload = 0;
897                 buffer_end = 0;
898         }
899
900         p = (struct fw_cdev_iso_packet __user *)u64_to_uptr(request->packets);
901
902         if (!access_ok(VERIFY_READ, p, request->size))
903                 return -EFAULT;
904
905         end = (void __user *)p + request->size;
906         count = 0;
907         while (p < end) {
908                 if (get_user(control, &p->control))
909                         return -EFAULT;
910                 u.packet.payload_length = GET_PAYLOAD_LENGTH(control);
911                 u.packet.interrupt = GET_INTERRUPT(control);
912                 u.packet.skip = GET_SKIP(control);
913                 u.packet.tag = GET_TAG(control);
914                 u.packet.sy = GET_SY(control);
915                 u.packet.header_length = GET_HEADER_LENGTH(control);
916
917                 if (ctx->type == FW_ISO_CONTEXT_TRANSMIT) {
918                         header_length = u.packet.header_length;
919                 } else {
920                         /*
921                          * We require that header_length is a multiple of
922                          * the fixed header size, ctx->header_size.
923                          */
924                         if (ctx->header_size == 0) {
925                                 if (u.packet.header_length > 0)
926                                         return -EINVAL;
927                         } else if (u.packet.header_length % ctx->header_size != 0) {
928                                 return -EINVAL;
929                         }
930                         header_length = 0;
931                 }
932
933                 next = (struct fw_cdev_iso_packet __user *)
934                         &p->header[header_length / 4];
935                 if (next > end)
936                         return -EINVAL;
937                 if (__copy_from_user
938                     (u.packet.header, p->header, header_length))
939                         return -EFAULT;
940                 if (u.packet.skip && ctx->type == FW_ISO_CONTEXT_TRANSMIT &&
941                     u.packet.header_length + u.packet.payload_length > 0)
942                         return -EINVAL;
943                 if (payload + u.packet.payload_length > buffer_end)
944                         return -EINVAL;
945
946                 if (fw_iso_context_queue(ctx, &u.packet,
947                                          &client->buffer, payload))
948                         break;
949
950                 p = next;
951                 payload += u.packet.payload_length;
952                 count++;
953         }
954
955         request->size    -= uptr_to_u64(p) - request->packets;
956         request->packets  = uptr_to_u64(p);
957         request->data     = client->vm_start + payload;
958
959         return count;
960 }
961
962 static int ioctl_start_iso(struct client *client, void *buffer)
963 {
964         struct fw_cdev_start_iso *request = buffer;
965
966         if (client->iso_context == NULL || request->handle != 0)
967                 return -EINVAL;
968
969         if (client->iso_context->type == FW_ISO_CONTEXT_RECEIVE) {
970                 if (request->tags == 0 || request->tags > 15)
971                         return -EINVAL;
972
973                 if (request->sync > 15)
974                         return -EINVAL;
975         }
976
977         return fw_iso_context_start(client->iso_context, request->cycle,
978                                     request->sync, request->tags);
979 }
980
981 static int ioctl_stop_iso(struct client *client, void *buffer)
982 {
983         struct fw_cdev_stop_iso *request = buffer;
984
985         if (client->iso_context == NULL || request->handle != 0)
986                 return -EINVAL;
987
988         return fw_iso_context_stop(client->iso_context);
989 }
990
991 static int ioctl_get_cycle_timer(struct client *client, void *buffer)
992 {
993         struct fw_cdev_get_cycle_timer *request = buffer;
994         struct fw_card *card = client->device->card;
995         unsigned long long bus_time;
996         struct timeval tv;
997         unsigned long flags;
998
999         preempt_disable();
1000         local_irq_save(flags);
1001
1002         bus_time = card->driver->get_bus_time(card);
1003         do_gettimeofday(&tv);
1004
1005         local_irq_restore(flags);
1006         preempt_enable();
1007
1008         request->local_time = tv.tv_sec * 1000000ULL + tv.tv_usec;
1009         request->cycle_timer = bus_time & 0xffffffff;
1010         return 0;
1011 }
1012
1013 static void iso_resource_work(struct work_struct *work)
1014 {
1015         struct iso_resource_event *e;
1016         struct iso_resource *r =
1017                         container_of(work, struct iso_resource, work.work);
1018         struct client *client = r->client;
1019         int generation, channel, bandwidth, todo;
1020         bool skip, free, success;
1021
1022         spin_lock_irq(&client->lock);
1023         generation = client->device->generation;
1024         todo = r->todo;
1025         /* Allow 1000ms grace period for other reallocations. */
1026         if (todo == ISO_RES_ALLOC &&
1027             time_is_after_jiffies(client->device->card->reset_jiffies + HZ)) {
1028                 if (schedule_delayed_work(&r->work, DIV_ROUND_UP(HZ, 3)))
1029                         client_get(client);
1030                 skip = true;
1031         } else {
1032                 /* We could be called twice within the same generation. */
1033                 skip = todo == ISO_RES_REALLOC &&
1034                        r->generation == generation;
1035         }
1036         free = todo == ISO_RES_DEALLOC;
1037         r->generation = generation;
1038         spin_unlock_irq(&client->lock);
1039
1040         if (skip)
1041                 goto out;
1042
1043         bandwidth = r->bandwidth;
1044
1045         fw_iso_resource_manage(client->device->card, generation,
1046                         r->channels, &channel, &bandwidth,
1047                         todo == ISO_RES_ALLOC || todo == ISO_RES_REALLOC);
1048         /*
1049          * Is this generation outdated already?  As long as this resource sticks
1050          * in the idr, it will be scheduled again for a newer generation or at
1051          * shutdown.
1052          */
1053         if (channel == -EAGAIN &&
1054             (todo == ISO_RES_ALLOC || todo == ISO_RES_REALLOC))
1055                 goto out;
1056
1057         success = channel >= 0 || bandwidth > 0;
1058
1059         spin_lock_irq(&client->lock);
1060         /*
1061          * Transit from allocation to reallocation, except if the client
1062          * requested deallocation in the meantime.
1063          */
1064         if (r->todo == ISO_RES_ALLOC)
1065                 r->todo = ISO_RES_REALLOC;
1066         /*
1067          * Allocation or reallocation failure?  Pull this resource out of the
1068          * idr and prepare for deletion, unless the client is shutting down.
1069          */
1070         if (r->todo == ISO_RES_REALLOC && !success &&
1071             !client->in_shutdown &&
1072             idr_find(&client->resource_idr, r->resource.handle)) {
1073                 idr_remove(&client->resource_idr, r->resource.handle);
1074                 client_put(client);
1075                 free = true;
1076         }
1077         spin_unlock_irq(&client->lock);
1078
1079         if (todo == ISO_RES_ALLOC && channel >= 0)
1080                 r->channels = 1ULL << (63 - channel);
1081
1082         if (todo == ISO_RES_REALLOC && success)
1083                 goto out;
1084
1085         if (todo == ISO_RES_ALLOC) {
1086                 e = r->e_alloc;
1087                 r->e_alloc = NULL;
1088         } else {
1089                 e = r->e_dealloc;
1090                 r->e_dealloc = NULL;
1091         }
1092         e->resource.handle      = r->resource.handle;
1093         e->resource.channel     = channel;
1094         e->resource.bandwidth   = bandwidth;
1095
1096         queue_event(client, &e->event,
1097                     &e->resource, sizeof(e->resource), NULL, 0);
1098
1099         if (free) {
1100                 cancel_delayed_work(&r->work);
1101                 kfree(r->e_alloc);
1102                 kfree(r->e_dealloc);
1103                 kfree(r);
1104         }
1105  out:
1106         client_put(client);
1107 }
1108
1109 static void schedule_iso_resource(struct iso_resource *r)
1110 {
1111         if (schedule_delayed_work(&r->work, 0))
1112                 client_get(r->client);
1113 }
1114
1115 static void release_iso_resource(struct client *client,
1116                                  struct client_resource *resource)
1117 {
1118         struct iso_resource *r =
1119                 container_of(resource, struct iso_resource, resource);
1120
1121         spin_lock_irq(&client->lock);
1122         r->todo = ISO_RES_DEALLOC;
1123         schedule_iso_resource(r);
1124         spin_unlock_irq(&client->lock);
1125 }
1126
1127 static int ioctl_allocate_iso_resource(struct client *client, void *buffer)
1128 {
1129         struct fw_cdev_allocate_iso_resource *request = buffer;
1130         struct iso_resource_event *e1, *e2;
1131         struct iso_resource *r;
1132         int ret;
1133
1134         if ((request->channels == 0 && request->bandwidth == 0) ||
1135             request->bandwidth > BANDWIDTH_AVAILABLE_INITIAL ||
1136             request->bandwidth < 0)
1137                 return -EINVAL;
1138
1139         r  = kmalloc(sizeof(*r), GFP_KERNEL);
1140         e1 = kmalloc(sizeof(*e1), GFP_KERNEL);
1141         e2 = kmalloc(sizeof(*e2), GFP_KERNEL);
1142         if (r == NULL || e1 == NULL || e2 == NULL) {
1143                 ret = -ENOMEM;
1144                 goto fail;
1145         }
1146
1147         INIT_DELAYED_WORK(&r->work, iso_resource_work);
1148         r->client       = client;
1149         r->todo         = ISO_RES_ALLOC;
1150         r->generation   = -1;
1151         r->channels     = request->channels;
1152         r->bandwidth    = request->bandwidth;
1153         r->e_alloc      = e1;
1154         r->e_dealloc    = e2;
1155
1156         e1->resource.closure    = request->closure;
1157         e1->resource.type       = FW_CDEV_EVENT_ISO_RESOURCE_ALLOCATED;
1158         e2->resource.closure    = request->closure;
1159         e2->resource.type       = FW_CDEV_EVENT_ISO_RESOURCE_DEALLOCATED;
1160
1161         r->resource.release = release_iso_resource;
1162         ret = add_client_resource(client, &r->resource, GFP_KERNEL);
1163         if (ret < 0)
1164                 goto fail;
1165         request->handle = r->resource.handle;
1166
1167         return 0;
1168  fail:
1169         kfree(r);
1170         kfree(e1);
1171         kfree(e2);
1172
1173         return ret;
1174 }
1175
1176 static int ioctl_deallocate_iso_resource(struct client *client, void *buffer)
1177 {
1178         struct fw_cdev_deallocate *request = buffer;
1179
1180         return release_client_resource(client, request->handle,
1181                                        release_iso_resource, NULL);
1182 }
1183
1184 static int (* const ioctl_handlers[])(struct client *client, void *buffer) = {
1185         ioctl_get_info,
1186         ioctl_send_request,
1187         ioctl_allocate,
1188         ioctl_deallocate,
1189         ioctl_send_response,
1190         ioctl_initiate_bus_reset,
1191         ioctl_add_descriptor,
1192         ioctl_remove_descriptor,
1193         ioctl_create_iso_context,
1194         ioctl_queue_iso,
1195         ioctl_start_iso,
1196         ioctl_stop_iso,
1197         ioctl_get_cycle_timer,
1198         ioctl_allocate_iso_resource,
1199         ioctl_deallocate_iso_resource,
1200 };
1201
1202 static int dispatch_ioctl(struct client *client,
1203                           unsigned int cmd, void __user *arg)
1204 {
1205         char buffer[256];
1206         int ret;
1207
1208         if (_IOC_TYPE(cmd) != '#' ||
1209             _IOC_NR(cmd) >= ARRAY_SIZE(ioctl_handlers))
1210                 return -EINVAL;
1211
1212         if (_IOC_DIR(cmd) & _IOC_WRITE) {
1213                 if (_IOC_SIZE(cmd) > sizeof(buffer) ||
1214                     copy_from_user(buffer, arg, _IOC_SIZE(cmd)))
1215                         return -EFAULT;
1216         }
1217
1218         ret = ioctl_handlers[_IOC_NR(cmd)](client, buffer);
1219         if (ret < 0)
1220                 return ret;
1221
1222         if (_IOC_DIR(cmd) & _IOC_READ) {
1223                 if (_IOC_SIZE(cmd) > sizeof(buffer) ||
1224                     copy_to_user(arg, buffer, _IOC_SIZE(cmd)))
1225                         return -EFAULT;
1226         }
1227
1228         return ret;
1229 }
1230
1231 static long fw_device_op_ioctl(struct file *file,
1232                                unsigned int cmd, unsigned long arg)
1233 {
1234         struct client *client = file->private_data;
1235
1236         if (fw_device_is_shutdown(client->device))
1237                 return -ENODEV;
1238
1239         return dispatch_ioctl(client, cmd, (void __user *) arg);
1240 }
1241
1242 #ifdef CONFIG_COMPAT
1243 static long fw_device_op_compat_ioctl(struct file *file,
1244                                       unsigned int cmd, unsigned long arg)
1245 {
1246         struct client *client = file->private_data;
1247
1248         if (fw_device_is_shutdown(client->device))
1249                 return -ENODEV;
1250
1251         return dispatch_ioctl(client, cmd, compat_ptr(arg));
1252 }
1253 #endif
1254
1255 static int fw_device_op_mmap(struct file *file, struct vm_area_struct *vma)
1256 {
1257         struct client *client = file->private_data;
1258         enum dma_data_direction direction;
1259         unsigned long size;
1260         int page_count, ret;
1261
1262         if (fw_device_is_shutdown(client->device))
1263                 return -ENODEV;
1264
1265         /* FIXME: We could support multiple buffers, but we don't. */
1266         if (client->buffer.pages != NULL)
1267                 return -EBUSY;
1268
1269         if (!(vma->vm_flags & VM_SHARED))
1270                 return -EINVAL;
1271
1272         if (vma->vm_start & ~PAGE_MASK)
1273                 return -EINVAL;
1274
1275         client->vm_start = vma->vm_start;
1276         size = vma->vm_end - vma->vm_start;
1277         page_count = size >> PAGE_SHIFT;
1278         if (size & ~PAGE_MASK)
1279                 return -EINVAL;
1280
1281         if (vma->vm_flags & VM_WRITE)
1282                 direction = DMA_TO_DEVICE;
1283         else
1284                 direction = DMA_FROM_DEVICE;
1285
1286         ret = fw_iso_buffer_init(&client->buffer, client->device->card,
1287                                  page_count, direction);
1288         if (ret < 0)
1289                 return ret;
1290
1291         ret = fw_iso_buffer_map(&client->buffer, vma);
1292         if (ret < 0)
1293                 fw_iso_buffer_destroy(&client->buffer, client->device->card);
1294
1295         return ret;
1296 }
1297
1298 static int shutdown_resource(int id, void *p, void *data)
1299 {
1300         struct client_resource *r = p;
1301         struct client *client = data;
1302
1303         r->release(client, r);
1304         client_put(client);
1305
1306         return 0;
1307 }
1308
1309 static int fw_device_op_release(struct inode *inode, struct file *file)
1310 {
1311         struct client *client = file->private_data;
1312         struct event *e, *next_e;
1313         unsigned long flags;
1314
1315         mutex_lock(&client->device->client_list_mutex);
1316         list_del(&client->link);
1317         mutex_unlock(&client->device->client_list_mutex);
1318
1319         if (client->buffer.pages)
1320                 fw_iso_buffer_destroy(&client->buffer, client->device->card);
1321
1322         if (client->iso_context)
1323                 fw_iso_context_destroy(client->iso_context);
1324
1325         /* Freeze client->resource_idr and client->event_list */
1326         spin_lock_irqsave(&client->lock, flags);
1327         client->in_shutdown = true;
1328         spin_unlock_irqrestore(&client->lock, flags);
1329
1330         idr_for_each(&client->resource_idr, shutdown_resource, client);
1331         idr_remove_all(&client->resource_idr);
1332         idr_destroy(&client->resource_idr);
1333
1334         list_for_each_entry_safe(e, next_e, &client->event_list, link)
1335                 kfree(e);
1336
1337         client_put(client);
1338
1339         return 0;
1340 }
1341
1342 static unsigned int fw_device_op_poll(struct file *file, poll_table * pt)
1343 {
1344         struct client *client = file->private_data;
1345         unsigned int mask = 0;
1346
1347         poll_wait(file, &client->wait, pt);
1348
1349         if (fw_device_is_shutdown(client->device))
1350                 mask |= POLLHUP | POLLERR;
1351         if (!list_empty(&client->event_list))
1352                 mask |= POLLIN | POLLRDNORM;
1353
1354         return mask;
1355 }
1356
1357 const struct file_operations fw_device_ops = {
1358         .owner          = THIS_MODULE,
1359         .open           = fw_device_op_open,
1360         .read           = fw_device_op_read,
1361         .unlocked_ioctl = fw_device_op_ioctl,
1362         .poll           = fw_device_op_poll,
1363         .release        = fw_device_op_release,
1364         .mmap           = fw_device_op_mmap,
1365
1366 #ifdef CONFIG_COMPAT
1367         .compat_ioctl   = fw_device_op_compat_ioctl,
1368 #endif
1369 };