Merge tag 'for-4.21/block-20190102' of git://git.kernel.dk/linux-block
[sfrench/cifs-2.6.git] / drivers / block / drbd / drbd_nl.c
1 /*
2    drbd_nl.c
3
4    This file is part of DRBD by Philipp Reisner and Lars Ellenberg.
5
6    Copyright (C) 2001-2008, LINBIT Information Technologies GmbH.
7    Copyright (C) 1999-2008, Philipp Reisner <philipp.reisner@linbit.com>.
8    Copyright (C) 2002-2008, Lars Ellenberg <lars.ellenberg@linbit.com>.
9
10    drbd is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 2, or (at your option)
13    any later version.
14
15    drbd is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with drbd; see the file COPYING.  If not, write to
22    the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
23
24  */
25
26 #define pr_fmt(fmt)     KBUILD_MODNAME ": " fmt
27
28 #include <linux/module.h>
29 #include <linux/drbd.h>
30 #include <linux/in.h>
31 #include <linux/fs.h>
32 #include <linux/file.h>
33 #include <linux/slab.h>
34 #include <linux/blkpg.h>
35 #include <linux/cpumask.h>
36 #include "drbd_int.h"
37 #include "drbd_protocol.h"
38 #include "drbd_req.h"
39 #include "drbd_state_change.h"
40 #include <asm/unaligned.h>
41 #include <linux/drbd_limits.h>
42 #include <linux/kthread.h>
43
44 #include <net/genetlink.h>
45
46 /* .doit */
47 // int drbd_adm_create_resource(struct sk_buff *skb, struct genl_info *info);
48 // int drbd_adm_delete_resource(struct sk_buff *skb, struct genl_info *info);
49
50 int drbd_adm_new_minor(struct sk_buff *skb, struct genl_info *info);
51 int drbd_adm_del_minor(struct sk_buff *skb, struct genl_info *info);
52
53 int drbd_adm_new_resource(struct sk_buff *skb, struct genl_info *info);
54 int drbd_adm_del_resource(struct sk_buff *skb, struct genl_info *info);
55 int drbd_adm_down(struct sk_buff *skb, struct genl_info *info);
56
57 int drbd_adm_set_role(struct sk_buff *skb, struct genl_info *info);
58 int drbd_adm_attach(struct sk_buff *skb, struct genl_info *info);
59 int drbd_adm_disk_opts(struct sk_buff *skb, struct genl_info *info);
60 int drbd_adm_detach(struct sk_buff *skb, struct genl_info *info);
61 int drbd_adm_connect(struct sk_buff *skb, struct genl_info *info);
62 int drbd_adm_net_opts(struct sk_buff *skb, struct genl_info *info);
63 int drbd_adm_resize(struct sk_buff *skb, struct genl_info *info);
64 int drbd_adm_start_ov(struct sk_buff *skb, struct genl_info *info);
65 int drbd_adm_new_c_uuid(struct sk_buff *skb, struct genl_info *info);
66 int drbd_adm_disconnect(struct sk_buff *skb, struct genl_info *info);
67 int drbd_adm_invalidate(struct sk_buff *skb, struct genl_info *info);
68 int drbd_adm_invalidate_peer(struct sk_buff *skb, struct genl_info *info);
69 int drbd_adm_pause_sync(struct sk_buff *skb, struct genl_info *info);
70 int drbd_adm_resume_sync(struct sk_buff *skb, struct genl_info *info);
71 int drbd_adm_suspend_io(struct sk_buff *skb, struct genl_info *info);
72 int drbd_adm_resume_io(struct sk_buff *skb, struct genl_info *info);
73 int drbd_adm_outdate(struct sk_buff *skb, struct genl_info *info);
74 int drbd_adm_resource_opts(struct sk_buff *skb, struct genl_info *info);
75 int drbd_adm_get_status(struct sk_buff *skb, struct genl_info *info);
76 int drbd_adm_get_timeout_type(struct sk_buff *skb, struct genl_info *info);
77 /* .dumpit */
78 int drbd_adm_get_status_all(struct sk_buff *skb, struct netlink_callback *cb);
79 int drbd_adm_dump_resources(struct sk_buff *skb, struct netlink_callback *cb);
80 int drbd_adm_dump_devices(struct sk_buff *skb, struct netlink_callback *cb);
81 int drbd_adm_dump_devices_done(struct netlink_callback *cb);
82 int drbd_adm_dump_connections(struct sk_buff *skb, struct netlink_callback *cb);
83 int drbd_adm_dump_connections_done(struct netlink_callback *cb);
84 int drbd_adm_dump_peer_devices(struct sk_buff *skb, struct netlink_callback *cb);
85 int drbd_adm_dump_peer_devices_done(struct netlink_callback *cb);
86 int drbd_adm_get_initial_state(struct sk_buff *skb, struct netlink_callback *cb);
87
88 #include <linux/drbd_genl_api.h>
89 #include "drbd_nla.h"
90 #include <linux/genl_magic_func.h>
91
92 static atomic_t drbd_genl_seq = ATOMIC_INIT(2); /* two. */
93 static atomic_t notify_genl_seq = ATOMIC_INIT(2); /* two. */
94
95 DEFINE_MUTEX(notification_mutex);
96
97 /* used blkdev_get_by_path, to claim our meta data device(s) */
98 static char *drbd_m_holder = "Hands off! this is DRBD's meta data device.";
99
100 static void drbd_adm_send_reply(struct sk_buff *skb, struct genl_info *info)
101 {
102         genlmsg_end(skb, genlmsg_data(nlmsg_data(nlmsg_hdr(skb))));
103         if (genlmsg_reply(skb, info))
104                 pr_err("error sending genl reply\n");
105 }
106
107 /* Used on a fresh "drbd_adm_prepare"d reply_skb, this cannot fail: The only
108  * reason it could fail was no space in skb, and there are 4k available. */
109 static int drbd_msg_put_info(struct sk_buff *skb, const char *info)
110 {
111         struct nlattr *nla;
112         int err = -EMSGSIZE;
113
114         if (!info || !info[0])
115                 return 0;
116
117         nla = nla_nest_start(skb, DRBD_NLA_CFG_REPLY);
118         if (!nla)
119                 return err;
120
121         err = nla_put_string(skb, T_info_text, info);
122         if (err) {
123                 nla_nest_cancel(skb, nla);
124                 return err;
125         } else
126                 nla_nest_end(skb, nla);
127         return 0;
128 }
129
130 __printf(2, 3)
131 static int drbd_msg_sprintf_info(struct sk_buff *skb, const char *fmt, ...)
132 {
133         va_list args;
134         struct nlattr *nla, *txt;
135         int err = -EMSGSIZE;
136         int len;
137
138         nla = nla_nest_start(skb, DRBD_NLA_CFG_REPLY);
139         if (!nla)
140                 return err;
141
142         txt = nla_reserve(skb, T_info_text, 256);
143         if (!txt) {
144                 nla_nest_cancel(skb, nla);
145                 return err;
146         }
147         va_start(args, fmt);
148         len = vscnprintf(nla_data(txt), 256, fmt, args);
149         va_end(args);
150
151         /* maybe: retry with larger reserve, if truncated */
152         txt->nla_len = nla_attr_size(len+1);
153         nlmsg_trim(skb, (char*)txt + NLA_ALIGN(txt->nla_len));
154         nla_nest_end(skb, nla);
155
156         return 0;
157 }
158
159 /* This would be a good candidate for a "pre_doit" hook,
160  * and per-family private info->pointers.
161  * But we need to stay compatible with older kernels.
162  * If it returns successfully, adm_ctx members are valid.
163  *
164  * At this point, we still rely on the global genl_lock().
165  * If we want to avoid that, and allow "genl_family.parallel_ops", we may need
166  * to add additional synchronization against object destruction/modification.
167  */
168 #define DRBD_ADM_NEED_MINOR     1
169 #define DRBD_ADM_NEED_RESOURCE  2
170 #define DRBD_ADM_NEED_CONNECTION 4
171 static int drbd_adm_prepare(struct drbd_config_context *adm_ctx,
172         struct sk_buff *skb, struct genl_info *info, unsigned flags)
173 {
174         struct drbd_genlmsghdr *d_in = info->userhdr;
175         const u8 cmd = info->genlhdr->cmd;
176         int err;
177
178         memset(adm_ctx, 0, sizeof(*adm_ctx));
179
180         /* genl_rcv_msg only checks for CAP_NET_ADMIN on "GENL_ADMIN_PERM" :( */
181         if (cmd != DRBD_ADM_GET_STATUS && !capable(CAP_NET_ADMIN))
182                return -EPERM;
183
184         adm_ctx->reply_skb = genlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
185         if (!adm_ctx->reply_skb) {
186                 err = -ENOMEM;
187                 goto fail;
188         }
189
190         adm_ctx->reply_dh = genlmsg_put_reply(adm_ctx->reply_skb,
191                                         info, &drbd_genl_family, 0, cmd);
192         /* put of a few bytes into a fresh skb of >= 4k will always succeed.
193          * but anyways */
194         if (!adm_ctx->reply_dh) {
195                 err = -ENOMEM;
196                 goto fail;
197         }
198
199         adm_ctx->reply_dh->minor = d_in->minor;
200         adm_ctx->reply_dh->ret_code = NO_ERROR;
201
202         adm_ctx->volume = VOLUME_UNSPECIFIED;
203         if (info->attrs[DRBD_NLA_CFG_CONTEXT]) {
204                 struct nlattr *nla;
205                 /* parse and validate only */
206                 err = drbd_cfg_context_from_attrs(NULL, info);
207                 if (err)
208                         goto fail;
209
210                 /* It was present, and valid,
211                  * copy it over to the reply skb. */
212                 err = nla_put_nohdr(adm_ctx->reply_skb,
213                                 info->attrs[DRBD_NLA_CFG_CONTEXT]->nla_len,
214                                 info->attrs[DRBD_NLA_CFG_CONTEXT]);
215                 if (err)
216                         goto fail;
217
218                 /* and assign stuff to the adm_ctx */
219                 nla = nested_attr_tb[__nla_type(T_ctx_volume)];
220                 if (nla)
221                         adm_ctx->volume = nla_get_u32(nla);
222                 nla = nested_attr_tb[__nla_type(T_ctx_resource_name)];
223                 if (nla)
224                         adm_ctx->resource_name = nla_data(nla);
225                 adm_ctx->my_addr = nested_attr_tb[__nla_type(T_ctx_my_addr)];
226                 adm_ctx->peer_addr = nested_attr_tb[__nla_type(T_ctx_peer_addr)];
227                 if ((adm_ctx->my_addr &&
228                      nla_len(adm_ctx->my_addr) > sizeof(adm_ctx->connection->my_addr)) ||
229                     (adm_ctx->peer_addr &&
230                      nla_len(adm_ctx->peer_addr) > sizeof(adm_ctx->connection->peer_addr))) {
231                         err = -EINVAL;
232                         goto fail;
233                 }
234         }
235
236         adm_ctx->minor = d_in->minor;
237         adm_ctx->device = minor_to_device(d_in->minor);
238
239         /* We are protected by the global genl_lock().
240          * But we may explicitly drop it/retake it in drbd_adm_set_role(),
241          * so make sure this object stays around. */
242         if (adm_ctx->device)
243                 kref_get(&adm_ctx->device->kref);
244
245         if (adm_ctx->resource_name) {
246                 adm_ctx->resource = drbd_find_resource(adm_ctx->resource_name);
247         }
248
249         if (!adm_ctx->device && (flags & DRBD_ADM_NEED_MINOR)) {
250                 drbd_msg_put_info(adm_ctx->reply_skb, "unknown minor");
251                 return ERR_MINOR_INVALID;
252         }
253         if (!adm_ctx->resource && (flags & DRBD_ADM_NEED_RESOURCE)) {
254                 drbd_msg_put_info(adm_ctx->reply_skb, "unknown resource");
255                 if (adm_ctx->resource_name)
256                         return ERR_RES_NOT_KNOWN;
257                 return ERR_INVALID_REQUEST;
258         }
259
260         if (flags & DRBD_ADM_NEED_CONNECTION) {
261                 if (adm_ctx->resource) {
262                         drbd_msg_put_info(adm_ctx->reply_skb, "no resource name expected");
263                         return ERR_INVALID_REQUEST;
264                 }
265                 if (adm_ctx->device) {
266                         drbd_msg_put_info(adm_ctx->reply_skb, "no minor number expected");
267                         return ERR_INVALID_REQUEST;
268                 }
269                 if (adm_ctx->my_addr && adm_ctx->peer_addr)
270                         adm_ctx->connection = conn_get_by_addrs(nla_data(adm_ctx->my_addr),
271                                                           nla_len(adm_ctx->my_addr),
272                                                           nla_data(adm_ctx->peer_addr),
273                                                           nla_len(adm_ctx->peer_addr));
274                 if (!adm_ctx->connection) {
275                         drbd_msg_put_info(adm_ctx->reply_skb, "unknown connection");
276                         return ERR_INVALID_REQUEST;
277                 }
278         }
279
280         /* some more paranoia, if the request was over-determined */
281         if (adm_ctx->device && adm_ctx->resource &&
282             adm_ctx->device->resource != adm_ctx->resource) {
283                 pr_warning("request: minor=%u, resource=%s; but that minor belongs to resource %s\n",
284                                 adm_ctx->minor, adm_ctx->resource->name,
285                                 adm_ctx->device->resource->name);
286                 drbd_msg_put_info(adm_ctx->reply_skb, "minor exists in different resource");
287                 return ERR_INVALID_REQUEST;
288         }
289         if (adm_ctx->device &&
290             adm_ctx->volume != VOLUME_UNSPECIFIED &&
291             adm_ctx->volume != adm_ctx->device->vnr) {
292                 pr_warning("request: minor=%u, volume=%u; but that minor is volume %u in %s\n",
293                                 adm_ctx->minor, adm_ctx->volume,
294                                 adm_ctx->device->vnr,
295                                 adm_ctx->device->resource->name);
296                 drbd_msg_put_info(adm_ctx->reply_skb, "minor exists as different volume");
297                 return ERR_INVALID_REQUEST;
298         }
299
300         /* still, provide adm_ctx->resource always, if possible. */
301         if (!adm_ctx->resource) {
302                 adm_ctx->resource = adm_ctx->device ? adm_ctx->device->resource
303                         : adm_ctx->connection ? adm_ctx->connection->resource : NULL;
304                 if (adm_ctx->resource)
305                         kref_get(&adm_ctx->resource->kref);
306         }
307
308         return NO_ERROR;
309
310 fail:
311         nlmsg_free(adm_ctx->reply_skb);
312         adm_ctx->reply_skb = NULL;
313         return err;
314 }
315
316 static int drbd_adm_finish(struct drbd_config_context *adm_ctx,
317         struct genl_info *info, int retcode)
318 {
319         if (adm_ctx->device) {
320                 kref_put(&adm_ctx->device->kref, drbd_destroy_device);
321                 adm_ctx->device = NULL;
322         }
323         if (adm_ctx->connection) {
324                 kref_put(&adm_ctx->connection->kref, &drbd_destroy_connection);
325                 adm_ctx->connection = NULL;
326         }
327         if (adm_ctx->resource) {
328                 kref_put(&adm_ctx->resource->kref, drbd_destroy_resource);
329                 adm_ctx->resource = NULL;
330         }
331
332         if (!adm_ctx->reply_skb)
333                 return -ENOMEM;
334
335         adm_ctx->reply_dh->ret_code = retcode;
336         drbd_adm_send_reply(adm_ctx->reply_skb, info);
337         return 0;
338 }
339
340 static void setup_khelper_env(struct drbd_connection *connection, char **envp)
341 {
342         char *afs;
343
344         /* FIXME: A future version will not allow this case. */
345         if (connection->my_addr_len == 0 || connection->peer_addr_len == 0)
346                 return;
347
348         switch (((struct sockaddr *)&connection->peer_addr)->sa_family) {
349         case AF_INET6:
350                 afs = "ipv6";
351                 snprintf(envp[4], 60, "DRBD_PEER_ADDRESS=%pI6",
352                          &((struct sockaddr_in6 *)&connection->peer_addr)->sin6_addr);
353                 break;
354         case AF_INET:
355                 afs = "ipv4";
356                 snprintf(envp[4], 60, "DRBD_PEER_ADDRESS=%pI4",
357                          &((struct sockaddr_in *)&connection->peer_addr)->sin_addr);
358                 break;
359         default:
360                 afs = "ssocks";
361                 snprintf(envp[4], 60, "DRBD_PEER_ADDRESS=%pI4",
362                          &((struct sockaddr_in *)&connection->peer_addr)->sin_addr);
363         }
364         snprintf(envp[3], 20, "DRBD_PEER_AF=%s", afs);
365 }
366
367 int drbd_khelper(struct drbd_device *device, char *cmd)
368 {
369         char *envp[] = { "HOME=/",
370                         "TERM=linux",
371                         "PATH=/sbin:/usr/sbin:/bin:/usr/bin",
372                          (char[20]) { }, /* address family */
373                          (char[60]) { }, /* address */
374                         NULL };
375         char mb[14];
376         char *argv[] = {drbd_usermode_helper, cmd, mb, NULL };
377         struct drbd_connection *connection = first_peer_device(device)->connection;
378         struct sib_info sib;
379         int ret;
380
381         if (current == connection->worker.task)
382                 set_bit(CALLBACK_PENDING, &connection->flags);
383
384         snprintf(mb, 14, "minor-%d", device_to_minor(device));
385         setup_khelper_env(connection, envp);
386
387         /* The helper may take some time.
388          * write out any unsynced meta data changes now */
389         drbd_md_sync(device);
390
391         drbd_info(device, "helper command: %s %s %s\n", drbd_usermode_helper, cmd, mb);
392         sib.sib_reason = SIB_HELPER_PRE;
393         sib.helper_name = cmd;
394         drbd_bcast_event(device, &sib);
395         notify_helper(NOTIFY_CALL, device, connection, cmd, 0);
396         ret = call_usermodehelper(drbd_usermode_helper, argv, envp, UMH_WAIT_PROC);
397         if (ret)
398                 drbd_warn(device, "helper command: %s %s %s exit code %u (0x%x)\n",
399                                 drbd_usermode_helper, cmd, mb,
400                                 (ret >> 8) & 0xff, ret);
401         else
402                 drbd_info(device, "helper command: %s %s %s exit code %u (0x%x)\n",
403                                 drbd_usermode_helper, cmd, mb,
404                                 (ret >> 8) & 0xff, ret);
405         sib.sib_reason = SIB_HELPER_POST;
406         sib.helper_exit_code = ret;
407         drbd_bcast_event(device, &sib);
408         notify_helper(NOTIFY_RESPONSE, device, connection, cmd, ret);
409
410         if (current == connection->worker.task)
411                 clear_bit(CALLBACK_PENDING, &connection->flags);
412
413         if (ret < 0) /* Ignore any ERRNOs we got. */
414                 ret = 0;
415
416         return ret;
417 }
418
419 enum drbd_peer_state conn_khelper(struct drbd_connection *connection, char *cmd)
420 {
421         char *envp[] = { "HOME=/",
422                         "TERM=linux",
423                         "PATH=/sbin:/usr/sbin:/bin:/usr/bin",
424                          (char[20]) { }, /* address family */
425                          (char[60]) { }, /* address */
426                         NULL };
427         char *resource_name = connection->resource->name;
428         char *argv[] = {drbd_usermode_helper, cmd, resource_name, NULL };
429         int ret;
430
431         setup_khelper_env(connection, envp);
432         conn_md_sync(connection);
433
434         drbd_info(connection, "helper command: %s %s %s\n", drbd_usermode_helper, cmd, resource_name);
435         /* TODO: conn_bcast_event() ?? */
436         notify_helper(NOTIFY_CALL, NULL, connection, cmd, 0);
437
438         ret = call_usermodehelper(drbd_usermode_helper, argv, envp, UMH_WAIT_PROC);
439         if (ret)
440                 drbd_warn(connection, "helper command: %s %s %s exit code %u (0x%x)\n",
441                           drbd_usermode_helper, cmd, resource_name,
442                           (ret >> 8) & 0xff, ret);
443         else
444                 drbd_info(connection, "helper command: %s %s %s exit code %u (0x%x)\n",
445                           drbd_usermode_helper, cmd, resource_name,
446                           (ret >> 8) & 0xff, ret);
447         /* TODO: conn_bcast_event() ?? */
448         notify_helper(NOTIFY_RESPONSE, NULL, connection, cmd, ret);
449
450         if (ret < 0) /* Ignore any ERRNOs we got. */
451                 ret = 0;
452
453         return ret;
454 }
455
456 static enum drbd_fencing_p highest_fencing_policy(struct drbd_connection *connection)
457 {
458         enum drbd_fencing_p fp = FP_NOT_AVAIL;
459         struct drbd_peer_device *peer_device;
460         int vnr;
461
462         rcu_read_lock();
463         idr_for_each_entry(&connection->peer_devices, peer_device, vnr) {
464                 struct drbd_device *device = peer_device->device;
465                 if (get_ldev_if_state(device, D_CONSISTENT)) {
466                         struct disk_conf *disk_conf =
467                                 rcu_dereference(peer_device->device->ldev->disk_conf);
468                         fp = max_t(enum drbd_fencing_p, fp, disk_conf->fencing);
469                         put_ldev(device);
470                 }
471         }
472         rcu_read_unlock();
473
474         return fp;
475 }
476
477 static bool resource_is_supended(struct drbd_resource *resource)
478 {
479         return resource->susp || resource->susp_fen || resource->susp_nod;
480 }
481
482 bool conn_try_outdate_peer(struct drbd_connection *connection)
483 {
484         struct drbd_resource * const resource = connection->resource;
485         unsigned int connect_cnt;
486         union drbd_state mask = { };
487         union drbd_state val = { };
488         enum drbd_fencing_p fp;
489         char *ex_to_string;
490         int r;
491
492         spin_lock_irq(&resource->req_lock);
493         if (connection->cstate >= C_WF_REPORT_PARAMS) {
494                 drbd_err(connection, "Expected cstate < C_WF_REPORT_PARAMS\n");
495                 spin_unlock_irq(&resource->req_lock);
496                 return false;
497         }
498
499         connect_cnt = connection->connect_cnt;
500         spin_unlock_irq(&resource->req_lock);
501
502         fp = highest_fencing_policy(connection);
503         switch (fp) {
504         case FP_NOT_AVAIL:
505                 drbd_warn(connection, "Not fencing peer, I'm not even Consistent myself.\n");
506                 spin_lock_irq(&resource->req_lock);
507                 if (connection->cstate < C_WF_REPORT_PARAMS) {
508                         _conn_request_state(connection,
509                                             (union drbd_state) { { .susp_fen = 1 } },
510                                             (union drbd_state) { { .susp_fen = 0 } },
511                                             CS_VERBOSE | CS_HARD | CS_DC_SUSP);
512                         /* We are no longer suspended due to the fencing policy.
513                          * We may still be suspended due to the on-no-data-accessible policy.
514                          * If that was OND_IO_ERROR, fail pending requests. */
515                         if (!resource_is_supended(resource))
516                                 _tl_restart(connection, CONNECTION_LOST_WHILE_PENDING);
517                 }
518                 /* Else: in case we raced with a connection handshake,
519                  * let the handshake figure out if we maybe can RESEND,
520                  * and do not resume/fail pending requests here.
521                  * Worst case is we stay suspended for now, which may be
522                  * resolved by either re-establishing the replication link, or
523                  * the next link failure, or eventually the administrator.  */
524                 spin_unlock_irq(&resource->req_lock);
525                 return false;
526
527         case FP_DONT_CARE:
528                 return true;
529         default: ;
530         }
531
532         r = conn_khelper(connection, "fence-peer");
533
534         switch ((r>>8) & 0xff) {
535         case P_INCONSISTENT: /* peer is inconsistent */
536                 ex_to_string = "peer is inconsistent or worse";
537                 mask.pdsk = D_MASK;
538                 val.pdsk = D_INCONSISTENT;
539                 break;
540         case P_OUTDATED: /* peer got outdated, or was already outdated */
541                 ex_to_string = "peer was fenced";
542                 mask.pdsk = D_MASK;
543                 val.pdsk = D_OUTDATED;
544                 break;
545         case P_DOWN: /* peer was down */
546                 if (conn_highest_disk(connection) == D_UP_TO_DATE) {
547                         /* we will(have) create(d) a new UUID anyways... */
548                         ex_to_string = "peer is unreachable, assumed to be dead";
549                         mask.pdsk = D_MASK;
550                         val.pdsk = D_OUTDATED;
551                 } else {
552                         ex_to_string = "peer unreachable, doing nothing since disk != UpToDate";
553                 }
554                 break;
555         case P_PRIMARY: /* Peer is primary, voluntarily outdate myself.
556                  * This is useful when an unconnected R_SECONDARY is asked to
557                  * become R_PRIMARY, but finds the other peer being active. */
558                 ex_to_string = "peer is active";
559                 drbd_warn(connection, "Peer is primary, outdating myself.\n");
560                 mask.disk = D_MASK;
561                 val.disk = D_OUTDATED;
562                 break;
563         case P_FENCING:
564                 /* THINK: do we need to handle this
565                  * like case 4, or more like case 5? */
566                 if (fp != FP_STONITH)
567                         drbd_err(connection, "fence-peer() = 7 && fencing != Stonith !!!\n");
568                 ex_to_string = "peer was stonithed";
569                 mask.pdsk = D_MASK;
570                 val.pdsk = D_OUTDATED;
571                 break;
572         default:
573                 /* The script is broken ... */
574                 drbd_err(connection, "fence-peer helper broken, returned %d\n", (r>>8)&0xff);
575                 return false; /* Eventually leave IO frozen */
576         }
577
578         drbd_info(connection, "fence-peer helper returned %d (%s)\n",
579                   (r>>8) & 0xff, ex_to_string);
580
581         /* Not using
582            conn_request_state(connection, mask, val, CS_VERBOSE);
583            here, because we might were able to re-establish the connection in the
584            meantime. */
585         spin_lock_irq(&resource->req_lock);
586         if (connection->cstate < C_WF_REPORT_PARAMS && !test_bit(STATE_SENT, &connection->flags)) {
587                 if (connection->connect_cnt != connect_cnt)
588                         /* In case the connection was established and droped
589                            while the fence-peer handler was running, ignore it */
590                         drbd_info(connection, "Ignoring fence-peer exit code\n");
591                 else
592                         _conn_request_state(connection, mask, val, CS_VERBOSE);
593         }
594         spin_unlock_irq(&resource->req_lock);
595
596         return conn_highest_pdsk(connection) <= D_OUTDATED;
597 }
598
599 static int _try_outdate_peer_async(void *data)
600 {
601         struct drbd_connection *connection = (struct drbd_connection *)data;
602
603         conn_try_outdate_peer(connection);
604
605         kref_put(&connection->kref, drbd_destroy_connection);
606         return 0;
607 }
608
609 void conn_try_outdate_peer_async(struct drbd_connection *connection)
610 {
611         struct task_struct *opa;
612
613         kref_get(&connection->kref);
614         /* We may just have force_sig()'ed this thread
615          * to get it out of some blocking network function.
616          * Clear signals; otherwise kthread_run(), which internally uses
617          * wait_on_completion_killable(), will mistake our pending signal
618          * for a new fatal signal and fail. */
619         flush_signals(current);
620         opa = kthread_run(_try_outdate_peer_async, connection, "drbd_async_h");
621         if (IS_ERR(opa)) {
622                 drbd_err(connection, "out of mem, failed to invoke fence-peer helper\n");
623                 kref_put(&connection->kref, drbd_destroy_connection);
624         }
625 }
626
627 enum drbd_state_rv
628 drbd_set_role(struct drbd_device *const device, enum drbd_role new_role, int force)
629 {
630         struct drbd_peer_device *const peer_device = first_peer_device(device);
631         struct drbd_connection *const connection = peer_device ? peer_device->connection : NULL;
632         const int max_tries = 4;
633         enum drbd_state_rv rv = SS_UNKNOWN_ERROR;
634         struct net_conf *nc;
635         int try = 0;
636         int forced = 0;
637         union drbd_state mask, val;
638
639         if (new_role == R_PRIMARY) {
640                 struct drbd_connection *connection;
641
642                 /* Detect dead peers as soon as possible.  */
643
644                 rcu_read_lock();
645                 for_each_connection(connection, device->resource)
646                         request_ping(connection);
647                 rcu_read_unlock();
648         }
649
650         mutex_lock(device->state_mutex);
651
652         mask.i = 0; mask.role = R_MASK;
653         val.i  = 0; val.role  = new_role;
654
655         while (try++ < max_tries) {
656                 rv = _drbd_request_state_holding_state_mutex(device, mask, val, CS_WAIT_COMPLETE);
657
658                 /* in case we first succeeded to outdate,
659                  * but now suddenly could establish a connection */
660                 if (rv == SS_CW_FAILED_BY_PEER && mask.pdsk != 0) {
661                         val.pdsk = 0;
662                         mask.pdsk = 0;
663                         continue;
664                 }
665
666                 if (rv == SS_NO_UP_TO_DATE_DISK && force &&
667                     (device->state.disk < D_UP_TO_DATE &&
668                      device->state.disk >= D_INCONSISTENT)) {
669                         mask.disk = D_MASK;
670                         val.disk  = D_UP_TO_DATE;
671                         forced = 1;
672                         continue;
673                 }
674
675                 if (rv == SS_NO_UP_TO_DATE_DISK &&
676                     device->state.disk == D_CONSISTENT && mask.pdsk == 0) {
677                         D_ASSERT(device, device->state.pdsk == D_UNKNOWN);
678
679                         if (conn_try_outdate_peer(connection)) {
680                                 val.disk = D_UP_TO_DATE;
681                                 mask.disk = D_MASK;
682                         }
683                         continue;
684                 }
685
686                 if (rv == SS_NOTHING_TO_DO)
687                         goto out;
688                 if (rv == SS_PRIMARY_NOP && mask.pdsk == 0) {
689                         if (!conn_try_outdate_peer(connection) && force) {
690                                 drbd_warn(device, "Forced into split brain situation!\n");
691                                 mask.pdsk = D_MASK;
692                                 val.pdsk  = D_OUTDATED;
693
694                         }
695                         continue;
696                 }
697                 if (rv == SS_TWO_PRIMARIES) {
698                         /* Maybe the peer is detected as dead very soon...
699                            retry at most once more in this case. */
700                         if (try < max_tries) {
701                                 int timeo;
702                                 try = max_tries - 1;
703                                 rcu_read_lock();
704                                 nc = rcu_dereference(connection->net_conf);
705                                 timeo = nc ? (nc->ping_timeo + 1) * HZ / 10 : 1;
706                                 rcu_read_unlock();
707                                 schedule_timeout_interruptible(timeo);
708                         }
709                         continue;
710                 }
711                 if (rv < SS_SUCCESS) {
712                         rv = _drbd_request_state(device, mask, val,
713                                                 CS_VERBOSE + CS_WAIT_COMPLETE);
714                         if (rv < SS_SUCCESS)
715                                 goto out;
716                 }
717                 break;
718         }
719
720         if (rv < SS_SUCCESS)
721                 goto out;
722
723         if (forced)
724                 drbd_warn(device, "Forced to consider local data as UpToDate!\n");
725
726         /* Wait until nothing is on the fly :) */
727         wait_event(device->misc_wait, atomic_read(&device->ap_pending_cnt) == 0);
728
729         /* FIXME also wait for all pending P_BARRIER_ACK? */
730
731         if (new_role == R_SECONDARY) {
732                 if (get_ldev(device)) {
733                         device->ldev->md.uuid[UI_CURRENT] &= ~(u64)1;
734                         put_ldev(device);
735                 }
736         } else {
737                 mutex_lock(&device->resource->conf_update);
738                 nc = connection->net_conf;
739                 if (nc)
740                         nc->discard_my_data = 0; /* without copy; single bit op is atomic */
741                 mutex_unlock(&device->resource->conf_update);
742
743                 if (get_ldev(device)) {
744                         if (((device->state.conn < C_CONNECTED ||
745                                device->state.pdsk <= D_FAILED)
746                               && device->ldev->md.uuid[UI_BITMAP] == 0) || forced)
747                                 drbd_uuid_new_current(device);
748
749                         device->ldev->md.uuid[UI_CURRENT] |=  (u64)1;
750                         put_ldev(device);
751                 }
752         }
753
754         /* writeout of activity log covered areas of the bitmap
755          * to stable storage done in after state change already */
756
757         if (device->state.conn >= C_WF_REPORT_PARAMS) {
758                 /* if this was forced, we should consider sync */
759                 if (forced)
760                         drbd_send_uuids(peer_device);
761                 drbd_send_current_state(peer_device);
762         }
763
764         drbd_md_sync(device);
765         set_disk_ro(device->vdisk, new_role == R_SECONDARY);
766         kobject_uevent(&disk_to_dev(device->vdisk)->kobj, KOBJ_CHANGE);
767 out:
768         mutex_unlock(device->state_mutex);
769         return rv;
770 }
771
772 static const char *from_attrs_err_to_txt(int err)
773 {
774         return  err == -ENOMSG ? "required attribute missing" :
775                 err == -EOPNOTSUPP ? "unknown mandatory attribute" :
776                 err == -EEXIST ? "can not change invariant setting" :
777                 "invalid attribute value";
778 }
779
780 int drbd_adm_set_role(struct sk_buff *skb, struct genl_info *info)
781 {
782         struct drbd_config_context adm_ctx;
783         struct set_role_parms parms;
784         int err;
785         enum drbd_ret_code retcode;
786
787         retcode = drbd_adm_prepare(&adm_ctx, skb, info, DRBD_ADM_NEED_MINOR);
788         if (!adm_ctx.reply_skb)
789                 return retcode;
790         if (retcode != NO_ERROR)
791                 goto out;
792
793         memset(&parms, 0, sizeof(parms));
794         if (info->attrs[DRBD_NLA_SET_ROLE_PARMS]) {
795                 err = set_role_parms_from_attrs(&parms, info);
796                 if (err) {
797                         retcode = ERR_MANDATORY_TAG;
798                         drbd_msg_put_info(adm_ctx.reply_skb, from_attrs_err_to_txt(err));
799                         goto out;
800                 }
801         }
802         genl_unlock();
803         mutex_lock(&adm_ctx.resource->adm_mutex);
804
805         if (info->genlhdr->cmd == DRBD_ADM_PRIMARY)
806                 retcode = drbd_set_role(adm_ctx.device, R_PRIMARY, parms.assume_uptodate);
807         else
808                 retcode = drbd_set_role(adm_ctx.device, R_SECONDARY, 0);
809
810         mutex_unlock(&adm_ctx.resource->adm_mutex);
811         genl_lock();
812 out:
813         drbd_adm_finish(&adm_ctx, info, retcode);
814         return 0;
815 }
816
817 /* Initializes the md.*_offset members, so we are able to find
818  * the on disk meta data.
819  *
820  * We currently have two possible layouts:
821  * external:
822  *   |----------- md_size_sect ------------------|
823  *   [ 4k superblock ][ activity log ][  Bitmap  ]
824  *   | al_offset == 8 |
825  *   | bm_offset = al_offset + X      |
826  *  ==> bitmap sectors = md_size_sect - bm_offset
827  *
828  * internal:
829  *            |----------- md_size_sect ------------------|
830  * [data.....][  Bitmap  ][ activity log ][ 4k superblock ]
831  *                        | al_offset < 0 |
832  *            | bm_offset = al_offset - Y |
833  *  ==> bitmap sectors = Y = al_offset - bm_offset
834  *
835  *  Activity log size used to be fixed 32kB,
836  *  but is about to become configurable.
837  */
838 static void drbd_md_set_sector_offsets(struct drbd_device *device,
839                                        struct drbd_backing_dev *bdev)
840 {
841         sector_t md_size_sect = 0;
842         unsigned int al_size_sect = bdev->md.al_size_4k * 8;
843
844         bdev->md.md_offset = drbd_md_ss(bdev);
845
846         switch (bdev->md.meta_dev_idx) {
847         default:
848                 /* v07 style fixed size indexed meta data */
849                 bdev->md.md_size_sect = MD_128MB_SECT;
850                 bdev->md.al_offset = MD_4kB_SECT;
851                 bdev->md.bm_offset = MD_4kB_SECT + al_size_sect;
852                 break;
853         case DRBD_MD_INDEX_FLEX_EXT:
854                 /* just occupy the full device; unit: sectors */
855                 bdev->md.md_size_sect = drbd_get_capacity(bdev->md_bdev);
856                 bdev->md.al_offset = MD_4kB_SECT;
857                 bdev->md.bm_offset = MD_4kB_SECT + al_size_sect;
858                 break;
859         case DRBD_MD_INDEX_INTERNAL:
860         case DRBD_MD_INDEX_FLEX_INT:
861                 /* al size is still fixed */
862                 bdev->md.al_offset = -al_size_sect;
863                 /* we need (slightly less than) ~ this much bitmap sectors: */
864                 md_size_sect = drbd_get_capacity(bdev->backing_bdev);
865                 md_size_sect = ALIGN(md_size_sect, BM_SECT_PER_EXT);
866                 md_size_sect = BM_SECT_TO_EXT(md_size_sect);
867                 md_size_sect = ALIGN(md_size_sect, 8);
868
869                 /* plus the "drbd meta data super block",
870                  * and the activity log; */
871                 md_size_sect += MD_4kB_SECT + al_size_sect;
872
873                 bdev->md.md_size_sect = md_size_sect;
874                 /* bitmap offset is adjusted by 'super' block size */
875                 bdev->md.bm_offset   = -md_size_sect + MD_4kB_SECT;
876                 break;
877         }
878 }
879
880 /* input size is expected to be in KB */
881 char *ppsize(char *buf, unsigned long long size)
882 {
883         /* Needs 9 bytes at max including trailing NUL:
884          * -1ULL ==> "16384 EB" */
885         static char units[] = { 'K', 'M', 'G', 'T', 'P', 'E' };
886         int base = 0;
887         while (size >= 10000 && base < sizeof(units)-1) {
888                 /* shift + round */
889                 size = (size >> 10) + !!(size & (1<<9));
890                 base++;
891         }
892         sprintf(buf, "%u %cB", (unsigned)size, units[base]);
893
894         return buf;
895 }
896
897 /* there is still a theoretical deadlock when called from receiver
898  * on an D_INCONSISTENT R_PRIMARY:
899  *  remote READ does inc_ap_bio, receiver would need to receive answer
900  *  packet from remote to dec_ap_bio again.
901  *  receiver receive_sizes(), comes here,
902  *  waits for ap_bio_cnt == 0. -> deadlock.
903  * but this cannot happen, actually, because:
904  *  R_PRIMARY D_INCONSISTENT, and peer's disk is unreachable
905  *  (not connected, or bad/no disk on peer):
906  *  see drbd_fail_request_early, ap_bio_cnt is zero.
907  *  R_PRIMARY D_INCONSISTENT, and C_SYNC_TARGET:
908  *  peer may not initiate a resize.
909  */
910 /* Note these are not to be confused with
911  * drbd_adm_suspend_io/drbd_adm_resume_io,
912  * which are (sub) state changes triggered by admin (drbdsetup),
913  * and can be long lived.
914  * This changes an device->flag, is triggered by drbd internals,
915  * and should be short-lived. */
916 /* It needs to be a counter, since multiple threads might
917    independently suspend and resume IO. */
918 void drbd_suspend_io(struct drbd_device *device)
919 {
920         atomic_inc(&device->suspend_cnt);
921         if (drbd_suspended(device))
922                 return;
923         wait_event(device->misc_wait, !atomic_read(&device->ap_bio_cnt));
924 }
925
926 void drbd_resume_io(struct drbd_device *device)
927 {
928         if (atomic_dec_and_test(&device->suspend_cnt))
929                 wake_up(&device->misc_wait);
930 }
931
932 /**
933  * drbd_determine_dev_size() -  Sets the right device size obeying all constraints
934  * @device:     DRBD device.
935  *
936  * Returns 0 on success, negative return values indicate errors.
937  * You should call drbd_md_sync() after calling this function.
938  */
939 enum determine_dev_size
940 drbd_determine_dev_size(struct drbd_device *device, enum dds_flags flags, struct resize_parms *rs) __must_hold(local)
941 {
942         struct md_offsets_and_sizes {
943                 u64 last_agreed_sect;
944                 u64 md_offset;
945                 s32 al_offset;
946                 s32 bm_offset;
947                 u32 md_size_sect;
948
949                 u32 al_stripes;
950                 u32 al_stripe_size_4k;
951         } prev;
952         sector_t u_size, size;
953         struct drbd_md *md = &device->ldev->md;
954         void *buffer;
955
956         int md_moved, la_size_changed;
957         enum determine_dev_size rv = DS_UNCHANGED;
958
959         /* We may change the on-disk offsets of our meta data below.  Lock out
960          * anything that may cause meta data IO, to avoid acting on incomplete
961          * layout changes or scribbling over meta data that is in the process
962          * of being moved.
963          *
964          * Move is not exactly correct, btw, currently we have all our meta
965          * data in core memory, to "move" it we just write it all out, there
966          * are no reads. */
967         drbd_suspend_io(device);
968         buffer = drbd_md_get_buffer(device, __func__); /* Lock meta-data IO */
969         if (!buffer) {
970                 drbd_resume_io(device);
971                 return DS_ERROR;
972         }
973
974         /* remember current offset and sizes */
975         prev.last_agreed_sect = md->la_size_sect;
976         prev.md_offset = md->md_offset;
977         prev.al_offset = md->al_offset;
978         prev.bm_offset = md->bm_offset;
979         prev.md_size_sect = md->md_size_sect;
980         prev.al_stripes = md->al_stripes;
981         prev.al_stripe_size_4k = md->al_stripe_size_4k;
982
983         if (rs) {
984                 /* rs is non NULL if we should change the AL layout only */
985                 md->al_stripes = rs->al_stripes;
986                 md->al_stripe_size_4k = rs->al_stripe_size / 4;
987                 md->al_size_4k = (u64)rs->al_stripes * rs->al_stripe_size / 4;
988         }
989
990         drbd_md_set_sector_offsets(device, device->ldev);
991
992         rcu_read_lock();
993         u_size = rcu_dereference(device->ldev->disk_conf)->disk_size;
994         rcu_read_unlock();
995         size = drbd_new_dev_size(device, device->ldev, u_size, flags & DDSF_FORCED);
996
997         if (size < prev.last_agreed_sect) {
998                 if (rs && u_size == 0) {
999                         /* Remove "rs &&" later. This check should always be active, but
1000                            right now the receiver expects the permissive behavior */
1001                         drbd_warn(device, "Implicit shrink not allowed. "
1002                                  "Use --size=%llus for explicit shrink.\n",
1003                                  (unsigned long long)size);
1004                         rv = DS_ERROR_SHRINK;
1005                 }
1006                 if (u_size > size)
1007                         rv = DS_ERROR_SPACE_MD;
1008                 if (rv != DS_UNCHANGED)
1009                         goto err_out;
1010         }
1011
1012         if (drbd_get_capacity(device->this_bdev) != size ||
1013             drbd_bm_capacity(device) != size) {
1014                 int err;
1015                 err = drbd_bm_resize(device, size, !(flags & DDSF_NO_RESYNC));
1016                 if (unlikely(err)) {
1017                         /* currently there is only one error: ENOMEM! */
1018                         size = drbd_bm_capacity(device);
1019                         if (size == 0) {
1020                                 drbd_err(device, "OUT OF MEMORY! "
1021                                     "Could not allocate bitmap!\n");
1022                         } else {
1023                                 drbd_err(device, "BM resizing failed. "
1024                                     "Leaving size unchanged\n");
1025                         }
1026                         rv = DS_ERROR;
1027                 }
1028                 /* racy, see comments above. */
1029                 drbd_set_my_capacity(device, size);
1030                 md->la_size_sect = size;
1031         }
1032         if (rv <= DS_ERROR)
1033                 goto err_out;
1034
1035         la_size_changed = (prev.last_agreed_sect != md->la_size_sect);
1036
1037         md_moved = prev.md_offset    != md->md_offset
1038                 || prev.md_size_sect != md->md_size_sect;
1039
1040         if (la_size_changed || md_moved || rs) {
1041                 u32 prev_flags;
1042
1043                 /* We do some synchronous IO below, which may take some time.
1044                  * Clear the timer, to avoid scary "timer expired!" messages,
1045                  * "Superblock" is written out at least twice below, anyways. */
1046                 del_timer(&device->md_sync_timer);
1047
1048                 /* We won't change the "al-extents" setting, we just may need
1049                  * to move the on-disk location of the activity log ringbuffer.
1050                  * Lock for transaction is good enough, it may well be "dirty"
1051                  * or even "starving". */
1052                 wait_event(device->al_wait, lc_try_lock_for_transaction(device->act_log));
1053
1054                 /* mark current on-disk bitmap and activity log as unreliable */
1055                 prev_flags = md->flags;
1056                 md->flags |= MDF_FULL_SYNC | MDF_AL_DISABLED;
1057                 drbd_md_write(device, buffer);
1058
1059                 drbd_al_initialize(device, buffer);
1060
1061                 drbd_info(device, "Writing the whole bitmap, %s\n",
1062                          la_size_changed && md_moved ? "size changed and md moved" :
1063                          la_size_changed ? "size changed" : "md moved");
1064                 /* next line implicitly does drbd_suspend_io()+drbd_resume_io() */
1065                 drbd_bitmap_io(device, md_moved ? &drbd_bm_write_all : &drbd_bm_write,
1066                                "size changed", BM_LOCKED_MASK);
1067
1068                 /* on-disk bitmap and activity log is authoritative again
1069                  * (unless there was an IO error meanwhile...) */
1070                 md->flags = prev_flags;
1071                 drbd_md_write(device, buffer);
1072
1073                 if (rs)
1074                         drbd_info(device, "Changed AL layout to al-stripes = %d, al-stripe-size-kB = %d\n",
1075                                   md->al_stripes, md->al_stripe_size_4k * 4);
1076         }
1077
1078         if (size > prev.last_agreed_sect)
1079                 rv = prev.last_agreed_sect ? DS_GREW : DS_GREW_FROM_ZERO;
1080         if (size < prev.last_agreed_sect)
1081                 rv = DS_SHRUNK;
1082
1083         if (0) {
1084         err_out:
1085                 /* restore previous offset and sizes */
1086                 md->la_size_sect = prev.last_agreed_sect;
1087                 md->md_offset = prev.md_offset;
1088                 md->al_offset = prev.al_offset;
1089                 md->bm_offset = prev.bm_offset;
1090                 md->md_size_sect = prev.md_size_sect;
1091                 md->al_stripes = prev.al_stripes;
1092                 md->al_stripe_size_4k = prev.al_stripe_size_4k;
1093                 md->al_size_4k = (u64)prev.al_stripes * prev.al_stripe_size_4k;
1094         }
1095         lc_unlock(device->act_log);
1096         wake_up(&device->al_wait);
1097         drbd_md_put_buffer(device);
1098         drbd_resume_io(device);
1099
1100         return rv;
1101 }
1102
1103 sector_t
1104 drbd_new_dev_size(struct drbd_device *device, struct drbd_backing_dev *bdev,
1105                   sector_t u_size, int assume_peer_has_space)
1106 {
1107         sector_t p_size = device->p_size;   /* partner's disk size. */
1108         sector_t la_size_sect = bdev->md.la_size_sect; /* last agreed size. */
1109         sector_t m_size; /* my size */
1110         sector_t size = 0;
1111
1112         m_size = drbd_get_max_capacity(bdev);
1113
1114         if (device->state.conn < C_CONNECTED && assume_peer_has_space) {
1115                 drbd_warn(device, "Resize while not connected was forced by the user!\n");
1116                 p_size = m_size;
1117         }
1118
1119         if (p_size && m_size) {
1120                 size = min_t(sector_t, p_size, m_size);
1121         } else {
1122                 if (la_size_sect) {
1123                         size = la_size_sect;
1124                         if (m_size && m_size < size)
1125                                 size = m_size;
1126                         if (p_size && p_size < size)
1127                                 size = p_size;
1128                 } else {
1129                         if (m_size)
1130                                 size = m_size;
1131                         if (p_size)
1132                                 size = p_size;
1133                 }
1134         }
1135
1136         if (size == 0)
1137                 drbd_err(device, "Both nodes diskless!\n");
1138
1139         if (u_size) {
1140                 if (u_size > size)
1141                         drbd_err(device, "Requested disk size is too big (%lu > %lu)\n",
1142                             (unsigned long)u_size>>1, (unsigned long)size>>1);
1143                 else
1144                         size = u_size;
1145         }
1146
1147         return size;
1148 }
1149
1150 /**
1151  * drbd_check_al_size() - Ensures that the AL is of the right size
1152  * @device:     DRBD device.
1153  *
1154  * Returns -EBUSY if current al lru is still used, -ENOMEM when allocation
1155  * failed, and 0 on success. You should call drbd_md_sync() after you called
1156  * this function.
1157  */
1158 static int drbd_check_al_size(struct drbd_device *device, struct disk_conf *dc)
1159 {
1160         struct lru_cache *n, *t;
1161         struct lc_element *e;
1162         unsigned int in_use;
1163         int i;
1164
1165         if (device->act_log &&
1166             device->act_log->nr_elements == dc->al_extents)
1167                 return 0;
1168
1169         in_use = 0;
1170         t = device->act_log;
1171         n = lc_create("act_log", drbd_al_ext_cache, AL_UPDATES_PER_TRANSACTION,
1172                 dc->al_extents, sizeof(struct lc_element), 0);
1173
1174         if (n == NULL) {
1175                 drbd_err(device, "Cannot allocate act_log lru!\n");
1176                 return -ENOMEM;
1177         }
1178         spin_lock_irq(&device->al_lock);
1179         if (t) {
1180                 for (i = 0; i < t->nr_elements; i++) {
1181                         e = lc_element_by_index(t, i);
1182                         if (e->refcnt)
1183                                 drbd_err(device, "refcnt(%d)==%d\n",
1184                                     e->lc_number, e->refcnt);
1185                         in_use += e->refcnt;
1186                 }
1187         }
1188         if (!in_use)
1189                 device->act_log = n;
1190         spin_unlock_irq(&device->al_lock);
1191         if (in_use) {
1192                 drbd_err(device, "Activity log still in use!\n");
1193                 lc_destroy(n);
1194                 return -EBUSY;
1195         } else {
1196                 lc_destroy(t);
1197         }
1198         drbd_md_mark_dirty(device); /* we changed device->act_log->nr_elemens */
1199         return 0;
1200 }
1201
1202 static void blk_queue_discard_granularity(struct request_queue *q, unsigned int granularity)
1203 {
1204         q->limits.discard_granularity = granularity;
1205 }
1206
1207 static unsigned int drbd_max_discard_sectors(struct drbd_connection *connection)
1208 {
1209         /* when we introduced REQ_WRITE_SAME support, we also bumped
1210          * our maximum supported batch bio size used for discards. */
1211         if (connection->agreed_features & DRBD_FF_WSAME)
1212                 return DRBD_MAX_BBIO_SECTORS;
1213         /* before, with DRBD <= 8.4.6, we only allowed up to one AL_EXTENT_SIZE. */
1214         return AL_EXTENT_SIZE >> 9;
1215 }
1216
1217 static void decide_on_discard_support(struct drbd_device *device,
1218                         struct request_queue *q,
1219                         struct request_queue *b,
1220                         bool discard_zeroes_if_aligned)
1221 {
1222         /* q = drbd device queue (device->rq_queue)
1223          * b = backing device queue (device->ldev->backing_bdev->bd_disk->queue),
1224          *     or NULL if diskless
1225          */
1226         struct drbd_connection *connection = first_peer_device(device)->connection;
1227         bool can_do = b ? blk_queue_discard(b) : true;
1228
1229         if (can_do && connection->cstate >= C_CONNECTED && !(connection->agreed_features & DRBD_FF_TRIM)) {
1230                 can_do = false;
1231                 drbd_info(connection, "peer DRBD too old, does not support TRIM: disabling discards\n");
1232         }
1233         if (can_do) {
1234                 /* We don't care for the granularity, really.
1235                  * Stacking limits below should fix it for the local
1236                  * device.  Whether or not it is a suitable granularity
1237                  * on the remote device is not our problem, really. If
1238                  * you care, you need to use devices with similar
1239                  * topology on all peers. */
1240                 blk_queue_discard_granularity(q, 512);
1241                 q->limits.max_discard_sectors = drbd_max_discard_sectors(connection);
1242                 blk_queue_flag_set(QUEUE_FLAG_DISCARD, q);
1243                 q->limits.max_write_zeroes_sectors = drbd_max_discard_sectors(connection);
1244         } else {
1245                 blk_queue_flag_clear(QUEUE_FLAG_DISCARD, q);
1246                 blk_queue_discard_granularity(q, 0);
1247                 q->limits.max_discard_sectors = 0;
1248                 q->limits.max_write_zeroes_sectors = 0;
1249         }
1250 }
1251
1252 static void fixup_discard_if_not_supported(struct request_queue *q)
1253 {
1254         /* To avoid confusion, if this queue does not support discard, clear
1255          * max_discard_sectors, which is what lsblk -D reports to the user.
1256          * Older kernels got this wrong in "stack limits".
1257          * */
1258         if (!blk_queue_discard(q)) {
1259                 blk_queue_max_discard_sectors(q, 0);
1260                 blk_queue_discard_granularity(q, 0);
1261         }
1262 }
1263
1264 static void fixup_write_zeroes(struct drbd_device *device, struct request_queue *q)
1265 {
1266         /* Fixup max_write_zeroes_sectors after blk_queue_stack_limits():
1267          * if we can handle "zeroes" efficiently on the protocol,
1268          * we want to do that, even if our backend does not announce
1269          * max_write_zeroes_sectors itself. */
1270         struct drbd_connection *connection = first_peer_device(device)->connection;
1271         /* If the peer announces WZEROES support, use it.  Otherwise, rather
1272          * send explicit zeroes than rely on some discard-zeroes-data magic. */
1273         if (connection->agreed_features & DRBD_FF_WZEROES)
1274                 q->limits.max_write_zeroes_sectors = DRBD_MAX_BBIO_SECTORS;
1275         else
1276                 q->limits.max_write_zeroes_sectors = 0;
1277 }
1278
1279 static void decide_on_write_same_support(struct drbd_device *device,
1280                         struct request_queue *q,
1281                         struct request_queue *b, struct o_qlim *o,
1282                         bool disable_write_same)
1283 {
1284         struct drbd_peer_device *peer_device = first_peer_device(device);
1285         struct drbd_connection *connection = peer_device->connection;
1286         bool can_do = b ? b->limits.max_write_same_sectors : true;
1287
1288         if (can_do && disable_write_same) {
1289                 can_do = false;
1290                 drbd_info(peer_device, "WRITE_SAME disabled by config\n");
1291         }
1292
1293         if (can_do && connection->cstate >= C_CONNECTED && !(connection->agreed_features & DRBD_FF_WSAME)) {
1294                 can_do = false;
1295                 drbd_info(peer_device, "peer does not support WRITE_SAME\n");
1296         }
1297
1298         if (o) {
1299                 /* logical block size; queue_logical_block_size(NULL) is 512 */
1300                 unsigned int peer_lbs = be32_to_cpu(o->logical_block_size);
1301                 unsigned int me_lbs_b = queue_logical_block_size(b);
1302                 unsigned int me_lbs = queue_logical_block_size(q);
1303
1304                 if (me_lbs_b != me_lbs) {
1305                         drbd_warn(device,
1306                                 "logical block size of local backend does not match (drbd:%u, backend:%u); was this a late attach?\n",
1307                                 me_lbs, me_lbs_b);
1308                         /* rather disable write same than trigger some BUG_ON later in the scsi layer. */
1309                         can_do = false;
1310                 }
1311                 if (me_lbs_b != peer_lbs) {
1312                         drbd_warn(peer_device, "logical block sizes do not match (me:%u, peer:%u); this may cause problems.\n",
1313                                 me_lbs, peer_lbs);
1314                         if (can_do) {
1315                                 drbd_dbg(peer_device, "logical block size mismatch: WRITE_SAME disabled.\n");
1316                                 can_do = false;
1317                         }
1318                         me_lbs = max(me_lbs, me_lbs_b);
1319                         /* We cannot change the logical block size of an in-use queue.
1320                          * We can only hope that access happens to be properly aligned.
1321                          * If not, the peer will likely produce an IO error, and detach. */
1322                         if (peer_lbs > me_lbs) {
1323                                 if (device->state.role != R_PRIMARY) {
1324                                         blk_queue_logical_block_size(q, peer_lbs);
1325                                         drbd_warn(peer_device, "logical block size set to %u\n", peer_lbs);
1326                                 } else {
1327                                         drbd_warn(peer_device,
1328                                                 "current Primary must NOT adjust logical block size (%u -> %u); hope for the best.\n",
1329                                                 me_lbs, peer_lbs);
1330                                 }
1331                         }
1332                 }
1333                 if (can_do && !o->write_same_capable) {
1334                         /* If we introduce an open-coded write-same loop on the receiving side,
1335                          * the peer would present itself as "capable". */
1336                         drbd_dbg(peer_device, "WRITE_SAME disabled (peer device not capable)\n");
1337                         can_do = false;
1338                 }
1339         }
1340
1341         blk_queue_max_write_same_sectors(q, can_do ? DRBD_MAX_BBIO_SECTORS : 0);
1342 }
1343
1344 static void drbd_setup_queue_param(struct drbd_device *device, struct drbd_backing_dev *bdev,
1345                                    unsigned int max_bio_size, struct o_qlim *o)
1346 {
1347         struct request_queue * const q = device->rq_queue;
1348         unsigned int max_hw_sectors = max_bio_size >> 9;
1349         unsigned int max_segments = 0;
1350         struct request_queue *b = NULL;
1351         struct disk_conf *dc;
1352         bool discard_zeroes_if_aligned = true;
1353         bool disable_write_same = false;
1354
1355         if (bdev) {
1356                 b = bdev->backing_bdev->bd_disk->queue;
1357
1358                 max_hw_sectors = min(queue_max_hw_sectors(b), max_bio_size >> 9);
1359                 rcu_read_lock();
1360                 dc = rcu_dereference(device->ldev->disk_conf);
1361                 max_segments = dc->max_bio_bvecs;
1362                 discard_zeroes_if_aligned = dc->discard_zeroes_if_aligned;
1363                 disable_write_same = dc->disable_write_same;
1364                 rcu_read_unlock();
1365
1366                 blk_set_stacking_limits(&q->limits);
1367         }
1368
1369         blk_queue_max_hw_sectors(q, max_hw_sectors);
1370         /* This is the workaround for "bio would need to, but cannot, be split" */
1371         blk_queue_max_segments(q, max_segments ? max_segments : BLK_MAX_SEGMENTS);
1372         blk_queue_segment_boundary(q, PAGE_SIZE-1);
1373         decide_on_discard_support(device, q, b, discard_zeroes_if_aligned);
1374         decide_on_write_same_support(device, q, b, o, disable_write_same);
1375
1376         if (b) {
1377                 blk_queue_stack_limits(q, b);
1378
1379                 if (q->backing_dev_info->ra_pages !=
1380                     b->backing_dev_info->ra_pages) {
1381                         drbd_info(device, "Adjusting my ra_pages to backing device's (%lu -> %lu)\n",
1382                                  q->backing_dev_info->ra_pages,
1383                                  b->backing_dev_info->ra_pages);
1384                         q->backing_dev_info->ra_pages =
1385                                                 b->backing_dev_info->ra_pages;
1386                 }
1387         }
1388         fixup_discard_if_not_supported(q);
1389         fixup_write_zeroes(device, q);
1390 }
1391
1392 void drbd_reconsider_queue_parameters(struct drbd_device *device, struct drbd_backing_dev *bdev, struct o_qlim *o)
1393 {
1394         unsigned int now, new, local, peer;
1395
1396         now = queue_max_hw_sectors(device->rq_queue) << 9;
1397         local = device->local_max_bio_size; /* Eventually last known value, from volatile memory */
1398         peer = device->peer_max_bio_size; /* Eventually last known value, from meta data */
1399
1400         if (bdev) {
1401                 local = queue_max_hw_sectors(bdev->backing_bdev->bd_disk->queue) << 9;
1402                 device->local_max_bio_size = local;
1403         }
1404         local = min(local, DRBD_MAX_BIO_SIZE);
1405
1406         /* We may ignore peer limits if the peer is modern enough.
1407            Because new from 8.3.8 onwards the peer can use multiple
1408            BIOs for a single peer_request */
1409         if (device->state.conn >= C_WF_REPORT_PARAMS) {
1410                 if (first_peer_device(device)->connection->agreed_pro_version < 94)
1411                         peer = min(device->peer_max_bio_size, DRBD_MAX_SIZE_H80_PACKET);
1412                         /* Correct old drbd (up to 8.3.7) if it believes it can do more than 32KiB */
1413                 else if (first_peer_device(device)->connection->agreed_pro_version == 94)
1414                         peer = DRBD_MAX_SIZE_H80_PACKET;
1415                 else if (first_peer_device(device)->connection->agreed_pro_version < 100)
1416                         peer = DRBD_MAX_BIO_SIZE_P95;  /* drbd 8.3.8 onwards, before 8.4.0 */
1417                 else
1418                         peer = DRBD_MAX_BIO_SIZE;
1419
1420                 /* We may later detach and re-attach on a disconnected Primary.
1421                  * Avoid this setting to jump back in that case.
1422                  * We want to store what we know the peer DRBD can handle,
1423                  * not what the peer IO backend can handle. */
1424                 if (peer > device->peer_max_bio_size)
1425                         device->peer_max_bio_size = peer;
1426         }
1427         new = min(local, peer);
1428
1429         if (device->state.role == R_PRIMARY && new < now)
1430                 drbd_err(device, "ASSERT FAILED new < now; (%u < %u)\n", new, now);
1431
1432         if (new != now)
1433                 drbd_info(device, "max BIO size = %u\n", new);
1434
1435         drbd_setup_queue_param(device, bdev, new, o);
1436 }
1437
1438 /* Starts the worker thread */
1439 static void conn_reconfig_start(struct drbd_connection *connection)
1440 {
1441         drbd_thread_start(&connection->worker);
1442         drbd_flush_workqueue(&connection->sender_work);
1443 }
1444
1445 /* if still unconfigured, stops worker again. */
1446 static void conn_reconfig_done(struct drbd_connection *connection)
1447 {
1448         bool stop_threads;
1449         spin_lock_irq(&connection->resource->req_lock);
1450         stop_threads = conn_all_vols_unconf(connection) &&
1451                 connection->cstate == C_STANDALONE;
1452         spin_unlock_irq(&connection->resource->req_lock);
1453         if (stop_threads) {
1454                 /* ack_receiver thread and ack_sender workqueue are implicitly
1455                  * stopped by receiver in conn_disconnect() */
1456                 drbd_thread_stop(&connection->receiver);
1457                 drbd_thread_stop(&connection->worker);
1458         }
1459 }
1460
1461 /* Make sure IO is suspended before calling this function(). */
1462 static void drbd_suspend_al(struct drbd_device *device)
1463 {
1464         int s = 0;
1465
1466         if (!lc_try_lock(device->act_log)) {
1467                 drbd_warn(device, "Failed to lock al in drbd_suspend_al()\n");
1468                 return;
1469         }
1470
1471         drbd_al_shrink(device);
1472         spin_lock_irq(&device->resource->req_lock);
1473         if (device->state.conn < C_CONNECTED)
1474                 s = !test_and_set_bit(AL_SUSPENDED, &device->flags);
1475         spin_unlock_irq(&device->resource->req_lock);
1476         lc_unlock(device->act_log);
1477
1478         if (s)
1479                 drbd_info(device, "Suspended AL updates\n");
1480 }
1481
1482
1483 static bool should_set_defaults(struct genl_info *info)
1484 {
1485         unsigned flags = ((struct drbd_genlmsghdr*)info->userhdr)->flags;
1486         return 0 != (flags & DRBD_GENL_F_SET_DEFAULTS);
1487 }
1488
1489 static unsigned int drbd_al_extents_max(struct drbd_backing_dev *bdev)
1490 {
1491         /* This is limited by 16 bit "slot" numbers,
1492          * and by available on-disk context storage.
1493          *
1494          * Also (u16)~0 is special (denotes a "free" extent).
1495          *
1496          * One transaction occupies one 4kB on-disk block,
1497          * we have n such blocks in the on disk ring buffer,
1498          * the "current" transaction may fail (n-1),
1499          * and there is 919 slot numbers context information per transaction.
1500          *
1501          * 72 transaction blocks amounts to more than 2**16 context slots,
1502          * so cap there first.
1503          */
1504         const unsigned int max_al_nr = DRBD_AL_EXTENTS_MAX;
1505         const unsigned int sufficient_on_disk =
1506                 (max_al_nr + AL_CONTEXT_PER_TRANSACTION -1)
1507                 /AL_CONTEXT_PER_TRANSACTION;
1508
1509         unsigned int al_size_4k = bdev->md.al_size_4k;
1510
1511         if (al_size_4k > sufficient_on_disk)
1512                 return max_al_nr;
1513
1514         return (al_size_4k - 1) * AL_CONTEXT_PER_TRANSACTION;
1515 }
1516
1517 static bool write_ordering_changed(struct disk_conf *a, struct disk_conf *b)
1518 {
1519         return  a->disk_barrier != b->disk_barrier ||
1520                 a->disk_flushes != b->disk_flushes ||
1521                 a->disk_drain != b->disk_drain;
1522 }
1523
1524 static void sanitize_disk_conf(struct drbd_device *device, struct disk_conf *disk_conf,
1525                                struct drbd_backing_dev *nbc)
1526 {
1527         struct request_queue * const q = nbc->backing_bdev->bd_disk->queue;
1528
1529         if (disk_conf->al_extents < DRBD_AL_EXTENTS_MIN)
1530                 disk_conf->al_extents = DRBD_AL_EXTENTS_MIN;
1531         if (disk_conf->al_extents > drbd_al_extents_max(nbc))
1532                 disk_conf->al_extents = drbd_al_extents_max(nbc);
1533
1534         if (!blk_queue_discard(q)) {
1535                 if (disk_conf->rs_discard_granularity) {
1536                         disk_conf->rs_discard_granularity = 0; /* disable feature */
1537                         drbd_info(device, "rs_discard_granularity feature disabled\n");
1538                 }
1539         }
1540
1541         if (disk_conf->rs_discard_granularity) {
1542                 int orig_value = disk_conf->rs_discard_granularity;
1543                 int remainder;
1544
1545                 if (q->limits.discard_granularity > disk_conf->rs_discard_granularity)
1546                         disk_conf->rs_discard_granularity = q->limits.discard_granularity;
1547
1548                 remainder = disk_conf->rs_discard_granularity % q->limits.discard_granularity;
1549                 disk_conf->rs_discard_granularity += remainder;
1550
1551                 if (disk_conf->rs_discard_granularity > q->limits.max_discard_sectors << 9)
1552                         disk_conf->rs_discard_granularity = q->limits.max_discard_sectors << 9;
1553
1554                 if (disk_conf->rs_discard_granularity != orig_value)
1555                         drbd_info(device, "rs_discard_granularity changed to %d\n",
1556                                   disk_conf->rs_discard_granularity);
1557         }
1558 }
1559
1560 static int disk_opts_check_al_size(struct drbd_device *device, struct disk_conf *dc)
1561 {
1562         int err = -EBUSY;
1563
1564         if (device->act_log &&
1565             device->act_log->nr_elements == dc->al_extents)
1566                 return 0;
1567
1568         drbd_suspend_io(device);
1569         /* If IO completion is currently blocked, we would likely wait
1570          * "forever" for the activity log to become unused. So we don't. */
1571         if (atomic_read(&device->ap_bio_cnt))
1572                 goto out;
1573
1574         wait_event(device->al_wait, lc_try_lock(device->act_log));
1575         drbd_al_shrink(device);
1576         err = drbd_check_al_size(device, dc);
1577         lc_unlock(device->act_log);
1578         wake_up(&device->al_wait);
1579 out:
1580         drbd_resume_io(device);
1581         return err;
1582 }
1583
1584 int drbd_adm_disk_opts(struct sk_buff *skb, struct genl_info *info)
1585 {
1586         struct drbd_config_context adm_ctx;
1587         enum drbd_ret_code retcode;
1588         struct drbd_device *device;
1589         struct disk_conf *new_disk_conf, *old_disk_conf;
1590         struct fifo_buffer *old_plan = NULL, *new_plan = NULL;
1591         int err, fifo_size;
1592
1593         retcode = drbd_adm_prepare(&adm_ctx, skb, info, DRBD_ADM_NEED_MINOR);
1594         if (!adm_ctx.reply_skb)
1595                 return retcode;
1596         if (retcode != NO_ERROR)
1597                 goto finish;
1598
1599         device = adm_ctx.device;
1600         mutex_lock(&adm_ctx.resource->adm_mutex);
1601
1602         /* we also need a disk
1603          * to change the options on */
1604         if (!get_ldev(device)) {
1605                 retcode = ERR_NO_DISK;
1606                 goto out;
1607         }
1608
1609         new_disk_conf = kmalloc(sizeof(struct disk_conf), GFP_KERNEL);
1610         if (!new_disk_conf) {
1611                 retcode = ERR_NOMEM;
1612                 goto fail;
1613         }
1614
1615         mutex_lock(&device->resource->conf_update);
1616         old_disk_conf = device->ldev->disk_conf;
1617         *new_disk_conf = *old_disk_conf;
1618         if (should_set_defaults(info))
1619                 set_disk_conf_defaults(new_disk_conf);
1620
1621         err = disk_conf_from_attrs_for_change(new_disk_conf, info);
1622         if (err && err != -ENOMSG) {
1623                 retcode = ERR_MANDATORY_TAG;
1624                 drbd_msg_put_info(adm_ctx.reply_skb, from_attrs_err_to_txt(err));
1625                 goto fail_unlock;
1626         }
1627
1628         if (!expect(new_disk_conf->resync_rate >= 1))
1629                 new_disk_conf->resync_rate = 1;
1630
1631         sanitize_disk_conf(device, new_disk_conf, device->ldev);
1632
1633         if (new_disk_conf->c_plan_ahead > DRBD_C_PLAN_AHEAD_MAX)
1634                 new_disk_conf->c_plan_ahead = DRBD_C_PLAN_AHEAD_MAX;
1635
1636         fifo_size = (new_disk_conf->c_plan_ahead * 10 * SLEEP_TIME) / HZ;
1637         if (fifo_size != device->rs_plan_s->size) {
1638                 new_plan = fifo_alloc(fifo_size);
1639                 if (!new_plan) {
1640                         drbd_err(device, "kmalloc of fifo_buffer failed");
1641                         retcode = ERR_NOMEM;
1642                         goto fail_unlock;
1643                 }
1644         }
1645
1646         err = disk_opts_check_al_size(device, new_disk_conf);
1647         if (err) {
1648                 /* Could be just "busy". Ignore?
1649                  * Introduce dedicated error code? */
1650                 drbd_msg_put_info(adm_ctx.reply_skb,
1651                         "Try again without changing current al-extents setting");
1652                 retcode = ERR_NOMEM;
1653                 goto fail_unlock;
1654         }
1655
1656         lock_all_resources();
1657         retcode = drbd_resync_after_valid(device, new_disk_conf->resync_after);
1658         if (retcode == NO_ERROR) {
1659                 rcu_assign_pointer(device->ldev->disk_conf, new_disk_conf);
1660                 drbd_resync_after_changed(device);
1661         }
1662         unlock_all_resources();
1663
1664         if (retcode != NO_ERROR)
1665                 goto fail_unlock;
1666
1667         if (new_plan) {
1668                 old_plan = device->rs_plan_s;
1669                 rcu_assign_pointer(device->rs_plan_s, new_plan);
1670         }
1671
1672         mutex_unlock(&device->resource->conf_update);
1673
1674         if (new_disk_conf->al_updates)
1675                 device->ldev->md.flags &= ~MDF_AL_DISABLED;
1676         else
1677                 device->ldev->md.flags |= MDF_AL_DISABLED;
1678
1679         if (new_disk_conf->md_flushes)
1680                 clear_bit(MD_NO_FUA, &device->flags);
1681         else
1682                 set_bit(MD_NO_FUA, &device->flags);
1683
1684         if (write_ordering_changed(old_disk_conf, new_disk_conf))
1685                 drbd_bump_write_ordering(device->resource, NULL, WO_BDEV_FLUSH);
1686
1687         if (old_disk_conf->discard_zeroes_if_aligned != new_disk_conf->discard_zeroes_if_aligned
1688         ||  old_disk_conf->disable_write_same != new_disk_conf->disable_write_same)
1689                 drbd_reconsider_queue_parameters(device, device->ldev, NULL);
1690
1691         drbd_md_sync(device);
1692
1693         if (device->state.conn >= C_CONNECTED) {
1694                 struct drbd_peer_device *peer_device;
1695
1696                 for_each_peer_device(peer_device, device)
1697                         drbd_send_sync_param(peer_device);
1698         }
1699
1700         synchronize_rcu();
1701         kfree(old_disk_conf);
1702         kfree(old_plan);
1703         mod_timer(&device->request_timer, jiffies + HZ);
1704         goto success;
1705
1706 fail_unlock:
1707         mutex_unlock(&device->resource->conf_update);
1708  fail:
1709         kfree(new_disk_conf);
1710         kfree(new_plan);
1711 success:
1712         put_ldev(device);
1713  out:
1714         mutex_unlock(&adm_ctx.resource->adm_mutex);
1715  finish:
1716         drbd_adm_finish(&adm_ctx, info, retcode);
1717         return 0;
1718 }
1719
1720 static struct block_device *open_backing_dev(struct drbd_device *device,
1721                 const char *bdev_path, void *claim_ptr, bool do_bd_link)
1722 {
1723         struct block_device *bdev;
1724         int err = 0;
1725
1726         bdev = blkdev_get_by_path(bdev_path,
1727                                   FMODE_READ | FMODE_WRITE | FMODE_EXCL, claim_ptr);
1728         if (IS_ERR(bdev)) {
1729                 drbd_err(device, "open(\"%s\") failed with %ld\n",
1730                                 bdev_path, PTR_ERR(bdev));
1731                 return bdev;
1732         }
1733
1734         if (!do_bd_link)
1735                 return bdev;
1736
1737         err = bd_link_disk_holder(bdev, device->vdisk);
1738         if (err) {
1739                 blkdev_put(bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL);
1740                 drbd_err(device, "bd_link_disk_holder(\"%s\", ...) failed with %d\n",
1741                                 bdev_path, err);
1742                 bdev = ERR_PTR(err);
1743         }
1744         return bdev;
1745 }
1746
1747 static int open_backing_devices(struct drbd_device *device,
1748                 struct disk_conf *new_disk_conf,
1749                 struct drbd_backing_dev *nbc)
1750 {
1751         struct block_device *bdev;
1752
1753         bdev = open_backing_dev(device, new_disk_conf->backing_dev, device, true);
1754         if (IS_ERR(bdev))
1755                 return ERR_OPEN_DISK;
1756         nbc->backing_bdev = bdev;
1757
1758         /*
1759          * meta_dev_idx >= 0: external fixed size, possibly multiple
1760          * drbd sharing one meta device.  TODO in that case, paranoia
1761          * check that [md_bdev, meta_dev_idx] is not yet used by some
1762          * other drbd minor!  (if you use drbd.conf + drbdadm, that
1763          * should check it for you already; but if you don't, or
1764          * someone fooled it, we need to double check here)
1765          */
1766         bdev = open_backing_dev(device, new_disk_conf->meta_dev,
1767                 /* claim ptr: device, if claimed exclusively; shared drbd_m_holder,
1768                  * if potentially shared with other drbd minors */
1769                         (new_disk_conf->meta_dev_idx < 0) ? (void*)device : (void*)drbd_m_holder,
1770                 /* avoid double bd_claim_by_disk() for the same (source,target) tuple,
1771                  * as would happen with internal metadata. */
1772                         (new_disk_conf->meta_dev_idx != DRBD_MD_INDEX_FLEX_INT &&
1773                          new_disk_conf->meta_dev_idx != DRBD_MD_INDEX_INTERNAL));
1774         if (IS_ERR(bdev))
1775                 return ERR_OPEN_MD_DISK;
1776         nbc->md_bdev = bdev;
1777         return NO_ERROR;
1778 }
1779
1780 static void close_backing_dev(struct drbd_device *device, struct block_device *bdev,
1781         bool do_bd_unlink)
1782 {
1783         if (!bdev)
1784                 return;
1785         if (do_bd_unlink)
1786                 bd_unlink_disk_holder(bdev, device->vdisk);
1787         blkdev_put(bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL);
1788 }
1789
1790 void drbd_backing_dev_free(struct drbd_device *device, struct drbd_backing_dev *ldev)
1791 {
1792         if (ldev == NULL)
1793                 return;
1794
1795         close_backing_dev(device, ldev->md_bdev, ldev->md_bdev != ldev->backing_bdev);
1796         close_backing_dev(device, ldev->backing_bdev, true);
1797
1798         kfree(ldev->disk_conf);
1799         kfree(ldev);
1800 }
1801
1802 int drbd_adm_attach(struct sk_buff *skb, struct genl_info *info)
1803 {
1804         struct drbd_config_context adm_ctx;
1805         struct drbd_device *device;
1806         struct drbd_peer_device *peer_device;
1807         struct drbd_connection *connection;
1808         int err;
1809         enum drbd_ret_code retcode;
1810         enum determine_dev_size dd;
1811         sector_t max_possible_sectors;
1812         sector_t min_md_device_sectors;
1813         struct drbd_backing_dev *nbc = NULL; /* new_backing_conf */
1814         struct disk_conf *new_disk_conf = NULL;
1815         struct lru_cache *resync_lru = NULL;
1816         struct fifo_buffer *new_plan = NULL;
1817         union drbd_state ns, os;
1818         enum drbd_state_rv rv;
1819         struct net_conf *nc;
1820
1821         retcode = drbd_adm_prepare(&adm_ctx, skb, info, DRBD_ADM_NEED_MINOR);
1822         if (!adm_ctx.reply_skb)
1823                 return retcode;
1824         if (retcode != NO_ERROR)
1825                 goto finish;
1826
1827         device = adm_ctx.device;
1828         mutex_lock(&adm_ctx.resource->adm_mutex);
1829         peer_device = first_peer_device(device);
1830         connection = peer_device->connection;
1831         conn_reconfig_start(connection);
1832
1833         /* if you want to reconfigure, please tear down first */
1834         if (device->state.disk > D_DISKLESS) {
1835                 retcode = ERR_DISK_CONFIGURED;
1836                 goto fail;
1837         }
1838         /* It may just now have detached because of IO error.  Make sure
1839          * drbd_ldev_destroy is done already, we may end up here very fast,
1840          * e.g. if someone calls attach from the on-io-error handler,
1841          * to realize a "hot spare" feature (not that I'd recommend that) */
1842         wait_event(device->misc_wait, !test_bit(GOING_DISKLESS, &device->flags));
1843
1844         /* make sure there is no leftover from previous force-detach attempts */
1845         clear_bit(FORCE_DETACH, &device->flags);
1846         clear_bit(WAS_IO_ERROR, &device->flags);
1847         clear_bit(WAS_READ_ERROR, &device->flags);
1848
1849         /* and no leftover from previously aborted resync or verify, either */
1850         device->rs_total = 0;
1851         device->rs_failed = 0;
1852         atomic_set(&device->rs_pending_cnt, 0);
1853
1854         /* allocation not in the IO path, drbdsetup context */
1855         nbc = kzalloc(sizeof(struct drbd_backing_dev), GFP_KERNEL);
1856         if (!nbc) {
1857                 retcode = ERR_NOMEM;
1858                 goto fail;
1859         }
1860         spin_lock_init(&nbc->md.uuid_lock);
1861
1862         new_disk_conf = kzalloc(sizeof(struct disk_conf), GFP_KERNEL);
1863         if (!new_disk_conf) {
1864                 retcode = ERR_NOMEM;
1865                 goto fail;
1866         }
1867         nbc->disk_conf = new_disk_conf;
1868
1869         set_disk_conf_defaults(new_disk_conf);
1870         err = disk_conf_from_attrs(new_disk_conf, info);
1871         if (err) {
1872                 retcode = ERR_MANDATORY_TAG;
1873                 drbd_msg_put_info(adm_ctx.reply_skb, from_attrs_err_to_txt(err));
1874                 goto fail;
1875         }
1876
1877         if (new_disk_conf->c_plan_ahead > DRBD_C_PLAN_AHEAD_MAX)
1878                 new_disk_conf->c_plan_ahead = DRBD_C_PLAN_AHEAD_MAX;
1879
1880         new_plan = fifo_alloc((new_disk_conf->c_plan_ahead * 10 * SLEEP_TIME) / HZ);
1881         if (!new_plan) {
1882                 retcode = ERR_NOMEM;
1883                 goto fail;
1884         }
1885
1886         if (new_disk_conf->meta_dev_idx < DRBD_MD_INDEX_FLEX_INT) {
1887                 retcode = ERR_MD_IDX_INVALID;
1888                 goto fail;
1889         }
1890
1891         rcu_read_lock();
1892         nc = rcu_dereference(connection->net_conf);
1893         if (nc) {
1894                 if (new_disk_conf->fencing == FP_STONITH && nc->wire_protocol == DRBD_PROT_A) {
1895                         rcu_read_unlock();
1896                         retcode = ERR_STONITH_AND_PROT_A;
1897                         goto fail;
1898                 }
1899         }
1900         rcu_read_unlock();
1901
1902         retcode = open_backing_devices(device, new_disk_conf, nbc);
1903         if (retcode != NO_ERROR)
1904                 goto fail;
1905
1906         if ((nbc->backing_bdev == nbc->md_bdev) !=
1907             (new_disk_conf->meta_dev_idx == DRBD_MD_INDEX_INTERNAL ||
1908              new_disk_conf->meta_dev_idx == DRBD_MD_INDEX_FLEX_INT)) {
1909                 retcode = ERR_MD_IDX_INVALID;
1910                 goto fail;
1911         }
1912
1913         resync_lru = lc_create("resync", drbd_bm_ext_cache,
1914                         1, 61, sizeof(struct bm_extent),
1915                         offsetof(struct bm_extent, lce));
1916         if (!resync_lru) {
1917                 retcode = ERR_NOMEM;
1918                 goto fail;
1919         }
1920
1921         /* Read our meta data super block early.
1922          * This also sets other on-disk offsets. */
1923         retcode = drbd_md_read(device, nbc);
1924         if (retcode != NO_ERROR)
1925                 goto fail;
1926
1927         sanitize_disk_conf(device, new_disk_conf, nbc);
1928
1929         if (drbd_get_max_capacity(nbc) < new_disk_conf->disk_size) {
1930                 drbd_err(device, "max capacity %llu smaller than disk size %llu\n",
1931                         (unsigned long long) drbd_get_max_capacity(nbc),
1932                         (unsigned long long) new_disk_conf->disk_size);
1933                 retcode = ERR_DISK_TOO_SMALL;
1934                 goto fail;
1935         }
1936
1937         if (new_disk_conf->meta_dev_idx < 0) {
1938                 max_possible_sectors = DRBD_MAX_SECTORS_FLEX;
1939                 /* at least one MB, otherwise it does not make sense */
1940                 min_md_device_sectors = (2<<10);
1941         } else {
1942                 max_possible_sectors = DRBD_MAX_SECTORS;
1943                 min_md_device_sectors = MD_128MB_SECT * (new_disk_conf->meta_dev_idx + 1);
1944         }
1945
1946         if (drbd_get_capacity(nbc->md_bdev) < min_md_device_sectors) {
1947                 retcode = ERR_MD_DISK_TOO_SMALL;
1948                 drbd_warn(device, "refusing attach: md-device too small, "
1949                      "at least %llu sectors needed for this meta-disk type\n",
1950                      (unsigned long long) min_md_device_sectors);
1951                 goto fail;
1952         }
1953
1954         /* Make sure the new disk is big enough
1955          * (we may currently be R_PRIMARY with no local disk...) */
1956         if (drbd_get_max_capacity(nbc) <
1957             drbd_get_capacity(device->this_bdev)) {
1958                 retcode = ERR_DISK_TOO_SMALL;
1959                 goto fail;
1960         }
1961
1962         nbc->known_size = drbd_get_capacity(nbc->backing_bdev);
1963
1964         if (nbc->known_size > max_possible_sectors) {
1965                 drbd_warn(device, "==> truncating very big lower level device "
1966                         "to currently maximum possible %llu sectors <==\n",
1967                         (unsigned long long) max_possible_sectors);
1968                 if (new_disk_conf->meta_dev_idx >= 0)
1969                         drbd_warn(device, "==>> using internal or flexible "
1970                                       "meta data may help <<==\n");
1971         }
1972
1973         drbd_suspend_io(device);
1974         /* also wait for the last barrier ack. */
1975         /* FIXME see also https://daiquiri.linbit/cgi-bin/bugzilla/show_bug.cgi?id=171
1976          * We need a way to either ignore barrier acks for barriers sent before a device
1977          * was attached, or a way to wait for all pending barrier acks to come in.
1978          * As barriers are counted per resource,
1979          * we'd need to suspend io on all devices of a resource.
1980          */
1981         wait_event(device->misc_wait, !atomic_read(&device->ap_pending_cnt) || drbd_suspended(device));
1982         /* and for any other previously queued work */
1983         drbd_flush_workqueue(&connection->sender_work);
1984
1985         rv = _drbd_request_state(device, NS(disk, D_ATTACHING), CS_VERBOSE);
1986         retcode = rv;  /* FIXME: Type mismatch. */
1987         drbd_resume_io(device);
1988         if (rv < SS_SUCCESS)
1989                 goto fail;
1990
1991         if (!get_ldev_if_state(device, D_ATTACHING))
1992                 goto force_diskless;
1993
1994         if (!device->bitmap) {
1995                 if (drbd_bm_init(device)) {
1996                         retcode = ERR_NOMEM;
1997                         goto force_diskless_dec;
1998                 }
1999         }
2000
2001         if (device->state.pdsk != D_UP_TO_DATE && device->ed_uuid &&
2002             (device->state.role == R_PRIMARY || device->state.peer == R_PRIMARY) &&
2003             (device->ed_uuid & ~((u64)1)) != (nbc->md.uuid[UI_CURRENT] & ~((u64)1))) {
2004                 drbd_err(device, "Can only attach to data with current UUID=%016llX\n",
2005                     (unsigned long long)device->ed_uuid);
2006                 retcode = ERR_DATA_NOT_CURRENT;
2007                 goto force_diskless_dec;
2008         }
2009
2010         /* Since we are diskless, fix the activity log first... */
2011         if (drbd_check_al_size(device, new_disk_conf)) {
2012                 retcode = ERR_NOMEM;
2013                 goto force_diskless_dec;
2014         }
2015
2016         /* Prevent shrinking of consistent devices ! */
2017         {
2018         unsigned long long nsz = drbd_new_dev_size(device, nbc, nbc->disk_conf->disk_size, 0);
2019         unsigned long long eff = nbc->md.la_size_sect;
2020         if (drbd_md_test_flag(nbc, MDF_CONSISTENT) && nsz < eff) {
2021                 if (nsz == nbc->disk_conf->disk_size) {
2022                         drbd_warn(device, "truncating a consistent device during attach (%llu < %llu)\n", nsz, eff);
2023                 } else {
2024                         drbd_warn(device, "refusing to truncate a consistent device (%llu < %llu)\n", nsz, eff);
2025                         drbd_msg_sprintf_info(adm_ctx.reply_skb,
2026                                 "To-be-attached device has last effective > current size, and is consistent\n"
2027                                 "(%llu > %llu sectors). Refusing to attach.", eff, nsz);
2028                         retcode = ERR_IMPLICIT_SHRINK;
2029                         goto force_diskless_dec;
2030                 }
2031         }
2032         }
2033
2034         lock_all_resources();
2035         retcode = drbd_resync_after_valid(device, new_disk_conf->resync_after);
2036         if (retcode != NO_ERROR) {
2037                 unlock_all_resources();
2038                 goto force_diskless_dec;
2039         }
2040
2041         /* Reset the "barriers don't work" bits here, then force meta data to
2042          * be written, to ensure we determine if barriers are supported. */
2043         if (new_disk_conf->md_flushes)
2044                 clear_bit(MD_NO_FUA, &device->flags);
2045         else
2046                 set_bit(MD_NO_FUA, &device->flags);
2047
2048         /* Point of no return reached.
2049          * Devices and memory are no longer released by error cleanup below.
2050          * now device takes over responsibility, and the state engine should
2051          * clean it up somewhere.  */
2052         D_ASSERT(device, device->ldev == NULL);
2053         device->ldev = nbc;
2054         device->resync = resync_lru;
2055         device->rs_plan_s = new_plan;
2056         nbc = NULL;
2057         resync_lru = NULL;
2058         new_disk_conf = NULL;
2059         new_plan = NULL;
2060
2061         drbd_resync_after_changed(device);
2062         drbd_bump_write_ordering(device->resource, device->ldev, WO_BDEV_FLUSH);
2063         unlock_all_resources();
2064
2065         if (drbd_md_test_flag(device->ldev, MDF_CRASHED_PRIMARY))
2066                 set_bit(CRASHED_PRIMARY, &device->flags);
2067         else
2068                 clear_bit(CRASHED_PRIMARY, &device->flags);
2069
2070         if (drbd_md_test_flag(device->ldev, MDF_PRIMARY_IND) &&
2071             !(device->state.role == R_PRIMARY && device->resource->susp_nod))
2072                 set_bit(CRASHED_PRIMARY, &device->flags);
2073
2074         device->send_cnt = 0;
2075         device->recv_cnt = 0;
2076         device->read_cnt = 0;
2077         device->writ_cnt = 0;
2078
2079         drbd_reconsider_queue_parameters(device, device->ldev, NULL);
2080
2081         /* If I am currently not R_PRIMARY,
2082          * but meta data primary indicator is set,
2083          * I just now recover from a hard crash,
2084          * and have been R_PRIMARY before that crash.
2085          *
2086          * Now, if I had no connection before that crash
2087          * (have been degraded R_PRIMARY), chances are that
2088          * I won't find my peer now either.
2089          *
2090          * In that case, and _only_ in that case,
2091          * we use the degr-wfc-timeout instead of the default,
2092          * so we can automatically recover from a crash of a
2093          * degraded but active "cluster" after a certain timeout.
2094          */
2095         clear_bit(USE_DEGR_WFC_T, &device->flags);
2096         if (device->state.role != R_PRIMARY &&
2097              drbd_md_test_flag(device->ldev, MDF_PRIMARY_IND) &&
2098             !drbd_md_test_flag(device->ldev, MDF_CONNECTED_IND))
2099                 set_bit(USE_DEGR_WFC_T, &device->flags);
2100
2101         dd = drbd_determine_dev_size(device, 0, NULL);
2102         if (dd <= DS_ERROR) {
2103                 retcode = ERR_NOMEM_BITMAP;
2104                 goto force_diskless_dec;
2105         } else if (dd == DS_GREW)
2106                 set_bit(RESYNC_AFTER_NEG, &device->flags);
2107
2108         if (drbd_md_test_flag(device->ldev, MDF_FULL_SYNC) ||
2109             (test_bit(CRASHED_PRIMARY, &device->flags) &&
2110              drbd_md_test_flag(device->ldev, MDF_AL_DISABLED))) {
2111                 drbd_info(device, "Assuming that all blocks are out of sync "
2112                      "(aka FullSync)\n");
2113                 if (drbd_bitmap_io(device, &drbd_bmio_set_n_write,
2114                         "set_n_write from attaching", BM_LOCKED_MASK)) {
2115                         retcode = ERR_IO_MD_DISK;
2116                         goto force_diskless_dec;
2117                 }
2118         } else {
2119                 if (drbd_bitmap_io(device, &drbd_bm_read,
2120                         "read from attaching", BM_LOCKED_MASK)) {
2121                         retcode = ERR_IO_MD_DISK;
2122                         goto force_diskless_dec;
2123                 }
2124         }
2125
2126         if (_drbd_bm_total_weight(device) == drbd_bm_bits(device))
2127                 drbd_suspend_al(device); /* IO is still suspended here... */
2128
2129         spin_lock_irq(&device->resource->req_lock);
2130         os = drbd_read_state(device);
2131         ns = os;
2132         /* If MDF_CONSISTENT is not set go into inconsistent state,
2133            otherwise investigate MDF_WasUpToDate...
2134            If MDF_WAS_UP_TO_DATE is not set go into D_OUTDATED disk state,
2135            otherwise into D_CONSISTENT state.
2136         */
2137         if (drbd_md_test_flag(device->ldev, MDF_CONSISTENT)) {
2138                 if (drbd_md_test_flag(device->ldev, MDF_WAS_UP_TO_DATE))
2139                         ns.disk = D_CONSISTENT;
2140                 else
2141                         ns.disk = D_OUTDATED;
2142         } else {
2143                 ns.disk = D_INCONSISTENT;
2144         }
2145
2146         if (drbd_md_test_flag(device->ldev, MDF_PEER_OUT_DATED))
2147                 ns.pdsk = D_OUTDATED;
2148
2149         rcu_read_lock();
2150         if (ns.disk == D_CONSISTENT &&
2151             (ns.pdsk == D_OUTDATED || rcu_dereference(device->ldev->disk_conf)->fencing == FP_DONT_CARE))
2152                 ns.disk = D_UP_TO_DATE;
2153
2154         /* All tests on MDF_PRIMARY_IND, MDF_CONNECTED_IND,
2155            MDF_CONSISTENT and MDF_WAS_UP_TO_DATE must happen before
2156            this point, because drbd_request_state() modifies these
2157            flags. */
2158
2159         if (rcu_dereference(device->ldev->disk_conf)->al_updates)
2160                 device->ldev->md.flags &= ~MDF_AL_DISABLED;
2161         else
2162                 device->ldev->md.flags |= MDF_AL_DISABLED;
2163
2164         rcu_read_unlock();
2165
2166         /* In case we are C_CONNECTED postpone any decision on the new disk
2167            state after the negotiation phase. */
2168         if (device->state.conn == C_CONNECTED) {
2169                 device->new_state_tmp.i = ns.i;
2170                 ns.i = os.i;
2171                 ns.disk = D_NEGOTIATING;
2172
2173                 /* We expect to receive up-to-date UUIDs soon.
2174                    To avoid a race in receive_state, free p_uuid while
2175                    holding req_lock. I.e. atomic with the state change */
2176                 kfree(device->p_uuid);
2177                 device->p_uuid = NULL;
2178         }
2179
2180         rv = _drbd_set_state(device, ns, CS_VERBOSE, NULL);
2181         spin_unlock_irq(&device->resource->req_lock);
2182
2183         if (rv < SS_SUCCESS)
2184                 goto force_diskless_dec;
2185
2186         mod_timer(&device->request_timer, jiffies + HZ);
2187
2188         if (device->state.role == R_PRIMARY)
2189                 device->ldev->md.uuid[UI_CURRENT] |=  (u64)1;
2190         else
2191                 device->ldev->md.uuid[UI_CURRENT] &= ~(u64)1;
2192
2193         drbd_md_mark_dirty(device);
2194         drbd_md_sync(device);
2195
2196         kobject_uevent(&disk_to_dev(device->vdisk)->kobj, KOBJ_CHANGE);
2197         put_ldev(device);
2198         conn_reconfig_done(connection);
2199         mutex_unlock(&adm_ctx.resource->adm_mutex);
2200         drbd_adm_finish(&adm_ctx, info, retcode);
2201         return 0;
2202
2203  force_diskless_dec:
2204         put_ldev(device);
2205  force_diskless:
2206         drbd_force_state(device, NS(disk, D_DISKLESS));
2207         drbd_md_sync(device);
2208  fail:
2209         conn_reconfig_done(connection);
2210         if (nbc) {
2211                 close_backing_dev(device, nbc->md_bdev, nbc->md_bdev != nbc->backing_bdev);
2212                 close_backing_dev(device, nbc->backing_bdev, true);
2213                 kfree(nbc);
2214         }
2215         kfree(new_disk_conf);
2216         lc_destroy(resync_lru);
2217         kfree(new_plan);
2218         mutex_unlock(&adm_ctx.resource->adm_mutex);
2219  finish:
2220         drbd_adm_finish(&adm_ctx, info, retcode);
2221         return 0;
2222 }
2223
2224 static int adm_detach(struct drbd_device *device, int force)
2225 {
2226         if (force) {
2227                 set_bit(FORCE_DETACH, &device->flags);
2228                 drbd_force_state(device, NS(disk, D_FAILED));
2229                 return SS_SUCCESS;
2230         }
2231
2232         return drbd_request_detach_interruptible(device);
2233 }
2234
2235 /* Detaching the disk is a process in multiple stages.  First we need to lock
2236  * out application IO, in-flight IO, IO stuck in drbd_al_begin_io.
2237  * Then we transition to D_DISKLESS, and wait for put_ldev() to return all
2238  * internal references as well.
2239  * Only then we have finally detached. */
2240 int drbd_adm_detach(struct sk_buff *skb, struct genl_info *info)
2241 {
2242         struct drbd_config_context adm_ctx;
2243         enum drbd_ret_code retcode;
2244         struct detach_parms parms = { };
2245         int err;
2246
2247         retcode = drbd_adm_prepare(&adm_ctx, skb, info, DRBD_ADM_NEED_MINOR);
2248         if (!adm_ctx.reply_skb)
2249                 return retcode;
2250         if (retcode != NO_ERROR)
2251                 goto out;
2252
2253         if (info->attrs[DRBD_NLA_DETACH_PARMS]) {
2254                 err = detach_parms_from_attrs(&parms, info);
2255                 if (err) {
2256                         retcode = ERR_MANDATORY_TAG;
2257                         drbd_msg_put_info(adm_ctx.reply_skb, from_attrs_err_to_txt(err));
2258                         goto out;
2259                 }
2260         }
2261
2262         mutex_lock(&adm_ctx.resource->adm_mutex);
2263         retcode = adm_detach(adm_ctx.device, parms.force_detach);
2264         mutex_unlock(&adm_ctx.resource->adm_mutex);
2265 out:
2266         drbd_adm_finish(&adm_ctx, info, retcode);
2267         return 0;
2268 }
2269
2270 static bool conn_resync_running(struct drbd_connection *connection)
2271 {
2272         struct drbd_peer_device *peer_device;
2273         bool rv = false;
2274         int vnr;
2275
2276         rcu_read_lock();
2277         idr_for_each_entry(&connection->peer_devices, peer_device, vnr) {
2278                 struct drbd_device *device = peer_device->device;
2279                 if (device->state.conn == C_SYNC_SOURCE ||
2280                     device->state.conn == C_SYNC_TARGET ||
2281                     device->state.conn == C_PAUSED_SYNC_S ||
2282                     device->state.conn == C_PAUSED_SYNC_T) {
2283                         rv = true;
2284                         break;
2285                 }
2286         }
2287         rcu_read_unlock();
2288
2289         return rv;
2290 }
2291
2292 static bool conn_ov_running(struct drbd_connection *connection)
2293 {
2294         struct drbd_peer_device *peer_device;
2295         bool rv = false;
2296         int vnr;
2297
2298         rcu_read_lock();
2299         idr_for_each_entry(&connection->peer_devices, peer_device, vnr) {
2300                 struct drbd_device *device = peer_device->device;
2301                 if (device->state.conn == C_VERIFY_S ||
2302                     device->state.conn == C_VERIFY_T) {
2303                         rv = true;
2304                         break;
2305                 }
2306         }
2307         rcu_read_unlock();
2308
2309         return rv;
2310 }
2311
2312 static enum drbd_ret_code
2313 _check_net_options(struct drbd_connection *connection, struct net_conf *old_net_conf, struct net_conf *new_net_conf)
2314 {
2315         struct drbd_peer_device *peer_device;
2316         int i;
2317
2318         if (old_net_conf && connection->cstate == C_WF_REPORT_PARAMS && connection->agreed_pro_version < 100) {
2319                 if (new_net_conf->wire_protocol != old_net_conf->wire_protocol)
2320                         return ERR_NEED_APV_100;
2321
2322                 if (new_net_conf->two_primaries != old_net_conf->two_primaries)
2323                         return ERR_NEED_APV_100;
2324
2325                 if (strcmp(new_net_conf->integrity_alg, old_net_conf->integrity_alg))
2326                         return ERR_NEED_APV_100;
2327         }
2328
2329         if (!new_net_conf->two_primaries &&
2330             conn_highest_role(connection) == R_PRIMARY &&
2331             conn_highest_peer(connection) == R_PRIMARY)
2332                 return ERR_NEED_ALLOW_TWO_PRI;
2333
2334         if (new_net_conf->two_primaries &&
2335             (new_net_conf->wire_protocol != DRBD_PROT_C))
2336                 return ERR_NOT_PROTO_C;
2337
2338         idr_for_each_entry(&connection->peer_devices, peer_device, i) {
2339                 struct drbd_device *device = peer_device->device;
2340                 if (get_ldev(device)) {
2341                         enum drbd_fencing_p fp = rcu_dereference(device->ldev->disk_conf)->fencing;
2342                         put_ldev(device);
2343                         if (new_net_conf->wire_protocol == DRBD_PROT_A && fp == FP_STONITH)
2344                                 return ERR_STONITH_AND_PROT_A;
2345                 }
2346                 if (device->state.role == R_PRIMARY && new_net_conf->discard_my_data)
2347                         return ERR_DISCARD_IMPOSSIBLE;
2348         }
2349
2350         if (new_net_conf->on_congestion != OC_BLOCK && new_net_conf->wire_protocol != DRBD_PROT_A)
2351                 return ERR_CONG_NOT_PROTO_A;
2352
2353         return NO_ERROR;
2354 }
2355
2356 static enum drbd_ret_code
2357 check_net_options(struct drbd_connection *connection, struct net_conf *new_net_conf)
2358 {
2359         enum drbd_ret_code rv;
2360         struct drbd_peer_device *peer_device;
2361         int i;
2362
2363         rcu_read_lock();
2364         rv = _check_net_options(connection, rcu_dereference(connection->net_conf), new_net_conf);
2365         rcu_read_unlock();
2366
2367         /* connection->peer_devices protected by genl_lock() here */
2368         idr_for_each_entry(&connection->peer_devices, peer_device, i) {
2369                 struct drbd_device *device = peer_device->device;
2370                 if (!device->bitmap) {
2371                         if (drbd_bm_init(device))
2372                                 return ERR_NOMEM;
2373                 }
2374         }
2375
2376         return rv;
2377 }
2378
2379 struct crypto {
2380         struct crypto_shash *verify_tfm;
2381         struct crypto_shash *csums_tfm;
2382         struct crypto_shash *cram_hmac_tfm;
2383         struct crypto_shash *integrity_tfm;
2384 };
2385
2386 static int
2387 alloc_shash(struct crypto_shash **tfm, char *tfm_name, int err_alg)
2388 {
2389         if (!tfm_name[0])
2390                 return NO_ERROR;
2391
2392         *tfm = crypto_alloc_shash(tfm_name, 0, 0);
2393         if (IS_ERR(*tfm)) {
2394                 *tfm = NULL;
2395                 return err_alg;
2396         }
2397
2398         return NO_ERROR;
2399 }
2400
2401 static enum drbd_ret_code
2402 alloc_crypto(struct crypto *crypto, struct net_conf *new_net_conf)
2403 {
2404         char hmac_name[CRYPTO_MAX_ALG_NAME];
2405         enum drbd_ret_code rv;
2406
2407         rv = alloc_shash(&crypto->csums_tfm, new_net_conf->csums_alg,
2408                          ERR_CSUMS_ALG);
2409         if (rv != NO_ERROR)
2410                 return rv;
2411         rv = alloc_shash(&crypto->verify_tfm, new_net_conf->verify_alg,
2412                          ERR_VERIFY_ALG);
2413         if (rv != NO_ERROR)
2414                 return rv;
2415         rv = alloc_shash(&crypto->integrity_tfm, new_net_conf->integrity_alg,
2416                          ERR_INTEGRITY_ALG);
2417         if (rv != NO_ERROR)
2418                 return rv;
2419         if (new_net_conf->cram_hmac_alg[0] != 0) {
2420                 snprintf(hmac_name, CRYPTO_MAX_ALG_NAME, "hmac(%s)",
2421                          new_net_conf->cram_hmac_alg);
2422
2423                 rv = alloc_shash(&crypto->cram_hmac_tfm, hmac_name,
2424                                  ERR_AUTH_ALG);
2425         }
2426
2427         return rv;
2428 }
2429
2430 static void free_crypto(struct crypto *crypto)
2431 {
2432         crypto_free_shash(crypto->cram_hmac_tfm);
2433         crypto_free_shash(crypto->integrity_tfm);
2434         crypto_free_shash(crypto->csums_tfm);
2435         crypto_free_shash(crypto->verify_tfm);
2436 }
2437
2438 int drbd_adm_net_opts(struct sk_buff *skb, struct genl_info *info)
2439 {
2440         struct drbd_config_context adm_ctx;
2441         enum drbd_ret_code retcode;
2442         struct drbd_connection *connection;
2443         struct net_conf *old_net_conf, *new_net_conf = NULL;
2444         int err;
2445         int ovr; /* online verify running */
2446         int rsr; /* re-sync running */
2447         struct crypto crypto = { };
2448
2449         retcode = drbd_adm_prepare(&adm_ctx, skb, info, DRBD_ADM_NEED_CONNECTION);
2450         if (!adm_ctx.reply_skb)
2451                 return retcode;
2452         if (retcode != NO_ERROR)
2453                 goto finish;
2454
2455         connection = adm_ctx.connection;
2456         mutex_lock(&adm_ctx.resource->adm_mutex);
2457
2458         new_net_conf = kzalloc(sizeof(struct net_conf), GFP_KERNEL);
2459         if (!new_net_conf) {
2460                 retcode = ERR_NOMEM;
2461                 goto out;
2462         }
2463
2464         conn_reconfig_start(connection);
2465
2466         mutex_lock(&connection->data.mutex);
2467         mutex_lock(&connection->resource->conf_update);
2468         old_net_conf = connection->net_conf;
2469
2470         if (!old_net_conf) {
2471                 drbd_msg_put_info(adm_ctx.reply_skb, "net conf missing, try connect");
2472                 retcode = ERR_INVALID_REQUEST;
2473                 goto fail;
2474         }
2475
2476         *new_net_conf = *old_net_conf;
2477         if (should_set_defaults(info))
2478                 set_net_conf_defaults(new_net_conf);
2479
2480         err = net_conf_from_attrs_for_change(new_net_conf, info);
2481         if (err && err != -ENOMSG) {
2482                 retcode = ERR_MANDATORY_TAG;
2483                 drbd_msg_put_info(adm_ctx.reply_skb, from_attrs_err_to_txt(err));
2484                 goto fail;
2485         }
2486
2487         retcode = check_net_options(connection, new_net_conf);
2488         if (retcode != NO_ERROR)
2489                 goto fail;
2490
2491         /* re-sync running */
2492         rsr = conn_resync_running(connection);
2493         if (rsr && strcmp(new_net_conf->csums_alg, old_net_conf->csums_alg)) {
2494                 retcode = ERR_CSUMS_RESYNC_RUNNING;
2495                 goto fail;
2496         }
2497
2498         /* online verify running */
2499         ovr = conn_ov_running(connection);
2500         if (ovr && strcmp(new_net_conf->verify_alg, old_net_conf->verify_alg)) {
2501                 retcode = ERR_VERIFY_RUNNING;
2502                 goto fail;
2503         }
2504
2505         retcode = alloc_crypto(&crypto, new_net_conf);
2506         if (retcode != NO_ERROR)
2507                 goto fail;
2508
2509         rcu_assign_pointer(connection->net_conf, new_net_conf);
2510
2511         if (!rsr) {
2512                 crypto_free_shash(connection->csums_tfm);
2513                 connection->csums_tfm = crypto.csums_tfm;
2514                 crypto.csums_tfm = NULL;
2515         }
2516         if (!ovr) {
2517                 crypto_free_shash(connection->verify_tfm);
2518                 connection->verify_tfm = crypto.verify_tfm;
2519                 crypto.verify_tfm = NULL;
2520         }
2521
2522         crypto_free_shash(connection->integrity_tfm);
2523         connection->integrity_tfm = crypto.integrity_tfm;
2524         if (connection->cstate >= C_WF_REPORT_PARAMS && connection->agreed_pro_version >= 100)
2525                 /* Do this without trying to take connection->data.mutex again.  */
2526                 __drbd_send_protocol(connection, P_PROTOCOL_UPDATE);
2527
2528         crypto_free_shash(connection->cram_hmac_tfm);
2529         connection->cram_hmac_tfm = crypto.cram_hmac_tfm;
2530
2531         mutex_unlock(&connection->resource->conf_update);
2532         mutex_unlock(&connection->data.mutex);
2533         synchronize_rcu();
2534         kfree(old_net_conf);
2535
2536         if (connection->cstate >= C_WF_REPORT_PARAMS) {
2537                 struct drbd_peer_device *peer_device;
2538                 int vnr;
2539
2540                 idr_for_each_entry(&connection->peer_devices, peer_device, vnr)
2541                         drbd_send_sync_param(peer_device);
2542         }
2543
2544         goto done;
2545
2546  fail:
2547         mutex_unlock(&connection->resource->conf_update);
2548         mutex_unlock(&connection->data.mutex);
2549         free_crypto(&crypto);
2550         kfree(new_net_conf);
2551  done:
2552         conn_reconfig_done(connection);
2553  out:
2554         mutex_unlock(&adm_ctx.resource->adm_mutex);
2555  finish:
2556         drbd_adm_finish(&adm_ctx, info, retcode);
2557         return 0;
2558 }
2559
2560 static void connection_to_info(struct connection_info *info,
2561                                struct drbd_connection *connection)
2562 {
2563         info->conn_connection_state = connection->cstate;
2564         info->conn_role = conn_highest_peer(connection);
2565 }
2566
2567 static void peer_device_to_info(struct peer_device_info *info,
2568                                 struct drbd_peer_device *peer_device)
2569 {
2570         struct drbd_device *device = peer_device->device;
2571
2572         info->peer_repl_state =
2573                 max_t(enum drbd_conns, C_WF_REPORT_PARAMS, device->state.conn);
2574         info->peer_disk_state = device->state.pdsk;
2575         info->peer_resync_susp_user = device->state.user_isp;
2576         info->peer_resync_susp_peer = device->state.peer_isp;
2577         info->peer_resync_susp_dependency = device->state.aftr_isp;
2578 }
2579
2580 int drbd_adm_connect(struct sk_buff *skb, struct genl_info *info)
2581 {
2582         struct connection_info connection_info;
2583         enum drbd_notification_type flags;
2584         unsigned int peer_devices = 0;
2585         struct drbd_config_context adm_ctx;
2586         struct drbd_peer_device *peer_device;
2587         struct net_conf *old_net_conf, *new_net_conf = NULL;
2588         struct crypto crypto = { };
2589         struct drbd_resource *resource;
2590         struct drbd_connection *connection;
2591         enum drbd_ret_code retcode;
2592         int i;
2593         int err;
2594
2595         retcode = drbd_adm_prepare(&adm_ctx, skb, info, DRBD_ADM_NEED_RESOURCE);
2596
2597         if (!adm_ctx.reply_skb)
2598                 return retcode;
2599         if (retcode != NO_ERROR)
2600                 goto out;
2601         if (!(adm_ctx.my_addr && adm_ctx.peer_addr)) {
2602                 drbd_msg_put_info(adm_ctx.reply_skb, "connection endpoint(s) missing");
2603                 retcode = ERR_INVALID_REQUEST;
2604                 goto out;
2605         }
2606
2607         /* No need for _rcu here. All reconfiguration is
2608          * strictly serialized on genl_lock(). We are protected against
2609          * concurrent reconfiguration/addition/deletion */
2610         for_each_resource(resource, &drbd_resources) {
2611                 for_each_connection(connection, resource) {
2612                         if (nla_len(adm_ctx.my_addr) == connection->my_addr_len &&
2613                             !memcmp(nla_data(adm_ctx.my_addr), &connection->my_addr,
2614                                     connection->my_addr_len)) {
2615                                 retcode = ERR_LOCAL_ADDR;
2616                                 goto out;
2617                         }
2618
2619                         if (nla_len(adm_ctx.peer_addr) == connection->peer_addr_len &&
2620                             !memcmp(nla_data(adm_ctx.peer_addr), &connection->peer_addr,
2621                                     connection->peer_addr_len)) {
2622                                 retcode = ERR_PEER_ADDR;
2623                                 goto out;
2624                         }
2625                 }
2626         }
2627
2628         mutex_lock(&adm_ctx.resource->adm_mutex);
2629         connection = first_connection(adm_ctx.resource);
2630         conn_reconfig_start(connection);
2631
2632         if (connection->cstate > C_STANDALONE) {
2633                 retcode = ERR_NET_CONFIGURED;
2634                 goto fail;
2635         }
2636
2637         /* allocation not in the IO path, drbdsetup / netlink process context */
2638         new_net_conf = kzalloc(sizeof(*new_net_conf), GFP_KERNEL);
2639         if (!new_net_conf) {
2640                 retcode = ERR_NOMEM;
2641                 goto fail;
2642         }
2643
2644         set_net_conf_defaults(new_net_conf);
2645
2646         err = net_conf_from_attrs(new_net_conf, info);
2647         if (err && err != -ENOMSG) {
2648                 retcode = ERR_MANDATORY_TAG;
2649                 drbd_msg_put_info(adm_ctx.reply_skb, from_attrs_err_to_txt(err));
2650                 goto fail;
2651         }
2652
2653         retcode = check_net_options(connection, new_net_conf);
2654         if (retcode != NO_ERROR)
2655                 goto fail;
2656
2657         retcode = alloc_crypto(&crypto, new_net_conf);
2658         if (retcode != NO_ERROR)
2659                 goto fail;
2660
2661         ((char *)new_net_conf->shared_secret)[SHARED_SECRET_MAX-1] = 0;
2662
2663         drbd_flush_workqueue(&connection->sender_work);
2664
2665         mutex_lock(&adm_ctx.resource->conf_update);
2666         old_net_conf = connection->net_conf;
2667         if (old_net_conf) {
2668                 retcode = ERR_NET_CONFIGURED;
2669                 mutex_unlock(&adm_ctx.resource->conf_update);
2670                 goto fail;
2671         }
2672         rcu_assign_pointer(connection->net_conf, new_net_conf);
2673
2674         conn_free_crypto(connection);
2675         connection->cram_hmac_tfm = crypto.cram_hmac_tfm;
2676         connection->integrity_tfm = crypto.integrity_tfm;
2677         connection->csums_tfm = crypto.csums_tfm;
2678         connection->verify_tfm = crypto.verify_tfm;
2679
2680         connection->my_addr_len = nla_len(adm_ctx.my_addr);
2681         memcpy(&connection->my_addr, nla_data(adm_ctx.my_addr), connection->my_addr_len);
2682         connection->peer_addr_len = nla_len(adm_ctx.peer_addr);
2683         memcpy(&connection->peer_addr, nla_data(adm_ctx.peer_addr), connection->peer_addr_len);
2684
2685         idr_for_each_entry(&connection->peer_devices, peer_device, i) {
2686                 peer_devices++;
2687         }
2688
2689         connection_to_info(&connection_info, connection);
2690         flags = (peer_devices--) ? NOTIFY_CONTINUES : 0;
2691         mutex_lock(&notification_mutex);
2692         notify_connection_state(NULL, 0, connection, &connection_info, NOTIFY_CREATE | flags);
2693         idr_for_each_entry(&connection->peer_devices, peer_device, i) {
2694                 struct peer_device_info peer_device_info;
2695
2696                 peer_device_to_info(&peer_device_info, peer_device);
2697                 flags = (peer_devices--) ? NOTIFY_CONTINUES : 0;
2698                 notify_peer_device_state(NULL, 0, peer_device, &peer_device_info, NOTIFY_CREATE | flags);
2699         }
2700         mutex_unlock(&notification_mutex);
2701         mutex_unlock(&adm_ctx.resource->conf_update);
2702
2703         rcu_read_lock();
2704         idr_for_each_entry(&connection->peer_devices, peer_device, i) {
2705                 struct drbd_device *device = peer_device->device;
2706                 device->send_cnt = 0;
2707                 device->recv_cnt = 0;
2708         }
2709         rcu_read_unlock();
2710
2711         retcode = conn_request_state(connection, NS(conn, C_UNCONNECTED), CS_VERBOSE);
2712
2713         conn_reconfig_done(connection);
2714         mutex_unlock(&adm_ctx.resource->adm_mutex);
2715         drbd_adm_finish(&adm_ctx, info, retcode);
2716         return 0;
2717
2718 fail:
2719         free_crypto(&crypto);
2720         kfree(new_net_conf);
2721
2722         conn_reconfig_done(connection);
2723         mutex_unlock(&adm_ctx.resource->adm_mutex);
2724 out:
2725         drbd_adm_finish(&adm_ctx, info, retcode);
2726         return 0;
2727 }
2728
2729 static enum drbd_state_rv conn_try_disconnect(struct drbd_connection *connection, bool force)
2730 {
2731         enum drbd_conns cstate;
2732         enum drbd_state_rv rv;
2733
2734 repeat:
2735         rv = conn_request_state(connection, NS(conn, C_DISCONNECTING),
2736                         force ? CS_HARD : 0);
2737
2738         switch (rv) {
2739         case SS_NOTHING_TO_DO:
2740                 break;
2741         case SS_ALREADY_STANDALONE:
2742                 return SS_SUCCESS;
2743         case SS_PRIMARY_NOP:
2744                 /* Our state checking code wants to see the peer outdated. */
2745                 rv = conn_request_state(connection, NS2(conn, C_DISCONNECTING, pdsk, D_OUTDATED), 0);
2746
2747                 if (rv == SS_OUTDATE_WO_CONN) /* lost connection before graceful disconnect succeeded */
2748                         rv = conn_request_state(connection, NS(conn, C_DISCONNECTING), CS_VERBOSE);
2749
2750                 break;
2751         case SS_CW_FAILED_BY_PEER:
2752                 spin_lock_irq(&connection->resource->req_lock);
2753                 cstate = connection->cstate;
2754                 spin_unlock_irq(&connection->resource->req_lock);
2755                 if (cstate <= C_WF_CONNECTION)
2756                         goto repeat;
2757                 /* The peer probably wants to see us outdated. */
2758                 rv = conn_request_state(connection, NS2(conn, C_DISCONNECTING,
2759                                                         disk, D_OUTDATED), 0);
2760                 if (rv == SS_IS_DISKLESS || rv == SS_LOWER_THAN_OUTDATED) {
2761                         rv = conn_request_state(connection, NS(conn, C_DISCONNECTING),
2762                                         CS_HARD);
2763                 }
2764                 break;
2765         default:;
2766                 /* no special handling necessary */
2767         }
2768
2769         if (rv >= SS_SUCCESS) {
2770                 enum drbd_state_rv rv2;
2771                 /* No one else can reconfigure the network while I am here.
2772                  * The state handling only uses drbd_thread_stop_nowait(),
2773                  * we want to really wait here until the receiver is no more.
2774                  */
2775                 drbd_thread_stop(&connection->receiver);
2776
2777                 /* Race breaker.  This additional state change request may be
2778                  * necessary, if this was a forced disconnect during a receiver
2779                  * restart.  We may have "killed" the receiver thread just
2780                  * after drbd_receiver() returned.  Typically, we should be
2781                  * C_STANDALONE already, now, and this becomes a no-op.
2782                  */
2783                 rv2 = conn_request_state(connection, NS(conn, C_STANDALONE),
2784                                 CS_VERBOSE | CS_HARD);
2785                 if (rv2 < SS_SUCCESS)
2786                         drbd_err(connection,
2787                                 "unexpected rv2=%d in conn_try_disconnect()\n",
2788                                 rv2);
2789                 /* Unlike in DRBD 9, the state engine has generated
2790                  * NOTIFY_DESTROY events before clearing connection->net_conf. */
2791         }
2792         return rv;
2793 }
2794
2795 int drbd_adm_disconnect(struct sk_buff *skb, struct genl_info *info)
2796 {
2797         struct drbd_config_context adm_ctx;
2798         struct disconnect_parms parms;
2799         struct drbd_connection *connection;
2800         enum drbd_state_rv rv;
2801         enum drbd_ret_code retcode;
2802         int err;
2803
2804         retcode = drbd_adm_prepare(&adm_ctx, skb, info, DRBD_ADM_NEED_CONNECTION);
2805         if (!adm_ctx.reply_skb)
2806                 return retcode;
2807         if (retcode != NO_ERROR)
2808                 goto fail;
2809
2810         connection = adm_ctx.connection;
2811         memset(&parms, 0, sizeof(parms));
2812         if (info->attrs[DRBD_NLA_DISCONNECT_PARMS]) {
2813                 err = disconnect_parms_from_attrs(&parms, info);
2814                 if (err) {
2815                         retcode = ERR_MANDATORY_TAG;
2816                         drbd_msg_put_info(adm_ctx.reply_skb, from_attrs_err_to_txt(err));
2817                         goto fail;
2818                 }
2819         }
2820
2821         mutex_lock(&adm_ctx.resource->adm_mutex);
2822         rv = conn_try_disconnect(connection, parms.force_disconnect);
2823         if (rv < SS_SUCCESS)
2824                 retcode = rv;  /* FIXME: Type mismatch. */
2825         else
2826                 retcode = NO_ERROR;
2827         mutex_unlock(&adm_ctx.resource->adm_mutex);
2828  fail:
2829         drbd_adm_finish(&adm_ctx, info, retcode);
2830         return 0;
2831 }
2832
2833 void resync_after_online_grow(struct drbd_device *device)
2834 {
2835         int iass; /* I am sync source */
2836
2837         drbd_info(device, "Resync of new storage after online grow\n");
2838         if (device->state.role != device->state.peer)
2839                 iass = (device->state.role == R_PRIMARY);
2840         else
2841                 iass = test_bit(RESOLVE_CONFLICTS, &first_peer_device(device)->connection->flags);
2842
2843         if (iass)
2844                 drbd_start_resync(device, C_SYNC_SOURCE);
2845         else
2846                 _drbd_request_state(device, NS(conn, C_WF_SYNC_UUID), CS_VERBOSE + CS_SERIALIZE);
2847 }
2848
2849 int drbd_adm_resize(struct sk_buff *skb, struct genl_info *info)
2850 {
2851         struct drbd_config_context adm_ctx;
2852         struct disk_conf *old_disk_conf, *new_disk_conf = NULL;
2853         struct resize_parms rs;
2854         struct drbd_device *device;
2855         enum drbd_ret_code retcode;
2856         enum determine_dev_size dd;
2857         bool change_al_layout = false;
2858         enum dds_flags ddsf;
2859         sector_t u_size;
2860         int err;
2861
2862         retcode = drbd_adm_prepare(&adm_ctx, skb, info, DRBD_ADM_NEED_MINOR);
2863         if (!adm_ctx.reply_skb)
2864                 return retcode;
2865         if (retcode != NO_ERROR)
2866                 goto finish;
2867
2868         mutex_lock(&adm_ctx.resource->adm_mutex);
2869         device = adm_ctx.device;
2870         if (!get_ldev(device)) {
2871                 retcode = ERR_NO_DISK;
2872                 goto fail;
2873         }
2874
2875         memset(&rs, 0, sizeof(struct resize_parms));
2876         rs.al_stripes = device->ldev->md.al_stripes;
2877         rs.al_stripe_size = device->ldev->md.al_stripe_size_4k * 4;
2878         if (info->attrs[DRBD_NLA_RESIZE_PARMS]) {
2879                 err = resize_parms_from_attrs(&rs, info);
2880                 if (err) {
2881                         retcode = ERR_MANDATORY_TAG;
2882                         drbd_msg_put_info(adm_ctx.reply_skb, from_attrs_err_to_txt(err));
2883                         goto fail_ldev;
2884                 }
2885         }
2886
2887         if (device->state.conn > C_CONNECTED) {
2888                 retcode = ERR_RESIZE_RESYNC;
2889                 goto fail_ldev;
2890         }
2891
2892         if (device->state.role == R_SECONDARY &&
2893             device->state.peer == R_SECONDARY) {
2894                 retcode = ERR_NO_PRIMARY;
2895                 goto fail_ldev;
2896         }
2897
2898         if (rs.no_resync && first_peer_device(device)->connection->agreed_pro_version < 93) {
2899                 retcode = ERR_NEED_APV_93;
2900                 goto fail_ldev;
2901         }
2902
2903         rcu_read_lock();
2904         u_size = rcu_dereference(device->ldev->disk_conf)->disk_size;
2905         rcu_read_unlock();
2906         if (u_size != (sector_t)rs.resize_size) {
2907                 new_disk_conf = kmalloc(sizeof(struct disk_conf), GFP_KERNEL);
2908                 if (!new_disk_conf) {
2909                         retcode = ERR_NOMEM;
2910                         goto fail_ldev;
2911                 }
2912         }
2913
2914         if (device->ldev->md.al_stripes != rs.al_stripes ||
2915             device->ldev->md.al_stripe_size_4k != rs.al_stripe_size / 4) {
2916                 u32 al_size_k = rs.al_stripes * rs.al_stripe_size;
2917
2918                 if (al_size_k > (16 * 1024 * 1024)) {
2919                         retcode = ERR_MD_LAYOUT_TOO_BIG;
2920                         goto fail_ldev;
2921                 }
2922
2923                 if (al_size_k < MD_32kB_SECT/2) {
2924                         retcode = ERR_MD_LAYOUT_TOO_SMALL;
2925                         goto fail_ldev;
2926                 }
2927
2928                 if (device->state.conn != C_CONNECTED && !rs.resize_force) {
2929                         retcode = ERR_MD_LAYOUT_CONNECTED;
2930                         goto fail_ldev;
2931                 }
2932
2933                 change_al_layout = true;
2934         }
2935
2936         if (device->ldev->known_size != drbd_get_capacity(device->ldev->backing_bdev))
2937                 device->ldev->known_size = drbd_get_capacity(device->ldev->backing_bdev);
2938
2939         if (new_disk_conf) {
2940                 mutex_lock(&device->resource->conf_update);
2941                 old_disk_conf = device->ldev->disk_conf;
2942                 *new_disk_conf = *old_disk_conf;
2943                 new_disk_conf->disk_size = (sector_t)rs.resize_size;
2944                 rcu_assign_pointer(device->ldev->disk_conf, new_disk_conf);
2945                 mutex_unlock(&device->resource->conf_update);
2946                 synchronize_rcu();
2947                 kfree(old_disk_conf);
2948                 new_disk_conf = NULL;
2949         }
2950
2951         ddsf = (rs.resize_force ? DDSF_FORCED : 0) | (rs.no_resync ? DDSF_NO_RESYNC : 0);
2952         dd = drbd_determine_dev_size(device, ddsf, change_al_layout ? &rs : NULL);
2953         drbd_md_sync(device);
2954         put_ldev(device);
2955         if (dd == DS_ERROR) {
2956                 retcode = ERR_NOMEM_BITMAP;
2957                 goto fail;
2958         } else if (dd == DS_ERROR_SPACE_MD) {
2959                 retcode = ERR_MD_LAYOUT_NO_FIT;
2960                 goto fail;
2961         } else if (dd == DS_ERROR_SHRINK) {
2962                 retcode = ERR_IMPLICIT_SHRINK;
2963                 goto fail;
2964         }
2965
2966         if (device->state.conn == C_CONNECTED) {
2967                 if (dd == DS_GREW)
2968                         set_bit(RESIZE_PENDING, &device->flags);
2969
2970                 drbd_send_uuids(first_peer_device(device));
2971                 drbd_send_sizes(first_peer_device(device), 1, ddsf);
2972         }
2973
2974  fail:
2975         mutex_unlock(&adm_ctx.resource->adm_mutex);
2976  finish:
2977         drbd_adm_finish(&adm_ctx, info, retcode);
2978         return 0;
2979
2980  fail_ldev:
2981         put_ldev(device);
2982         kfree(new_disk_conf);
2983         goto fail;
2984 }
2985
2986 int drbd_adm_resource_opts(struct sk_buff *skb, struct genl_info *info)
2987 {
2988         struct drbd_config_context adm_ctx;
2989         enum drbd_ret_code retcode;
2990         struct res_opts res_opts;
2991         int err;
2992
2993         retcode = drbd_adm_prepare(&adm_ctx, skb, info, DRBD_ADM_NEED_RESOURCE);
2994         if (!adm_ctx.reply_skb)
2995                 return retcode;
2996         if (retcode != NO_ERROR)
2997                 goto fail;
2998
2999         res_opts = adm_ctx.resource->res_opts;
3000         if (should_set_defaults(info))
3001                 set_res_opts_defaults(&res_opts);
3002
3003         err = res_opts_from_attrs(&res_opts, info);
3004         if (err && err != -ENOMSG) {
3005                 retcode = ERR_MANDATORY_TAG;
3006                 drbd_msg_put_info(adm_ctx.reply_skb, from_attrs_err_to_txt(err));
3007                 goto fail;
3008         }
3009
3010         mutex_lock(&adm_ctx.resource->adm_mutex);
3011         err = set_resource_options(adm_ctx.resource, &res_opts);
3012         if (err) {
3013                 retcode = ERR_INVALID_REQUEST;
3014                 if (err == -ENOMEM)
3015                         retcode = ERR_NOMEM;
3016         }
3017         mutex_unlock(&adm_ctx.resource->adm_mutex);
3018
3019 fail:
3020         drbd_adm_finish(&adm_ctx, info, retcode);
3021         return 0;
3022 }
3023
3024 int drbd_adm_invalidate(struct sk_buff *skb, struct genl_info *info)
3025 {
3026         struct drbd_config_context adm_ctx;
3027         struct drbd_device *device;
3028         int retcode; /* enum drbd_ret_code rsp. enum drbd_state_rv */
3029
3030         retcode = drbd_adm_prepare(&adm_ctx, skb, info, DRBD_ADM_NEED_MINOR);
3031         if (!adm_ctx.reply_skb)
3032                 return retcode;
3033         if (retcode != NO_ERROR)
3034                 goto out;
3035
3036         device = adm_ctx.device;
3037         if (!get_ldev(device)) {
3038                 retcode = ERR_NO_DISK;
3039                 goto out;
3040         }
3041
3042         mutex_lock(&adm_ctx.resource->adm_mutex);
3043
3044         /* If there is still bitmap IO pending, probably because of a previous
3045          * resync just being finished, wait for it before requesting a new resync.
3046          * Also wait for it's after_state_ch(). */
3047         drbd_suspend_io(device);
3048         wait_event(device->misc_wait, !test_bit(BITMAP_IO, &device->flags));
3049         drbd_flush_workqueue(&first_peer_device(device)->connection->sender_work);
3050
3051         /* If we happen to be C_STANDALONE R_SECONDARY, just change to
3052          * D_INCONSISTENT, and set all bits in the bitmap.  Otherwise,
3053          * try to start a resync handshake as sync target for full sync.
3054          */
3055         if (device->state.conn == C_STANDALONE && device->state.role == R_SECONDARY) {
3056                 retcode = drbd_request_state(device, NS(disk, D_INCONSISTENT));
3057                 if (retcode >= SS_SUCCESS) {
3058                         if (drbd_bitmap_io(device, &drbd_bmio_set_n_write,
3059                                 "set_n_write from invalidate", BM_LOCKED_MASK))
3060                                 retcode = ERR_IO_MD_DISK;
3061                 }
3062         } else
3063                 retcode = drbd_request_state(device, NS(conn, C_STARTING_SYNC_T));
3064         drbd_resume_io(device);
3065         mutex_unlock(&adm_ctx.resource->adm_mutex);
3066         put_ldev(device);
3067 out:
3068         drbd_adm_finish(&adm_ctx, info, retcode);
3069         return 0;
3070 }
3071
3072 static int drbd_adm_simple_request_state(struct sk_buff *skb, struct genl_info *info,
3073                 union drbd_state mask, union drbd_state val)
3074 {
3075         struct drbd_config_context adm_ctx;
3076         enum drbd_ret_code retcode;
3077
3078         retcode = drbd_adm_prepare(&adm_ctx, skb, info, DRBD_ADM_NEED_MINOR);
3079         if (!adm_ctx.reply_skb)
3080                 return retcode;
3081         if (retcode != NO_ERROR)
3082                 goto out;
3083
3084         mutex_lock(&adm_ctx.resource->adm_mutex);
3085         retcode = drbd_request_state(adm_ctx.device, mask, val);
3086         mutex_unlock(&adm_ctx.resource->adm_mutex);
3087 out:
3088         drbd_adm_finish(&adm_ctx, info, retcode);
3089         return 0;
3090 }
3091
3092 static int drbd_bmio_set_susp_al(struct drbd_device *device) __must_hold(local)
3093 {
3094         int rv;
3095
3096         rv = drbd_bmio_set_n_write(device);
3097         drbd_suspend_al(device);
3098         return rv;
3099 }
3100
3101 int drbd_adm_invalidate_peer(struct sk_buff *skb, struct genl_info *info)
3102 {
3103         struct drbd_config_context adm_ctx;
3104         int retcode; /* drbd_ret_code, drbd_state_rv */
3105         struct drbd_device *device;