Staging: pohmelfs: Populate dentry cache when receiving the new readdir entry.
[pandora-kernel.git] / drivers / staging / pohmelfs / net.c
1 /*
2  * 2007+ Copyright (c) Evgeniy Polyakov <zbr@ioremap.net>
3  * All rights reserved.
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  */
15
16 #include <linux/fsnotify.h>
17 #include <linux/jhash.h>
18 #include <linux/in.h>
19 #include <linux/in6.h>
20 #include <linux/kthread.h>
21 #include <linux/pagemap.h>
22 #include <linux/poll.h>
23 #include <linux/swap.h>
24 #include <linux/syscalls.h>
25 #include <linux/vmalloc.h>
26
27 #include "netfs.h"
28
29 static int pohmelfs_ftrans_size = 10240;
30 static u32 *pohmelfs_ftrans;
31
32 int pohmelfs_ftrans_init(void)
33 {
34         pohmelfs_ftrans = vmalloc(pohmelfs_ftrans_size * 4);
35         if (!pohmelfs_ftrans)
36                 return -ENOMEM;
37
38         return 0;
39 }
40
41 void pohmelfs_ftrans_exit(void)
42 {
43         vfree(pohmelfs_ftrans);
44 }
45
46 void pohmelfs_ftrans_clean(u64 id)
47 {
48         if (pohmelfs_ftrans) {
49                 u32 i = id & 0xffffffff;
50                 int idx = i % pohmelfs_ftrans_size;
51
52                 pohmelfs_ftrans[idx] = 0;
53         }
54 }
55
56 void pohmelfs_ftrans_update(u64 id)
57 {
58         if (pohmelfs_ftrans) {
59                 u32 i = id & 0xffffffff;
60                 int idx = i % pohmelfs_ftrans_size;
61
62                 pohmelfs_ftrans[idx] = i;
63         }
64 }
65
66 int pohmelfs_ftrans_check(u64 id)
67 {
68         if (pohmelfs_ftrans) {
69                 u32 i = id & 0xffffffff;
70                 int idx = i % pohmelfs_ftrans_size;
71
72                 return (pohmelfs_ftrans[idx] == i);
73         }
74
75         return -1;
76 }
77
78 /*
79  * Async machinery lives here.
80  * All commands being sent to server do _not_ require sync reply,
81  * instead, if it is really needed, like readdir or readpage, caller
82  * sleeps waiting for data, which will be placed into provided buffer
83  * and caller will be awakened.
84  *
85  * Every command response can come without some listener. For example
86  * readdir response will add new objects into cache without appropriate
87  * request from userspace. This is used in cache coherency.
88  *
89  * If object is not found for given data, it is discarded.
90  *
91  * All requests are received by dedicated kernel thread.
92  */
93
94 /*
95  * Basic network sending/receiving functions.
96  * Blocked mode is used.
97  */
98 static int netfs_data_recv(struct netfs_state *st, void *buf, u64 size)
99 {
100         struct msghdr msg;
101         struct kvec iov;
102         int err;
103
104         BUG_ON(!size);
105
106         iov.iov_base = buf;
107         iov.iov_len = size;
108
109         msg.msg_iov = (struct iovec *)&iov;
110         msg.msg_iovlen = 1;
111         msg.msg_name = NULL;
112         msg.msg_namelen = 0;
113         msg.msg_control = NULL;
114         msg.msg_controllen = 0;
115         msg.msg_flags = MSG_DONTWAIT;
116
117         err = kernel_recvmsg(st->socket, &msg, &iov, 1, iov.iov_len,
118                         msg.msg_flags);
119         if (err <= 0) {
120                 printk("%s: failed to recv data: size: %llu, err: %d.\n", __func__, size, err);
121                 if (err == 0)
122                         err = -ECONNRESET;
123         }
124
125         return err;
126 }
127
128 static int pohmelfs_data_recv(struct netfs_state *st, void *data, unsigned int size)
129 {
130         unsigned int revents = 0;
131         unsigned int err_mask = POLLERR | POLLHUP | POLLRDHUP;
132         unsigned int mask = err_mask | POLLIN;
133         int err = 0;
134
135         while (size && !err) {
136                 revents = netfs_state_poll(st);
137
138                 if (!(revents & mask)) {
139                         DEFINE_WAIT(wait);
140
141                         for (;;) {
142                                 prepare_to_wait(&st->thread_wait, &wait, TASK_INTERRUPTIBLE);
143                                 if (kthread_should_stop())
144                                         break;
145
146                                 revents = netfs_state_poll(st);
147
148                                 if (revents & mask)
149                                         break;
150
151                                 if (signal_pending(current))
152                                         break;
153
154                                 schedule();
155                                 continue;
156                         }
157                         finish_wait(&st->thread_wait, &wait);
158                 }
159
160                 err = 0;
161                 netfs_state_lock(st);
162                 if (st->socket && (st->read_socket == st->socket) && (revents & POLLIN)) {
163                         err = netfs_data_recv(st, data, size);
164                         if (err > 0) {
165                                 data += err;
166                                 size -= err;
167                                 err = 0;
168                         } else if (err == 0)
169                                 err = -ECONNRESET;
170                 }
171
172                 if (revents & err_mask) {
173                         printk("%s: revents: %x, socket: %p, size: %u, err: %d.\n",
174                                         __func__, revents, st->socket, size, err);
175                         err = -ECONNRESET;
176                 }
177                 netfs_state_unlock(st);
178
179                 if (err < 0) {
180                         if (netfs_state_trylock_send(st)) {
181                                 netfs_state_exit(st);
182                                 err = netfs_state_init(st);
183                                 if (!err)
184                                         err = -EAGAIN;
185                                 netfs_state_unlock_send(st);
186                         } else {
187                                 st->need_reset = 1;
188                         }
189                 }
190
191                 if (kthread_should_stop())
192                         err = -ENODEV;
193
194                 if (err)
195                         printk("%s: socket: %p, read_socket: %p, revents: %x, rev_error: %d, "
196                                         "should_stop: %d, size: %u, err: %d.\n",
197                                 __func__, st->socket, st->read_socket,
198                                 revents, revents & err_mask, kthread_should_stop(), size, err);
199         }
200
201         return err;
202 }
203
204 int pohmelfs_data_recv_and_check(struct netfs_state *st, void *data, unsigned int size)
205 {
206         struct netfs_cmd *cmd = &st->cmd;
207         int err;
208
209         err = pohmelfs_data_recv(st, data, size);
210         if (err)
211                 return err;
212
213         return pohmelfs_crypto_process_input_data(&st->eng, cmd->iv, data, NULL, size);
214 }
215
216 /*
217  * Polling machinery.
218  */
219
220 struct netfs_poll_helper
221 {
222         poll_table              pt;
223         struct netfs_state      *st;
224 };
225
226 static int netfs_queue_wake(wait_queue_t *wait, unsigned mode, int sync, void *key)
227 {
228         struct netfs_state *st = container_of(wait, struct netfs_state, wait);
229
230         wake_up(&st->thread_wait);
231         return 1;
232 }
233
234 static void netfs_queue_func(struct file *file, wait_queue_head_t *whead,
235                                  poll_table *pt)
236 {
237         struct netfs_state *st = container_of(pt, struct netfs_poll_helper, pt)->st;
238
239         st->whead = whead;
240         init_waitqueue_func_entry(&st->wait, netfs_queue_wake);
241         add_wait_queue(whead, &st->wait);
242 }
243
244 static void netfs_poll_exit(struct netfs_state *st)
245 {
246         if (st->whead) {
247                 remove_wait_queue(st->whead, &st->wait);
248                 st->whead = NULL;
249         }
250 }
251
252 static int netfs_poll_init(struct netfs_state *st)
253 {
254         struct netfs_poll_helper ph;
255
256         ph.st = st;
257         init_poll_funcptr(&ph.pt, &netfs_queue_func);
258
259         st->socket->ops->poll(NULL, st->socket, &ph.pt);
260         return 0;
261 }
262
263 /*
264  * Get response for readpage command. We search inode and page in its mapping
265  * and copy data into. If it was async request, then we queue page into shared
266  * data and wakeup listener, who will copy it to userspace.
267  *
268  * There is a work in progress of allowing to call copy_to_user() directly from
269  * async receiving kernel thread.
270  */
271 static int pohmelfs_read_page_response(struct netfs_state *st)
272 {
273         struct pohmelfs_sb *psb = st->psb;
274         struct netfs_cmd *cmd = &st->cmd;
275         struct inode *inode;
276         struct page *page;
277         int err = 0;
278
279         if (cmd->size > PAGE_CACHE_SIZE) {
280                 err = -EINVAL;
281                 goto err_out_exit;
282         }
283
284         inode = ilookup(st->psb->sb, cmd->id);
285         if (!inode) {
286                 printk("%s: failed to find inode: id: %llu.\n", __func__, cmd->id);
287                 err = -ENOENT;
288                 goto err_out_exit;
289         }
290
291         page = find_get_page(inode->i_mapping, cmd->start >> PAGE_CACHE_SHIFT);
292         if (!page || !PageLocked(page)) {
293                 printk("%s: failed to find/lock page: page: %p, id: %llu, start: %llu, index: %llu.\n",
294                                 __func__, page, cmd->id, cmd->start, cmd->start >> PAGE_CACHE_SHIFT);
295
296                 while (cmd->size) {
297                         unsigned int sz = min(cmd->size, st->size);
298
299                         err = pohmelfs_data_recv(st, st->data, sz);
300                         if (err)
301                                 break;
302
303                         cmd->size -= sz;
304                 }
305
306                 err = -ENODEV;
307                 if (page)
308                         goto err_out_page_put;
309                 goto err_out_put;
310         }
311
312         if (cmd->size) {
313                 void *addr;
314
315                 addr = kmap(page);
316                 err = pohmelfs_data_recv(st, addr, cmd->size);
317                 kunmap(page);
318
319                 if (err)
320                         goto err_out_page_unlock;
321         }
322
323         dprintk("%s: page: %p, start: %llu, size: %u, locked: %d.\n",
324                 __func__, page, cmd->start, cmd->size, PageLocked(page));
325
326         SetPageChecked(page);
327         if ((psb->hash_string || psb->cipher_string) && psb->perform_crypto && cmd->size) {
328                 err = pohmelfs_crypto_process_input_page(&st->eng, page, cmd->size, cmd->iv);
329                 if (err < 0)
330                         goto err_out_page_unlock;
331         } else {
332                 SetPageUptodate(page);
333                 unlock_page(page);
334                 page_cache_release(page);
335         }
336
337         pohmelfs_put_inode(POHMELFS_I(inode));
338         wake_up(&st->psb->wait);
339
340         return 0;
341
342 err_out_page_unlock:
343         SetPageError(page);
344         unlock_page(page);
345 err_out_page_put:
346         page_cache_release(page);
347 err_out_put:
348         pohmelfs_put_inode(POHMELFS_I(inode));
349 err_out_exit:
350         wake_up(&st->psb->wait);
351         return err;
352 }
353
354 static int pohmelfs_check_name(struct pohmelfs_inode *parent, struct qstr *str,
355                 struct netfs_inode_info *info)
356 {
357         struct inode *inode;
358         struct pohmelfs_name *n;
359         int err = 0;
360         u64 ino = 0;
361
362         mutex_lock(&parent->offset_lock);
363         n = pohmelfs_search_hash(parent, str->hash);
364         if (n)
365                 ino = n->ino;
366         mutex_unlock(&parent->offset_lock);
367
368         if (!ino)
369                 goto out;
370
371         inode = ilookup(parent->vfs_inode.i_sb, ino);
372         if (!inode)
373                 goto out;
374
375         dprintk("%s: parent: %llu, inode: %llu.\n", __func__, parent->ino, ino);
376
377         pohmelfs_fill_inode(inode, info);
378         pohmelfs_put_inode(POHMELFS_I(inode));
379         err = -EEXIST;
380 out:
381         return err;
382 }
383
384 /*
385  * Readdir response from server. If special field is set, we wakeup
386  * listener (readdir() call), which will copy data to userspace.
387  */
388 static int pohmelfs_readdir_response(struct netfs_state *st)
389 {
390         struct inode *inode;
391         struct netfs_cmd *cmd = &st->cmd;
392         struct netfs_inode_info *info;
393         struct pohmelfs_inode *parent = NULL, *npi;
394         int err = 0, last = cmd->ext;
395         struct qstr str;
396
397         if (cmd->size > st->size)
398                 return -EINVAL;
399
400         inode = ilookup(st->psb->sb, cmd->id);
401         if (!inode) {
402                 printk("%s: failed to find inode: id: %llu.\n", __func__, cmd->id);
403                 return -ENOENT;
404         }
405         parent = POHMELFS_I(inode);
406
407         if (!cmd->size && cmd->start) {
408                 err = -cmd->start;
409                 goto out;
410         }
411
412         if (cmd->size) {
413                 char *name;
414
415                 err = pohmelfs_data_recv_and_check(st, st->data, cmd->size);
416                 if (err)
417                         goto err_out_put;
418
419                 info = (struct netfs_inode_info *)(st->data);
420
421                 name = (char *)(info + 1);
422                 str.len = cmd->size - sizeof(struct netfs_inode_info) - 1 - cmd->cpad;
423                 name[str.len] = 0;
424                 str.name = name;
425                 str.hash = jhash(str.name, str.len, 0);
426
427                 netfs_convert_inode_info(info);
428
429                 if (parent) {
430                         err = pohmelfs_check_name(parent, &str, info);
431                         if (err) {
432                                 if (err == -EEXIST)
433                                         err = 0;
434                                 goto out;
435                         }
436                 }
437
438                 info->ino = cmd->start;
439                 if (!info->ino)
440                         info->ino = pohmelfs_new_ino(st->psb);
441
442                 dprintk("%s: parent: %llu, ino: %llu, name: '%s', hash: %x, len: %u, mode: %o.\n",
443                                 __func__, parent->ino, info->ino, str.name, str.hash, str.len,
444                                 info->mode);
445
446                 npi = pohmelfs_new_inode(st->psb, parent, &str, info, 0);
447                 if (IS_ERR(npi)) {
448                         err = PTR_ERR(npi);
449
450                         if (err != -EEXIST)
451                                 goto err_out_put;
452                 } else {
453                         struct dentry *dentry, *alias, *pd;
454
455                         set_bit(NETFS_INODE_REMOTE_SYNCED, &npi->state);
456                         clear_bit(NETFS_INODE_OWNED, &npi->state);
457
458                         pd = d_find_alias(&parent->vfs_inode);
459                         if (pd) {
460                                 str.hash = full_name_hash(str.name, str.len);
461                                 dentry = d_alloc(pd, &str);
462                                 if (dentry) {
463                                         alias = d_materialise_unique(dentry, &npi->vfs_inode);
464                                         if (alias)
465                                                 dput(dentry);
466                                 }
467
468                                 dput(dentry);
469                                 dput(pd);
470                         }
471                 }
472         }
473 out:
474         if (last) {
475                 set_bit(NETFS_INODE_REMOTE_DIR_SYNCED, &parent->state);
476                 set_bit(NETFS_INODE_REMOTE_SYNCED, &parent->state);
477                 wake_up(&st->psb->wait);
478         }
479         pohmelfs_put_inode(parent);
480
481         return err;
482
483 err_out_put:
484         clear_bit(NETFS_INODE_REMOTE_DIR_SYNCED, &parent->state);
485         printk("%s: parent: %llu, ino: %llu, cmd_id: %llu.\n", __func__, parent->ino, cmd->start, cmd->id);
486         pohmelfs_put_inode(parent);
487         wake_up(&st->psb->wait);
488         return err;
489 }
490
491 /*
492  * Lookup command response.
493  * It searches for inode to be looked at (if it exists) and substitutes
494  * its inode information (size, permission, mode and so on), if inode does
495  * not exist, new one will be created and inserted into caches.
496  */
497 static int pohmelfs_lookup_response(struct netfs_state *st)
498 {
499         struct inode *inode = NULL;
500         struct netfs_cmd *cmd = &st->cmd;
501         struct netfs_inode_info *info;
502         struct pohmelfs_inode *parent = NULL, *npi;
503         int err = -EINVAL;
504         char *name;
505
506         inode = ilookup(st->psb->sb, cmd->id);
507         if (!inode) {
508                 printk("%s: lookup response: id: %llu, start: %llu, size: %u.\n",
509                                 __func__, cmd->id, cmd->start, cmd->size);
510                 err = -ENOENT;
511                 goto err_out_exit;
512         }
513         parent = POHMELFS_I(inode);
514
515         if (!cmd->size) {
516                 err = -cmd->start;
517                 goto err_out_put;
518         }
519
520         if (cmd->size < sizeof(struct netfs_inode_info)) {
521                 printk("%s: broken lookup response: id: %llu, start: %llu, size: %u.\n",
522                                 __func__, cmd->id, cmd->start, cmd->size);
523                 err = -EINVAL;
524                 goto err_out_put;
525         }
526
527         err = pohmelfs_data_recv_and_check(st, st->data, cmd->size);
528         if (err)
529                 goto err_out_put;
530
531         info = (struct netfs_inode_info *)(st->data);
532         name = (char *)(info + 1);
533
534         netfs_convert_inode_info(info);
535
536         info->ino = cmd->start;
537         if (!info->ino)
538                 info->ino = pohmelfs_new_ino(st->psb);
539
540         dprintk("%s: parent: %llu, ino: %llu, name: '%s', start: %llu.\n",
541                         __func__, parent->ino, info->ino, name, cmd->start);
542
543         if (cmd->start)
544                 npi = pohmelfs_new_inode(st->psb, parent, NULL, info, 0);
545         else {
546                 struct qstr str;
547
548                 str.name = name;
549                 str.len = cmd->size - sizeof(struct netfs_inode_info) - 1 - cmd->cpad;
550                 str.hash = jhash(name, str.len, 0);
551
552                 npi = pohmelfs_new_inode(st->psb, parent, &str, info, 0);
553         }
554         if (IS_ERR(npi)) {
555                 err = PTR_ERR(npi);
556
557                 if (err != -EEXIST)
558                         goto err_out_put;
559         } else {
560                 set_bit(NETFS_INODE_REMOTE_SYNCED, &npi->state);
561                 clear_bit(NETFS_INODE_OWNED, &npi->state);
562         }
563
564         clear_bit(NETFS_COMMAND_PENDING, &parent->state);
565         pohmelfs_put_inode(parent);
566
567         wake_up(&st->psb->wait);
568
569         return 0;
570
571 err_out_put:
572         pohmelfs_put_inode(parent);
573 err_out_exit:
574         clear_bit(NETFS_COMMAND_PENDING, &parent->state);
575         wake_up(&st->psb->wait);
576         printk("%s: inode: %p, id: %llu, start: %llu, size: %u, err: %d.\n",
577                         __func__, inode, cmd->id, cmd->start, cmd->size, err);
578         return err;
579 }
580
581 /*
582  * Create response, just marks local inode as 'created', so that writeback
583  * for any of its children (or own) would not try to sync it again.
584  */
585 static int pohmelfs_create_response(struct netfs_state *st)
586 {
587         struct inode *inode;
588         struct netfs_cmd *cmd = &st->cmd;
589         struct pohmelfs_inode *pi;
590
591         inode = ilookup(st->psb->sb, cmd->id);
592         if (!inode) {
593                 printk("%s: failed to find inode: id: %llu, start: %llu.\n",
594                                 __func__, cmd->id, cmd->start);
595                 goto err_out_exit;
596         }
597
598         pi = POHMELFS_I(inode);
599
600         /*
601          * To lock or not to lock?
602          * We actually do not care if it races...
603          */
604         if (cmd->start)
605                 make_bad_inode(inode);
606         set_bit(NETFS_INODE_REMOTE_SYNCED, &pi->state);
607
608         pohmelfs_put_inode(pi);
609
610         wake_up(&st->psb->wait);
611         return 0;
612
613 err_out_exit:
614         wake_up(&st->psb->wait);
615         return -ENOENT;
616 }
617
618 /*
619  * Object remove response. Just says that remove request has been received.
620  * Used in cache coherency protocol.
621  */
622 static int pohmelfs_remove_response(struct netfs_state *st)
623 {
624         struct netfs_cmd *cmd = &st->cmd;
625         int err;
626
627         err = pohmelfs_data_recv_and_check(st, st->data, cmd->size);
628         if (err)
629                 return err;
630
631         dprintk("%s: parent: %llu, path: '%s'.\n", __func__, cmd->id, (char *)st->data);
632
633         return 0;
634 }
635
636 /*
637  * Transaction reply processing.
638  *
639  * Find transaction based on its generation number, bump its reference counter,
640  * so that none could free it under us, drop from the trees and lists and
641  * drop reference counter. When it hits zero (when all destinations replied
642  * and all timeout handled by async scanning code), completion will be called
643  * and transaction will be freed.
644  */
645 static int pohmelfs_transaction_response(struct netfs_state *st)
646 {
647         struct netfs_trans_dst *dst;
648         struct netfs_trans *t = NULL;
649         struct netfs_cmd *cmd = &st->cmd;
650         short err = (signed)cmd->ext;
651
652         mutex_lock(&st->trans_lock);
653         dst = netfs_trans_search(st, cmd->start);
654         if (dst) {
655                 netfs_trans_remove_nolock(dst, st);
656                 t = dst->trans;
657
658                 pohmelfs_ftrans_update(cmd->start);
659         }
660         mutex_unlock(&st->trans_lock);
661
662         if (!t) {
663                 int check = pohmelfs_ftrans_check(cmd->start);
664                 printk("%s: failed to find transaction: start: %llu: id: %llu, size: %u, ext: %u, double: %d.\n",
665                                 __func__, cmd->start, cmd->id, cmd->size, cmd->ext, check);
666                 err = -EINVAL;
667                 goto out;
668         }
669
670         t->result = err;
671         netfs_trans_drop_dst_nostate(dst);
672
673 out:
674         wake_up(&st->psb->wait);
675         return err;
676 }
677
678 /*
679  * Inode metadata cache coherency message.
680  */
681 static int pohmelfs_page_cache_response(struct netfs_state *st)
682 {
683         struct netfs_cmd *cmd = &st->cmd;
684         struct inode *inode;
685
686         dprintk("%s: st: %p, id: %llu, start: %llu, size: %u.\n", __func__, st, cmd->id, cmd->start, cmd->size);
687
688         inode = ilookup(st->psb->sb, cmd->id);
689         if (!inode) {
690                 printk("%s: failed to find inode: id: %llu.\n", __func__, cmd->id);
691                 return -ENOENT;
692         }
693
694         set_bit(NETFS_INODE_NEED_FLUSH, &POHMELFS_I(inode)->state);
695         pohmelfs_put_inode(POHMELFS_I(inode));
696
697         return 0;
698 }
699
700 /*
701  * Root capabilities response: export statistics
702  * like used and available size, number of files and dirs,
703  * permissions.
704  */
705 static int pohmelfs_root_cap_response(struct netfs_state *st)
706 {
707         struct netfs_cmd *cmd = &st->cmd;
708         struct netfs_root_capabilities *cap;
709         struct pohmelfs_sb *psb = st->psb;
710
711         if (cmd->size != sizeof(struct netfs_root_capabilities)) {
712                 psb->flags = EPROTO;
713                 wake_up(&psb->wait);
714                 return -EPROTO;
715         }
716
717         cap = st->data;
718
719         netfs_convert_root_capabilities(cap);
720
721         if (psb->total_size < cap->used + cap->avail)
722                 psb->total_size = cap->used + cap->avail;
723         if (cap->avail)
724                 psb->avail_size = cap->avail;
725         psb->state_flags = cap->flags;
726
727         if (psb->state_flags & POHMELFS_FLAGS_RO) {
728                 psb->sb->s_flags |= MS_RDONLY;
729                 printk(KERN_INFO "Mounting POHMELFS (%d) read-only.\n", psb->idx);
730         }
731
732         if (psb->state_flags & POHMELFS_FLAGS_XATTR)
733                 printk(KERN_INFO "Mounting POHMELFS (%d) "
734                         "with extended attributes support.\n", psb->idx);
735
736         if (atomic_read(&psb->total_inodes) <= 1)
737                 atomic_long_set(&psb->total_inodes, cap->nr_files);
738
739         dprintk("%s: total: %llu, avail: %llu, flags: %llx, inodes: %llu.\n",
740                 __func__, psb->total_size, psb->avail_size, psb->state_flags, cap->nr_files);
741
742         psb->flags = 0;
743         wake_up(&psb->wait);
744         return 0;
745 }
746
747 /*
748  * Crypto capabilities of the server, where it says that
749  * it supports or does not requested hash/cipher algorithms.
750  */
751 static int pohmelfs_crypto_cap_response(struct netfs_state *st)
752 {
753         struct netfs_cmd *cmd = &st->cmd;
754         struct netfs_crypto_capabilities *cap;
755         struct pohmelfs_sb *psb = st->psb;
756         int err = 0;
757
758         if (cmd->size != sizeof(struct netfs_crypto_capabilities)) {
759                 psb->flags = EPROTO;
760                 wake_up(&psb->wait);
761                 return -EPROTO;
762         }
763
764         cap = st->data;
765
766         dprintk("%s: cipher '%s': %s, hash: '%s': %s.\n",
767                         __func__,
768                         psb->cipher_string, (cap->cipher_strlen)?"SUPPORTED":"NOT SUPPORTED",
769                         psb->hash_string, (cap->hash_strlen)?"SUPPORTED":"NOT SUPPORTED");
770
771         if (!cap->hash_strlen) {
772                 if (psb->hash_strlen && psb->crypto_fail_unsupported)
773                         err = -ENOTSUPP;
774                 psb->hash_strlen = 0;
775                 kfree(psb->hash_string);
776                 psb->hash_string = NULL;
777         }
778
779         if (!cap->cipher_strlen) {
780                 if (psb->cipher_strlen && psb->crypto_fail_unsupported)
781                         err = -ENOTSUPP;
782                 psb->cipher_strlen = 0;
783                 kfree(psb->cipher_string);
784                 psb->cipher_string = NULL;
785         }
786
787         return err;
788 }
789
790 /*
791  * Capabilities handshake response.
792  */
793 static int pohmelfs_capabilities_response(struct netfs_state *st)
794 {
795         struct netfs_cmd *cmd = &st->cmd;
796         int err = 0;
797
798         err = pohmelfs_data_recv(st, st->data, cmd->size);
799         if (err)
800                 return err;
801
802         switch (cmd->id) {
803                 case POHMELFS_CRYPTO_CAPABILITIES:
804                         return pohmelfs_crypto_cap_response(st);
805                 case POHMELFS_ROOT_CAPABILITIES:
806                         return pohmelfs_root_cap_response(st);
807                 default:
808                         break;
809         }
810         return -EINVAL;
811 }
812
813 /*
814  * Receiving extended attribute.
815  * Does not work properly if received size is more than requested one,
816  * it should not happen with current request/reply model though.
817  */
818 static int pohmelfs_getxattr_response(struct netfs_state *st)
819 {
820         struct pohmelfs_sb *psb = st->psb;
821         struct netfs_cmd *cmd = &st->cmd;
822         struct pohmelfs_mcache *m;
823         short error = (signed short)cmd->ext, err;
824         unsigned int sz, total_size;
825
826         m = pohmelfs_mcache_search(psb, cmd->id);
827
828         dprintk("%s: id: %llu, gen: %llu, err: %d.\n",
829                 __func__, cmd->id, (m)?m->gen:0, error);
830
831         if (!m) {
832                 printk("%s: failed to find getxattr cache entry: id: %llu.\n", __func__, cmd->id);
833                 return -ENOENT;
834         }
835
836         if (cmd->size) {
837                 sz = min_t(unsigned int, cmd->size, m->size);
838                 err = pohmelfs_data_recv_and_check(st, m->data, sz);
839                 if (err) {
840                         error = err;
841                         goto out;
842                 }
843
844                 m->size = sz;
845                 total_size = cmd->size - sz;
846
847                 while (total_size) {
848                         sz = min(total_size, st->size);
849
850                         err = pohmelfs_data_recv_and_check(st, st->data, sz);
851                         if (err) {
852                                 error = err;
853                                 break;
854                         }
855
856                         total_size -= sz;
857                 }
858         }
859
860 out:
861         m->err = error;
862         complete(&m->complete);
863         pohmelfs_mcache_put(psb, m);
864
865         return error;
866 }
867
868 int pohmelfs_data_lock_response(struct netfs_state *st)
869 {
870         struct pohmelfs_sb *psb = st->psb;
871         struct netfs_cmd *cmd = &st->cmd;
872         struct pohmelfs_mcache *m;
873         short err = (signed short)cmd->ext;
874         u64 id = cmd->id;
875
876         m = pohmelfs_mcache_search(psb, id);
877
878         dprintk("%s: id: %llu, gen: %llu, err: %d.\n",
879                 __func__, cmd->id, (m)?m->gen:0, err);
880
881         if (!m) {
882                 pohmelfs_data_recv(st, st->data, cmd->size);
883                 printk("%s: failed to find data lock response: id: %llu.\n", __func__, cmd->id);
884                 return -ENOENT;
885         }
886
887         if (cmd->size)
888                 err = pohmelfs_data_recv_and_check(st, &m->info, cmd->size);
889
890         m->err = err;
891         complete(&m->complete);
892         pohmelfs_mcache_put(psb, m);
893
894         return err;
895 }
896
897 static void __inline__ netfs_state_reset(struct netfs_state *st)
898 {
899         netfs_state_lock_send(st);
900         netfs_state_exit(st);
901         netfs_state_init(st);
902         netfs_state_unlock_send(st);
903 }
904
905 /*
906  * Main receiving function, called from dedicated kernel thread.
907  */
908 static int pohmelfs_recv(void *data)
909 {
910         int err = -EINTR;
911         struct netfs_state *st = data;
912         struct netfs_cmd *cmd = &st->cmd;
913
914         while (!kthread_should_stop()) {
915                 /*
916                  * If socket will be reset after this statement, then
917                  * pohmelfs_data_recv() will just fail and loop will
918                  * start again, so it can be done without any locks.
919                  *
920                  * st->read_socket is needed to prevents state machine
921                  * breaking between this data reading and subsequent one
922                  * in protocol specific functions during connection reset.
923                  * In case of reset we have to read next command and do
924                  * not expect data for old command to magically appear in
925                  * new connection.
926                  */
927                 st->read_socket = st->socket;
928                 err = pohmelfs_data_recv(st, cmd, sizeof(struct netfs_cmd));
929                 if (err) {
930                         msleep(1000);
931                         continue;
932                 }
933
934                 netfs_convert_cmd(cmd);
935
936                 dprintk("%s: cmd: %u, id: %llu, start: %llu, size: %u, "
937                                 "ext: %u, csize: %u, cpad: %u.\n",
938                                 __func__, cmd->cmd, cmd->id, cmd->start,
939                                 cmd->size, cmd->ext, cmd->csize, cmd->cpad);
940
941                 if (cmd->csize) {
942                         struct pohmelfs_crypto_engine *e = &st->eng;
943
944                         if (unlikely(cmd->csize > e->size/2)) {
945                                 netfs_state_reset(st);
946                                 continue;
947                         }
948
949                         if (e->hash && unlikely(cmd->csize != st->psb->crypto_attached_size)) {
950                                 dprintk("%s: cmd: cmd: %u, id: %llu, start: %llu, size: %u, "
951                                                 "csize: %u != digest size %u.\n",
952                                                 __func__, cmd->cmd, cmd->id, cmd->start, cmd->size,
953                                                 cmd->csize, st->psb->crypto_attached_size);
954                                 netfs_state_reset(st);
955                                 continue;
956                         }
957
958                         err = pohmelfs_data_recv(st, e->data, cmd->csize);
959                         if (err) {
960                                 netfs_state_reset(st);
961                                 continue;
962                         }
963
964 #ifdef CONFIG_POHMELFS_DEBUG
965                         {
966                                 unsigned int i;
967                                 unsigned char *hash = e->data;
968
969                                 dprintk("%s: received hash: ", __func__);
970                                 for (i=0; i<cmd->csize; ++i) {
971                                         printk("%02x ", hash[i]);
972                                 }
973                                 printk("\n");
974                         }
975 #endif
976                         cmd->size -= cmd->csize;
977                 }
978
979                 /*
980                  * This should catch protocol breakage and random garbage instead of commands.
981                  */
982                 if (unlikely((cmd->size > st->size) && (cmd->cmd != NETFS_XATTR_GET))) {
983                         netfs_state_reset(st);
984                         continue;
985                 }
986
987                 switch (cmd->cmd) {
988                         case NETFS_READ_PAGE:
989                                 err = pohmelfs_read_page_response(st);
990                                 break;
991                         case NETFS_READDIR:
992                                 err = pohmelfs_readdir_response(st);
993                                 break;
994                         case NETFS_LOOKUP:
995                                 err = pohmelfs_lookup_response(st);
996                                 break;
997                         case NETFS_CREATE:
998                                 err = pohmelfs_create_response(st);
999                                 break;
1000                         case NETFS_REMOVE:
1001                                 err = pohmelfs_remove_response(st);
1002                                 break;
1003                         case NETFS_TRANS:
1004                                 err = pohmelfs_transaction_response(st);
1005                                 break;
1006                         case NETFS_PAGE_CACHE:
1007                                 err = pohmelfs_page_cache_response(st);
1008                                 break;
1009                         case NETFS_CAPABILITIES:
1010                                 err = pohmelfs_capabilities_response(st);
1011                                 break;
1012                         case NETFS_LOCK:
1013                                 err = pohmelfs_data_lock_response(st);
1014                                 break;
1015                         case NETFS_XATTR_GET:
1016                                 err = pohmelfs_getxattr_response(st);
1017                                 break;
1018                         default:
1019                                 printk("%s: wrong cmd: %u, id: %llu, start: %llu, size: %u, ext: %u.\n",
1020                                         __func__, cmd->cmd, cmd->id, cmd->start, cmd->size, cmd->ext);
1021                                 netfs_state_reset(st);
1022                                 break;
1023                 }
1024         }
1025
1026         while (!kthread_should_stop())
1027                 schedule_timeout_uninterruptible(msecs_to_jiffies(10));
1028
1029         return err;
1030 }
1031
1032 int netfs_state_init(struct netfs_state *st)
1033 {
1034         int err;
1035         struct pohmelfs_ctl *ctl = &st->ctl;
1036
1037         err = sock_create(ctl->addr.sa_family, ctl->type, ctl->proto, &st->socket);
1038         if (err) {
1039                 printk("%s: failed to create a socket: family: %d, type: %d, proto: %d, err: %d.\n",
1040                                 __func__, ctl->addr.sa_family, ctl->type, ctl->proto, err);
1041                 goto err_out_exit;
1042         }
1043
1044         st->socket->sk->sk_allocation = GFP_NOIO;
1045         st->socket->sk->sk_sndtimeo = st->socket->sk->sk_rcvtimeo = msecs_to_jiffies(60000);
1046
1047         err = kernel_connect(st->socket, (struct sockaddr *)&ctl->addr, ctl->addrlen, 0);
1048         if (err) {
1049                 printk("%s: failed to connect to server: idx: %u, err: %d.\n",
1050                                 __func__, st->psb->idx, err);
1051                 goto err_out_release;
1052         }
1053         st->socket->sk->sk_sndtimeo = st->socket->sk->sk_rcvtimeo = msecs_to_jiffies(60000);
1054
1055         err = netfs_poll_init(st);
1056         if (err)
1057                 goto err_out_release;
1058
1059         if (st->socket->ops->family == AF_INET) {
1060                 struct sockaddr_in *sin = (struct sockaddr_in *)&ctl->addr;
1061                 printk(KERN_INFO "%s: (re)connected to peer %u.%u.%u.%u:%d.\n", __func__,
1062                         NIPQUAD(sin->sin_addr.s_addr), ntohs(sin->sin_port));
1063         } else if (st->socket->ops->family == AF_INET6) {
1064                 struct sockaddr_in6 *sin = (struct sockaddr_in6 *)&ctl->addr;
1065                 printk(KERN_INFO "%s: (re)connected to peer "
1066                         "%pi6:%d",
1067                         __func__, &sin->sin6_addr, ntohs(sin->sin6_port));
1068         }
1069
1070         return 0;
1071
1072 err_out_release:
1073         sock_release(st->socket);
1074 err_out_exit:
1075         st->socket = NULL;
1076         return err;
1077 }
1078
1079 void netfs_state_exit(struct netfs_state *st)
1080 {
1081         if (st->socket) {
1082                 netfs_poll_exit(st);
1083                 st->socket->ops->shutdown(st->socket, 2);
1084
1085                 if (st->socket->ops->family == AF_INET) {
1086                         struct sockaddr_in *sin = (struct sockaddr_in *)&st->ctl.addr;
1087                         printk("%s: disconnected from peer %u.%u.%u.%u:%d.\n", __func__,
1088                                 NIPQUAD(sin->sin_addr.s_addr), ntohs(sin->sin_port));
1089                 } else if (st->socket->ops->family == AF_INET6) {
1090                         struct sockaddr_in6 *sin = (struct sockaddr_in6 *)&st->ctl.addr;
1091                         printk("%s: disconnected from peer "
1092                                 "%pi6:%d",
1093                                 __func__, &sin->sin6_addr, ntohs(sin->sin6_port));
1094                 }
1095
1096                 sock_release(st->socket);
1097                 st->socket = NULL;
1098                 st->read_socket = NULL;
1099                 st->need_reset = 0;
1100         }
1101 }
1102
1103 int pohmelfs_state_init_one(struct pohmelfs_sb *psb, struct pohmelfs_config *conf)
1104 {
1105         struct netfs_state *st = &conf->state;
1106         int err = -ENOMEM;
1107
1108         mutex_init(&st->__state_lock);
1109         mutex_init(&st->__state_send_lock);
1110         init_waitqueue_head(&st->thread_wait);
1111
1112         st->psb = psb;
1113         st->trans_root = RB_ROOT;
1114         mutex_init(&st->trans_lock);
1115
1116         st->size = psb->trans_data_size;
1117         st->data = kmalloc(st->size, GFP_KERNEL);
1118         if (!st->data)
1119                 goto err_out_exit;
1120
1121         if (psb->perform_crypto) {
1122                 err = pohmelfs_crypto_engine_init(&st->eng, psb);
1123                 if (err)
1124                         goto err_out_free_data;
1125         }
1126
1127         err = netfs_state_init(st);
1128         if (err)
1129                 goto err_out_free_engine;
1130
1131         st->thread = kthread_run(pohmelfs_recv, st, "pohmelfs/%u", psb->idx);
1132         if (IS_ERR(st->thread)) {
1133                 err = PTR_ERR(st->thread);
1134                 goto err_out_netfs_exit;
1135         }
1136
1137         if (!psb->active_state)
1138                 psb->active_state = conf;
1139
1140         dprintk("%s: conf: %p, st: %p, socket: %p.\n",
1141                         __func__, conf, st, st->socket);
1142         return 0;
1143
1144 err_out_netfs_exit:
1145         netfs_state_exit(st);
1146 err_out_free_engine:
1147         pohmelfs_crypto_engine_exit(&st->eng);
1148 err_out_free_data:
1149         kfree(st->data);
1150 err_out_exit:
1151         return err;
1152
1153 }
1154
1155 void pohmelfs_state_flush_transactions(struct netfs_state *st)
1156 {
1157         struct rb_node *rb_node;
1158         struct netfs_trans_dst *dst;
1159
1160         mutex_lock(&st->trans_lock);
1161         for (rb_node = rb_first(&st->trans_root); rb_node; ) {
1162                 dst = rb_entry(rb_node, struct netfs_trans_dst, state_entry);
1163                 rb_node = rb_next(rb_node);
1164
1165                 dst->trans->result = -EINVAL;
1166                 netfs_trans_remove_nolock(dst, st);
1167                 netfs_trans_drop_dst_nostate(dst);
1168         }
1169         mutex_unlock(&st->trans_lock);
1170 }
1171
1172 static void pohmelfs_state_exit_one(struct pohmelfs_config *c)
1173 {
1174         struct netfs_state *st = &c->state;
1175
1176         dprintk("%s: exiting, st: %p.\n", __func__, st);
1177         if (st->thread) {
1178                 kthread_stop(st->thread);
1179                 st->thread = NULL;
1180         }
1181
1182         netfs_state_lock_send(st);
1183         netfs_state_exit(st);
1184         netfs_state_unlock_send(st);
1185
1186         pohmelfs_state_flush_transactions(st);
1187
1188         pohmelfs_crypto_engine_exit(&st->eng);
1189         kfree(st->data);
1190
1191         kfree(c);
1192 }
1193
1194 /*
1195  * Initialize network stack. It searches for given ID in global
1196  * configuration table, this contains information of the remote server
1197  * (address (any supported by socket interface) and port, protocol and so on).
1198  */
1199 int pohmelfs_state_init(struct pohmelfs_sb *psb)
1200 {
1201         int err = -ENOMEM;
1202
1203         err = pohmelfs_copy_config(psb);
1204         if (err) {
1205                 pohmelfs_state_exit(psb);
1206                 return err;
1207         }
1208
1209         return 0;
1210 }
1211
1212 void pohmelfs_state_exit(struct pohmelfs_sb *psb)
1213 {
1214         struct pohmelfs_config *c, *tmp;
1215
1216         list_for_each_entry_safe(c, tmp, &psb->state_list, config_entry) {
1217                 list_del(&c->config_entry);
1218                 pohmelfs_state_exit_one(c);
1219         }
1220 }
1221
1222 void pohmelfs_switch_active(struct pohmelfs_sb *psb)
1223 {
1224         struct pohmelfs_config *c = psb->active_state;
1225
1226         if (!list_empty(&psb->state_list)) {
1227                 if (c->config_entry.next != &psb->state_list) {
1228                         psb->active_state = list_entry(c->config_entry.next,
1229                                 struct pohmelfs_config, config_entry);
1230                 } else {
1231                         psb->active_state = list_entry(psb->state_list.next,
1232                                 struct pohmelfs_config, config_entry);
1233                 }
1234
1235                 dprintk("%s: empty: %d, active %p -> %p.\n",
1236                         __func__, list_empty(&psb->state_list), c,
1237                         psb->active_state);
1238         } else
1239                 psb->active_state = NULL;
1240 }
1241
1242 void pohmelfs_check_states(struct pohmelfs_sb *psb)
1243 {
1244         struct pohmelfs_config *c, *tmp;
1245         LIST_HEAD(delete_list);
1246
1247         mutex_lock(&psb->state_lock);
1248         list_for_each_entry_safe(c, tmp, &psb->state_list, config_entry) {
1249                 if (pohmelfs_config_check(c, psb->idx)) {
1250
1251                         if (psb->active_state == c)
1252                                 pohmelfs_switch_active(psb);
1253                         list_move(&c->config_entry, &delete_list);
1254                 }
1255         }
1256         pohmelfs_copy_config(psb);
1257         mutex_unlock(&psb->state_lock);
1258
1259         list_for_each_entry_safe(c, tmp, &delete_list, config_entry) {
1260                 list_del(&c->config_entry);
1261                 pohmelfs_state_exit_one(c);
1262         }
1263 }