xref: /linux/drivers/block/drbd/drbd_main.c (revision f8eacd8ad7a658b805c635f8ffad7913981f863c)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3    drbd.c
4 
5    This file is part of DRBD by Philipp Reisner and Lars Ellenberg.
6 
7    Copyright (C) 2001-2008, LINBIT Information Technologies GmbH.
8    Copyright (C) 1999-2008, Philipp Reisner <philipp.reisner@linbit.com>.
9    Copyright (C) 2002-2008, Lars Ellenberg <lars.ellenberg@linbit.com>.
10 
11    Thanks to Carter Burden, Bart Grantham and Gennadiy Nerubayev
12    from Logicworks, Inc. for making SDP replication support possible.
13 
14 
15  */
16 
17 #define pr_fmt(fmt)	KBUILD_MODNAME ": " fmt
18 
19 #include <linux/module.h>
20 #include <linux/jiffies.h>
21 #include <linux/drbd.h>
22 #include <linux/uaccess.h>
23 #include <asm/types.h>
24 #include <net/sock.h>
25 #include <linux/ctype.h>
26 #include <linux/mutex.h>
27 #include <linux/fs.h>
28 #include <linux/file.h>
29 #include <linux/proc_fs.h>
30 #include <linux/init.h>
31 #include <linux/mm.h>
32 #include <linux/memcontrol.h>
33 #include <linux/mm_inline.h>
34 #include <linux/slab.h>
35 #include <linux/random.h>
36 #include <linux/reboot.h>
37 #include <linux/notifier.h>
38 #include <linux/kthread.h>
39 #include <linux/workqueue.h>
40 #include <linux/unistd.h>
41 #include <linux/vmalloc.h>
42 #include <linux/sched/signal.h>
43 
44 #include <linux/drbd_limits.h>
45 #include "drbd_int.h"
46 #include "drbd_protocol.h"
47 #include "drbd_req.h" /* only for _req_mod in tl_release and tl_clear */
48 #include "drbd_vli.h"
49 #include "drbd_debugfs.h"
50 
51 static DEFINE_MUTEX(drbd_main_mutex);
52 static int drbd_open(struct gendisk *disk, blk_mode_t mode);
53 static void drbd_release(struct gendisk *gd);
54 static void md_sync_timer_fn(struct timer_list *t);
55 static int w_bitmap_io(struct drbd_work *w, int unused);
56 
57 MODULE_AUTHOR("Philipp Reisner <phil@linbit.com>, "
58 	      "Lars Ellenberg <lars@linbit.com>");
59 MODULE_DESCRIPTION("drbd - Distributed Replicated Block Device v" REL_VERSION);
60 MODULE_VERSION(REL_VERSION);
61 MODULE_LICENSE("GPL");
62 MODULE_PARM_DESC(minor_count, "Approximate number of drbd devices ("
63 		 __stringify(DRBD_MINOR_COUNT_MIN) "-" __stringify(DRBD_MINOR_COUNT_MAX) ")");
64 MODULE_ALIAS_BLOCKDEV_MAJOR(DRBD_MAJOR);
65 
66 #include <linux/moduleparam.h>
67 /* thanks to these macros, if compiled into the kernel (not-module),
68  * these become boot parameters (e.g., drbd.minor_count) */
69 
70 #ifdef CONFIG_DRBD_FAULT_INJECTION
71 int drbd_enable_faults;
72 int drbd_fault_rate;
73 static int drbd_fault_count;
74 static int drbd_fault_devs;
75 /* bitmap of enabled faults */
76 module_param_named(enable_faults, drbd_enable_faults, int, 0664);
77 /* fault rate % value - applies to all enabled faults */
78 module_param_named(fault_rate, drbd_fault_rate, int, 0664);
79 /* count of faults inserted */
80 module_param_named(fault_count, drbd_fault_count, int, 0664);
81 /* bitmap of devices to insert faults on */
82 module_param_named(fault_devs, drbd_fault_devs, int, 0644);
83 #endif
84 
85 /* module parameters we can keep static */
86 static bool drbd_allow_oos; /* allow_open_on_secondary */
87 static bool drbd_disable_sendpage;
88 MODULE_PARM_DESC(allow_oos, "DONT USE!");
89 module_param_named(allow_oos, drbd_allow_oos, bool, 0);
90 module_param_named(disable_sendpage, drbd_disable_sendpage, bool, 0644);
91 
92 /* module parameters we share */
93 int drbd_proc_details; /* Detail level in proc drbd*/
94 module_param_named(proc_details, drbd_proc_details, int, 0644);
95 /* module parameters shared with defaults */
96 unsigned int drbd_minor_count = DRBD_MINOR_COUNT_DEF;
97 /* Module parameter for setting the user mode helper program
98  * to run. Default is /sbin/drbdadm */
99 char drbd_usermode_helper[80] = "/sbin/drbdadm";
100 module_param_named(minor_count, drbd_minor_count, uint, 0444);
101 module_param_string(usermode_helper, drbd_usermode_helper, sizeof(drbd_usermode_helper), 0644);
102 
103 /* in 2.6.x, our device mapping and config info contains our virtual gendisks
104  * as member "struct gendisk *vdisk;"
105  */
106 struct idr drbd_devices;
107 struct list_head drbd_resources;
108 struct mutex resources_mutex;
109 
110 struct kmem_cache *drbd_request_cache;
111 struct kmem_cache *drbd_ee_cache;	/* peer requests */
112 struct kmem_cache *drbd_bm_ext_cache;	/* bitmap extents */
113 struct kmem_cache *drbd_al_ext_cache;	/* activity log extents */
114 mempool_t drbd_request_mempool;
115 mempool_t drbd_ee_mempool;
116 mempool_t drbd_md_io_page_pool;
117 struct bio_set drbd_md_io_bio_set;
118 struct bio_set drbd_io_bio_set;
119 
120 /* I do not use a standard mempool, because:
121    1) I want to hand out the pre-allocated objects first.
122    2) I want to be able to interrupt sleeping allocation with a signal.
123    Note: This is a single linked list, the next pointer is the private
124 	 member of struct page.
125  */
126 struct page *drbd_pp_pool;
127 DEFINE_SPINLOCK(drbd_pp_lock);
128 int          drbd_pp_vacant;
129 wait_queue_head_t drbd_pp_wait;
130 
131 DEFINE_RATELIMIT_STATE(drbd_ratelimit_state, 5 * HZ, 5);
132 
133 static const struct block_device_operations drbd_ops = {
134 	.owner		= THIS_MODULE,
135 	.submit_bio	= drbd_submit_bio,
136 	.open		= drbd_open,
137 	.release	= drbd_release,
138 };
139 
140 #ifdef __CHECKER__
141 /* When checking with sparse, and this is an inline function, sparse will
142    give tons of false positives. When this is a real functions sparse works.
143  */
_get_ldev_if_state(struct drbd_device * device,enum drbd_disk_state mins)144 int _get_ldev_if_state(struct drbd_device *device, enum drbd_disk_state mins)
145 {
146 	int io_allowed;
147 
148 	atomic_inc(&device->local_cnt);
149 	io_allowed = (device->state.disk >= mins);
150 	if (!io_allowed) {
151 		if (atomic_dec_and_test(&device->local_cnt))
152 			wake_up(&device->misc_wait);
153 	}
154 	return io_allowed;
155 }
156 
157 #endif
158 
159 /**
160  * tl_release() - mark as BARRIER_ACKED all requests in the corresponding transfer log epoch
161  * @connection:	DRBD connection.
162  * @barrier_nr:	Expected identifier of the DRBD write barrier packet.
163  * @set_size:	Expected number of requests before that barrier.
164  *
165  * In case the passed barrier_nr or set_size does not match the oldest
166  * epoch of not yet barrier-acked requests, this function will cause a
167  * termination of the connection.
168  */
tl_release(struct drbd_connection * connection,unsigned int barrier_nr,unsigned int set_size)169 void tl_release(struct drbd_connection *connection, unsigned int barrier_nr,
170 		unsigned int set_size)
171 {
172 	struct drbd_request *r;
173 	struct drbd_request *req = NULL, *tmp = NULL;
174 	int expect_epoch = 0;
175 	int expect_size = 0;
176 
177 	spin_lock_irq(&connection->resource->req_lock);
178 
179 	/* find oldest not yet barrier-acked write request,
180 	 * count writes in its epoch. */
181 	list_for_each_entry(r, &connection->transfer_log, tl_requests) {
182 		const unsigned s = r->rq_state;
183 		if (!req) {
184 			if (!(s & RQ_WRITE))
185 				continue;
186 			if (!(s & RQ_NET_MASK))
187 				continue;
188 			if (s & RQ_NET_DONE)
189 				continue;
190 			req = r;
191 			expect_epoch = req->epoch;
192 			expect_size ++;
193 		} else {
194 			if (r->epoch != expect_epoch)
195 				break;
196 			if (!(s & RQ_WRITE))
197 				continue;
198 			/* if (s & RQ_DONE): not expected */
199 			/* if (!(s & RQ_NET_MASK)): not expected */
200 			expect_size++;
201 		}
202 	}
203 
204 	/* first some paranoia code */
205 	if (req == NULL) {
206 		drbd_err(connection, "BAD! BarrierAck #%u received, but no epoch in tl!?\n",
207 			 barrier_nr);
208 		goto bail;
209 	}
210 	if (expect_epoch != barrier_nr) {
211 		drbd_err(connection, "BAD! BarrierAck #%u received, expected #%u!\n",
212 			 barrier_nr, expect_epoch);
213 		goto bail;
214 	}
215 
216 	if (expect_size != set_size) {
217 		drbd_err(connection, "BAD! BarrierAck #%u received with n_writes=%u, expected n_writes=%u!\n",
218 			 barrier_nr, set_size, expect_size);
219 		goto bail;
220 	}
221 
222 	/* Clean up list of requests processed during current epoch. */
223 	/* this extra list walk restart is paranoia,
224 	 * to catch requests being barrier-acked "unexpectedly".
225 	 * It usually should find the same req again, or some READ preceding it. */
226 	list_for_each_entry(req, &connection->transfer_log, tl_requests)
227 		if (req->epoch == expect_epoch) {
228 			tmp = req;
229 			break;
230 		}
231 	req = list_prepare_entry(tmp, &connection->transfer_log, tl_requests);
232 	list_for_each_entry_safe_from(req, r, &connection->transfer_log, tl_requests) {
233 		struct drbd_peer_device *peer_device;
234 		if (req->epoch != expect_epoch)
235 			break;
236 		peer_device = conn_peer_device(connection, req->device->vnr);
237 		_req_mod(req, BARRIER_ACKED, peer_device);
238 	}
239 	spin_unlock_irq(&connection->resource->req_lock);
240 
241 	return;
242 
243 bail:
244 	spin_unlock_irq(&connection->resource->req_lock);
245 	conn_request_state(connection, NS(conn, C_PROTOCOL_ERROR), CS_HARD);
246 }
247 
248 
249 /**
250  * _tl_restart() - Walks the transfer log, and applies an action to all requests
251  * @connection:	DRBD connection to operate on.
252  * @what:       The action/event to perform with all request objects
253  *
254  * @what might be one of CONNECTION_LOST_WHILE_PENDING, RESEND, FAIL_FROZEN_DISK_IO,
255  * RESTART_FROZEN_DISK_IO.
256  */
257 /* must hold resource->req_lock */
_tl_restart(struct drbd_connection * connection,enum drbd_req_event what)258 void _tl_restart(struct drbd_connection *connection, enum drbd_req_event what)
259 {
260 	struct drbd_peer_device *peer_device;
261 	struct drbd_request *req, *r;
262 
263 	list_for_each_entry_safe(req, r, &connection->transfer_log, tl_requests) {
264 		peer_device = conn_peer_device(connection, req->device->vnr);
265 		_req_mod(req, what, peer_device);
266 	}
267 }
268 
tl_restart(struct drbd_connection * connection,enum drbd_req_event what)269 void tl_restart(struct drbd_connection *connection, enum drbd_req_event what)
270 {
271 	spin_lock_irq(&connection->resource->req_lock);
272 	_tl_restart(connection, what);
273 	spin_unlock_irq(&connection->resource->req_lock);
274 }
275 
276 /**
277  * tl_clear() - Clears all requests and &struct drbd_tl_epoch objects out of the TL
278  * @connection:	DRBD connection.
279  *
280  * This is called after the connection to the peer was lost. The storage covered
281  * by the requests on the transfer gets marked as our of sync. Called from the
282  * receiver thread and the worker thread.
283  */
tl_clear(struct drbd_connection * connection)284 void tl_clear(struct drbd_connection *connection)
285 {
286 	tl_restart(connection, CONNECTION_LOST_WHILE_PENDING);
287 }
288 
289 /**
290  * tl_abort_disk_io() - Abort disk I/O for all requests for a certain device in the TL
291  * @device:	DRBD device.
292  */
tl_abort_disk_io(struct drbd_device * device)293 void tl_abort_disk_io(struct drbd_device *device)
294 {
295 	struct drbd_connection *connection = first_peer_device(device)->connection;
296 	struct drbd_request *req, *r;
297 
298 	spin_lock_irq(&connection->resource->req_lock);
299 	list_for_each_entry_safe(req, r, &connection->transfer_log, tl_requests) {
300 		if (!(req->rq_state & RQ_LOCAL_PENDING))
301 			continue;
302 		if (req->device != device)
303 			continue;
304 		_req_mod(req, ABORT_DISK_IO, NULL);
305 	}
306 	spin_unlock_irq(&connection->resource->req_lock);
307 }
308 
drbd_thread_setup(void * arg)309 static int drbd_thread_setup(void *arg)
310 {
311 	struct drbd_thread *thi = (struct drbd_thread *) arg;
312 	struct drbd_resource *resource = thi->resource;
313 	unsigned long flags;
314 	int retval;
315 
316 	snprintf(current->comm, sizeof(current->comm), "drbd_%c_%s",
317 		 thi->name[0],
318 		 resource->name);
319 
320 	allow_kernel_signal(DRBD_SIGKILL);
321 	allow_kernel_signal(SIGXCPU);
322 restart:
323 	retval = thi->function(thi);
324 
325 	spin_lock_irqsave(&thi->t_lock, flags);
326 
327 	/* if the receiver has been "EXITING", the last thing it did
328 	 * was set the conn state to "StandAlone",
329 	 * if now a re-connect request comes in, conn state goes C_UNCONNECTED,
330 	 * and receiver thread will be "started".
331 	 * drbd_thread_start needs to set "RESTARTING" in that case.
332 	 * t_state check and assignment needs to be within the same spinlock,
333 	 * so either thread_start sees EXITING, and can remap to RESTARTING,
334 	 * or thread_start see NONE, and can proceed as normal.
335 	 */
336 
337 	if (thi->t_state == RESTARTING) {
338 		drbd_info(resource, "Restarting %s thread\n", thi->name);
339 		thi->t_state = RUNNING;
340 		spin_unlock_irqrestore(&thi->t_lock, flags);
341 		goto restart;
342 	}
343 
344 	thi->task = NULL;
345 	thi->t_state = NONE;
346 	smp_mb();
347 	complete_all(&thi->stop);
348 	spin_unlock_irqrestore(&thi->t_lock, flags);
349 
350 	drbd_info(resource, "Terminating %s\n", current->comm);
351 
352 	/* Release mod reference taken when thread was started */
353 
354 	if (thi->connection)
355 		kref_put(&thi->connection->kref, drbd_destroy_connection);
356 	kref_put(&resource->kref, drbd_destroy_resource);
357 	module_put(THIS_MODULE);
358 	return retval;
359 }
360 
drbd_thread_init(struct drbd_resource * resource,struct drbd_thread * thi,int (* func)(struct drbd_thread *),const char * name)361 static void drbd_thread_init(struct drbd_resource *resource, struct drbd_thread *thi,
362 			     int (*func) (struct drbd_thread *), const char *name)
363 {
364 	spin_lock_init(&thi->t_lock);
365 	thi->task    = NULL;
366 	thi->t_state = NONE;
367 	thi->function = func;
368 	thi->resource = resource;
369 	thi->connection = NULL;
370 	thi->name = name;
371 }
372 
drbd_thread_start(struct drbd_thread * thi)373 int drbd_thread_start(struct drbd_thread *thi)
374 {
375 	struct drbd_resource *resource = thi->resource;
376 	struct task_struct *nt;
377 	unsigned long flags;
378 
379 	/* is used from state engine doing drbd_thread_stop_nowait,
380 	 * while holding the req lock irqsave */
381 	spin_lock_irqsave(&thi->t_lock, flags);
382 
383 	switch (thi->t_state) {
384 	case NONE:
385 		drbd_info(resource, "Starting %s thread (from %s [%d])\n",
386 			 thi->name, current->comm, current->pid);
387 
388 		/* Get ref on module for thread - this is released when thread exits */
389 		if (!try_module_get(THIS_MODULE)) {
390 			drbd_err(resource, "Failed to get module reference in drbd_thread_start\n");
391 			spin_unlock_irqrestore(&thi->t_lock, flags);
392 			return false;
393 		}
394 
395 		kref_get(&resource->kref);
396 		if (thi->connection)
397 			kref_get(&thi->connection->kref);
398 
399 		init_completion(&thi->stop);
400 		thi->reset_cpu_mask = 1;
401 		thi->t_state = RUNNING;
402 		spin_unlock_irqrestore(&thi->t_lock, flags);
403 		flush_signals(current); /* otherw. may get -ERESTARTNOINTR */
404 
405 		nt = kthread_create(drbd_thread_setup, (void *) thi,
406 				    "drbd_%c_%s", thi->name[0], thi->resource->name);
407 
408 		if (IS_ERR(nt)) {
409 			drbd_err(resource, "Couldn't start thread\n");
410 
411 			if (thi->connection)
412 				kref_put(&thi->connection->kref, drbd_destroy_connection);
413 			kref_put(&resource->kref, drbd_destroy_resource);
414 			module_put(THIS_MODULE);
415 			return false;
416 		}
417 		spin_lock_irqsave(&thi->t_lock, flags);
418 		thi->task = nt;
419 		thi->t_state = RUNNING;
420 		spin_unlock_irqrestore(&thi->t_lock, flags);
421 		wake_up_process(nt);
422 		break;
423 	case EXITING:
424 		thi->t_state = RESTARTING;
425 		drbd_info(resource, "Restarting %s thread (from %s [%d])\n",
426 				thi->name, current->comm, current->pid);
427 		fallthrough;
428 	case RUNNING:
429 	case RESTARTING:
430 	default:
431 		spin_unlock_irqrestore(&thi->t_lock, flags);
432 		break;
433 	}
434 
435 	return true;
436 }
437 
438 
_drbd_thread_stop(struct drbd_thread * thi,int restart,int wait)439 void _drbd_thread_stop(struct drbd_thread *thi, int restart, int wait)
440 {
441 	unsigned long flags;
442 
443 	enum drbd_thread_state ns = restart ? RESTARTING : EXITING;
444 
445 	/* may be called from state engine, holding the req lock irqsave */
446 	spin_lock_irqsave(&thi->t_lock, flags);
447 
448 	if (thi->t_state == NONE) {
449 		spin_unlock_irqrestore(&thi->t_lock, flags);
450 		if (restart)
451 			drbd_thread_start(thi);
452 		return;
453 	}
454 
455 	if (thi->t_state != ns) {
456 		if (thi->task == NULL) {
457 			spin_unlock_irqrestore(&thi->t_lock, flags);
458 			return;
459 		}
460 
461 		thi->t_state = ns;
462 		smp_mb();
463 		init_completion(&thi->stop);
464 		if (thi->task != current)
465 			send_sig(DRBD_SIGKILL, thi->task, 1);
466 	}
467 
468 	spin_unlock_irqrestore(&thi->t_lock, flags);
469 
470 	if (wait)
471 		wait_for_completion(&thi->stop);
472 }
473 
474 #ifdef CONFIG_SMP
475 /*
476  * drbd_calc_cpu_mask() - Generate CPU masks, spread over all CPUs
477  *
478  * Forces all threads of a resource onto the same CPU. This is beneficial for
479  * DRBD's performance. May be overwritten by user's configuration.
480  */
drbd_calc_cpu_mask(cpumask_var_t * cpu_mask)481 static void drbd_calc_cpu_mask(cpumask_var_t *cpu_mask)
482 {
483 	unsigned int *resources_per_cpu, min_index = ~0;
484 
485 	resources_per_cpu = kcalloc(nr_cpu_ids, sizeof(*resources_per_cpu),
486 				    GFP_KERNEL);
487 	if (resources_per_cpu) {
488 		struct drbd_resource *resource;
489 		unsigned int cpu, min = ~0;
490 
491 		rcu_read_lock();
492 		for_each_resource_rcu(resource, &drbd_resources) {
493 			for_each_cpu(cpu, resource->cpu_mask)
494 				resources_per_cpu[cpu]++;
495 		}
496 		rcu_read_unlock();
497 		for_each_online_cpu(cpu) {
498 			if (resources_per_cpu[cpu] < min) {
499 				min = resources_per_cpu[cpu];
500 				min_index = cpu;
501 			}
502 		}
503 		kfree(resources_per_cpu);
504 	}
505 	if (min_index == ~0) {
506 		cpumask_setall(*cpu_mask);
507 		return;
508 	}
509 	cpumask_set_cpu(min_index, *cpu_mask);
510 }
511 
512 /**
513  * drbd_thread_current_set_cpu() - modifies the cpu mask of the _current_ thread
514  * @thi:	drbd_thread object
515  *
516  * call in the "main loop" of _all_ threads, no need for any mutex, current won't die
517  * prematurely.
518  */
drbd_thread_current_set_cpu(struct drbd_thread * thi)519 void drbd_thread_current_set_cpu(struct drbd_thread *thi)
520 {
521 	struct drbd_resource *resource = thi->resource;
522 	struct task_struct *p = current;
523 
524 	if (!thi->reset_cpu_mask)
525 		return;
526 	thi->reset_cpu_mask = 0;
527 	set_cpus_allowed_ptr(p, resource->cpu_mask);
528 }
529 #else
530 #define drbd_calc_cpu_mask(A) ({})
531 #endif
532 
533 /*
534  * drbd_header_size  -  size of a packet header
535  *
536  * The header size is a multiple of 8, so any payload following the header is
537  * word aligned on 64-bit architectures.  (The bitmap send and receive code
538  * relies on this.)
539  */
drbd_header_size(struct drbd_connection * connection)540 unsigned int drbd_header_size(struct drbd_connection *connection)
541 {
542 	if (connection->agreed_pro_version >= 100) {
543 		BUILD_BUG_ON(!IS_ALIGNED(sizeof(struct p_header100), 8));
544 		return sizeof(struct p_header100);
545 	} else {
546 		BUILD_BUG_ON(sizeof(struct p_header80) !=
547 			     sizeof(struct p_header95));
548 		BUILD_BUG_ON(!IS_ALIGNED(sizeof(struct p_header80), 8));
549 		return sizeof(struct p_header80);
550 	}
551 }
552 
prepare_header80(struct p_header80 * h,enum drbd_packet cmd,int size)553 static unsigned int prepare_header80(struct p_header80 *h, enum drbd_packet cmd, int size)
554 {
555 	h->magic   = cpu_to_be32(DRBD_MAGIC);
556 	h->command = cpu_to_be16(cmd);
557 	h->length  = cpu_to_be16(size);
558 	return sizeof(struct p_header80);
559 }
560 
prepare_header95(struct p_header95 * h,enum drbd_packet cmd,int size)561 static unsigned int prepare_header95(struct p_header95 *h, enum drbd_packet cmd, int size)
562 {
563 	h->magic   = cpu_to_be16(DRBD_MAGIC_BIG);
564 	h->command = cpu_to_be16(cmd);
565 	h->length = cpu_to_be32(size);
566 	return sizeof(struct p_header95);
567 }
568 
prepare_header100(struct p_header100 * h,enum drbd_packet cmd,int size,int vnr)569 static unsigned int prepare_header100(struct p_header100 *h, enum drbd_packet cmd,
570 				      int size, int vnr)
571 {
572 	h->magic = cpu_to_be32(DRBD_MAGIC_100);
573 	h->volume = cpu_to_be16(vnr);
574 	h->command = cpu_to_be16(cmd);
575 	h->length = cpu_to_be32(size);
576 	h->pad = 0;
577 	return sizeof(struct p_header100);
578 }
579 
prepare_header(struct drbd_connection * connection,int vnr,void * buffer,enum drbd_packet cmd,int size)580 static unsigned int prepare_header(struct drbd_connection *connection, int vnr,
581 				   void *buffer, enum drbd_packet cmd, int size)
582 {
583 	if (connection->agreed_pro_version >= 100)
584 		return prepare_header100(buffer, cmd, size, vnr);
585 	else if (connection->agreed_pro_version >= 95 &&
586 		 size > DRBD_MAX_SIZE_H80_PACKET)
587 		return prepare_header95(buffer, cmd, size);
588 	else
589 		return prepare_header80(buffer, cmd, size);
590 }
591 
__conn_prepare_command(struct drbd_connection * connection,struct drbd_socket * sock)592 static void *__conn_prepare_command(struct drbd_connection *connection,
593 				    struct drbd_socket *sock)
594 {
595 	if (!sock->socket)
596 		return NULL;
597 	return sock->sbuf + drbd_header_size(connection);
598 }
599 
conn_prepare_command(struct drbd_connection * connection,struct drbd_socket * sock)600 void *conn_prepare_command(struct drbd_connection *connection, struct drbd_socket *sock)
601 {
602 	void *p;
603 
604 	mutex_lock(&sock->mutex);
605 	p = __conn_prepare_command(connection, sock);
606 	if (!p)
607 		mutex_unlock(&sock->mutex);
608 
609 	return p;
610 }
611 
drbd_prepare_command(struct drbd_peer_device * peer_device,struct drbd_socket * sock)612 void *drbd_prepare_command(struct drbd_peer_device *peer_device, struct drbd_socket *sock)
613 {
614 	return conn_prepare_command(peer_device->connection, sock);
615 }
616 
__send_command(struct drbd_connection * connection,int vnr,struct drbd_socket * sock,enum drbd_packet cmd,unsigned int header_size,void * data,unsigned int size)617 static int __send_command(struct drbd_connection *connection, int vnr,
618 			  struct drbd_socket *sock, enum drbd_packet cmd,
619 			  unsigned int header_size, void *data,
620 			  unsigned int size)
621 {
622 	int msg_flags;
623 	int err;
624 
625 	/*
626 	 * Called with @data == NULL and the size of the data blocks in @size
627 	 * for commands that send data blocks.  For those commands, omit the
628 	 * MSG_MORE flag: this will increase the likelihood that data blocks
629 	 * which are page aligned on the sender will end up page aligned on the
630 	 * receiver.
631 	 */
632 	msg_flags = data ? MSG_MORE : 0;
633 
634 	header_size += prepare_header(connection, vnr, sock->sbuf, cmd,
635 				      header_size + size);
636 	err = drbd_send_all(connection, sock->socket, sock->sbuf, header_size,
637 			    msg_flags);
638 	if (data && !err)
639 		err = drbd_send_all(connection, sock->socket, data, size, 0);
640 	/* DRBD protocol "pings" are latency critical.
641 	 * This is supposed to trigger tcp_push_pending_frames() */
642 	if (!err && (cmd == P_PING || cmd == P_PING_ACK))
643 		tcp_sock_set_nodelay(sock->socket->sk);
644 
645 	return err;
646 }
647 
__conn_send_command(struct drbd_connection * connection,struct drbd_socket * sock,enum drbd_packet cmd,unsigned int header_size,void * data,unsigned int size)648 static int __conn_send_command(struct drbd_connection *connection, struct drbd_socket *sock,
649 			       enum drbd_packet cmd, unsigned int header_size,
650 			       void *data, unsigned int size)
651 {
652 	return __send_command(connection, 0, sock, cmd, header_size, data, size);
653 }
654 
conn_send_command(struct drbd_connection * connection,struct drbd_socket * sock,enum drbd_packet cmd,unsigned int header_size,void * data,unsigned int size)655 int conn_send_command(struct drbd_connection *connection, struct drbd_socket *sock,
656 		      enum drbd_packet cmd, unsigned int header_size,
657 		      void *data, unsigned int size)
658 {
659 	int err;
660 
661 	err = __conn_send_command(connection, sock, cmd, header_size, data, size);
662 	mutex_unlock(&sock->mutex);
663 	return err;
664 }
665 
drbd_send_command(struct drbd_peer_device * peer_device,struct drbd_socket * sock,enum drbd_packet cmd,unsigned int header_size,void * data,unsigned int size)666 int drbd_send_command(struct drbd_peer_device *peer_device, struct drbd_socket *sock,
667 		      enum drbd_packet cmd, unsigned int header_size,
668 		      void *data, unsigned int size)
669 {
670 	int err;
671 
672 	err = __send_command(peer_device->connection, peer_device->device->vnr,
673 			     sock, cmd, header_size, data, size);
674 	mutex_unlock(&sock->mutex);
675 	return err;
676 }
677 
drbd_send_ping(struct drbd_connection * connection)678 int drbd_send_ping(struct drbd_connection *connection)
679 {
680 	struct drbd_socket *sock;
681 
682 	sock = &connection->meta;
683 	if (!conn_prepare_command(connection, sock))
684 		return -EIO;
685 	return conn_send_command(connection, sock, P_PING, 0, NULL, 0);
686 }
687 
drbd_send_ping_ack(struct drbd_connection * connection)688 int drbd_send_ping_ack(struct drbd_connection *connection)
689 {
690 	struct drbd_socket *sock;
691 
692 	sock = &connection->meta;
693 	if (!conn_prepare_command(connection, sock))
694 		return -EIO;
695 	return conn_send_command(connection, sock, P_PING_ACK, 0, NULL, 0);
696 }
697 
drbd_send_sync_param(struct drbd_peer_device * peer_device)698 int drbd_send_sync_param(struct drbd_peer_device *peer_device)
699 {
700 	struct drbd_socket *sock;
701 	struct p_rs_param_95 *p;
702 	int size;
703 	const int apv = peer_device->connection->agreed_pro_version;
704 	enum drbd_packet cmd;
705 	struct net_conf *nc;
706 	struct disk_conf *dc;
707 
708 	sock = &peer_device->connection->data;
709 	p = drbd_prepare_command(peer_device, sock);
710 	if (!p)
711 		return -EIO;
712 
713 	rcu_read_lock();
714 	nc = rcu_dereference(peer_device->connection->net_conf);
715 
716 	size = apv <= 87 ? sizeof(struct p_rs_param)
717 		: apv == 88 ? sizeof(struct p_rs_param)
718 			+ strlen(nc->verify_alg) + 1
719 		: apv <= 94 ? sizeof(struct p_rs_param_89)
720 		: /* apv >= 95 */ sizeof(struct p_rs_param_95);
721 
722 	cmd = apv >= 89 ? P_SYNC_PARAM89 : P_SYNC_PARAM;
723 
724 	/* initialize verify_alg and csums_alg */
725 	BUILD_BUG_ON(sizeof(p->algs) != 2 * SHARED_SECRET_MAX);
726 	memset(&p->algs, 0, sizeof(p->algs));
727 
728 	if (get_ldev(peer_device->device)) {
729 		dc = rcu_dereference(peer_device->device->ldev->disk_conf);
730 		p->resync_rate = cpu_to_be32(dc->resync_rate);
731 		p->c_plan_ahead = cpu_to_be32(dc->c_plan_ahead);
732 		p->c_delay_target = cpu_to_be32(dc->c_delay_target);
733 		p->c_fill_target = cpu_to_be32(dc->c_fill_target);
734 		p->c_max_rate = cpu_to_be32(dc->c_max_rate);
735 		put_ldev(peer_device->device);
736 	} else {
737 		p->resync_rate = cpu_to_be32(DRBD_RESYNC_RATE_DEF);
738 		p->c_plan_ahead = cpu_to_be32(DRBD_C_PLAN_AHEAD_DEF);
739 		p->c_delay_target = cpu_to_be32(DRBD_C_DELAY_TARGET_DEF);
740 		p->c_fill_target = cpu_to_be32(DRBD_C_FILL_TARGET_DEF);
741 		p->c_max_rate = cpu_to_be32(DRBD_C_MAX_RATE_DEF);
742 	}
743 
744 	if (apv >= 88)
745 		strcpy(p->verify_alg, nc->verify_alg);
746 	if (apv >= 89)
747 		strcpy(p->csums_alg, nc->csums_alg);
748 	rcu_read_unlock();
749 
750 	return drbd_send_command(peer_device, sock, cmd, size, NULL, 0);
751 }
752 
__drbd_send_protocol(struct drbd_connection * connection,enum drbd_packet cmd)753 int __drbd_send_protocol(struct drbd_connection *connection, enum drbd_packet cmd)
754 {
755 	struct drbd_socket *sock;
756 	struct p_protocol *p;
757 	struct net_conf *nc;
758 	int size, cf;
759 
760 	sock = &connection->data;
761 	p = __conn_prepare_command(connection, sock);
762 	if (!p)
763 		return -EIO;
764 
765 	rcu_read_lock();
766 	nc = rcu_dereference(connection->net_conf);
767 
768 	if (nc->tentative && connection->agreed_pro_version < 92) {
769 		rcu_read_unlock();
770 		drbd_err(connection, "--dry-run is not supported by peer");
771 		return -EOPNOTSUPP;
772 	}
773 
774 	size = sizeof(*p);
775 	if (connection->agreed_pro_version >= 87)
776 		size += strlen(nc->integrity_alg) + 1;
777 
778 	p->protocol      = cpu_to_be32(nc->wire_protocol);
779 	p->after_sb_0p   = cpu_to_be32(nc->after_sb_0p);
780 	p->after_sb_1p   = cpu_to_be32(nc->after_sb_1p);
781 	p->after_sb_2p   = cpu_to_be32(nc->after_sb_2p);
782 	p->two_primaries = cpu_to_be32(nc->two_primaries);
783 	cf = 0;
784 	if (nc->discard_my_data)
785 		cf |= CF_DISCARD_MY_DATA;
786 	if (nc->tentative)
787 		cf |= CF_DRY_RUN;
788 	p->conn_flags    = cpu_to_be32(cf);
789 
790 	if (connection->agreed_pro_version >= 87)
791 		strcpy(p->integrity_alg, nc->integrity_alg);
792 	rcu_read_unlock();
793 
794 	return __conn_send_command(connection, sock, cmd, size, NULL, 0);
795 }
796 
drbd_send_protocol(struct drbd_connection * connection)797 int drbd_send_protocol(struct drbd_connection *connection)
798 {
799 	int err;
800 
801 	mutex_lock(&connection->data.mutex);
802 	err = __drbd_send_protocol(connection, P_PROTOCOL);
803 	mutex_unlock(&connection->data.mutex);
804 
805 	return err;
806 }
807 
_drbd_send_uuids(struct drbd_peer_device * peer_device,u64 uuid_flags)808 static int _drbd_send_uuids(struct drbd_peer_device *peer_device, u64 uuid_flags)
809 {
810 	struct drbd_device *device = peer_device->device;
811 	struct drbd_socket *sock;
812 	struct p_uuids *p;
813 	int i;
814 
815 	if (!get_ldev_if_state(device, D_NEGOTIATING))
816 		return 0;
817 
818 	sock = &peer_device->connection->data;
819 	p = drbd_prepare_command(peer_device, sock);
820 	if (!p) {
821 		put_ldev(device);
822 		return -EIO;
823 	}
824 	spin_lock_irq(&device->ldev->md.uuid_lock);
825 	for (i = UI_CURRENT; i < UI_SIZE; i++)
826 		p->uuid[i] = cpu_to_be64(device->ldev->md.uuid[i]);
827 	spin_unlock_irq(&device->ldev->md.uuid_lock);
828 
829 	device->comm_bm_set = drbd_bm_total_weight(device);
830 	p->uuid[UI_SIZE] = cpu_to_be64(device->comm_bm_set);
831 	rcu_read_lock();
832 	uuid_flags |= rcu_dereference(peer_device->connection->net_conf)->discard_my_data ? 1 : 0;
833 	rcu_read_unlock();
834 	uuid_flags |= test_bit(CRASHED_PRIMARY, &device->flags) ? 2 : 0;
835 	uuid_flags |= device->new_state_tmp.disk == D_INCONSISTENT ? 4 : 0;
836 	p->uuid[UI_FLAGS] = cpu_to_be64(uuid_flags);
837 
838 	put_ldev(device);
839 	return drbd_send_command(peer_device, sock, P_UUIDS, sizeof(*p), NULL, 0);
840 }
841 
drbd_send_uuids(struct drbd_peer_device * peer_device)842 int drbd_send_uuids(struct drbd_peer_device *peer_device)
843 {
844 	return _drbd_send_uuids(peer_device, 0);
845 }
846 
drbd_send_uuids_skip_initial_sync(struct drbd_peer_device * peer_device)847 int drbd_send_uuids_skip_initial_sync(struct drbd_peer_device *peer_device)
848 {
849 	return _drbd_send_uuids(peer_device, 8);
850 }
851 
drbd_print_uuids(struct drbd_device * device,const char * text)852 void drbd_print_uuids(struct drbd_device *device, const char *text)
853 {
854 	if (get_ldev_if_state(device, D_NEGOTIATING)) {
855 		u64 *uuid = device->ldev->md.uuid;
856 		drbd_info(device, "%s %016llX:%016llX:%016llX:%016llX\n",
857 		     text,
858 		     (unsigned long long)uuid[UI_CURRENT],
859 		     (unsigned long long)uuid[UI_BITMAP],
860 		     (unsigned long long)uuid[UI_HISTORY_START],
861 		     (unsigned long long)uuid[UI_HISTORY_END]);
862 		put_ldev(device);
863 	} else {
864 		drbd_info(device, "%s effective data uuid: %016llX\n",
865 				text,
866 				(unsigned long long)device->ed_uuid);
867 	}
868 }
869 
drbd_gen_and_send_sync_uuid(struct drbd_peer_device * peer_device)870 void drbd_gen_and_send_sync_uuid(struct drbd_peer_device *peer_device)
871 {
872 	struct drbd_device *device = peer_device->device;
873 	struct drbd_socket *sock;
874 	struct p_rs_uuid *p;
875 	u64 uuid;
876 
877 	D_ASSERT(device, device->state.disk == D_UP_TO_DATE);
878 
879 	uuid = device->ldev->md.uuid[UI_BITMAP];
880 	if (uuid && uuid != UUID_JUST_CREATED)
881 		uuid = uuid + UUID_NEW_BM_OFFSET;
882 	else
883 		get_random_bytes(&uuid, sizeof(u64));
884 	drbd_uuid_set(device, UI_BITMAP, uuid);
885 	drbd_print_uuids(device, "updated sync UUID");
886 	drbd_md_sync(device);
887 
888 	sock = &peer_device->connection->data;
889 	p = drbd_prepare_command(peer_device, sock);
890 	if (p) {
891 		p->uuid = cpu_to_be64(uuid);
892 		drbd_send_command(peer_device, sock, P_SYNC_UUID, sizeof(*p), NULL, 0);
893 	}
894 }
895 
drbd_send_sizes(struct drbd_peer_device * peer_device,int trigger_reply,enum dds_flags flags)896 int drbd_send_sizes(struct drbd_peer_device *peer_device, int trigger_reply, enum dds_flags flags)
897 {
898 	struct drbd_device *device = peer_device->device;
899 	struct drbd_socket *sock;
900 	struct p_sizes *p;
901 	sector_t d_size, u_size;
902 	int q_order_type;
903 	unsigned int max_bio_size;
904 	unsigned int packet_size;
905 
906 	sock = &peer_device->connection->data;
907 	p = drbd_prepare_command(peer_device, sock);
908 	if (!p)
909 		return -EIO;
910 
911 	packet_size = sizeof(*p);
912 	if (peer_device->connection->agreed_features & DRBD_FF_WSAME)
913 		packet_size += sizeof(p->qlim[0]);
914 
915 	memset(p, 0, packet_size);
916 	if (get_ldev_if_state(device, D_NEGOTIATING)) {
917 		struct block_device *bdev = device->ldev->backing_bdev;
918 		struct request_queue *q = bdev_get_queue(bdev);
919 
920 		d_size = drbd_get_max_capacity(device->ldev);
921 		rcu_read_lock();
922 		u_size = rcu_dereference(device->ldev->disk_conf)->disk_size;
923 		rcu_read_unlock();
924 		q_order_type = drbd_queue_order_type(device);
925 		max_bio_size = queue_max_hw_sectors(q) << 9;
926 		max_bio_size = min(max_bio_size, DRBD_MAX_BIO_SIZE);
927 		p->qlim->physical_block_size =
928 			cpu_to_be32(bdev_physical_block_size(bdev));
929 		p->qlim->logical_block_size =
930 			cpu_to_be32(bdev_logical_block_size(bdev));
931 		p->qlim->alignment_offset =
932 			cpu_to_be32(bdev_alignment_offset(bdev));
933 		p->qlim->io_min = cpu_to_be32(bdev_io_min(bdev));
934 		p->qlim->io_opt = cpu_to_be32(bdev_io_opt(bdev));
935 		p->qlim->discard_enabled = !!bdev_max_discard_sectors(bdev);
936 		put_ldev(device);
937 	} else {
938 		struct request_queue *q = device->rq_queue;
939 
940 		p->qlim->physical_block_size =
941 			cpu_to_be32(queue_physical_block_size(q));
942 		p->qlim->logical_block_size =
943 			cpu_to_be32(queue_logical_block_size(q));
944 		p->qlim->alignment_offset = 0;
945 		p->qlim->io_min = cpu_to_be32(queue_io_min(q));
946 		p->qlim->io_opt = cpu_to_be32(queue_io_opt(q));
947 		p->qlim->discard_enabled = 0;
948 
949 		d_size = 0;
950 		u_size = 0;
951 		q_order_type = QUEUE_ORDERED_NONE;
952 		max_bio_size = DRBD_MAX_BIO_SIZE; /* ... multiple BIOs per peer_request */
953 	}
954 
955 	if (peer_device->connection->agreed_pro_version <= 94)
956 		max_bio_size = min(max_bio_size, DRBD_MAX_SIZE_H80_PACKET);
957 	else if (peer_device->connection->agreed_pro_version < 100)
958 		max_bio_size = min(max_bio_size, DRBD_MAX_BIO_SIZE_P95);
959 
960 	p->d_size = cpu_to_be64(d_size);
961 	p->u_size = cpu_to_be64(u_size);
962 	if (trigger_reply)
963 		p->c_size = 0;
964 	else
965 		p->c_size = cpu_to_be64(get_capacity(device->vdisk));
966 	p->max_bio_size = cpu_to_be32(max_bio_size);
967 	p->queue_order_type = cpu_to_be16(q_order_type);
968 	p->dds_flags = cpu_to_be16(flags);
969 
970 	return drbd_send_command(peer_device, sock, P_SIZES, packet_size, NULL, 0);
971 }
972 
973 /**
974  * drbd_send_current_state() - Sends the drbd state to the peer
975  * @peer_device:	DRBD peer device.
976  */
drbd_send_current_state(struct drbd_peer_device * peer_device)977 int drbd_send_current_state(struct drbd_peer_device *peer_device)
978 {
979 	struct drbd_socket *sock;
980 	struct p_state *p;
981 
982 	sock = &peer_device->connection->data;
983 	p = drbd_prepare_command(peer_device, sock);
984 	if (!p)
985 		return -EIO;
986 	p->state = cpu_to_be32(peer_device->device->state.i); /* Within the send mutex */
987 	return drbd_send_command(peer_device, sock, P_STATE, sizeof(*p), NULL, 0);
988 }
989 
990 /**
991  * drbd_send_state() - After a state change, sends the new state to the peer
992  * @peer_device:      DRBD peer device.
993  * @state:     the state to send, not necessarily the current state.
994  *
995  * Each state change queues an "after_state_ch" work, which will eventually
996  * send the resulting new state to the peer. If more state changes happen
997  * between queuing and processing of the after_state_ch work, we still
998  * want to send each intermediary state in the order it occurred.
999  */
drbd_send_state(struct drbd_peer_device * peer_device,union drbd_state state)1000 int drbd_send_state(struct drbd_peer_device *peer_device, union drbd_state state)
1001 {
1002 	struct drbd_socket *sock;
1003 	struct p_state *p;
1004 
1005 	sock = &peer_device->connection->data;
1006 	p = drbd_prepare_command(peer_device, sock);
1007 	if (!p)
1008 		return -EIO;
1009 	p->state = cpu_to_be32(state.i); /* Within the send mutex */
1010 	return drbd_send_command(peer_device, sock, P_STATE, sizeof(*p), NULL, 0);
1011 }
1012 
drbd_send_state_req(struct drbd_peer_device * peer_device,union drbd_state mask,union drbd_state val)1013 int drbd_send_state_req(struct drbd_peer_device *peer_device, union drbd_state mask, union drbd_state val)
1014 {
1015 	struct drbd_socket *sock;
1016 	struct p_req_state *p;
1017 
1018 	sock = &peer_device->connection->data;
1019 	p = drbd_prepare_command(peer_device, sock);
1020 	if (!p)
1021 		return -EIO;
1022 	p->mask = cpu_to_be32(mask.i);
1023 	p->val = cpu_to_be32(val.i);
1024 	return drbd_send_command(peer_device, sock, P_STATE_CHG_REQ, sizeof(*p), NULL, 0);
1025 }
1026 
conn_send_state_req(struct drbd_connection * connection,union drbd_state mask,union drbd_state val)1027 int conn_send_state_req(struct drbd_connection *connection, union drbd_state mask, union drbd_state val)
1028 {
1029 	enum drbd_packet cmd;
1030 	struct drbd_socket *sock;
1031 	struct p_req_state *p;
1032 
1033 	cmd = connection->agreed_pro_version < 100 ? P_STATE_CHG_REQ : P_CONN_ST_CHG_REQ;
1034 	sock = &connection->data;
1035 	p = conn_prepare_command(connection, sock);
1036 	if (!p)
1037 		return -EIO;
1038 	p->mask = cpu_to_be32(mask.i);
1039 	p->val = cpu_to_be32(val.i);
1040 	return conn_send_command(connection, sock, cmd, sizeof(*p), NULL, 0);
1041 }
1042 
drbd_send_sr_reply(struct drbd_peer_device * peer_device,enum drbd_state_rv retcode)1043 void drbd_send_sr_reply(struct drbd_peer_device *peer_device, enum drbd_state_rv retcode)
1044 {
1045 	struct drbd_socket *sock;
1046 	struct p_req_state_reply *p;
1047 
1048 	sock = &peer_device->connection->meta;
1049 	p = drbd_prepare_command(peer_device, sock);
1050 	if (p) {
1051 		p->retcode = cpu_to_be32(retcode);
1052 		drbd_send_command(peer_device, sock, P_STATE_CHG_REPLY, sizeof(*p), NULL, 0);
1053 	}
1054 }
1055 
conn_send_sr_reply(struct drbd_connection * connection,enum drbd_state_rv retcode)1056 void conn_send_sr_reply(struct drbd_connection *connection, enum drbd_state_rv retcode)
1057 {
1058 	struct drbd_socket *sock;
1059 	struct p_req_state_reply *p;
1060 	enum drbd_packet cmd = connection->agreed_pro_version < 100 ? P_STATE_CHG_REPLY : P_CONN_ST_CHG_REPLY;
1061 
1062 	sock = &connection->meta;
1063 	p = conn_prepare_command(connection, sock);
1064 	if (p) {
1065 		p->retcode = cpu_to_be32(retcode);
1066 		conn_send_command(connection, sock, cmd, sizeof(*p), NULL, 0);
1067 	}
1068 }
1069 
dcbp_set_code(struct p_compressed_bm * p,enum drbd_bitmap_code code)1070 static void dcbp_set_code(struct p_compressed_bm *p, enum drbd_bitmap_code code)
1071 {
1072 	BUG_ON(code & ~0xf);
1073 	p->encoding = (p->encoding & ~0xf) | code;
1074 }
1075 
dcbp_set_start(struct p_compressed_bm * p,int set)1076 static void dcbp_set_start(struct p_compressed_bm *p, int set)
1077 {
1078 	p->encoding = (p->encoding & ~0x80) | (set ? 0x80 : 0);
1079 }
1080 
dcbp_set_pad_bits(struct p_compressed_bm * p,int n)1081 static void dcbp_set_pad_bits(struct p_compressed_bm *p, int n)
1082 {
1083 	BUG_ON(n & ~0x7);
1084 	p->encoding = (p->encoding & (~0x7 << 4)) | (n << 4);
1085 }
1086 
fill_bitmap_rle_bits(struct drbd_device * device,struct p_compressed_bm * p,unsigned int size,struct bm_xfer_ctx * c)1087 static int fill_bitmap_rle_bits(struct drbd_device *device,
1088 			 struct p_compressed_bm *p,
1089 			 unsigned int size,
1090 			 struct bm_xfer_ctx *c)
1091 {
1092 	struct bitstream bs;
1093 	unsigned long plain_bits;
1094 	unsigned long tmp;
1095 	unsigned long rl;
1096 	unsigned len;
1097 	unsigned toggle;
1098 	int bits, use_rle;
1099 
1100 	/* may we use this feature? */
1101 	rcu_read_lock();
1102 	use_rle = rcu_dereference(first_peer_device(device)->connection->net_conf)->use_rle;
1103 	rcu_read_unlock();
1104 	if (!use_rle || first_peer_device(device)->connection->agreed_pro_version < 90)
1105 		return 0;
1106 
1107 	if (c->bit_offset >= c->bm_bits)
1108 		return 0; /* nothing to do. */
1109 
1110 	/* use at most thus many bytes */
1111 	bitstream_init(&bs, p->code, size, 0);
1112 	memset(p->code, 0, size);
1113 	/* plain bits covered in this code string */
1114 	plain_bits = 0;
1115 
1116 	/* p->encoding & 0x80 stores whether the first run length is set.
1117 	 * bit offset is implicit.
1118 	 * start with toggle == 2 to be able to tell the first iteration */
1119 	toggle = 2;
1120 
1121 	/* see how much plain bits we can stuff into one packet
1122 	 * using RLE and VLI. */
1123 	do {
1124 		tmp = (toggle == 0) ? _drbd_bm_find_next_zero(device, c->bit_offset)
1125 				    : _drbd_bm_find_next(device, c->bit_offset);
1126 		if (tmp == -1UL)
1127 			tmp = c->bm_bits;
1128 		rl = tmp - c->bit_offset;
1129 
1130 		if (toggle == 2) { /* first iteration */
1131 			if (rl == 0) {
1132 				/* the first checked bit was set,
1133 				 * store start value, */
1134 				dcbp_set_start(p, 1);
1135 				/* but skip encoding of zero run length */
1136 				toggle = !toggle;
1137 				continue;
1138 			}
1139 			dcbp_set_start(p, 0);
1140 		}
1141 
1142 		/* paranoia: catch zero runlength.
1143 		 * can only happen if bitmap is modified while we scan it. */
1144 		if (rl == 0) {
1145 			drbd_err(device, "unexpected zero runlength while encoding bitmap "
1146 			    "t:%u bo:%lu\n", toggle, c->bit_offset);
1147 			return -1;
1148 		}
1149 
1150 		bits = vli_encode_bits(&bs, rl);
1151 		if (bits == -ENOBUFS) /* buffer full */
1152 			break;
1153 		if (bits <= 0) {
1154 			drbd_err(device, "error while encoding bitmap: %d\n", bits);
1155 			return 0;
1156 		}
1157 
1158 		toggle = !toggle;
1159 		plain_bits += rl;
1160 		c->bit_offset = tmp;
1161 	} while (c->bit_offset < c->bm_bits);
1162 
1163 	len = bs.cur.b - p->code + !!bs.cur.bit;
1164 
1165 	if (plain_bits < (len << 3)) {
1166 		/* incompressible with this method.
1167 		 * we need to rewind both word and bit position. */
1168 		c->bit_offset -= plain_bits;
1169 		bm_xfer_ctx_bit_to_word_offset(c);
1170 		c->bit_offset = c->word_offset * BITS_PER_LONG;
1171 		return 0;
1172 	}
1173 
1174 	/* RLE + VLI was able to compress it just fine.
1175 	 * update c->word_offset. */
1176 	bm_xfer_ctx_bit_to_word_offset(c);
1177 
1178 	/* store pad_bits */
1179 	dcbp_set_pad_bits(p, (8 - bs.cur.bit) & 0x7);
1180 
1181 	return len;
1182 }
1183 
1184 /*
1185  * send_bitmap_rle_or_plain
1186  *
1187  * Return 0 when done, 1 when another iteration is needed, and a negative error
1188  * code upon failure.
1189  */
1190 static int
send_bitmap_rle_or_plain(struct drbd_peer_device * peer_device,struct bm_xfer_ctx * c)1191 send_bitmap_rle_or_plain(struct drbd_peer_device *peer_device, struct bm_xfer_ctx *c)
1192 {
1193 	struct drbd_device *device = peer_device->device;
1194 	struct drbd_socket *sock = &peer_device->connection->data;
1195 	unsigned int header_size = drbd_header_size(peer_device->connection);
1196 	struct p_compressed_bm *p = sock->sbuf + header_size;
1197 	int len, err;
1198 
1199 	len = fill_bitmap_rle_bits(device, p,
1200 			DRBD_SOCKET_BUFFER_SIZE - header_size - sizeof(*p), c);
1201 	if (len < 0)
1202 		return -EIO;
1203 
1204 	if (len) {
1205 		dcbp_set_code(p, RLE_VLI_Bits);
1206 		err = __send_command(peer_device->connection, device->vnr, sock,
1207 				     P_COMPRESSED_BITMAP, sizeof(*p) + len,
1208 				     NULL, 0);
1209 		c->packets[0]++;
1210 		c->bytes[0] += header_size + sizeof(*p) + len;
1211 
1212 		if (c->bit_offset >= c->bm_bits)
1213 			len = 0; /* DONE */
1214 	} else {
1215 		/* was not compressible.
1216 		 * send a buffer full of plain text bits instead. */
1217 		unsigned int data_size;
1218 		unsigned long num_words;
1219 		unsigned long *p = sock->sbuf + header_size;
1220 
1221 		data_size = DRBD_SOCKET_BUFFER_SIZE - header_size;
1222 		num_words = min_t(size_t, data_size / sizeof(*p),
1223 				  c->bm_words - c->word_offset);
1224 		len = num_words * sizeof(*p);
1225 		if (len)
1226 			drbd_bm_get_lel(device, c->word_offset, num_words, p);
1227 		err = __send_command(peer_device->connection, device->vnr, sock, P_BITMAP,
1228 				     len, NULL, 0);
1229 		c->word_offset += num_words;
1230 		c->bit_offset = c->word_offset * BITS_PER_LONG;
1231 
1232 		c->packets[1]++;
1233 		c->bytes[1] += header_size + len;
1234 
1235 		if (c->bit_offset > c->bm_bits)
1236 			c->bit_offset = c->bm_bits;
1237 	}
1238 	if (!err) {
1239 		if (len == 0) {
1240 			INFO_bm_xfer_stats(peer_device, "send", c);
1241 			return 0;
1242 		} else
1243 			return 1;
1244 	}
1245 	return -EIO;
1246 }
1247 
1248 /* See the comment at receive_bitmap() */
_drbd_send_bitmap(struct drbd_device * device,struct drbd_peer_device * peer_device)1249 static int _drbd_send_bitmap(struct drbd_device *device,
1250 			    struct drbd_peer_device *peer_device)
1251 {
1252 	struct bm_xfer_ctx c;
1253 	int err;
1254 
1255 	if (!expect(device, device->bitmap))
1256 		return false;
1257 
1258 	if (get_ldev(device)) {
1259 		if (drbd_md_test_flag(device->ldev, MDF_FULL_SYNC)) {
1260 			drbd_info(device, "Writing the whole bitmap, MDF_FullSync was set.\n");
1261 			drbd_bm_set_all(device);
1262 			if (drbd_bm_write(device, peer_device)) {
1263 				/* write_bm did fail! Leave full sync flag set in Meta P_DATA
1264 				 * but otherwise process as per normal - need to tell other
1265 				 * side that a full resync is required! */
1266 				drbd_err(device, "Failed to write bitmap to disk!\n");
1267 			} else {
1268 				drbd_md_clear_flag(device, MDF_FULL_SYNC);
1269 				drbd_md_sync(device);
1270 			}
1271 		}
1272 		put_ldev(device);
1273 	}
1274 
1275 	c = (struct bm_xfer_ctx) {
1276 		.bm_bits = drbd_bm_bits(device),
1277 		.bm_words = drbd_bm_words(device),
1278 	};
1279 
1280 	do {
1281 		err = send_bitmap_rle_or_plain(peer_device, &c);
1282 	} while (err > 0);
1283 
1284 	return err == 0;
1285 }
1286 
drbd_send_bitmap(struct drbd_device * device,struct drbd_peer_device * peer_device)1287 int drbd_send_bitmap(struct drbd_device *device, struct drbd_peer_device *peer_device)
1288 {
1289 	struct drbd_socket *sock = &peer_device->connection->data;
1290 	int err = -1;
1291 
1292 	mutex_lock(&sock->mutex);
1293 	if (sock->socket)
1294 		err = !_drbd_send_bitmap(device, peer_device);
1295 	mutex_unlock(&sock->mutex);
1296 	return err;
1297 }
1298 
drbd_send_b_ack(struct drbd_connection * connection,u32 barrier_nr,u32 set_size)1299 void drbd_send_b_ack(struct drbd_connection *connection, u32 barrier_nr, u32 set_size)
1300 {
1301 	struct drbd_socket *sock;
1302 	struct p_barrier_ack *p;
1303 
1304 	if (connection->cstate < C_WF_REPORT_PARAMS)
1305 		return;
1306 
1307 	sock = &connection->meta;
1308 	p = conn_prepare_command(connection, sock);
1309 	if (!p)
1310 		return;
1311 	p->barrier = barrier_nr;
1312 	p->set_size = cpu_to_be32(set_size);
1313 	conn_send_command(connection, sock, P_BARRIER_ACK, sizeof(*p), NULL, 0);
1314 }
1315 
1316 /**
1317  * _drbd_send_ack() - Sends an ack packet
1318  * @peer_device:	DRBD peer device.
1319  * @cmd:		Packet command code.
1320  * @sector:		sector, needs to be in big endian byte order
1321  * @blksize:		size in byte, needs to be in big endian byte order
1322  * @block_id:		Id, big endian byte order
1323  */
_drbd_send_ack(struct drbd_peer_device * peer_device,enum drbd_packet cmd,u64 sector,u32 blksize,u64 block_id)1324 static int _drbd_send_ack(struct drbd_peer_device *peer_device, enum drbd_packet cmd,
1325 			  u64 sector, u32 blksize, u64 block_id)
1326 {
1327 	struct drbd_socket *sock;
1328 	struct p_block_ack *p;
1329 
1330 	if (peer_device->device->state.conn < C_CONNECTED)
1331 		return -EIO;
1332 
1333 	sock = &peer_device->connection->meta;
1334 	p = drbd_prepare_command(peer_device, sock);
1335 	if (!p)
1336 		return -EIO;
1337 	p->sector = sector;
1338 	p->block_id = block_id;
1339 	p->blksize = blksize;
1340 	p->seq_num = cpu_to_be32(atomic_inc_return(&peer_device->device->packet_seq));
1341 	return drbd_send_command(peer_device, sock, cmd, sizeof(*p), NULL, 0);
1342 }
1343 
1344 /* dp->sector and dp->block_id already/still in network byte order,
1345  * data_size is payload size according to dp->head,
1346  * and may need to be corrected for digest size. */
drbd_send_ack_dp(struct drbd_peer_device * peer_device,enum drbd_packet cmd,struct p_data * dp,int data_size)1347 void drbd_send_ack_dp(struct drbd_peer_device *peer_device, enum drbd_packet cmd,
1348 		      struct p_data *dp, int data_size)
1349 {
1350 	if (peer_device->connection->peer_integrity_tfm)
1351 		data_size -= crypto_shash_digestsize(peer_device->connection->peer_integrity_tfm);
1352 	_drbd_send_ack(peer_device, cmd, dp->sector, cpu_to_be32(data_size),
1353 		       dp->block_id);
1354 }
1355 
drbd_send_ack_rp(struct drbd_peer_device * peer_device,enum drbd_packet cmd,struct p_block_req * rp)1356 void drbd_send_ack_rp(struct drbd_peer_device *peer_device, enum drbd_packet cmd,
1357 		      struct p_block_req *rp)
1358 {
1359 	_drbd_send_ack(peer_device, cmd, rp->sector, rp->blksize, rp->block_id);
1360 }
1361 
1362 /**
1363  * drbd_send_ack() - Sends an ack packet
1364  * @peer_device:	DRBD peer device
1365  * @cmd:		packet command code
1366  * @peer_req:		peer request
1367  */
drbd_send_ack(struct drbd_peer_device * peer_device,enum drbd_packet cmd,struct drbd_peer_request * peer_req)1368 int drbd_send_ack(struct drbd_peer_device *peer_device, enum drbd_packet cmd,
1369 		  struct drbd_peer_request *peer_req)
1370 {
1371 	return _drbd_send_ack(peer_device, cmd,
1372 			      cpu_to_be64(peer_req->i.sector),
1373 			      cpu_to_be32(peer_req->i.size),
1374 			      peer_req->block_id);
1375 }
1376 
1377 /* This function misuses the block_id field to signal if the blocks
1378  * are is sync or not. */
drbd_send_ack_ex(struct drbd_peer_device * peer_device,enum drbd_packet cmd,sector_t sector,int blksize,u64 block_id)1379 int drbd_send_ack_ex(struct drbd_peer_device *peer_device, enum drbd_packet cmd,
1380 		     sector_t sector, int blksize, u64 block_id)
1381 {
1382 	return _drbd_send_ack(peer_device, cmd,
1383 			      cpu_to_be64(sector),
1384 			      cpu_to_be32(blksize),
1385 			      cpu_to_be64(block_id));
1386 }
1387 
drbd_send_rs_deallocated(struct drbd_peer_device * peer_device,struct drbd_peer_request * peer_req)1388 int drbd_send_rs_deallocated(struct drbd_peer_device *peer_device,
1389 			     struct drbd_peer_request *peer_req)
1390 {
1391 	struct drbd_socket *sock;
1392 	struct p_block_desc *p;
1393 
1394 	sock = &peer_device->connection->data;
1395 	p = drbd_prepare_command(peer_device, sock);
1396 	if (!p)
1397 		return -EIO;
1398 	p->sector = cpu_to_be64(peer_req->i.sector);
1399 	p->blksize = cpu_to_be32(peer_req->i.size);
1400 	p->pad = 0;
1401 	return drbd_send_command(peer_device, sock, P_RS_DEALLOCATED, sizeof(*p), NULL, 0);
1402 }
1403 
drbd_send_drequest(struct drbd_peer_device * peer_device,int cmd,sector_t sector,int size,u64 block_id)1404 int drbd_send_drequest(struct drbd_peer_device *peer_device, int cmd,
1405 		       sector_t sector, int size, u64 block_id)
1406 {
1407 	struct drbd_socket *sock;
1408 	struct p_block_req *p;
1409 
1410 	sock = &peer_device->connection->data;
1411 	p = drbd_prepare_command(peer_device, sock);
1412 	if (!p)
1413 		return -EIO;
1414 	p->sector = cpu_to_be64(sector);
1415 	p->block_id = block_id;
1416 	p->blksize = cpu_to_be32(size);
1417 	return drbd_send_command(peer_device, sock, cmd, sizeof(*p), NULL, 0);
1418 }
1419 
drbd_send_drequest_csum(struct drbd_peer_device * peer_device,sector_t sector,int size,void * digest,int digest_size,enum drbd_packet cmd)1420 int drbd_send_drequest_csum(struct drbd_peer_device *peer_device, sector_t sector, int size,
1421 			    void *digest, int digest_size, enum drbd_packet cmd)
1422 {
1423 	struct drbd_socket *sock;
1424 	struct p_block_req *p;
1425 
1426 	/* FIXME: Put the digest into the preallocated socket buffer.  */
1427 
1428 	sock = &peer_device->connection->data;
1429 	p = drbd_prepare_command(peer_device, sock);
1430 	if (!p)
1431 		return -EIO;
1432 	p->sector = cpu_to_be64(sector);
1433 	p->block_id = ID_SYNCER /* unused */;
1434 	p->blksize = cpu_to_be32(size);
1435 	return drbd_send_command(peer_device, sock, cmd, sizeof(*p), digest, digest_size);
1436 }
1437 
drbd_send_ov_request(struct drbd_peer_device * peer_device,sector_t sector,int size)1438 int drbd_send_ov_request(struct drbd_peer_device *peer_device, sector_t sector, int size)
1439 {
1440 	struct drbd_socket *sock;
1441 	struct p_block_req *p;
1442 
1443 	sock = &peer_device->connection->data;
1444 	p = drbd_prepare_command(peer_device, sock);
1445 	if (!p)
1446 		return -EIO;
1447 	p->sector = cpu_to_be64(sector);
1448 	p->block_id = ID_SYNCER /* unused */;
1449 	p->blksize = cpu_to_be32(size);
1450 	return drbd_send_command(peer_device, sock, P_OV_REQUEST, sizeof(*p), NULL, 0);
1451 }
1452 
1453 /* called on sndtimeo
1454  * returns false if we should retry,
1455  * true if we think connection is dead
1456  */
we_should_drop_the_connection(struct drbd_connection * connection,struct socket * sock)1457 static int we_should_drop_the_connection(struct drbd_connection *connection, struct socket *sock)
1458 {
1459 	int drop_it;
1460 	/* long elapsed = (long)(jiffies - device->last_received); */
1461 
1462 	drop_it =   connection->meta.socket == sock
1463 		|| !connection->ack_receiver.task
1464 		|| get_t_state(&connection->ack_receiver) != RUNNING
1465 		|| connection->cstate < C_WF_REPORT_PARAMS;
1466 
1467 	if (drop_it)
1468 		return true;
1469 
1470 	drop_it = !--connection->ko_count;
1471 	if (!drop_it) {
1472 		drbd_err(connection, "[%s/%d] sock_sendmsg time expired, ko = %u\n",
1473 			 current->comm, current->pid, connection->ko_count);
1474 		request_ping(connection);
1475 	}
1476 
1477 	return drop_it; /* && (device->state == R_PRIMARY) */;
1478 }
1479 
drbd_update_congested(struct drbd_connection * connection)1480 static void drbd_update_congested(struct drbd_connection *connection)
1481 {
1482 	struct sock *sk = connection->data.socket->sk;
1483 	if (sk->sk_wmem_queued > sk->sk_sndbuf * 4 / 5)
1484 		set_bit(NET_CONGESTED, &connection->flags);
1485 }
1486 
1487 /* The idea of sendpage seems to be to put some kind of reference
1488  * to the page into the skb, and to hand it over to the NIC. In
1489  * this process get_page() gets called.
1490  *
1491  * As soon as the page was really sent over the network put_page()
1492  * gets called by some part of the network layer. [ NIC driver? ]
1493  *
1494  * [ get_page() / put_page() increment/decrement the count. If count
1495  *   reaches 0 the page will be freed. ]
1496  *
1497  * This works nicely with pages from FSs.
1498  * But this means that in protocol A we might signal IO completion too early!
1499  *
1500  * In order not to corrupt data during a resync we must make sure
1501  * that we do not reuse our own buffer pages (EEs) to early, therefore
1502  * we have the net_ee list.
1503  *
1504  * XFS seems to have problems, still, it submits pages with page_count == 0!
1505  * As a workaround, we disable sendpage on pages
1506  * with page_count == 0 or PageSlab.
1507  */
_drbd_no_send_page(struct drbd_peer_device * peer_device,struct page * page,int offset,size_t size,unsigned msg_flags)1508 static int _drbd_no_send_page(struct drbd_peer_device *peer_device, struct page *page,
1509 			      int offset, size_t size, unsigned msg_flags)
1510 {
1511 	struct socket *socket;
1512 	void *addr;
1513 	int err;
1514 
1515 	socket = peer_device->connection->data.socket;
1516 	addr = kmap(page) + offset;
1517 	err = drbd_send_all(peer_device->connection, socket, addr, size, msg_flags);
1518 	kunmap(page);
1519 	if (!err)
1520 		peer_device->device->send_cnt += size >> 9;
1521 	return err;
1522 }
1523 
_drbd_send_page(struct drbd_peer_device * peer_device,struct page * page,int offset,size_t size,unsigned msg_flags)1524 static int _drbd_send_page(struct drbd_peer_device *peer_device, struct page *page,
1525 		    int offset, size_t size, unsigned msg_flags)
1526 {
1527 	struct socket *socket = peer_device->connection->data.socket;
1528 	struct msghdr msg = { .msg_flags = msg_flags, };
1529 	struct bio_vec bvec;
1530 	int len = size;
1531 	int err = -EIO;
1532 
1533 	/* e.g. XFS meta- & log-data is in slab pages, which have a
1534 	 * page_count of 0 and/or have PageSlab() set.
1535 	 * we cannot use send_page for those, as that does get_page();
1536 	 * put_page(); and would cause either a VM_BUG directly, or
1537 	 * __page_cache_release a page that would actually still be referenced
1538 	 * by someone, leading to some obscure delayed Oops somewhere else. */
1539 	if (!drbd_disable_sendpage && sendpages_ok(page, len, offset))
1540 		msg.msg_flags |= MSG_NOSIGNAL | MSG_SPLICE_PAGES;
1541 
1542 	drbd_update_congested(peer_device->connection);
1543 	do {
1544 		int sent;
1545 
1546 		bvec_set_page(&bvec, page, len, offset);
1547 		iov_iter_bvec(&msg.msg_iter, ITER_SOURCE, &bvec, 1, len);
1548 
1549 		sent = sock_sendmsg(socket, &msg);
1550 		if (sent <= 0) {
1551 			if (sent == -EAGAIN) {
1552 				if (we_should_drop_the_connection(peer_device->connection, socket))
1553 					break;
1554 				continue;
1555 			}
1556 			drbd_warn(peer_device->device, "%s: size=%d len=%d sent=%d\n",
1557 			     __func__, (int)size, len, sent);
1558 			if (sent < 0)
1559 				err = sent;
1560 			break;
1561 		}
1562 		len    -= sent;
1563 		offset += sent;
1564 	} while (len > 0 /* THINK && device->cstate >= C_CONNECTED*/);
1565 	clear_bit(NET_CONGESTED, &peer_device->connection->flags);
1566 
1567 	if (len == 0) {
1568 		err = 0;
1569 		peer_device->device->send_cnt += size >> 9;
1570 	}
1571 	return err;
1572 }
1573 
_drbd_send_bio(struct drbd_peer_device * peer_device,struct bio * bio)1574 static int _drbd_send_bio(struct drbd_peer_device *peer_device, struct bio *bio)
1575 {
1576 	struct bio_vec bvec;
1577 	struct bvec_iter iter;
1578 
1579 	/* hint all but last page with MSG_MORE */
1580 	bio_for_each_segment(bvec, bio, iter) {
1581 		int err;
1582 
1583 		err = _drbd_no_send_page(peer_device, bvec.bv_page,
1584 					 bvec.bv_offset, bvec.bv_len,
1585 					 bio_iter_last(bvec, iter)
1586 					 ? 0 : MSG_MORE);
1587 		if (err)
1588 			return err;
1589 	}
1590 	return 0;
1591 }
1592 
_drbd_send_zc_bio(struct drbd_peer_device * peer_device,struct bio * bio)1593 static int _drbd_send_zc_bio(struct drbd_peer_device *peer_device, struct bio *bio)
1594 {
1595 	struct bio_vec bvec;
1596 	struct bvec_iter iter;
1597 
1598 	/* hint all but last page with MSG_MORE */
1599 	bio_for_each_segment(bvec, bio, iter) {
1600 		int err;
1601 
1602 		err = _drbd_send_page(peer_device, bvec.bv_page,
1603 				      bvec.bv_offset, bvec.bv_len,
1604 				      bio_iter_last(bvec, iter) ? 0 : MSG_MORE);
1605 		if (err)
1606 			return err;
1607 	}
1608 	return 0;
1609 }
1610 
_drbd_send_zc_ee(struct drbd_peer_device * peer_device,struct drbd_peer_request * peer_req)1611 static int _drbd_send_zc_ee(struct drbd_peer_device *peer_device,
1612 			    struct drbd_peer_request *peer_req)
1613 {
1614 	struct page *page = peer_req->pages;
1615 	unsigned len = peer_req->i.size;
1616 	int err;
1617 
1618 	/* hint all but last page with MSG_MORE */
1619 	page_chain_for_each(page) {
1620 		unsigned l = min_t(unsigned, len, PAGE_SIZE);
1621 
1622 		err = _drbd_send_page(peer_device, page, 0, l,
1623 				      page_chain_next(page) ? MSG_MORE : 0);
1624 		if (err)
1625 			return err;
1626 		len -= l;
1627 	}
1628 	return 0;
1629 }
1630 
bio_flags_to_wire(struct drbd_connection * connection,struct bio * bio)1631 static u32 bio_flags_to_wire(struct drbd_connection *connection,
1632 			     struct bio *bio)
1633 {
1634 	if (connection->agreed_pro_version >= 95)
1635 		return  (bio->bi_opf & REQ_SYNC ? DP_RW_SYNC : 0) |
1636 			(bio->bi_opf & REQ_FUA ? DP_FUA : 0) |
1637 			(bio->bi_opf & REQ_PREFLUSH ? DP_FLUSH : 0) |
1638 			(bio_op(bio) == REQ_OP_DISCARD ? DP_DISCARD : 0) |
1639 			(bio_op(bio) == REQ_OP_WRITE_ZEROES ?
1640 			  ((connection->agreed_features & DRBD_FF_WZEROES) ?
1641 			   (DP_ZEROES |(!(bio->bi_opf & REQ_NOUNMAP) ? DP_DISCARD : 0))
1642 			   : DP_DISCARD)
1643 			: 0);
1644 	else
1645 		return bio->bi_opf & REQ_SYNC ? DP_RW_SYNC : 0;
1646 }
1647 
1648 /* Used to send write or TRIM aka REQ_OP_DISCARD requests
1649  * R_PRIMARY -> Peer	(P_DATA, P_TRIM)
1650  */
drbd_send_dblock(struct drbd_peer_device * peer_device,struct drbd_request * req)1651 int drbd_send_dblock(struct drbd_peer_device *peer_device, struct drbd_request *req)
1652 {
1653 	struct drbd_device *device = peer_device->device;
1654 	struct drbd_socket *sock;
1655 	struct p_data *p;
1656 	void *digest_out;
1657 	unsigned int dp_flags = 0;
1658 	int digest_size;
1659 	int err;
1660 
1661 	sock = &peer_device->connection->data;
1662 	p = drbd_prepare_command(peer_device, sock);
1663 	digest_size = peer_device->connection->integrity_tfm ?
1664 		      crypto_shash_digestsize(peer_device->connection->integrity_tfm) : 0;
1665 
1666 	if (!p)
1667 		return -EIO;
1668 	p->sector = cpu_to_be64(req->i.sector);
1669 	p->block_id = (unsigned long)req;
1670 	p->seq_num = cpu_to_be32(atomic_inc_return(&device->packet_seq));
1671 	dp_flags = bio_flags_to_wire(peer_device->connection, req->master_bio);
1672 	if (device->state.conn >= C_SYNC_SOURCE &&
1673 	    device->state.conn <= C_PAUSED_SYNC_T)
1674 		dp_flags |= DP_MAY_SET_IN_SYNC;
1675 	if (peer_device->connection->agreed_pro_version >= 100) {
1676 		if (req->rq_state & RQ_EXP_RECEIVE_ACK)
1677 			dp_flags |= DP_SEND_RECEIVE_ACK;
1678 		/* During resync, request an explicit write ack,
1679 		 * even in protocol != C */
1680 		if (req->rq_state & RQ_EXP_WRITE_ACK
1681 		|| (dp_flags & DP_MAY_SET_IN_SYNC))
1682 			dp_flags |= DP_SEND_WRITE_ACK;
1683 	}
1684 	p->dp_flags = cpu_to_be32(dp_flags);
1685 
1686 	if (dp_flags & (DP_DISCARD|DP_ZEROES)) {
1687 		enum drbd_packet cmd = (dp_flags & DP_ZEROES) ? P_ZEROES : P_TRIM;
1688 		struct p_trim *t = (struct p_trim*)p;
1689 		t->size = cpu_to_be32(req->i.size);
1690 		err = __send_command(peer_device->connection, device->vnr, sock, cmd, sizeof(*t), NULL, 0);
1691 		goto out;
1692 	}
1693 	digest_out = p + 1;
1694 
1695 	/* our digest is still only over the payload.
1696 	 * TRIM does not carry any payload. */
1697 	if (digest_size)
1698 		drbd_csum_bio(peer_device->connection->integrity_tfm, req->master_bio, digest_out);
1699 	err = __send_command(peer_device->connection, device->vnr, sock, P_DATA,
1700 			     sizeof(*p) + digest_size, NULL, req->i.size);
1701 	if (!err) {
1702 		/* For protocol A, we have to memcpy the payload into
1703 		 * socket buffers, as we may complete right away
1704 		 * as soon as we handed it over to tcp, at which point the data
1705 		 * pages may become invalid.
1706 		 *
1707 		 * For data-integrity enabled, we copy it as well, so we can be
1708 		 * sure that even if the bio pages may still be modified, it
1709 		 * won't change the data on the wire, thus if the digest checks
1710 		 * out ok after sending on this side, but does not fit on the
1711 		 * receiving side, we sure have detected corruption elsewhere.
1712 		 */
1713 		if (!(req->rq_state & (RQ_EXP_RECEIVE_ACK | RQ_EXP_WRITE_ACK)) || digest_size)
1714 			err = _drbd_send_bio(peer_device, req->master_bio);
1715 		else
1716 			err = _drbd_send_zc_bio(peer_device, req->master_bio);
1717 
1718 		/* double check digest, sometimes buffers have been modified in flight. */
1719 		if (digest_size > 0 && digest_size <= 64) {
1720 			/* 64 byte, 512 bit, is the largest digest size
1721 			 * currently supported in kernel crypto. */
1722 			unsigned char digest[64];
1723 			drbd_csum_bio(peer_device->connection->integrity_tfm, req->master_bio, digest);
1724 			if (memcmp(p + 1, digest, digest_size)) {
1725 				drbd_warn(device,
1726 					"Digest mismatch, buffer modified by upper layers during write: %llus +%u\n",
1727 					(unsigned long long)req->i.sector, req->i.size);
1728 			}
1729 		} /* else if (digest_size > 64) {
1730 		     ... Be noisy about digest too large ...
1731 		} */
1732 	}
1733 out:
1734 	mutex_unlock(&sock->mutex);  /* locked by drbd_prepare_command() */
1735 
1736 	return err;
1737 }
1738 
1739 /* answer packet, used to send data back for read requests:
1740  *  Peer       -> (diskless) R_PRIMARY   (P_DATA_REPLY)
1741  *  C_SYNC_SOURCE -> C_SYNC_TARGET         (P_RS_DATA_REPLY)
1742  */
drbd_send_block(struct drbd_peer_device * peer_device,enum drbd_packet cmd,struct drbd_peer_request * peer_req)1743 int drbd_send_block(struct drbd_peer_device *peer_device, enum drbd_packet cmd,
1744 		    struct drbd_peer_request *peer_req)
1745 {
1746 	struct drbd_device *device = peer_device->device;
1747 	struct drbd_socket *sock;
1748 	struct p_data *p;
1749 	int err;
1750 	int digest_size;
1751 
1752 	sock = &peer_device->connection->data;
1753 	p = drbd_prepare_command(peer_device, sock);
1754 
1755 	digest_size = peer_device->connection->integrity_tfm ?
1756 		      crypto_shash_digestsize(peer_device->connection->integrity_tfm) : 0;
1757 
1758 	if (!p)
1759 		return -EIO;
1760 	p->sector = cpu_to_be64(peer_req->i.sector);
1761 	p->block_id = peer_req->block_id;
1762 	p->seq_num = 0;  /* unused */
1763 	p->dp_flags = 0;
1764 	if (digest_size)
1765 		drbd_csum_ee(peer_device->connection->integrity_tfm, peer_req, p + 1);
1766 	err = __send_command(peer_device->connection, device->vnr, sock, cmd, sizeof(*p) + digest_size, NULL, peer_req->i.size);
1767 	if (!err)
1768 		err = _drbd_send_zc_ee(peer_device, peer_req);
1769 	mutex_unlock(&sock->mutex);  /* locked by drbd_prepare_command() */
1770 
1771 	return err;
1772 }
1773 
drbd_send_out_of_sync(struct drbd_peer_device * peer_device,struct drbd_request * req)1774 int drbd_send_out_of_sync(struct drbd_peer_device *peer_device, struct drbd_request *req)
1775 {
1776 	struct drbd_socket *sock;
1777 	struct p_block_desc *p;
1778 
1779 	sock = &peer_device->connection->data;
1780 	p = drbd_prepare_command(peer_device, sock);
1781 	if (!p)
1782 		return -EIO;
1783 	p->sector = cpu_to_be64(req->i.sector);
1784 	p->blksize = cpu_to_be32(req->i.size);
1785 	return drbd_send_command(peer_device, sock, P_OUT_OF_SYNC, sizeof(*p), NULL, 0);
1786 }
1787 
1788 /*
1789   drbd_send distinguishes two cases:
1790 
1791   Packets sent via the data socket "sock"
1792   and packets sent via the meta data socket "msock"
1793 
1794 		    sock                      msock
1795   -----------------+-------------------------+------------------------------
1796   timeout           conf.timeout / 2          conf.timeout / 2
1797   timeout action    send a ping via msock     Abort communication
1798 					      and close all sockets
1799 */
1800 
1801 /*
1802  * you must have down()ed the appropriate [m]sock_mutex elsewhere!
1803  */
drbd_send(struct drbd_connection * connection,struct socket * sock,void * buf,size_t size,unsigned msg_flags)1804 int drbd_send(struct drbd_connection *connection, struct socket *sock,
1805 	      void *buf, size_t size, unsigned msg_flags)
1806 {
1807 	struct kvec iov = {.iov_base = buf, .iov_len = size};
1808 	struct msghdr msg = {.msg_flags = msg_flags | MSG_NOSIGNAL};
1809 	int rv, sent = 0;
1810 
1811 	if (!sock)
1812 		return -EBADR;
1813 
1814 	/* THINK  if (signal_pending) return ... ? */
1815 
1816 	iov_iter_kvec(&msg.msg_iter, ITER_SOURCE, &iov, 1, size);
1817 
1818 	if (sock == connection->data.socket) {
1819 		rcu_read_lock();
1820 		connection->ko_count = rcu_dereference(connection->net_conf)->ko_count;
1821 		rcu_read_unlock();
1822 		drbd_update_congested(connection);
1823 	}
1824 	do {
1825 		rv = sock_sendmsg(sock, &msg);
1826 		if (rv == -EAGAIN) {
1827 			if (we_should_drop_the_connection(connection, sock))
1828 				break;
1829 			else
1830 				continue;
1831 		}
1832 		if (rv == -EINTR) {
1833 			flush_signals(current);
1834 			rv = 0;
1835 		}
1836 		if (rv < 0)
1837 			break;
1838 		sent += rv;
1839 	} while (sent < size);
1840 
1841 	if (sock == connection->data.socket)
1842 		clear_bit(NET_CONGESTED, &connection->flags);
1843 
1844 	if (rv <= 0) {
1845 		if (rv != -EAGAIN) {
1846 			drbd_err(connection, "%s_sendmsg returned %d\n",
1847 				 sock == connection->meta.socket ? "msock" : "sock",
1848 				 rv);
1849 			conn_request_state(connection, NS(conn, C_BROKEN_PIPE), CS_HARD);
1850 		} else
1851 			conn_request_state(connection, NS(conn, C_TIMEOUT), CS_HARD);
1852 	}
1853 
1854 	return sent;
1855 }
1856 
1857 /*
1858  * drbd_send_all  -  Send an entire buffer
1859  *
1860  * Returns 0 upon success and a negative error value otherwise.
1861  */
drbd_send_all(struct drbd_connection * connection,struct socket * sock,void * buffer,size_t size,unsigned msg_flags)1862 int drbd_send_all(struct drbd_connection *connection, struct socket *sock, void *buffer,
1863 		  size_t size, unsigned msg_flags)
1864 {
1865 	int err;
1866 
1867 	err = drbd_send(connection, sock, buffer, size, msg_flags);
1868 	if (err < 0)
1869 		return err;
1870 	if (err != size)
1871 		return -EIO;
1872 	return 0;
1873 }
1874 
drbd_open(struct gendisk * disk,blk_mode_t mode)1875 static int drbd_open(struct gendisk *disk, blk_mode_t mode)
1876 {
1877 	struct drbd_device *device = disk->private_data;
1878 	unsigned long flags;
1879 	int rv = 0;
1880 
1881 	mutex_lock(&drbd_main_mutex);
1882 	spin_lock_irqsave(&device->resource->req_lock, flags);
1883 	/* to have a stable device->state.role
1884 	 * and no race with updating open_cnt */
1885 
1886 	if (device->state.role != R_PRIMARY) {
1887 		if (mode & BLK_OPEN_WRITE)
1888 			rv = -EROFS;
1889 		else if (!drbd_allow_oos)
1890 			rv = -EMEDIUMTYPE;
1891 	}
1892 
1893 	if (!rv)
1894 		device->open_cnt++;
1895 	spin_unlock_irqrestore(&device->resource->req_lock, flags);
1896 	mutex_unlock(&drbd_main_mutex);
1897 
1898 	return rv;
1899 }
1900 
drbd_release(struct gendisk * gd)1901 static void drbd_release(struct gendisk *gd)
1902 {
1903 	struct drbd_device *device = gd->private_data;
1904 
1905 	mutex_lock(&drbd_main_mutex);
1906 	device->open_cnt--;
1907 	mutex_unlock(&drbd_main_mutex);
1908 }
1909 
1910 /* need to hold resource->req_lock */
drbd_queue_unplug(struct drbd_device * device)1911 void drbd_queue_unplug(struct drbd_device *device)
1912 {
1913 	if (device->state.pdsk >= D_INCONSISTENT && device->state.conn >= C_CONNECTED) {
1914 		D_ASSERT(device, device->state.role == R_PRIMARY);
1915 		if (test_and_clear_bit(UNPLUG_REMOTE, &device->flags)) {
1916 			drbd_queue_work_if_unqueued(
1917 				&first_peer_device(device)->connection->sender_work,
1918 				&device->unplug_work);
1919 		}
1920 	}
1921 }
1922 
drbd_set_defaults(struct drbd_device * device)1923 static void drbd_set_defaults(struct drbd_device *device)
1924 {
1925 	/* Beware! The actual layout differs
1926 	 * between big endian and little endian */
1927 	device->state = (union drbd_dev_state) {
1928 		{ .role = R_SECONDARY,
1929 		  .peer = R_UNKNOWN,
1930 		  .conn = C_STANDALONE,
1931 		  .disk = D_DISKLESS,
1932 		  .pdsk = D_UNKNOWN,
1933 		} };
1934 }
1935 
drbd_init_set_defaults(struct drbd_device * device)1936 void drbd_init_set_defaults(struct drbd_device *device)
1937 {
1938 	/* the memset(,0,) did most of this.
1939 	 * note: only assignments, no allocation in here */
1940 
1941 	drbd_set_defaults(device);
1942 
1943 	atomic_set(&device->ap_bio_cnt, 0);
1944 	atomic_set(&device->ap_actlog_cnt, 0);
1945 	atomic_set(&device->ap_pending_cnt, 0);
1946 	atomic_set(&device->rs_pending_cnt, 0);
1947 	atomic_set(&device->unacked_cnt, 0);
1948 	atomic_set(&device->local_cnt, 0);
1949 	atomic_set(&device->pp_in_use_by_net, 0);
1950 	atomic_set(&device->rs_sect_in, 0);
1951 	atomic_set(&device->rs_sect_ev, 0);
1952 	atomic_set(&device->ap_in_flight, 0);
1953 	atomic_set(&device->md_io.in_use, 0);
1954 
1955 	mutex_init(&device->own_state_mutex);
1956 	device->state_mutex = &device->own_state_mutex;
1957 
1958 	spin_lock_init(&device->al_lock);
1959 	spin_lock_init(&device->peer_seq_lock);
1960 
1961 	INIT_LIST_HEAD(&device->active_ee);
1962 	INIT_LIST_HEAD(&device->sync_ee);
1963 	INIT_LIST_HEAD(&device->done_ee);
1964 	INIT_LIST_HEAD(&device->read_ee);
1965 	INIT_LIST_HEAD(&device->net_ee);
1966 	INIT_LIST_HEAD(&device->resync_reads);
1967 	INIT_LIST_HEAD(&device->resync_work.list);
1968 	INIT_LIST_HEAD(&device->unplug_work.list);
1969 	INIT_LIST_HEAD(&device->bm_io_work.w.list);
1970 	INIT_LIST_HEAD(&device->pending_master_completion[0]);
1971 	INIT_LIST_HEAD(&device->pending_master_completion[1]);
1972 	INIT_LIST_HEAD(&device->pending_completion[0]);
1973 	INIT_LIST_HEAD(&device->pending_completion[1]);
1974 
1975 	device->resync_work.cb  = w_resync_timer;
1976 	device->unplug_work.cb  = w_send_write_hint;
1977 	device->bm_io_work.w.cb = w_bitmap_io;
1978 
1979 	timer_setup(&device->resync_timer, resync_timer_fn, 0);
1980 	timer_setup(&device->md_sync_timer, md_sync_timer_fn, 0);
1981 	timer_setup(&device->start_resync_timer, start_resync_timer_fn, 0);
1982 	timer_setup(&device->request_timer, request_timer_fn, 0);
1983 
1984 	init_waitqueue_head(&device->misc_wait);
1985 	init_waitqueue_head(&device->state_wait);
1986 	init_waitqueue_head(&device->ee_wait);
1987 	init_waitqueue_head(&device->al_wait);
1988 	init_waitqueue_head(&device->seq_wait);
1989 
1990 	device->resync_wenr = LC_FREE;
1991 	device->peer_max_bio_size = DRBD_MAX_BIO_SIZE_SAFE;
1992 	device->local_max_bio_size = DRBD_MAX_BIO_SIZE_SAFE;
1993 }
1994 
drbd_set_my_capacity(struct drbd_device * device,sector_t size)1995 void drbd_set_my_capacity(struct drbd_device *device, sector_t size)
1996 {
1997 	char ppb[10];
1998 
1999 	set_capacity_and_notify(device->vdisk, size);
2000 
2001 	drbd_info(device, "size = %s (%llu KB)\n",
2002 		ppsize(ppb, size>>1), (unsigned long long)size>>1);
2003 }
2004 
drbd_device_cleanup(struct drbd_device * device)2005 void drbd_device_cleanup(struct drbd_device *device)
2006 {
2007 	int i;
2008 	if (first_peer_device(device)->connection->receiver.t_state != NONE)
2009 		drbd_err(device, "ASSERT FAILED: receiver t_state == %d expected 0.\n",
2010 				first_peer_device(device)->connection->receiver.t_state);
2011 
2012 	device->al_writ_cnt  =
2013 	device->bm_writ_cnt  =
2014 	device->read_cnt     =
2015 	device->recv_cnt     =
2016 	device->send_cnt     =
2017 	device->writ_cnt     =
2018 	device->p_size       =
2019 	device->rs_start     =
2020 	device->rs_total     =
2021 	device->rs_failed    = 0;
2022 	device->rs_last_events = 0;
2023 	device->rs_last_sect_ev = 0;
2024 	for (i = 0; i < DRBD_SYNC_MARKS; i++) {
2025 		device->rs_mark_left[i] = 0;
2026 		device->rs_mark_time[i] = 0;
2027 	}
2028 	D_ASSERT(device, first_peer_device(device)->connection->net_conf == NULL);
2029 
2030 	set_capacity_and_notify(device->vdisk, 0);
2031 	if (device->bitmap) {
2032 		/* maybe never allocated. */
2033 		drbd_bm_resize(device, 0, 1);
2034 		drbd_bm_cleanup(device);
2035 	}
2036 
2037 	drbd_backing_dev_free(device, device->ldev);
2038 	device->ldev = NULL;
2039 
2040 	clear_bit(AL_SUSPENDED, &device->flags);
2041 
2042 	D_ASSERT(device, list_empty(&device->active_ee));
2043 	D_ASSERT(device, list_empty(&device->sync_ee));
2044 	D_ASSERT(device, list_empty(&device->done_ee));
2045 	D_ASSERT(device, list_empty(&device->read_ee));
2046 	D_ASSERT(device, list_empty(&device->net_ee));
2047 	D_ASSERT(device, list_empty(&device->resync_reads));
2048 	D_ASSERT(device, list_empty(&first_peer_device(device)->connection->sender_work.q));
2049 	D_ASSERT(device, list_empty(&device->resync_work.list));
2050 	D_ASSERT(device, list_empty(&device->unplug_work.list));
2051 
2052 	drbd_set_defaults(device);
2053 }
2054 
2055 
drbd_destroy_mempools(void)2056 static void drbd_destroy_mempools(void)
2057 {
2058 	struct page *page;
2059 
2060 	while (drbd_pp_pool) {
2061 		page = drbd_pp_pool;
2062 		drbd_pp_pool = (struct page *)page_private(page);
2063 		__free_page(page);
2064 		drbd_pp_vacant--;
2065 	}
2066 
2067 	/* D_ASSERT(device, atomic_read(&drbd_pp_vacant)==0); */
2068 
2069 	bioset_exit(&drbd_io_bio_set);
2070 	bioset_exit(&drbd_md_io_bio_set);
2071 	mempool_exit(&drbd_md_io_page_pool);
2072 	mempool_exit(&drbd_ee_mempool);
2073 	mempool_exit(&drbd_request_mempool);
2074 	kmem_cache_destroy(drbd_ee_cache);
2075 	kmem_cache_destroy(drbd_request_cache);
2076 	kmem_cache_destroy(drbd_bm_ext_cache);
2077 	kmem_cache_destroy(drbd_al_ext_cache);
2078 
2079 	drbd_ee_cache        = NULL;
2080 	drbd_request_cache   = NULL;
2081 	drbd_bm_ext_cache    = NULL;
2082 	drbd_al_ext_cache    = NULL;
2083 
2084 	return;
2085 }
2086 
drbd_create_mempools(void)2087 static int drbd_create_mempools(void)
2088 {
2089 	struct page *page;
2090 	const int number = (DRBD_MAX_BIO_SIZE/PAGE_SIZE) * drbd_minor_count;
2091 	int i, ret;
2092 
2093 	/* caches */
2094 	drbd_request_cache = kmem_cache_create(
2095 		"drbd_req", sizeof(struct drbd_request), 0, 0, NULL);
2096 	if (drbd_request_cache == NULL)
2097 		goto Enomem;
2098 
2099 	drbd_ee_cache = kmem_cache_create(
2100 		"drbd_ee", sizeof(struct drbd_peer_request), 0, 0, NULL);
2101 	if (drbd_ee_cache == NULL)
2102 		goto Enomem;
2103 
2104 	drbd_bm_ext_cache = kmem_cache_create(
2105 		"drbd_bm", sizeof(struct bm_extent), 0, 0, NULL);
2106 	if (drbd_bm_ext_cache == NULL)
2107 		goto Enomem;
2108 
2109 	drbd_al_ext_cache = kmem_cache_create(
2110 		"drbd_al", sizeof(struct lc_element), 0, 0, NULL);
2111 	if (drbd_al_ext_cache == NULL)
2112 		goto Enomem;
2113 
2114 	/* mempools */
2115 	ret = bioset_init(&drbd_io_bio_set, BIO_POOL_SIZE, 0, 0);
2116 	if (ret)
2117 		goto Enomem;
2118 
2119 	ret = bioset_init(&drbd_md_io_bio_set, DRBD_MIN_POOL_PAGES, 0,
2120 			  BIOSET_NEED_BVECS);
2121 	if (ret)
2122 		goto Enomem;
2123 
2124 	ret = mempool_init_page_pool(&drbd_md_io_page_pool, DRBD_MIN_POOL_PAGES, 0);
2125 	if (ret)
2126 		goto Enomem;
2127 
2128 	ret = mempool_init_slab_pool(&drbd_request_mempool, number,
2129 				     drbd_request_cache);
2130 	if (ret)
2131 		goto Enomem;
2132 
2133 	ret = mempool_init_slab_pool(&drbd_ee_mempool, number, drbd_ee_cache);
2134 	if (ret)
2135 		goto Enomem;
2136 
2137 	for (i = 0; i < number; i++) {
2138 		page = alloc_page(GFP_HIGHUSER);
2139 		if (!page)
2140 			goto Enomem;
2141 		set_page_private(page, (unsigned long)drbd_pp_pool);
2142 		drbd_pp_pool = page;
2143 	}
2144 	drbd_pp_vacant = number;
2145 
2146 	return 0;
2147 
2148 Enomem:
2149 	drbd_destroy_mempools(); /* in case we allocated some */
2150 	return -ENOMEM;
2151 }
2152 
drbd_release_all_peer_reqs(struct drbd_device * device)2153 static void drbd_release_all_peer_reqs(struct drbd_device *device)
2154 {
2155 	int rr;
2156 
2157 	rr = drbd_free_peer_reqs(device, &device->active_ee);
2158 	if (rr)
2159 		drbd_err(device, "%d EEs in active list found!\n", rr);
2160 
2161 	rr = drbd_free_peer_reqs(device, &device->sync_ee);
2162 	if (rr)
2163 		drbd_err(device, "%d EEs in sync list found!\n", rr);
2164 
2165 	rr = drbd_free_peer_reqs(device, &device->read_ee);
2166 	if (rr)
2167 		drbd_err(device, "%d EEs in read list found!\n", rr);
2168 
2169 	rr = drbd_free_peer_reqs(device, &device->done_ee);
2170 	if (rr)
2171 		drbd_err(device, "%d EEs in done list found!\n", rr);
2172 
2173 	rr = drbd_free_peer_reqs(device, &device->net_ee);
2174 	if (rr)
2175 		drbd_err(device, "%d EEs in net list found!\n", rr);
2176 }
2177 
2178 /* caution. no locking. */
drbd_destroy_device(struct kref * kref)2179 void drbd_destroy_device(struct kref *kref)
2180 {
2181 	struct drbd_device *device = container_of(kref, struct drbd_device, kref);
2182 	struct drbd_resource *resource = device->resource;
2183 	struct drbd_peer_device *peer_device, *tmp_peer_device;
2184 
2185 	timer_shutdown_sync(&device->request_timer);
2186 
2187 	/* paranoia asserts */
2188 	D_ASSERT(device, device->open_cnt == 0);
2189 	/* end paranoia asserts */
2190 
2191 	/* cleanup stuff that may have been allocated during
2192 	 * device (re-)configuration or state changes */
2193 
2194 	drbd_backing_dev_free(device, device->ldev);
2195 	device->ldev = NULL;
2196 
2197 	drbd_release_all_peer_reqs(device);
2198 
2199 	lc_destroy(device->act_log);
2200 	lc_destroy(device->resync);
2201 
2202 	kfree(device->p_uuid);
2203 	/* device->p_uuid = NULL; */
2204 
2205 	if (device->bitmap) /* should no longer be there. */
2206 		drbd_bm_cleanup(device);
2207 	__free_page(device->md_io.page);
2208 	put_disk(device->vdisk);
2209 	kfree(device->rs_plan_s);
2210 
2211 	/* not for_each_connection(connection, resource):
2212 	 * those may have been cleaned up and disassociated already.
2213 	 */
2214 	for_each_peer_device_safe(peer_device, tmp_peer_device, device) {
2215 		kref_put(&peer_device->connection->kref, drbd_destroy_connection);
2216 		kfree(peer_device);
2217 	}
2218 	if (device->submit.wq)
2219 		destroy_workqueue(device->submit.wq);
2220 	kfree(device);
2221 	kref_put(&resource->kref, drbd_destroy_resource);
2222 }
2223 
2224 /* One global retry thread, if we need to push back some bio and have it
2225  * reinserted through our make request function.
2226  */
2227 static struct retry_worker {
2228 	struct workqueue_struct *wq;
2229 	struct work_struct worker;
2230 
2231 	spinlock_t lock;
2232 	struct list_head writes;
2233 } retry;
2234 
do_retry(struct work_struct * ws)2235 static void do_retry(struct work_struct *ws)
2236 {
2237 	struct retry_worker *retry = container_of(ws, struct retry_worker, worker);
2238 	LIST_HEAD(writes);
2239 	struct drbd_request *req, *tmp;
2240 
2241 	spin_lock_irq(&retry->lock);
2242 	list_splice_init(&retry->writes, &writes);
2243 	spin_unlock_irq(&retry->lock);
2244 
2245 	list_for_each_entry_safe(req, tmp, &writes, tl_requests) {
2246 		struct drbd_device *device = req->device;
2247 		struct bio *bio = req->master_bio;
2248 		bool expected;
2249 
2250 		expected =
2251 			expect(device, atomic_read(&req->completion_ref) == 0) &&
2252 			expect(device, req->rq_state & RQ_POSTPONED) &&
2253 			expect(device, (req->rq_state & RQ_LOCAL_PENDING) == 0 ||
2254 				(req->rq_state & RQ_LOCAL_ABORTED) != 0);
2255 
2256 		if (!expected)
2257 			drbd_err(device, "req=%p completion_ref=%d rq_state=%x\n",
2258 				req, atomic_read(&req->completion_ref),
2259 				req->rq_state);
2260 
2261 		/* We still need to put one kref associated with the
2262 		 * "completion_ref" going zero in the code path that queued it
2263 		 * here.  The request object may still be referenced by a
2264 		 * frozen local req->private_bio, in case we force-detached.
2265 		 */
2266 		kref_put(&req->kref, drbd_req_destroy);
2267 
2268 		/* A single suspended or otherwise blocking device may stall
2269 		 * all others as well.  Fortunately, this code path is to
2270 		 * recover from a situation that "should not happen":
2271 		 * concurrent writes in multi-primary setup.
2272 		 * In a "normal" lifecycle, this workqueue is supposed to be
2273 		 * destroyed without ever doing anything.
2274 		 * If it turns out to be an issue anyways, we can do per
2275 		 * resource (replication group) or per device (minor) retry
2276 		 * workqueues instead.
2277 		 */
2278 
2279 		/* We are not just doing submit_bio_noacct(),
2280 		 * as we want to keep the start_time information. */
2281 		inc_ap_bio(device);
2282 		__drbd_make_request(device, bio);
2283 	}
2284 }
2285 
2286 /* called via drbd_req_put_completion_ref(),
2287  * holds resource->req_lock */
drbd_restart_request(struct drbd_request * req)2288 void drbd_restart_request(struct drbd_request *req)
2289 {
2290 	unsigned long flags;
2291 	spin_lock_irqsave(&retry.lock, flags);
2292 	list_move_tail(&req->tl_requests, &retry.writes);
2293 	spin_unlock_irqrestore(&retry.lock, flags);
2294 
2295 	/* Drop the extra reference that would otherwise
2296 	 * have been dropped by complete_master_bio.
2297 	 * do_retry() needs to grab a new one. */
2298 	dec_ap_bio(req->device);
2299 
2300 	queue_work(retry.wq, &retry.worker);
2301 }
2302 
drbd_destroy_resource(struct kref * kref)2303 void drbd_destroy_resource(struct kref *kref)
2304 {
2305 	struct drbd_resource *resource =
2306 		container_of(kref, struct drbd_resource, kref);
2307 
2308 	idr_destroy(&resource->devices);
2309 	free_cpumask_var(resource->cpu_mask);
2310 	kfree(resource->name);
2311 	kfree(resource);
2312 }
2313 
drbd_free_resource(struct drbd_resource * resource)2314 void drbd_free_resource(struct drbd_resource *resource)
2315 {
2316 	struct drbd_connection *connection, *tmp;
2317 
2318 	for_each_connection_safe(connection, tmp, resource) {
2319 		list_del(&connection->connections);
2320 		drbd_debugfs_connection_cleanup(connection);
2321 		kref_put(&connection->kref, drbd_destroy_connection);
2322 	}
2323 	drbd_debugfs_resource_cleanup(resource);
2324 	kref_put(&resource->kref, drbd_destroy_resource);
2325 }
2326 
drbd_cleanup(void)2327 static void drbd_cleanup(void)
2328 {
2329 	unsigned int i;
2330 	struct drbd_device *device;
2331 	struct drbd_resource *resource, *tmp;
2332 
2333 	/* first remove proc,
2334 	 * drbdsetup uses it's presence to detect
2335 	 * whether DRBD is loaded.
2336 	 * If we would get stuck in proc removal,
2337 	 * but have netlink already deregistered,
2338 	 * some drbdsetup commands may wait forever
2339 	 * for an answer.
2340 	 */
2341 	if (drbd_proc)
2342 		remove_proc_entry("drbd", NULL);
2343 
2344 	if (retry.wq)
2345 		destroy_workqueue(retry.wq);
2346 
2347 	drbd_genl_unregister();
2348 
2349 	idr_for_each_entry(&drbd_devices, device, i)
2350 		drbd_delete_device(device);
2351 
2352 	/* not _rcu since, no other updater anymore. Genl already unregistered */
2353 	for_each_resource_safe(resource, tmp, &drbd_resources) {
2354 		list_del(&resource->resources);
2355 		drbd_free_resource(resource);
2356 	}
2357 
2358 	drbd_debugfs_cleanup();
2359 
2360 	drbd_destroy_mempools();
2361 	unregister_blkdev(DRBD_MAJOR, "drbd");
2362 
2363 	idr_destroy(&drbd_devices);
2364 
2365 	pr_info("module cleanup done.\n");
2366 }
2367 
drbd_init_workqueue(struct drbd_work_queue * wq)2368 static void drbd_init_workqueue(struct drbd_work_queue* wq)
2369 {
2370 	spin_lock_init(&wq->q_lock);
2371 	INIT_LIST_HEAD(&wq->q);
2372 	init_waitqueue_head(&wq->q_wait);
2373 }
2374 
2375 struct completion_work {
2376 	struct drbd_work w;
2377 	struct completion done;
2378 };
2379 
w_complete(struct drbd_work * w,int cancel)2380 static int w_complete(struct drbd_work *w, int cancel)
2381 {
2382 	struct completion_work *completion_work =
2383 		container_of(w, struct completion_work, w);
2384 
2385 	complete(&completion_work->done);
2386 	return 0;
2387 }
2388 
drbd_flush_workqueue(struct drbd_work_queue * work_queue)2389 void drbd_flush_workqueue(struct drbd_work_queue *work_queue)
2390 {
2391 	struct completion_work completion_work;
2392 
2393 	completion_work.w.cb = w_complete;
2394 	init_completion(&completion_work.done);
2395 	drbd_queue_work(work_queue, &completion_work.w);
2396 	wait_for_completion(&completion_work.done);
2397 }
2398 
drbd_find_resource(const char * name)2399 struct drbd_resource *drbd_find_resource(const char *name)
2400 {
2401 	struct drbd_resource *resource;
2402 
2403 	if (!name || !name[0])
2404 		return NULL;
2405 
2406 	rcu_read_lock();
2407 	for_each_resource_rcu(resource, &drbd_resources) {
2408 		if (!strcmp(resource->name, name)) {
2409 			kref_get(&resource->kref);
2410 			goto found;
2411 		}
2412 	}
2413 	resource = NULL;
2414 found:
2415 	rcu_read_unlock();
2416 	return resource;
2417 }
2418 
conn_get_by_addrs(void * my_addr,int my_addr_len,void * peer_addr,int peer_addr_len)2419 struct drbd_connection *conn_get_by_addrs(void *my_addr, int my_addr_len,
2420 				     void *peer_addr, int peer_addr_len)
2421 {
2422 	struct drbd_resource *resource;
2423 	struct drbd_connection *connection;
2424 
2425 	rcu_read_lock();
2426 	for_each_resource_rcu(resource, &drbd_resources) {
2427 		for_each_connection_rcu(connection, resource) {
2428 			if (connection->my_addr_len == my_addr_len &&
2429 			    connection->peer_addr_len == peer_addr_len &&
2430 			    !memcmp(&connection->my_addr, my_addr, my_addr_len) &&
2431 			    !memcmp(&connection->peer_addr, peer_addr, peer_addr_len)) {
2432 				kref_get(&connection->kref);
2433 				goto found;
2434 			}
2435 		}
2436 	}
2437 	connection = NULL;
2438 found:
2439 	rcu_read_unlock();
2440 	return connection;
2441 }
2442 
drbd_alloc_socket(struct drbd_socket * socket)2443 static int drbd_alloc_socket(struct drbd_socket *socket)
2444 {
2445 	socket->rbuf = (void *) __get_free_page(GFP_KERNEL);
2446 	if (!socket->rbuf)
2447 		return -ENOMEM;
2448 	socket->sbuf = (void *) __get_free_page(GFP_KERNEL);
2449 	if (!socket->sbuf)
2450 		return -ENOMEM;
2451 	return 0;
2452 }
2453 
drbd_free_socket(struct drbd_socket * socket)2454 static void drbd_free_socket(struct drbd_socket *socket)
2455 {
2456 	free_page((unsigned long) socket->sbuf);
2457 	free_page((unsigned long) socket->rbuf);
2458 }
2459 
conn_free_crypto(struct drbd_connection * connection)2460 void conn_free_crypto(struct drbd_connection *connection)
2461 {
2462 	drbd_free_sock(connection);
2463 
2464 	crypto_free_shash(connection->csums_tfm);
2465 	crypto_free_shash(connection->verify_tfm);
2466 	crypto_free_shash(connection->cram_hmac_tfm);
2467 	crypto_free_shash(connection->integrity_tfm);
2468 	crypto_free_shash(connection->peer_integrity_tfm);
2469 	kfree(connection->int_dig_in);
2470 	kfree(connection->int_dig_vv);
2471 
2472 	connection->csums_tfm = NULL;
2473 	connection->verify_tfm = NULL;
2474 	connection->cram_hmac_tfm = NULL;
2475 	connection->integrity_tfm = NULL;
2476 	connection->peer_integrity_tfm = NULL;
2477 	connection->int_dig_in = NULL;
2478 	connection->int_dig_vv = NULL;
2479 }
2480 
set_resource_options(struct drbd_resource * resource,struct res_opts * res_opts)2481 int set_resource_options(struct drbd_resource *resource, struct res_opts *res_opts)
2482 {
2483 	struct drbd_connection *connection;
2484 	cpumask_var_t new_cpu_mask;
2485 	int err;
2486 
2487 	if (!zalloc_cpumask_var(&new_cpu_mask, GFP_KERNEL))
2488 		return -ENOMEM;
2489 
2490 	/* silently ignore cpu mask on UP kernel */
2491 	if (nr_cpu_ids > 1 && res_opts->cpu_mask[0] != 0) {
2492 		err = bitmap_parse(res_opts->cpu_mask, DRBD_CPU_MASK_SIZE,
2493 				   cpumask_bits(new_cpu_mask), nr_cpu_ids);
2494 		if (err == -EOVERFLOW) {
2495 			/* So what. mask it out. */
2496 			cpumask_var_t tmp_cpu_mask;
2497 			if (zalloc_cpumask_var(&tmp_cpu_mask, GFP_KERNEL)) {
2498 				cpumask_setall(tmp_cpu_mask);
2499 				cpumask_and(new_cpu_mask, new_cpu_mask, tmp_cpu_mask);
2500 				drbd_warn(resource, "Overflow in bitmap_parse(%.12s%s), truncating to %u bits\n",
2501 					res_opts->cpu_mask,
2502 					strlen(res_opts->cpu_mask) > 12 ? "..." : "",
2503 					nr_cpu_ids);
2504 				free_cpumask_var(tmp_cpu_mask);
2505 				err = 0;
2506 			}
2507 		}
2508 		if (err) {
2509 			drbd_warn(resource, "bitmap_parse() failed with %d\n", err);
2510 			/* retcode = ERR_CPU_MASK_PARSE; */
2511 			goto fail;
2512 		}
2513 	}
2514 	resource->res_opts = *res_opts;
2515 	if (cpumask_empty(new_cpu_mask))
2516 		drbd_calc_cpu_mask(&new_cpu_mask);
2517 	if (!cpumask_equal(resource->cpu_mask, new_cpu_mask)) {
2518 		cpumask_copy(resource->cpu_mask, new_cpu_mask);
2519 		for_each_connection_rcu(connection, resource) {
2520 			connection->receiver.reset_cpu_mask = 1;
2521 			connection->ack_receiver.reset_cpu_mask = 1;
2522 			connection->worker.reset_cpu_mask = 1;
2523 		}
2524 	}
2525 	err = 0;
2526 
2527 fail:
2528 	free_cpumask_var(new_cpu_mask);
2529 	return err;
2530 
2531 }
2532 
drbd_create_resource(const char * name)2533 struct drbd_resource *drbd_create_resource(const char *name)
2534 {
2535 	struct drbd_resource *resource;
2536 
2537 	resource = kzalloc(sizeof(struct drbd_resource), GFP_KERNEL);
2538 	if (!resource)
2539 		goto fail;
2540 	resource->name = kstrdup(name, GFP_KERNEL);
2541 	if (!resource->name)
2542 		goto fail_free_resource;
2543 	if (!zalloc_cpumask_var(&resource->cpu_mask, GFP_KERNEL))
2544 		goto fail_free_name;
2545 	kref_init(&resource->kref);
2546 	idr_init(&resource->devices);
2547 	INIT_LIST_HEAD(&resource->connections);
2548 	resource->write_ordering = WO_BDEV_FLUSH;
2549 	list_add_tail_rcu(&resource->resources, &drbd_resources);
2550 	mutex_init(&resource->conf_update);
2551 	mutex_init(&resource->adm_mutex);
2552 	spin_lock_init(&resource->req_lock);
2553 	drbd_debugfs_resource_add(resource);
2554 	return resource;
2555 
2556 fail_free_name:
2557 	kfree(resource->name);
2558 fail_free_resource:
2559 	kfree(resource);
2560 fail:
2561 	return NULL;
2562 }
2563 
2564 /* caller must be under adm_mutex */
conn_create(const char * name,struct res_opts * res_opts)2565 struct drbd_connection *conn_create(const char *name, struct res_opts *res_opts)
2566 {
2567 	struct drbd_resource *resource;
2568 	struct drbd_connection *connection;
2569 
2570 	connection = kzalloc(sizeof(struct drbd_connection), GFP_KERNEL);
2571 	if (!connection)
2572 		return NULL;
2573 
2574 	if (drbd_alloc_socket(&connection->data))
2575 		goto fail;
2576 	if (drbd_alloc_socket(&connection->meta))
2577 		goto fail;
2578 
2579 	connection->current_epoch = kzalloc(sizeof(struct drbd_epoch), GFP_KERNEL);
2580 	if (!connection->current_epoch)
2581 		goto fail;
2582 
2583 	INIT_LIST_HEAD(&connection->transfer_log);
2584 
2585 	INIT_LIST_HEAD(&connection->current_epoch->list);
2586 	connection->epochs = 1;
2587 	spin_lock_init(&connection->epoch_lock);
2588 
2589 	connection->send.seen_any_write_yet = false;
2590 	connection->send.current_epoch_nr = 0;
2591 	connection->send.current_epoch_writes = 0;
2592 
2593 	resource = drbd_create_resource(name);
2594 	if (!resource)
2595 		goto fail;
2596 
2597 	connection->cstate = C_STANDALONE;
2598 	mutex_init(&connection->cstate_mutex);
2599 	init_waitqueue_head(&connection->ping_wait);
2600 	idr_init(&connection->peer_devices);
2601 
2602 	drbd_init_workqueue(&connection->sender_work);
2603 	mutex_init(&connection->data.mutex);
2604 	mutex_init(&connection->meta.mutex);
2605 
2606 	drbd_thread_init(resource, &connection->receiver, drbd_receiver, "receiver");
2607 	connection->receiver.connection = connection;
2608 	drbd_thread_init(resource, &connection->worker, drbd_worker, "worker");
2609 	connection->worker.connection = connection;
2610 	drbd_thread_init(resource, &connection->ack_receiver, drbd_ack_receiver, "ack_recv");
2611 	connection->ack_receiver.connection = connection;
2612 
2613 	kref_init(&connection->kref);
2614 
2615 	connection->resource = resource;
2616 
2617 	if (set_resource_options(resource, res_opts))
2618 		goto fail_resource;
2619 
2620 	kref_get(&resource->kref);
2621 	list_add_tail_rcu(&connection->connections, &resource->connections);
2622 	drbd_debugfs_connection_add(connection);
2623 	return connection;
2624 
2625 fail_resource:
2626 	list_del(&resource->resources);
2627 	drbd_free_resource(resource);
2628 fail:
2629 	kfree(connection->current_epoch);
2630 	drbd_free_socket(&connection->meta);
2631 	drbd_free_socket(&connection->data);
2632 	kfree(connection);
2633 	return NULL;
2634 }
2635 
drbd_destroy_connection(struct kref * kref)2636 void drbd_destroy_connection(struct kref *kref)
2637 {
2638 	struct drbd_connection *connection = container_of(kref, struct drbd_connection, kref);
2639 	struct drbd_resource *resource = connection->resource;
2640 
2641 	if (atomic_read(&connection->current_epoch->epoch_size) !=  0)
2642 		drbd_err(connection, "epoch_size:%d\n", atomic_read(&connection->current_epoch->epoch_size));
2643 	kfree(connection->current_epoch);
2644 
2645 	idr_destroy(&connection->peer_devices);
2646 
2647 	drbd_free_socket(&connection->meta);
2648 	drbd_free_socket(&connection->data);
2649 	kfree(connection->int_dig_in);
2650 	kfree(connection->int_dig_vv);
2651 	kfree(connection);
2652 	kref_put(&resource->kref, drbd_destroy_resource);
2653 }
2654 
init_submitter(struct drbd_device * device)2655 static int init_submitter(struct drbd_device *device)
2656 {
2657 	/* opencoded create_singlethread_workqueue(),
2658 	 * to be able to say "drbd%d", ..., minor */
2659 	device->submit.wq =
2660 		alloc_ordered_workqueue("drbd%u_submit", WQ_MEM_RECLAIM, device->minor);
2661 	if (!device->submit.wq)
2662 		return -ENOMEM;
2663 
2664 	INIT_WORK(&device->submit.worker, do_submit);
2665 	INIT_LIST_HEAD(&device->submit.writes);
2666 	return 0;
2667 }
2668 
drbd_create_device(struct drbd_config_context * adm_ctx,unsigned int minor)2669 enum drbd_ret_code drbd_create_device(struct drbd_config_context *adm_ctx, unsigned int minor)
2670 {
2671 	struct drbd_resource *resource = adm_ctx->resource;
2672 	struct drbd_connection *connection, *n;
2673 	struct drbd_device *device;
2674 	struct drbd_peer_device *peer_device, *tmp_peer_device;
2675 	struct gendisk *disk;
2676 	int id;
2677 	int vnr = adm_ctx->volume;
2678 	enum drbd_ret_code err = ERR_NOMEM;
2679 	struct queue_limits lim = {
2680 		/*
2681 		 * Setting the max_hw_sectors to an odd value of 8kibyte here.
2682 		 * This triggers a max_bio_size message upon first attach or
2683 		 * connect.
2684 		 */
2685 		.max_hw_sectors		= DRBD_MAX_BIO_SIZE_SAFE >> 8,
2686 		.features		= BLK_FEAT_WRITE_CACHE | BLK_FEAT_FUA |
2687 					  BLK_FEAT_ROTATIONAL |
2688 					  BLK_FEAT_STABLE_WRITES,
2689 	};
2690 
2691 	device = minor_to_device(minor);
2692 	if (device)
2693 		return ERR_MINOR_OR_VOLUME_EXISTS;
2694 
2695 	/* GFP_KERNEL, we are outside of all write-out paths */
2696 	device = kzalloc(sizeof(struct drbd_device), GFP_KERNEL);
2697 	if (!device)
2698 		return ERR_NOMEM;
2699 	kref_init(&device->kref);
2700 
2701 	kref_get(&resource->kref);
2702 	device->resource = resource;
2703 	device->minor = minor;
2704 	device->vnr = vnr;
2705 
2706 	drbd_init_set_defaults(device);
2707 
2708 	disk = blk_alloc_disk(&lim, NUMA_NO_NODE);
2709 	if (IS_ERR(disk)) {
2710 		err = PTR_ERR(disk);
2711 		goto out_no_disk;
2712 	}
2713 
2714 	device->vdisk = disk;
2715 	device->rq_queue = disk->queue;
2716 
2717 	set_disk_ro(disk, true);
2718 
2719 	disk->major = DRBD_MAJOR;
2720 	disk->first_minor = minor;
2721 	disk->minors = 1;
2722 	disk->fops = &drbd_ops;
2723 	disk->flags |= GENHD_FL_NO_PART;
2724 	sprintf(disk->disk_name, "drbd%d", minor);
2725 	disk->private_data = device;
2726 
2727 	device->md_io.page = alloc_page(GFP_KERNEL);
2728 	if (!device->md_io.page)
2729 		goto out_no_io_page;
2730 
2731 	if (drbd_bm_init(device))
2732 		goto out_no_bitmap;
2733 	device->read_requests = RB_ROOT;
2734 	device->write_requests = RB_ROOT;
2735 
2736 	id = idr_alloc(&drbd_devices, device, minor, minor + 1, GFP_KERNEL);
2737 	if (id < 0) {
2738 		if (id == -ENOSPC)
2739 			err = ERR_MINOR_OR_VOLUME_EXISTS;
2740 		goto out_no_minor_idr;
2741 	}
2742 	kref_get(&device->kref);
2743 
2744 	id = idr_alloc(&resource->devices, device, vnr, vnr + 1, GFP_KERNEL);
2745 	if (id < 0) {
2746 		if (id == -ENOSPC)
2747 			err = ERR_MINOR_OR_VOLUME_EXISTS;
2748 		goto out_idr_remove_minor;
2749 	}
2750 	kref_get(&device->kref);
2751 
2752 	INIT_LIST_HEAD(&device->peer_devices);
2753 	INIT_LIST_HEAD(&device->pending_bitmap_io);
2754 	for_each_connection(connection, resource) {
2755 		peer_device = kzalloc(sizeof(struct drbd_peer_device), GFP_KERNEL);
2756 		if (!peer_device)
2757 			goto out_idr_remove_from_resource;
2758 		peer_device->connection = connection;
2759 		peer_device->device = device;
2760 
2761 		list_add(&peer_device->peer_devices, &device->peer_devices);
2762 		kref_get(&device->kref);
2763 
2764 		id = idr_alloc(&connection->peer_devices, peer_device, vnr, vnr + 1, GFP_KERNEL);
2765 		if (id < 0) {
2766 			if (id == -ENOSPC)
2767 				err = ERR_INVALID_REQUEST;
2768 			goto out_idr_remove_from_resource;
2769 		}
2770 		kref_get(&connection->kref);
2771 		INIT_WORK(&peer_device->send_acks_work, drbd_send_acks_wf);
2772 	}
2773 
2774 	if (init_submitter(device)) {
2775 		err = ERR_NOMEM;
2776 		goto out_idr_remove_from_resource;
2777 	}
2778 
2779 	err = add_disk(disk);
2780 	if (err)
2781 		goto out_destroy_workqueue;
2782 
2783 	/* inherit the connection state */
2784 	device->state.conn = first_connection(resource)->cstate;
2785 	if (device->state.conn == C_WF_REPORT_PARAMS) {
2786 		for_each_peer_device(peer_device, device)
2787 			drbd_connected(peer_device);
2788 	}
2789 	/* move to create_peer_device() */
2790 	for_each_peer_device(peer_device, device)
2791 		drbd_debugfs_peer_device_add(peer_device);
2792 	drbd_debugfs_device_add(device);
2793 	return NO_ERROR;
2794 
2795 out_destroy_workqueue:
2796 	destroy_workqueue(device->submit.wq);
2797 out_idr_remove_from_resource:
2798 	for_each_connection_safe(connection, n, resource) {
2799 		peer_device = idr_remove(&connection->peer_devices, vnr);
2800 		if (peer_device)
2801 			kref_put(&connection->kref, drbd_destroy_connection);
2802 	}
2803 	for_each_peer_device_safe(peer_device, tmp_peer_device, device) {
2804 		list_del(&peer_device->peer_devices);
2805 		kfree(peer_device);
2806 	}
2807 	idr_remove(&resource->devices, vnr);
2808 out_idr_remove_minor:
2809 	idr_remove(&drbd_devices, minor);
2810 	synchronize_rcu();
2811 out_no_minor_idr:
2812 	drbd_bm_cleanup(device);
2813 out_no_bitmap:
2814 	__free_page(device->md_io.page);
2815 out_no_io_page:
2816 	put_disk(disk);
2817 out_no_disk:
2818 	kref_put(&resource->kref, drbd_destroy_resource);
2819 	kfree(device);
2820 	return err;
2821 }
2822 
drbd_delete_device(struct drbd_device * device)2823 void drbd_delete_device(struct drbd_device *device)
2824 {
2825 	struct drbd_resource *resource = device->resource;
2826 	struct drbd_connection *connection;
2827 	struct drbd_peer_device *peer_device;
2828 
2829 	/* move to free_peer_device() */
2830 	for_each_peer_device(peer_device, device)
2831 		drbd_debugfs_peer_device_cleanup(peer_device);
2832 	drbd_debugfs_device_cleanup(device);
2833 	for_each_connection(connection, resource) {
2834 		idr_remove(&connection->peer_devices, device->vnr);
2835 		kref_put(&device->kref, drbd_destroy_device);
2836 	}
2837 	idr_remove(&resource->devices, device->vnr);
2838 	kref_put(&device->kref, drbd_destroy_device);
2839 	idr_remove(&drbd_devices, device_to_minor(device));
2840 	kref_put(&device->kref, drbd_destroy_device);
2841 	del_gendisk(device->vdisk);
2842 	synchronize_rcu();
2843 	kref_put(&device->kref, drbd_destroy_device);
2844 }
2845 
drbd_init(void)2846 static int __init drbd_init(void)
2847 {
2848 	int err;
2849 
2850 	if (drbd_minor_count < DRBD_MINOR_COUNT_MIN || drbd_minor_count > DRBD_MINOR_COUNT_MAX) {
2851 		pr_err("invalid minor_count (%d)\n", drbd_minor_count);
2852 #ifdef MODULE
2853 		return -EINVAL;
2854 #else
2855 		drbd_minor_count = DRBD_MINOR_COUNT_DEF;
2856 #endif
2857 	}
2858 
2859 	err = register_blkdev(DRBD_MAJOR, "drbd");
2860 	if (err) {
2861 		pr_err("unable to register block device major %d\n",
2862 		       DRBD_MAJOR);
2863 		return err;
2864 	}
2865 
2866 	/*
2867 	 * allocate all necessary structs
2868 	 */
2869 	init_waitqueue_head(&drbd_pp_wait);
2870 
2871 	drbd_proc = NULL; /* play safe for drbd_cleanup */
2872 	idr_init(&drbd_devices);
2873 
2874 	mutex_init(&resources_mutex);
2875 	INIT_LIST_HEAD(&drbd_resources);
2876 
2877 	err = drbd_genl_register();
2878 	if (err) {
2879 		pr_err("unable to register generic netlink family\n");
2880 		goto fail;
2881 	}
2882 
2883 	err = drbd_create_mempools();
2884 	if (err)
2885 		goto fail;
2886 
2887 	err = -ENOMEM;
2888 	drbd_proc = proc_create_single("drbd", S_IFREG | 0444 , NULL, drbd_seq_show);
2889 	if (!drbd_proc)	{
2890 		pr_err("unable to register proc file\n");
2891 		goto fail;
2892 	}
2893 
2894 	retry.wq = create_singlethread_workqueue("drbd-reissue");
2895 	if (!retry.wq) {
2896 		pr_err("unable to create retry workqueue\n");
2897 		goto fail;
2898 	}
2899 	INIT_WORK(&retry.worker, do_retry);
2900 	spin_lock_init(&retry.lock);
2901 	INIT_LIST_HEAD(&retry.writes);
2902 
2903 	drbd_debugfs_init();
2904 
2905 	pr_info("initialized. "
2906 	       "Version: " REL_VERSION " (api:%d/proto:%d-%d)\n",
2907 	       GENL_MAGIC_VERSION, PRO_VERSION_MIN, PRO_VERSION_MAX);
2908 	pr_info("%s\n", drbd_buildtag());
2909 	pr_info("registered as block device major %d\n", DRBD_MAJOR);
2910 	return 0; /* Success! */
2911 
2912 fail:
2913 	drbd_cleanup();
2914 	if (err == -ENOMEM)
2915 		pr_err("ran out of memory\n");
2916 	else
2917 		pr_err("initialization failure\n");
2918 	return err;
2919 }
2920 
drbd_free_one_sock(struct drbd_socket * ds)2921 static void drbd_free_one_sock(struct drbd_socket *ds)
2922 {
2923 	struct socket *s;
2924 	mutex_lock(&ds->mutex);
2925 	s = ds->socket;
2926 	ds->socket = NULL;
2927 	mutex_unlock(&ds->mutex);
2928 	if (s) {
2929 		/* so debugfs does not need to mutex_lock() */
2930 		synchronize_rcu();
2931 		kernel_sock_shutdown(s, SHUT_RDWR);
2932 		sock_release(s);
2933 	}
2934 }
2935 
drbd_free_sock(struct drbd_connection * connection)2936 void drbd_free_sock(struct drbd_connection *connection)
2937 {
2938 	if (connection->data.socket)
2939 		drbd_free_one_sock(&connection->data);
2940 	if (connection->meta.socket)
2941 		drbd_free_one_sock(&connection->meta);
2942 }
2943 
2944 /* meta data management */
2945 
conn_md_sync(struct drbd_connection * connection)2946 void conn_md_sync(struct drbd_connection *connection)
2947 {
2948 	struct drbd_peer_device *peer_device;
2949 	int vnr;
2950 
2951 	rcu_read_lock();
2952 	idr_for_each_entry(&connection->peer_devices, peer_device, vnr) {
2953 		struct drbd_device *device = peer_device->device;
2954 
2955 		kref_get(&device->kref);
2956 		rcu_read_unlock();
2957 		drbd_md_sync(device);
2958 		kref_put(&device->kref, drbd_destroy_device);
2959 		rcu_read_lock();
2960 	}
2961 	rcu_read_unlock();
2962 }
2963 
2964 /* aligned 4kByte */
2965 struct meta_data_on_disk {
2966 	u64 la_size_sect;      /* last agreed size. */
2967 	u64 uuid[UI_SIZE];   /* UUIDs. */
2968 	u64 device_uuid;
2969 	u64 reserved_u64_1;
2970 	u32 flags;             /* MDF */
2971 	u32 magic;
2972 	u32 md_size_sect;
2973 	u32 al_offset;         /* offset to this block */
2974 	u32 al_nr_extents;     /* important for restoring the AL (userspace) */
2975 	      /* `-- act_log->nr_elements <-- ldev->dc.al_extents */
2976 	u32 bm_offset;         /* offset to the bitmap, from here */
2977 	u32 bm_bytes_per_bit;  /* BM_BLOCK_SIZE */
2978 	u32 la_peer_max_bio_size;   /* last peer max_bio_size */
2979 
2980 	/* see al_tr_number_to_on_disk_sector() */
2981 	u32 al_stripes;
2982 	u32 al_stripe_size_4k;
2983 
2984 	u8 reserved_u8[4096 - (7*8 + 10*4)];
2985 } __packed;
2986 
2987 
2988 
drbd_md_write(struct drbd_device * device,void * b)2989 void drbd_md_write(struct drbd_device *device, void *b)
2990 {
2991 	struct meta_data_on_disk *buffer = b;
2992 	sector_t sector;
2993 	int i;
2994 
2995 	memset(buffer, 0, sizeof(*buffer));
2996 
2997 	buffer->la_size_sect = cpu_to_be64(get_capacity(device->vdisk));
2998 	for (i = UI_CURRENT; i < UI_SIZE; i++)
2999 		buffer->uuid[i] = cpu_to_be64(device->ldev->md.uuid[i]);
3000 	buffer->flags = cpu_to_be32(device->ldev->md.flags);
3001 	buffer->magic = cpu_to_be32(DRBD_MD_MAGIC_84_UNCLEAN);
3002 
3003 	buffer->md_size_sect  = cpu_to_be32(device->ldev->md.md_size_sect);
3004 	buffer->al_offset     = cpu_to_be32(device->ldev->md.al_offset);
3005 	buffer->al_nr_extents = cpu_to_be32(device->act_log->nr_elements);
3006 	buffer->bm_bytes_per_bit = cpu_to_be32(BM_BLOCK_SIZE);
3007 	buffer->device_uuid = cpu_to_be64(device->ldev->md.device_uuid);
3008 
3009 	buffer->bm_offset = cpu_to_be32(device->ldev->md.bm_offset);
3010 	buffer->la_peer_max_bio_size = cpu_to_be32(device->peer_max_bio_size);
3011 
3012 	buffer->al_stripes = cpu_to_be32(device->ldev->md.al_stripes);
3013 	buffer->al_stripe_size_4k = cpu_to_be32(device->ldev->md.al_stripe_size_4k);
3014 
3015 	D_ASSERT(device, drbd_md_ss(device->ldev) == device->ldev->md.md_offset);
3016 	sector = device->ldev->md.md_offset;
3017 
3018 	if (drbd_md_sync_page_io(device, device->ldev, sector, REQ_OP_WRITE)) {
3019 		/* this was a try anyways ... */
3020 		drbd_err(device, "meta data update failed!\n");
3021 		drbd_chk_io_error(device, 1, DRBD_META_IO_ERROR);
3022 	}
3023 }
3024 
3025 /**
3026  * drbd_md_sync() - Writes the meta data super block if the MD_DIRTY flag bit is set
3027  * @device:	DRBD device.
3028  */
drbd_md_sync(struct drbd_device * device)3029 void drbd_md_sync(struct drbd_device *device)
3030 {
3031 	struct meta_data_on_disk *buffer;
3032 
3033 	/* Don't accidentally change the DRBD meta data layout. */
3034 	BUILD_BUG_ON(UI_SIZE != 4);
3035 	BUILD_BUG_ON(sizeof(struct meta_data_on_disk) != 4096);
3036 
3037 	del_timer(&device->md_sync_timer);
3038 	/* timer may be rearmed by drbd_md_mark_dirty() now. */
3039 	if (!test_and_clear_bit(MD_DIRTY, &device->flags))
3040 		return;
3041 
3042 	/* We use here D_FAILED and not D_ATTACHING because we try to write
3043 	 * metadata even if we detach due to a disk failure! */
3044 	if (!get_ldev_if_state(device, D_FAILED))
3045 		return;
3046 
3047 	buffer = drbd_md_get_buffer(device, __func__);
3048 	if (!buffer)
3049 		goto out;
3050 
3051 	drbd_md_write(device, buffer);
3052 
3053 	/* Update device->ldev->md.la_size_sect,
3054 	 * since we updated it on metadata. */
3055 	device->ldev->md.la_size_sect = get_capacity(device->vdisk);
3056 
3057 	drbd_md_put_buffer(device);
3058 out:
3059 	put_ldev(device);
3060 }
3061 
check_activity_log_stripe_size(struct drbd_device * device,struct meta_data_on_disk * on_disk,struct drbd_md * in_core)3062 static int check_activity_log_stripe_size(struct drbd_device *device,
3063 		struct meta_data_on_disk *on_disk,
3064 		struct drbd_md *in_core)
3065 {
3066 	u32 al_stripes = be32_to_cpu(on_disk->al_stripes);
3067 	u32 al_stripe_size_4k = be32_to_cpu(on_disk->al_stripe_size_4k);
3068 	u64 al_size_4k;
3069 
3070 	/* both not set: default to old fixed size activity log */
3071 	if (al_stripes == 0 && al_stripe_size_4k == 0) {
3072 		al_stripes = 1;
3073 		al_stripe_size_4k = MD_32kB_SECT/8;
3074 	}
3075 
3076 	/* some paranoia plausibility checks */
3077 
3078 	/* we need both values to be set */
3079 	if (al_stripes == 0 || al_stripe_size_4k == 0)
3080 		goto err;
3081 
3082 	al_size_4k = (u64)al_stripes * al_stripe_size_4k;
3083 
3084 	/* Upper limit of activity log area, to avoid potential overflow
3085 	 * problems in al_tr_number_to_on_disk_sector(). As right now, more
3086 	 * than 72 * 4k blocks total only increases the amount of history,
3087 	 * limiting this arbitrarily to 16 GB is not a real limitation ;-)  */
3088 	if (al_size_4k > (16 * 1024 * 1024/4))
3089 		goto err;
3090 
3091 	/* Lower limit: we need at least 8 transaction slots (32kB)
3092 	 * to not break existing setups */
3093 	if (al_size_4k < MD_32kB_SECT/8)
3094 		goto err;
3095 
3096 	in_core->al_stripe_size_4k = al_stripe_size_4k;
3097 	in_core->al_stripes = al_stripes;
3098 	in_core->al_size_4k = al_size_4k;
3099 
3100 	return 0;
3101 err:
3102 	drbd_err(device, "invalid activity log striping: al_stripes=%u, al_stripe_size_4k=%u\n",
3103 			al_stripes, al_stripe_size_4k);
3104 	return -EINVAL;
3105 }
3106 
check_offsets_and_sizes(struct drbd_device * device,struct drbd_backing_dev * bdev)3107 static int check_offsets_and_sizes(struct drbd_device *device, struct drbd_backing_dev *bdev)
3108 {
3109 	sector_t capacity = drbd_get_capacity(bdev->md_bdev);
3110 	struct drbd_md *in_core = &bdev->md;
3111 	s32 on_disk_al_sect;
3112 	s32 on_disk_bm_sect;
3113 
3114 	/* The on-disk size of the activity log, calculated from offsets, and
3115 	 * the size of the activity log calculated from the stripe settings,
3116 	 * should match.
3117 	 * Though we could relax this a bit: it is ok, if the striped activity log
3118 	 * fits in the available on-disk activity log size.
3119 	 * Right now, that would break how resize is implemented.
3120 	 * TODO: make drbd_determine_dev_size() (and the drbdmeta tool) aware
3121 	 * of possible unused padding space in the on disk layout. */
3122 	if (in_core->al_offset < 0) {
3123 		if (in_core->bm_offset > in_core->al_offset)
3124 			goto err;
3125 		on_disk_al_sect = -in_core->al_offset;
3126 		on_disk_bm_sect = in_core->al_offset - in_core->bm_offset;
3127 	} else {
3128 		if (in_core->al_offset != MD_4kB_SECT)
3129 			goto err;
3130 		if (in_core->bm_offset < in_core->al_offset + in_core->al_size_4k * MD_4kB_SECT)
3131 			goto err;
3132 
3133 		on_disk_al_sect = in_core->bm_offset - MD_4kB_SECT;
3134 		on_disk_bm_sect = in_core->md_size_sect - in_core->bm_offset;
3135 	}
3136 
3137 	/* old fixed size meta data is exactly that: fixed. */
3138 	if (in_core->meta_dev_idx >= 0) {
3139 		if (in_core->md_size_sect != MD_128MB_SECT
3140 		||  in_core->al_offset != MD_4kB_SECT
3141 		||  in_core->bm_offset != MD_4kB_SECT + MD_32kB_SECT
3142 		||  in_core->al_stripes != 1
3143 		||  in_core->al_stripe_size_4k != MD_32kB_SECT/8)
3144 			goto err;
3145 	}
3146 
3147 	if (capacity < in_core->md_size_sect)
3148 		goto err;
3149 	if (capacity - in_core->md_size_sect < drbd_md_first_sector(bdev))
3150 		goto err;
3151 
3152 	/* should be aligned, and at least 32k */
3153 	if ((on_disk_al_sect & 7) || (on_disk_al_sect < MD_32kB_SECT))
3154 		goto err;
3155 
3156 	/* should fit (for now: exactly) into the available on-disk space;
3157 	 * overflow prevention is in check_activity_log_stripe_size() above. */
3158 	if (on_disk_al_sect != in_core->al_size_4k * MD_4kB_SECT)
3159 		goto err;
3160 
3161 	/* again, should be aligned */
3162 	if (in_core->bm_offset & 7)
3163 		goto err;
3164 
3165 	/* FIXME check for device grow with flex external meta data? */
3166 
3167 	/* can the available bitmap space cover the last agreed device size? */
3168 	if (on_disk_bm_sect < (in_core->la_size_sect+7)/MD_4kB_SECT/8/512)
3169 		goto err;
3170 
3171 	return 0;
3172 
3173 err:
3174 	drbd_err(device, "meta data offsets don't make sense: idx=%d "
3175 			"al_s=%u, al_sz4k=%u, al_offset=%d, bm_offset=%d, "
3176 			"md_size_sect=%u, la_size=%llu, md_capacity=%llu\n",
3177 			in_core->meta_dev_idx,
3178 			in_core->al_stripes, in_core->al_stripe_size_4k,
3179 			in_core->al_offset, in_core->bm_offset, in_core->md_size_sect,
3180 			(unsigned long long)in_core->la_size_sect,
3181 			(unsigned long long)capacity);
3182 
3183 	return -EINVAL;
3184 }
3185 
3186 
3187 /**
3188  * drbd_md_read() - Reads in the meta data super block
3189  * @device:	DRBD device.
3190  * @bdev:	Device from which the meta data should be read in.
3191  *
3192  * Return NO_ERROR on success, and an enum drbd_ret_code in case
3193  * something goes wrong.
3194  *
3195  * Called exactly once during drbd_adm_attach(), while still being D_DISKLESS,
3196  * even before @bdev is assigned to @device->ldev.
3197  */
drbd_md_read(struct drbd_device * device,struct drbd_backing_dev * bdev)3198 int drbd_md_read(struct drbd_device *device, struct drbd_backing_dev *bdev)
3199 {
3200 	struct meta_data_on_disk *buffer;
3201 	u32 magic, flags;
3202 	int i, rv = NO_ERROR;
3203 
3204 	if (device->state.disk != D_DISKLESS)
3205 		return ERR_DISK_CONFIGURED;
3206 
3207 	buffer = drbd_md_get_buffer(device, __func__);
3208 	if (!buffer)
3209 		return ERR_NOMEM;
3210 
3211 	/* First, figure out where our meta data superblock is located,
3212 	 * and read it. */
3213 	bdev->md.meta_dev_idx = bdev->disk_conf->meta_dev_idx;
3214 	bdev->md.md_offset = drbd_md_ss(bdev);
3215 	/* Even for (flexible or indexed) external meta data,
3216 	 * initially restrict us to the 4k superblock for now.
3217 	 * Affects the paranoia out-of-range access check in drbd_md_sync_page_io(). */
3218 	bdev->md.md_size_sect = 8;
3219 
3220 	if (drbd_md_sync_page_io(device, bdev, bdev->md.md_offset,
3221 				 REQ_OP_READ)) {
3222 		/* NOTE: can't do normal error processing here as this is
3223 		   called BEFORE disk is attached */
3224 		drbd_err(device, "Error while reading metadata.\n");
3225 		rv = ERR_IO_MD_DISK;
3226 		goto err;
3227 	}
3228 
3229 	magic = be32_to_cpu(buffer->magic);
3230 	flags = be32_to_cpu(buffer->flags);
3231 	if (magic == DRBD_MD_MAGIC_84_UNCLEAN ||
3232 	    (magic == DRBD_MD_MAGIC_08 && !(flags & MDF_AL_CLEAN))) {
3233 			/* btw: that's Activity Log clean, not "all" clean. */
3234 		drbd_err(device, "Found unclean meta data. Did you \"drbdadm apply-al\"?\n");
3235 		rv = ERR_MD_UNCLEAN;
3236 		goto err;
3237 	}
3238 
3239 	rv = ERR_MD_INVALID;
3240 	if (magic != DRBD_MD_MAGIC_08) {
3241 		if (magic == DRBD_MD_MAGIC_07)
3242 			drbd_err(device, "Found old (0.7) meta data magic. Did you \"drbdadm create-md\"?\n");
3243 		else
3244 			drbd_err(device, "Meta data magic not found. Did you \"drbdadm create-md\"?\n");
3245 		goto err;
3246 	}
3247 
3248 	if (be32_to_cpu(buffer->bm_bytes_per_bit) != BM_BLOCK_SIZE) {
3249 		drbd_err(device, "unexpected bm_bytes_per_bit: %u (expected %u)\n",
3250 		    be32_to_cpu(buffer->bm_bytes_per_bit), BM_BLOCK_SIZE);
3251 		goto err;
3252 	}
3253 
3254 
3255 	/* convert to in_core endian */
3256 	bdev->md.la_size_sect = be64_to_cpu(buffer->la_size_sect);
3257 	for (i = UI_CURRENT; i < UI_SIZE; i++)
3258 		bdev->md.uuid[i] = be64_to_cpu(buffer->uuid[i]);
3259 	bdev->md.flags = be32_to_cpu(buffer->flags);
3260 	bdev->md.device_uuid = be64_to_cpu(buffer->device_uuid);
3261 
3262 	bdev->md.md_size_sect = be32_to_cpu(buffer->md_size_sect);
3263 	bdev->md.al_offset = be32_to_cpu(buffer->al_offset);
3264 	bdev->md.bm_offset = be32_to_cpu(buffer->bm_offset);
3265 
3266 	if (check_activity_log_stripe_size(device, buffer, &bdev->md))
3267 		goto err;
3268 	if (check_offsets_and_sizes(device, bdev))
3269 		goto err;
3270 
3271 	if (be32_to_cpu(buffer->bm_offset) != bdev->md.bm_offset) {
3272 		drbd_err(device, "unexpected bm_offset: %d (expected %d)\n",
3273 		    be32_to_cpu(buffer->bm_offset), bdev->md.bm_offset);
3274 		goto err;
3275 	}
3276 	if (be32_to_cpu(buffer->md_size_sect) != bdev->md.md_size_sect) {
3277 		drbd_err(device, "unexpected md_size: %u (expected %u)\n",
3278 		    be32_to_cpu(buffer->md_size_sect), bdev->md.md_size_sect);
3279 		goto err;
3280 	}
3281 
3282 	rv = NO_ERROR;
3283 
3284 	spin_lock_irq(&device->resource->req_lock);
3285 	if (device->state.conn < C_CONNECTED) {
3286 		unsigned int peer;
3287 		peer = be32_to_cpu(buffer->la_peer_max_bio_size);
3288 		peer = max(peer, DRBD_MAX_BIO_SIZE_SAFE);
3289 		device->peer_max_bio_size = peer;
3290 	}
3291 	spin_unlock_irq(&device->resource->req_lock);
3292 
3293  err:
3294 	drbd_md_put_buffer(device);
3295 
3296 	return rv;
3297 }
3298 
3299 /**
3300  * drbd_md_mark_dirty() - Mark meta data super block as dirty
3301  * @device:	DRBD device.
3302  *
3303  * Call this function if you change anything that should be written to
3304  * the meta-data super block. This function sets MD_DIRTY, and starts a
3305  * timer that ensures that within five seconds you have to call drbd_md_sync().
3306  */
drbd_md_mark_dirty(struct drbd_device * device)3307 void drbd_md_mark_dirty(struct drbd_device *device)
3308 {
3309 	if (!test_and_set_bit(MD_DIRTY, &device->flags))
3310 		mod_timer(&device->md_sync_timer, jiffies + 5*HZ);
3311 }
3312 
drbd_uuid_move_history(struct drbd_device * device)3313 void drbd_uuid_move_history(struct drbd_device *device) __must_hold(local)
3314 {
3315 	int i;
3316 
3317 	for (i = UI_HISTORY_START; i < UI_HISTORY_END; i++)
3318 		device->ldev->md.uuid[i+1] = device->ldev->md.uuid[i];
3319 }
3320 
__drbd_uuid_set(struct drbd_device * device,int idx,u64 val)3321 void __drbd_uuid_set(struct drbd_device *device, int idx, u64 val) __must_hold(local)
3322 {
3323 	if (idx == UI_CURRENT) {
3324 		if (device->state.role == R_PRIMARY)
3325 			val |= 1;
3326 		else
3327 			val &= ~((u64)1);
3328 
3329 		drbd_set_ed_uuid(device, val);
3330 	}
3331 
3332 	device->ldev->md.uuid[idx] = val;
3333 	drbd_md_mark_dirty(device);
3334 }
3335 
_drbd_uuid_set(struct drbd_device * device,int idx,u64 val)3336 void _drbd_uuid_set(struct drbd_device *device, int idx, u64 val) __must_hold(local)
3337 {
3338 	unsigned long flags;
3339 	spin_lock_irqsave(&device->ldev->md.uuid_lock, flags);
3340 	__drbd_uuid_set(device, idx, val);
3341 	spin_unlock_irqrestore(&device->ldev->md.uuid_lock, flags);
3342 }
3343 
drbd_uuid_set(struct drbd_device * device,int idx,u64 val)3344 void drbd_uuid_set(struct drbd_device *device, int idx, u64 val) __must_hold(local)
3345 {
3346 	unsigned long flags;
3347 	spin_lock_irqsave(&device->ldev->md.uuid_lock, flags);
3348 	if (device->ldev->md.uuid[idx]) {
3349 		drbd_uuid_move_history(device);
3350 		device->ldev->md.uuid[UI_HISTORY_START] = device->ldev->md.uuid[idx];
3351 	}
3352 	__drbd_uuid_set(device, idx, val);
3353 	spin_unlock_irqrestore(&device->ldev->md.uuid_lock, flags);
3354 }
3355 
3356 /**
3357  * drbd_uuid_new_current() - Creates a new current UUID
3358  * @device:	DRBD device.
3359  *
3360  * Creates a new current UUID, and rotates the old current UUID into
3361  * the bitmap slot. Causes an incremental resync upon next connect.
3362  */
drbd_uuid_new_current(struct drbd_device * device)3363 void drbd_uuid_new_current(struct drbd_device *device) __must_hold(local)
3364 {
3365 	u64 val;
3366 	unsigned long long bm_uuid;
3367 
3368 	get_random_bytes(&val, sizeof(u64));
3369 
3370 	spin_lock_irq(&device->ldev->md.uuid_lock);
3371 	bm_uuid = device->ldev->md.uuid[UI_BITMAP];
3372 
3373 	if (bm_uuid)
3374 		drbd_warn(device, "bm UUID was already set: %llX\n", bm_uuid);
3375 
3376 	device->ldev->md.uuid[UI_BITMAP] = device->ldev->md.uuid[UI_CURRENT];
3377 	__drbd_uuid_set(device, UI_CURRENT, val);
3378 	spin_unlock_irq(&device->ldev->md.uuid_lock);
3379 
3380 	drbd_print_uuids(device, "new current UUID");
3381 	/* get it to stable storage _now_ */
3382 	drbd_md_sync(device);
3383 }
3384 
drbd_uuid_set_bm(struct drbd_device * device,u64 val)3385 void drbd_uuid_set_bm(struct drbd_device *device, u64 val) __must_hold(local)
3386 {
3387 	unsigned long flags;
3388 	spin_lock_irqsave(&device->ldev->md.uuid_lock, flags);
3389 	if (device->ldev->md.uuid[UI_BITMAP] == 0 && val == 0) {
3390 		spin_unlock_irqrestore(&device->ldev->md.uuid_lock, flags);
3391 		return;
3392 	}
3393 
3394 	if (val == 0) {
3395 		drbd_uuid_move_history(device);
3396 		device->ldev->md.uuid[UI_HISTORY_START] = device->ldev->md.uuid[UI_BITMAP];
3397 		device->ldev->md.uuid[UI_BITMAP] = 0;
3398 	} else {
3399 		unsigned long long bm_uuid = device->ldev->md.uuid[UI_BITMAP];
3400 		if (bm_uuid)
3401 			drbd_warn(device, "bm UUID was already set: %llX\n", bm_uuid);
3402 
3403 		device->ldev->md.uuid[UI_BITMAP] = val & ~((u64)1);
3404 	}
3405 	spin_unlock_irqrestore(&device->ldev->md.uuid_lock, flags);
3406 
3407 	drbd_md_mark_dirty(device);
3408 }
3409 
3410 /**
3411  * drbd_bmio_set_n_write() - io_fn for drbd_queue_bitmap_io() or drbd_bitmap_io()
3412  * @device:	DRBD device.
3413  * @peer_device: Peer DRBD device.
3414  *
3415  * Sets all bits in the bitmap and writes the whole bitmap to stable storage.
3416  */
drbd_bmio_set_n_write(struct drbd_device * device,struct drbd_peer_device * peer_device)3417 int drbd_bmio_set_n_write(struct drbd_device *device,
3418 			  struct drbd_peer_device *peer_device) __must_hold(local)
3419 
3420 {
3421 	int rv = -EIO;
3422 
3423 	drbd_md_set_flag(device, MDF_FULL_SYNC);
3424 	drbd_md_sync(device);
3425 	drbd_bm_set_all(device);
3426 
3427 	rv = drbd_bm_write(device, peer_device);
3428 
3429 	if (!rv) {
3430 		drbd_md_clear_flag(device, MDF_FULL_SYNC);
3431 		drbd_md_sync(device);
3432 	}
3433 
3434 	return rv;
3435 }
3436 
3437 /**
3438  * drbd_bmio_clear_n_write() - io_fn for drbd_queue_bitmap_io() or drbd_bitmap_io()
3439  * @device:	DRBD device.
3440  * @peer_device: Peer DRBD device.
3441  *
3442  * Clears all bits in the bitmap and writes the whole bitmap to stable storage.
3443  */
drbd_bmio_clear_n_write(struct drbd_device * device,struct drbd_peer_device * peer_device)3444 int drbd_bmio_clear_n_write(struct drbd_device *device,
3445 			  struct drbd_peer_device *peer_device) __must_hold(local)
3446 
3447 {
3448 	drbd_resume_al(device);
3449 	drbd_bm_clear_all(device);
3450 	return drbd_bm_write(device, peer_device);
3451 }
3452 
w_bitmap_io(struct drbd_work * w,int unused)3453 static int w_bitmap_io(struct drbd_work *w, int unused)
3454 {
3455 	struct drbd_device *device =
3456 		container_of(w, struct drbd_device, bm_io_work.w);
3457 	struct bm_io_work *work = &device->bm_io_work;
3458 	int rv = -EIO;
3459 
3460 	if (work->flags != BM_LOCKED_CHANGE_ALLOWED) {
3461 		int cnt = atomic_read(&device->ap_bio_cnt);
3462 		if (cnt)
3463 			drbd_err(device, "FIXME: ap_bio_cnt %d, expected 0; queued for '%s'\n",
3464 					cnt, work->why);
3465 	}
3466 
3467 	if (get_ldev(device)) {
3468 		drbd_bm_lock(device, work->why, work->flags);
3469 		rv = work->io_fn(device, work->peer_device);
3470 		drbd_bm_unlock(device);
3471 		put_ldev(device);
3472 	}
3473 
3474 	clear_bit_unlock(BITMAP_IO, &device->flags);
3475 	wake_up(&device->misc_wait);
3476 
3477 	if (work->done)
3478 		work->done(device, rv);
3479 
3480 	clear_bit(BITMAP_IO_QUEUED, &device->flags);
3481 	work->why = NULL;
3482 	work->flags = 0;
3483 
3484 	return 0;
3485 }
3486 
3487 /**
3488  * drbd_queue_bitmap_io() - Queues an IO operation on the whole bitmap
3489  * @device:	DRBD device.
3490  * @io_fn:	IO callback to be called when bitmap IO is possible
3491  * @done:	callback to be called after the bitmap IO was performed
3492  * @why:	Descriptive text of the reason for doing the IO
3493  * @flags:	Bitmap flags
3494  * @peer_device: Peer DRBD device.
3495  *
3496  * While IO on the bitmap happens we freeze application IO thus we ensure
3497  * that drbd_set_out_of_sync() can not be called. This function MAY ONLY be
3498  * called from worker context. It MUST NOT be used while a previous such
3499  * work is still pending!
3500  *
3501  * Its worker function encloses the call of io_fn() by get_ldev() and
3502  * put_ldev().
3503  */
drbd_queue_bitmap_io(struct drbd_device * device,int (* io_fn)(struct drbd_device *,struct drbd_peer_device *),void (* done)(struct drbd_device *,int),char * why,enum bm_flag flags,struct drbd_peer_device * peer_device)3504 void drbd_queue_bitmap_io(struct drbd_device *device,
3505 			  int (*io_fn)(struct drbd_device *, struct drbd_peer_device *),
3506 			  void (*done)(struct drbd_device *, int),
3507 			  char *why, enum bm_flag flags,
3508 			  struct drbd_peer_device *peer_device)
3509 {
3510 	D_ASSERT(device, current == peer_device->connection->worker.task);
3511 
3512 	D_ASSERT(device, !test_bit(BITMAP_IO_QUEUED, &device->flags));
3513 	D_ASSERT(device, !test_bit(BITMAP_IO, &device->flags));
3514 	D_ASSERT(device, list_empty(&device->bm_io_work.w.list));
3515 	if (device->bm_io_work.why)
3516 		drbd_err(device, "FIXME going to queue '%s' but '%s' still pending?\n",
3517 			why, device->bm_io_work.why);
3518 
3519 	device->bm_io_work.peer_device = peer_device;
3520 	device->bm_io_work.io_fn = io_fn;
3521 	device->bm_io_work.done = done;
3522 	device->bm_io_work.why = why;
3523 	device->bm_io_work.flags = flags;
3524 
3525 	spin_lock_irq(&device->resource->req_lock);
3526 	set_bit(BITMAP_IO, &device->flags);
3527 	/* don't wait for pending application IO if the caller indicates that
3528 	 * application IO does not conflict anyways. */
3529 	if (flags == BM_LOCKED_CHANGE_ALLOWED || atomic_read(&device->ap_bio_cnt) == 0) {
3530 		if (!test_and_set_bit(BITMAP_IO_QUEUED, &device->flags))
3531 			drbd_queue_work(&peer_device->connection->sender_work,
3532 					&device->bm_io_work.w);
3533 	}
3534 	spin_unlock_irq(&device->resource->req_lock);
3535 }
3536 
3537 /**
3538  * drbd_bitmap_io() -  Does an IO operation on the whole bitmap
3539  * @device:	DRBD device.
3540  * @io_fn:	IO callback to be called when bitmap IO is possible
3541  * @why:	Descriptive text of the reason for doing the IO
3542  * @flags:	Bitmap flags
3543  * @peer_device: Peer DRBD device.
3544  *
3545  * freezes application IO while that the actual IO operations runs. This
3546  * functions MAY NOT be called from worker context.
3547  */
drbd_bitmap_io(struct drbd_device * device,int (* io_fn)(struct drbd_device *,struct drbd_peer_device *),char * why,enum bm_flag flags,struct drbd_peer_device * peer_device)3548 int drbd_bitmap_io(struct drbd_device *device,
3549 		int (*io_fn)(struct drbd_device *, struct drbd_peer_device *),
3550 		char *why, enum bm_flag flags,
3551 		struct drbd_peer_device *peer_device)
3552 {
3553 	/* Only suspend io, if some operation is supposed to be locked out */
3554 	const bool do_suspend_io = flags & (BM_DONT_CLEAR|BM_DONT_SET|BM_DONT_TEST);
3555 	int rv;
3556 
3557 	D_ASSERT(device, current != first_peer_device(device)->connection->worker.task);
3558 
3559 	if (do_suspend_io)
3560 		drbd_suspend_io(device);
3561 
3562 	drbd_bm_lock(device, why, flags);
3563 	rv = io_fn(device, peer_device);
3564 	drbd_bm_unlock(device);
3565 
3566 	if (do_suspend_io)
3567 		drbd_resume_io(device);
3568 
3569 	return rv;
3570 }
3571 
drbd_md_set_flag(struct drbd_device * device,int flag)3572 void drbd_md_set_flag(struct drbd_device *device, int flag) __must_hold(local)
3573 {
3574 	if ((device->ldev->md.flags & flag) != flag) {
3575 		drbd_md_mark_dirty(device);
3576 		device->ldev->md.flags |= flag;
3577 	}
3578 }
3579 
drbd_md_clear_flag(struct drbd_device * device,int flag)3580 void drbd_md_clear_flag(struct drbd_device *device, int flag) __must_hold(local)
3581 {
3582 	if ((device->ldev->md.flags & flag) != 0) {
3583 		drbd_md_mark_dirty(device);
3584 		device->ldev->md.flags &= ~flag;
3585 	}
3586 }
drbd_md_test_flag(struct drbd_backing_dev * bdev,int flag)3587 int drbd_md_test_flag(struct drbd_backing_dev *bdev, int flag)
3588 {
3589 	return (bdev->md.flags & flag) != 0;
3590 }
3591 
md_sync_timer_fn(struct timer_list * t)3592 static void md_sync_timer_fn(struct timer_list *t)
3593 {
3594 	struct drbd_device *device = from_timer(device, t, md_sync_timer);
3595 	drbd_device_post_work(device, MD_SYNC);
3596 }
3597 
cmdname(enum drbd_packet cmd)3598 const char *cmdname(enum drbd_packet cmd)
3599 {
3600 	/* THINK may need to become several global tables
3601 	 * when we want to support more than
3602 	 * one PRO_VERSION */
3603 	static const char *cmdnames[] = {
3604 
3605 		[P_DATA]	        = "Data",
3606 		[P_DATA_REPLY]	        = "DataReply",
3607 		[P_RS_DATA_REPLY]	= "RSDataReply",
3608 		[P_BARRIER]	        = "Barrier",
3609 		[P_BITMAP]	        = "ReportBitMap",
3610 		[P_BECOME_SYNC_TARGET]  = "BecomeSyncTarget",
3611 		[P_BECOME_SYNC_SOURCE]  = "BecomeSyncSource",
3612 		[P_UNPLUG_REMOTE]	= "UnplugRemote",
3613 		[P_DATA_REQUEST]	= "DataRequest",
3614 		[P_RS_DATA_REQUEST]     = "RSDataRequest",
3615 		[P_SYNC_PARAM]	        = "SyncParam",
3616 		[P_PROTOCOL]            = "ReportProtocol",
3617 		[P_UUIDS]	        = "ReportUUIDs",
3618 		[P_SIZES]	        = "ReportSizes",
3619 		[P_STATE]	        = "ReportState",
3620 		[P_SYNC_UUID]           = "ReportSyncUUID",
3621 		[P_AUTH_CHALLENGE]      = "AuthChallenge",
3622 		[P_AUTH_RESPONSE]	= "AuthResponse",
3623 		[P_STATE_CHG_REQ]       = "StateChgRequest",
3624 		[P_PING]		= "Ping",
3625 		[P_PING_ACK]	        = "PingAck",
3626 		[P_RECV_ACK]	        = "RecvAck",
3627 		[P_WRITE_ACK]	        = "WriteAck",
3628 		[P_RS_WRITE_ACK]	= "RSWriteAck",
3629 		[P_SUPERSEDED]          = "Superseded",
3630 		[P_NEG_ACK]	        = "NegAck",
3631 		[P_NEG_DREPLY]	        = "NegDReply",
3632 		[P_NEG_RS_DREPLY]	= "NegRSDReply",
3633 		[P_BARRIER_ACK]	        = "BarrierAck",
3634 		[P_STATE_CHG_REPLY]     = "StateChgReply",
3635 		[P_OV_REQUEST]          = "OVRequest",
3636 		[P_OV_REPLY]            = "OVReply",
3637 		[P_OV_RESULT]           = "OVResult",
3638 		[P_CSUM_RS_REQUEST]     = "CsumRSRequest",
3639 		[P_RS_IS_IN_SYNC]	= "CsumRSIsInSync",
3640 		[P_SYNC_PARAM89]	= "SyncParam89",
3641 		[P_COMPRESSED_BITMAP]   = "CBitmap",
3642 		[P_DELAY_PROBE]         = "DelayProbe",
3643 		[P_OUT_OF_SYNC]		= "OutOfSync",
3644 		[P_RS_CANCEL]		= "RSCancel",
3645 		[P_CONN_ST_CHG_REQ]	= "conn_st_chg_req",
3646 		[P_CONN_ST_CHG_REPLY]	= "conn_st_chg_reply",
3647 		[P_PROTOCOL_UPDATE]	= "protocol_update",
3648 		[P_TRIM]	        = "Trim",
3649 		[P_RS_THIN_REQ]         = "rs_thin_req",
3650 		[P_RS_DEALLOCATED]      = "rs_deallocated",
3651 		[P_WSAME]	        = "WriteSame",
3652 		[P_ZEROES]		= "Zeroes",
3653 
3654 		/* enum drbd_packet, but not commands - obsoleted flags:
3655 		 *	P_MAY_IGNORE
3656 		 *	P_MAX_OPT_CMD
3657 		 */
3658 	};
3659 
3660 	/* too big for the array: 0xfffX */
3661 	if (cmd == P_INITIAL_META)
3662 		return "InitialMeta";
3663 	if (cmd == P_INITIAL_DATA)
3664 		return "InitialData";
3665 	if (cmd == P_CONNECTION_FEATURES)
3666 		return "ConnectionFeatures";
3667 	if (cmd >= ARRAY_SIZE(cmdnames))
3668 		return "Unknown";
3669 	return cmdnames[cmd];
3670 }
3671 
3672 /**
3673  * drbd_wait_misc  -  wait for a request to make progress
3674  * @device:	device associated with the request
3675  * @i:		the struct drbd_interval embedded in struct drbd_request or
3676  *		struct drbd_peer_request
3677  */
drbd_wait_misc(struct drbd_device * device,struct drbd_interval * i)3678 int drbd_wait_misc(struct drbd_device *device, struct drbd_interval *i)
3679 {
3680 	struct net_conf *nc;
3681 	DEFINE_WAIT(wait);
3682 	long timeout;
3683 
3684 	rcu_read_lock();
3685 	nc = rcu_dereference(first_peer_device(device)->connection->net_conf);
3686 	if (!nc) {
3687 		rcu_read_unlock();
3688 		return -ETIMEDOUT;
3689 	}
3690 	timeout = nc->ko_count ? nc->timeout * HZ / 10 * nc->ko_count : MAX_SCHEDULE_TIMEOUT;
3691 	rcu_read_unlock();
3692 
3693 	/* Indicate to wake up device->misc_wait on progress.  */
3694 	i->waiting = true;
3695 	prepare_to_wait(&device->misc_wait, &wait, TASK_INTERRUPTIBLE);
3696 	spin_unlock_irq(&device->resource->req_lock);
3697 	timeout = schedule_timeout(timeout);
3698 	finish_wait(&device->misc_wait, &wait);
3699 	spin_lock_irq(&device->resource->req_lock);
3700 	if (!timeout || device->state.conn < C_CONNECTED)
3701 		return -ETIMEDOUT;
3702 	if (signal_pending(current))
3703 		return -ERESTARTSYS;
3704 	return 0;
3705 }
3706 
lock_all_resources(void)3707 void lock_all_resources(void)
3708 {
3709 	struct drbd_resource *resource;
3710 	int __maybe_unused i = 0;
3711 
3712 	mutex_lock(&resources_mutex);
3713 	local_irq_disable();
3714 	for_each_resource(resource, &drbd_resources)
3715 		spin_lock_nested(&resource->req_lock, i++);
3716 }
3717 
unlock_all_resources(void)3718 void unlock_all_resources(void)
3719 {
3720 	struct drbd_resource *resource;
3721 
3722 	for_each_resource(resource, &drbd_resources)
3723 		spin_unlock(&resource->req_lock);
3724 	local_irq_enable();
3725 	mutex_unlock(&resources_mutex);
3726 }
3727 
3728 #ifdef CONFIG_DRBD_FAULT_INJECTION
3729 /* Fault insertion support including random number generator shamelessly
3730  * stolen from kernel/rcutorture.c */
3731 struct fault_random_state {
3732 	unsigned long state;
3733 	unsigned long count;
3734 };
3735 
3736 #define FAULT_RANDOM_MULT 39916801  /* prime */
3737 #define FAULT_RANDOM_ADD	479001701 /* prime */
3738 #define FAULT_RANDOM_REFRESH 10000
3739 
3740 /*
3741  * Crude but fast random-number generator.  Uses a linear congruential
3742  * generator, with occasional help from get_random_bytes().
3743  */
3744 static unsigned long
_drbd_fault_random(struct fault_random_state * rsp)3745 _drbd_fault_random(struct fault_random_state *rsp)
3746 {
3747 	long refresh;
3748 
3749 	if (!rsp->count--) {
3750 		get_random_bytes(&refresh, sizeof(refresh));
3751 		rsp->state += refresh;
3752 		rsp->count = FAULT_RANDOM_REFRESH;
3753 	}
3754 	rsp->state = rsp->state * FAULT_RANDOM_MULT + FAULT_RANDOM_ADD;
3755 	return swahw32(rsp->state);
3756 }
3757 
3758 static char *
_drbd_fault_str(unsigned int type)3759 _drbd_fault_str(unsigned int type) {
3760 	static char *_faults[] = {
3761 		[DRBD_FAULT_MD_WR] = "Meta-data write",
3762 		[DRBD_FAULT_MD_RD] = "Meta-data read",
3763 		[DRBD_FAULT_RS_WR] = "Resync write",
3764 		[DRBD_FAULT_RS_RD] = "Resync read",
3765 		[DRBD_FAULT_DT_WR] = "Data write",
3766 		[DRBD_FAULT_DT_RD] = "Data read",
3767 		[DRBD_FAULT_DT_RA] = "Data read ahead",
3768 		[DRBD_FAULT_BM_ALLOC] = "BM allocation",
3769 		[DRBD_FAULT_AL_EE] = "EE allocation",
3770 		[DRBD_FAULT_RECEIVE] = "receive data corruption",
3771 	};
3772 
3773 	return (type < DRBD_FAULT_MAX) ? _faults[type] : "**Unknown**";
3774 }
3775 
3776 unsigned int
_drbd_insert_fault(struct drbd_device * device,unsigned int type)3777 _drbd_insert_fault(struct drbd_device *device, unsigned int type)
3778 {
3779 	static struct fault_random_state rrs = {0, 0};
3780 
3781 	unsigned int ret = (
3782 		(drbd_fault_devs == 0 ||
3783 			((1 << device_to_minor(device)) & drbd_fault_devs) != 0) &&
3784 		(((_drbd_fault_random(&rrs) % 100) + 1) <= drbd_fault_rate));
3785 
3786 	if (ret) {
3787 		drbd_fault_count++;
3788 
3789 		if (drbd_ratelimit())
3790 			drbd_warn(device, "***Simulating %s failure\n",
3791 				_drbd_fault_str(type));
3792 	}
3793 
3794 	return ret;
3795 }
3796 #endif
3797 
3798 module_init(drbd_init)
3799 module_exit(drbd_cleanup)
3800 
3801 EXPORT_SYMBOL(drbd_conn_str);
3802 EXPORT_SYMBOL(drbd_role_str);
3803 EXPORT_SYMBOL(drbd_disk_str);
3804 EXPORT_SYMBOL(drbd_set_st_err_str);
3805