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