1/*
2 * An implementation of file copy service.
3 *
4 * Copyright (C) 2014, Microsoft, Inc.
5 *
6 * Author : K. Y. Srinivasan <ksrinivasan@novell.com>
7 *
8 * This program is free software; you can redistribute it and/or modify it
9 * under the terms of the GNU General Public License version 2 as published
10 * by the Free Software Foundation.
11 *
12 * This program is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or
15 * NON INFRINGEMENT.  See the GNU General Public License for more
16 * details.
17 *
18 */
19
20#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
21
22#include <linux/semaphore.h>
23#include <linux/fs.h>
24#include <linux/nls.h>
25#include <linux/workqueue.h>
26#include <linux/cdev.h>
27#include <linux/hyperv.h>
28#include <linux/sched.h>
29#include <linux/uaccess.h>
30#include <linux/miscdevice.h>
31
32#include "hyperv_vmbus.h"
33
34#define WIN8_SRV_MAJOR		1
35#define WIN8_SRV_MINOR		1
36#define WIN8_SRV_VERSION	(WIN8_SRV_MAJOR << 16 | WIN8_SRV_MINOR)
37
38/*
39 * Global state maintained for transaction that is being processed.
40 * For a class of integration services, including the "file copy service",
41 * the specified protocol is a "request/response" protocol which means that
42 * there can only be single outstanding transaction from the host at any
43 * given point in time. We use this to simplify memory management in this
44 * driver - we cache and process only one message at a time.
45 *
46 * While the request/response protocol is guaranteed by the host, we further
47 * ensure this by serializing packet processing in this driver - we do not
48 * read additional packets from the VMBUs until the current packet is fully
49 * handled.
50 *
51 * The transaction "active" state is set when we receive a request from the
52 * host and we cleanup this state when the transaction is completed - when we
53 * respond to the host with our response. When the transaction active state is
54 * set, we defer handling incoming packets.
55 */
56
57static struct {
58	bool active; /* transaction status - active or not */
59	int recv_len; /* number of bytes received. */
60	struct hv_fcopy_hdr  *fcopy_msg; /* current message */
61	struct hv_start_fcopy  message; /*  sent to daemon */
62	struct vmbus_channel *recv_channel; /* chn we got the request */
63	u64 recv_req_id; /* request ID. */
64	void *fcopy_context; /* for the channel callback */
65	struct semaphore read_sema;
66} fcopy_transaction;
67
68static bool opened; /* currently device opened */
69
70/*
71 * Before we can accept copy messages from the host, we need
72 * to handshake with the user level daemon. This state tracks
73 * if we are in the handshake phase.
74 */
75static bool in_hand_shake = true;
76static void fcopy_send_data(void);
77static void fcopy_respond_to_host(int error);
78static void fcopy_work_func(struct work_struct *dummy);
79static DECLARE_DELAYED_WORK(fcopy_work, fcopy_work_func);
80static u8 *recv_buffer;
81
82static void fcopy_work_func(struct work_struct *dummy)
83{
84	/*
85	 * If the timer fires, the user-mode component has not responded;
86	 * process the pending transaction.
87	 */
88	fcopy_respond_to_host(HV_E_FAIL);
89
90	/* In the case the user-space daemon crashes, hangs or is killed, we
91	 * need to down the semaphore, otherwise, after the daemon starts next
92	 * time, the obsolete data in fcopy_transaction.message or
93	 * fcopy_transaction.fcopy_msg will be used immediately.
94	 *
95	 * NOTE: fcopy_read() happens to get the semaphore (very rare)? We're
96	 * still OK, because we've reported the failure to the host.
97	 */
98	if (down_trylock(&fcopy_transaction.read_sema))
99		;
100
101}
102
103static int fcopy_handle_handshake(u32 version)
104{
105	switch (version) {
106	case FCOPY_CURRENT_VERSION:
107		break;
108	default:
109		/*
110		 * For now we will fail the registration.
111		 * If and when we have multiple versions to
112		 * deal with, we will be backward compatible.
113		 * We will add this code when needed.
114		 */
115		return -EINVAL;
116	}
117	pr_info("FCP: user-mode registering done. Daemon version: %d\n",
118		version);
119	fcopy_transaction.active = false;
120	if (fcopy_transaction.fcopy_context)
121		hv_fcopy_onchannelcallback(fcopy_transaction.fcopy_context);
122	in_hand_shake = false;
123	return 0;
124}
125
126static void fcopy_send_data(void)
127{
128	struct hv_start_fcopy *smsg_out = &fcopy_transaction.message;
129	int operation = fcopy_transaction.fcopy_msg->operation;
130	struct hv_start_fcopy *smsg_in;
131
132	/*
133	 * The  strings sent from the host are encoded in
134	 * in utf16; convert it to utf8 strings.
135	 * The host assures us that the utf16 strings will not exceed
136	 * the max lengths specified. We will however, reserve room
137	 * for the string terminating character - in the utf16s_utf8s()
138	 * function we limit the size of the buffer where the converted
139	 * string is placed to W_MAX_PATH -1 to guarantee
140	 * that the strings can be properly terminated!
141	 */
142
143	switch (operation) {
144	case START_FILE_COPY:
145		memset(smsg_out, 0, sizeof(struct hv_start_fcopy));
146		smsg_out->hdr.operation = operation;
147		smsg_in = (struct hv_start_fcopy *)fcopy_transaction.fcopy_msg;
148
149		utf16s_to_utf8s((wchar_t *)smsg_in->file_name, W_MAX_PATH,
150				UTF16_LITTLE_ENDIAN,
151				(__u8 *)smsg_out->file_name, W_MAX_PATH - 1);
152
153		utf16s_to_utf8s((wchar_t *)smsg_in->path_name, W_MAX_PATH,
154				UTF16_LITTLE_ENDIAN,
155				(__u8 *)smsg_out->path_name, W_MAX_PATH - 1);
156
157		smsg_out->copy_flags = smsg_in->copy_flags;
158		smsg_out->file_size = smsg_in->file_size;
159		break;
160
161	default:
162		break;
163	}
164	up(&fcopy_transaction.read_sema);
165	return;
166}
167
168/*
169 * Send a response back to the host.
170 */
171
172static void
173fcopy_respond_to_host(int error)
174{
175	struct icmsg_hdr *icmsghdr;
176	u32 buf_len;
177	struct vmbus_channel *channel;
178	u64 req_id;
179
180	/*
181	 * Copy the global state for completing the transaction. Note that
182	 * only one transaction can be active at a time. This is guaranteed
183	 * by the file copy protocol implemented by the host. Furthermore,
184	 * the "transaction active" state we maintain ensures that there can
185	 * only be one active transaction at a time.
186	 */
187
188	buf_len = fcopy_transaction.recv_len;
189	channel = fcopy_transaction.recv_channel;
190	req_id = fcopy_transaction.recv_req_id;
191
192	fcopy_transaction.active = false;
193
194	icmsghdr = (struct icmsg_hdr *)
195			&recv_buffer[sizeof(struct vmbuspipe_hdr)];
196
197	if (channel->onchannel_callback == NULL)
198		/*
199		 * We have raced with util driver being unloaded;
200		 * silently return.
201		 */
202		return;
203
204	icmsghdr->status = error;
205	icmsghdr->icflags = ICMSGHDRFLAG_TRANSACTION | ICMSGHDRFLAG_RESPONSE;
206	vmbus_sendpacket(channel, recv_buffer, buf_len, req_id,
207				VM_PKT_DATA_INBAND, 0);
208}
209
210void hv_fcopy_onchannelcallback(void *context)
211{
212	struct vmbus_channel *channel = context;
213	u32 recvlen;
214	u64 requestid;
215	struct hv_fcopy_hdr *fcopy_msg;
216	struct icmsg_hdr *icmsghdr;
217	struct icmsg_negotiate *negop = NULL;
218	int util_fw_version;
219	int fcopy_srv_version;
220
221	if (fcopy_transaction.active) {
222		/*
223		 * We will defer processing this callback once
224		 * the current transaction is complete.
225		 */
226		fcopy_transaction.fcopy_context = context;
227		return;
228	}
229
230	vmbus_recvpacket(channel, recv_buffer, PAGE_SIZE * 2, &recvlen,
231			 &requestid);
232	if (recvlen <= 0)
233		return;
234
235	icmsghdr = (struct icmsg_hdr *)&recv_buffer[
236			sizeof(struct vmbuspipe_hdr)];
237	if (icmsghdr->icmsgtype == ICMSGTYPE_NEGOTIATE) {
238		util_fw_version = UTIL_FW_VERSION;
239		fcopy_srv_version = WIN8_SRV_VERSION;
240		vmbus_prep_negotiate_resp(icmsghdr, negop, recv_buffer,
241				util_fw_version, fcopy_srv_version);
242	} else {
243		fcopy_msg = (struct hv_fcopy_hdr *)&recv_buffer[
244				sizeof(struct vmbuspipe_hdr) +
245				sizeof(struct icmsg_hdr)];
246
247		/*
248		 * Stash away this global state for completing the
249		 * transaction; note transactions are serialized.
250		 */
251
252		fcopy_transaction.active = true;
253		fcopy_transaction.recv_len = recvlen;
254		fcopy_transaction.recv_channel = channel;
255		fcopy_transaction.recv_req_id = requestid;
256		fcopy_transaction.fcopy_msg = fcopy_msg;
257
258		/*
259		 * Send the information to the user-level daemon.
260		 */
261		schedule_delayed_work(&fcopy_work, 5*HZ);
262		fcopy_send_data();
263		return;
264	}
265	icmsghdr->icflags = ICMSGHDRFLAG_TRANSACTION | ICMSGHDRFLAG_RESPONSE;
266	vmbus_sendpacket(channel, recv_buffer, recvlen, requestid,
267			VM_PKT_DATA_INBAND, 0);
268}
269
270/*
271 * Create a char device that can support read/write for passing
272 * the payload.
273 */
274
275static ssize_t fcopy_read(struct file *file, char __user *buf,
276		size_t count, loff_t *ppos)
277{
278	void *src;
279	size_t copy_size;
280	int operation;
281
282	/*
283	 * Wait until there is something to be read.
284	 */
285	if (down_interruptible(&fcopy_transaction.read_sema))
286		return -EINTR;
287
288	/*
289	 * The channel may be rescinded and in this case, we will wakeup the
290	 * the thread blocked on the semaphore and we will use the opened
291	 * state to correctly handle this case.
292	 */
293	if (!opened)
294		return -ENODEV;
295
296	operation = fcopy_transaction.fcopy_msg->operation;
297
298	if (operation == START_FILE_COPY) {
299		src = &fcopy_transaction.message;
300		copy_size = sizeof(struct hv_start_fcopy);
301		if (count < copy_size)
302			return 0;
303	} else {
304		src = fcopy_transaction.fcopy_msg;
305		copy_size = sizeof(struct hv_do_fcopy);
306		if (count < copy_size)
307			return 0;
308	}
309	if (copy_to_user(buf, src, copy_size))
310		return -EFAULT;
311
312	return copy_size;
313}
314
315static ssize_t fcopy_write(struct file *file, const char __user *buf,
316			size_t count, loff_t *ppos)
317{
318	int response = 0;
319
320	if (count != sizeof(int))
321		return -EINVAL;
322
323	if (copy_from_user(&response, buf, sizeof(int)))
324		return -EFAULT;
325
326	if (in_hand_shake) {
327		if (fcopy_handle_handshake(response))
328			return -EINVAL;
329		return sizeof(int);
330	}
331
332	/*
333	 * Complete the transaction by forwarding the result
334	 * to the host. But first, cancel the timeout.
335	 */
336	if (cancel_delayed_work_sync(&fcopy_work))
337		fcopy_respond_to_host(response);
338
339	return sizeof(int);
340}
341
342static int fcopy_open(struct inode *inode, struct file *f)
343{
344	/*
345	 * The user level daemon that will open this device is
346	 * really an extension of this driver. We can have only
347	 * active open at a time.
348	 */
349	if (opened)
350		return -EBUSY;
351
352	/*
353	 * The daemon is alive; setup the state.
354	 */
355	opened = true;
356	return 0;
357}
358
359/* XXX: there are still some tricky corner cases, e.g.,
360 * 1) In a SMP guest, when fcopy_release() runs between
361 * schedule_delayed_work() and fcopy_send_data(), there is
362 * still a chance an obsolete message will be queued.
363 *
364 * 2) When the fcopy daemon is running, if we unload the driver,
365 * we'll notice a kernel oops when we kill the daemon later.
366 */
367static int fcopy_release(struct inode *inode, struct file *f)
368{
369	/*
370	 * The daemon has exited; reset the state.
371	 */
372	in_hand_shake = true;
373	opened = false;
374
375	if (cancel_delayed_work_sync(&fcopy_work)) {
376		/* We haven't up()-ed the semaphore(very rare)? */
377		if (down_trylock(&fcopy_transaction.read_sema))
378			;
379		fcopy_respond_to_host(HV_E_FAIL);
380	}
381	return 0;
382}
383
384
385static const struct file_operations fcopy_fops = {
386	.read           = fcopy_read,
387	.write          = fcopy_write,
388	.release	= fcopy_release,
389	.open		= fcopy_open,
390};
391
392static struct miscdevice fcopy_misc = {
393	.minor          = MISC_DYNAMIC_MINOR,
394	.name           = "vmbus/hv_fcopy",
395	.fops           = &fcopy_fops,
396};
397
398static int fcopy_dev_init(void)
399{
400	return misc_register(&fcopy_misc);
401}
402
403static void fcopy_dev_deinit(void)
404{
405
406	/*
407	 * The device is going away - perhaps because the
408	 * host has rescinded the channel. Setup state so that
409	 * user level daemon can gracefully exit if it is blocked
410	 * on the read semaphore.
411	 */
412	opened = false;
413	/*
414	 * Signal the semaphore as the device is
415	 * going away.
416	 */
417	up(&fcopy_transaction.read_sema);
418	misc_deregister(&fcopy_misc);
419}
420
421int hv_fcopy_init(struct hv_util_service *srv)
422{
423	recv_buffer = srv->recv_buffer;
424
425	/*
426	 * When this driver loads, the user level daemon that
427	 * processes the host requests may not yet be running.
428	 * Defer processing channel callbacks until the daemon
429	 * has registered.
430	 */
431	fcopy_transaction.active = true;
432	sema_init(&fcopy_transaction.read_sema, 0);
433
434	return fcopy_dev_init();
435}
436
437void hv_fcopy_deinit(void)
438{
439	cancel_delayed_work_sync(&fcopy_work);
440	fcopy_dev_deinit();
441}
442